import {createHash} from 'node:crypto'; import {defineTool} from '@deepseek-ai/dsh-tools'; import {compactResult} from './model_results.mjs'; export const lifecycleNames=['dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations']; export function registerLifecycle(ctx){ const pending=new Map(); ctx.on('dx/task-lifecycle-result',value=>pending.get(value.request_id)?.resolve(value)); ctx.effect(()=>()=>{for(const request of pending.values())request.reject(Error('Task center disconnected'));},'dx-task: lifecycle requests'); async function request(capability,spec,exec){ if(process.env.DX_DSH_PARENT_PIPE!=='1')throw Error('This capability requires the task-center desktop.'); if(!spec||typeof spec!=='object'||JSON.stringify(spec).length>16000)throw Error('Invalid task request'); const request_id=createHash('sha256').update((exec.agent?.id||'')+':'+exec.callId).digest('hex').slice(0,32); if(pending.has(request_id))return pending.get(request_id).promise; let resolve,reject,timer; const promise=new Promise((yes,no)=>{resolve=yes;reject=no;}); const cancel=()=>{ process.stdout.write('DX_DSH_LIFECYCLE_CANCEL '+JSON.stringify({request_id,reason:'conversation_cancelled'})+'\n'); reject(Error('Conversation wait cancelled. Confirmed configuration writes and executions retain their own lifetime. Inspect actual task receipts; request task pause explicitly when needed.')); }; pending.set(request_id,{promise,resolve,reject}); try{ exec.signal.throwIfAborted();exec.signal.addEventListener('abort',cancel,{once:true}); timer=setTimeout(cancel,capability==='execute'&&spec.operation==='start'?86400000:300000); process.stdout.write('DX_DSH_LIFECYCLE_REQUEST '+JSON.stringify({request_id,capability,spec})+'\n'); return await promise; }finally{clearTimeout(timer);exec.signal.removeEventListener('abort',cancel);pending.delete(request_id);} } const output={schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(compactResult(value))}]}; const ids={type:'array',required:true,items:{type:'string'},description:'1 to 20 distinct real task IDs obtained from current records, in execution order. Never infer IDs.'}; const definitions=[ {name:'dx_task_catalog',capability:'catalog',parameters:{task_id:{type:'string',description:'Optional real task ID to also read its saved rule mappings, Value policy and execution phase.'}}, description:'List real tasks and their IDs, names, groups, statuses and notes. Optionally read one task in detail, including existing rule mappings and bounded saved target identities/Value policies. Target value_mode is the explicit saved selection: inherit uses the task default, preserve retains original Value, part_label reads the library label during execution, part_number uses the replacement number, custom uses explicit text. value_policy is its effective mode; omitted_targets reports unreturned targets. Use real IDs before changing, copying or executing. Reads saved records only. Interactive conversations only.'}, {name:'dx_task_preflight',capability:'preflight',parameters:{task_ids:ids}, description:'Check the selected saved tasks before execution. Reports project availability, enabled rules/targets, existing execution evidence, unresolved failures and resource blockers. No CAD connection or engineering writes. Returns concrete blockers; does not guarantee a successful CAD run. Interactive conversations only.'}, {name:'dx_task_manage',capability:'manage',parameters:{ operation:{type:'string',required:true,enum:['select','copy','update','archive','import_bom']},task_id:{type:'string',required:true}, patch:{type:'object',additionalProperties:false,description:'Only for update. Omit fields the user did not request. Rule edits propagate to the existing task batch and are shown in the native preview.',properties:{ name:{type:'string'},note:{type:'string'},copy_part_number_to_value:{type:'boolean'}, rules:{type:'array',items:{type:'object',additionalProperties:false,properties:{old_part_number:{type:'string',required:true}, new_part_number:{type:'string'},target_cell:{type:'string'},custom_value:{type:'string'},custom_value_enabled:{type:'boolean'},sync_nc:{type:'boolean'},enabled:{type:'boolean'}}}}}}}, description:'Manage an existing real task. select changes the task-center selection. update previews explicit metadata and existing rule changes, then waits for native user confirmation. archive moves only that task to the recycle bin, preserving evidence. copy copies mapping configuration and opens the native selector for NEW engineering scope; never duplicates execution evidence or executes CAD. import_bom requires the task already selected and loaded: after native confirmation opens the existing multi-file Excel picker, validation and preview workflow. User chooses files and separately saves the checked batch plan; handed_off never means imported or saved. File paths and confirmation are never model arguments. Returns committed IDs/results or cancellation. Native user confirmation cannot be supplied by model arguments. Interactive conversations only.'}, {name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause','resume']},task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string',description:'For resume only, use the real saved run ID from execution history. Original frozen scope/order and existing checkpoint are inspected, then natively confirmed.'}}, description:'Start or continue the existing serial execution queue for an explicit ordered list of real task IDs. Prechecks and native confirmation are required; actual execution can replace and save engineering files using existing backup, interruption and verification gates. Waits for real results including saved, failed and no-match counts. For pause, provide exactly the active run scope; requests safe stopping after the current item and returns pause_requested, not a claim that stopping has completed. No force-stop, no new CAD scripting or hidden retry. Interactive conversations only.'}, {name:'dx_task_operations',capability:'operations',parameters:{ operation:{type:'string',required:true,enum:['refresh','history','health','decisions','impact','experience','tickets','refresh_ticket','schedule','schedule_dialog','cancel_schedule','run_schedule','reconcile_schedule','resume']}, task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string'},schedule_id:{type:'string'},incident_id:{type:'string'},issue_code:{type:'string'}, title:{type:'string'},priority:{type:'string',enum:['low','normal','high','urgent']}, not_before:{type:'string',description:'For schedule: earliest run time as ISO 8601 with explicit timezone offset, e.g. 2026-10-30T18:00:00+08:00. Ask when ambiguous; never guess a date.'}, due_at:{type:'string',description:'Optional deadline with timezone offset'},dependencies:{type:'array',items:{type:'string'},description:'Actual preceding task IDs that must complete without unresolved evidence'}, auto_start:{type:'boolean',description:'Future idle execution intent only. Native confirmation explicitly authorizes the frozen scope; never a bypass. Default false.'}}, description:'Read execution history/recoverable runs, exact saved impact or unknown mapping counts, evidence-backed local experiences, and existing Git issue status/replies. Refresh one bound ticket by real incident ID; cannot write comments. Plan tasks with priority/time/dependencies and optional idle execution using a native confirmation. App must remain open; changed plans, pause, uncertainty and blockers prevent scheduled execution. reconcile_schedule requests native confirmation to close an orphan claimed schedule only when no execution owns it and resources are released; preserves the original run for recovery and never starts execution. Use only fields relevant to the selected operation. history/refresh return real saved run and schedule IDs. resume reconfirms an original frozen queue. Interactive conversations only.'}, ]; for(const {capability,...definition} of definitions){ ctx.tools.register(defineTool({...definition,output,execute:(spec,exec)=>request(capability,spec,exec)})); } }