@agimon-ai/doompi-task 0.0.1-alpha.0 → 0.0.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/delegation/manager.cjs +2 -1
- package/dist/delegation/manager.cjs.map +1 -1
- package/dist/delegation/manager.d.cts.map +1 -1
- package/dist/delegation/manager.d.mts.map +1 -1
- package/dist/delegation/manager.mjs +2 -1
- package/dist/delegation/manager.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/store/reducer.cjs +1 -1
- package/dist/store/reducer.cjs.map +1 -1
- package/dist/store/reducer.mjs +1 -1
- package/dist/store/reducer.mjs.map +1 -1
- package/dist/tool/promptGuidelines.cjs +1 -1
- package/dist/tool/promptGuidelines.cjs.map +1 -1
- package/dist/tool/promptGuidelines.mjs +1 -1
- package/dist/tool/promptGuidelines.mjs.map +1 -1
- package/dist/tui/selectors.cjs +1 -1
- package/dist/tui/selectors.cjs.map +1 -1
- package/dist/tui/selectors.d.cts +16 -8
- package/dist/tui/selectors.d.cts.map +1 -1
- package/dist/tui/selectors.d.mts +16 -8
- package/dist/tui/selectors.d.mts.map +1 -1
- package/dist/tui/selectors.mjs +1 -1
- package/dist/tui/selectors.mjs.map +1 -1
- package/dist/tui/taskOverlay.cjs +1 -1
- package/dist/tui/taskOverlay.cjs.map +1 -1
- package/dist/tui/taskOverlay.d.cts.map +1 -1
- package/dist/tui/taskOverlay.d.mts.map +1 -1
- package/dist/tui/taskOverlay.mjs +1 -1
- package/dist/tui/taskOverlay.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../logSinkTelemetry.cjs"),n=require("../store/types.cjs"),r=require("../store/reconcile.cjs"),i=require("../store/taskGraph.cjs");let a=require("node:crypto"),o=require("node:path");o=e.__toESM(o,1);let s=require("@agimon-ai/doompi-extension-contracts/delegation"),c=require("@agimon-ai/doompi-extension-contracts/protocol");const l=`doom-task-notify`,u=`completed`,d=`failed`,f=`cancelled`,p=`task.id`,m=`delegation.request_id`,h=`delegation.agent_name`,g=`delegation.context_present`,_=`delegation.context_file_count`,v=`delegation.context_notes_length`,y=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,b=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,x=`Subagent did not acknowledge the cancel request`;function S(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function C(e){return e instanceof Error?e.message:String(e)}function w(e,t){if(!o.default.isAbsolute(e))return o.default.normalize(e);let n=o.default.relative(t,e);return n&&!n.startsWith(`..`)?n:e}function T(e,t){let n=new Set;for(let r of e.relevantFiles??[]){if(n.size>=12)break;let e=w(r.trim(),t);e&&e!==`.`&&n.add(e)}return{files:[...n],notes:S(e.priorFindings?.trim(),1500)}}function E(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../logSinkTelemetry.cjs"),n=require("../store/types.cjs"),r=require("../store/reconcile.cjs"),i=require("../store/taskGraph.cjs");let a=require("node:crypto"),o=require("node:path");o=e.__toESM(o,1);let s=require("@agimon-ai/doompi-extension-contracts/delegation"),c=require("@agimon-ai/doompi-extension-contracts/protocol");const l=`doom-task-notify`,u=`completed`,d=`failed`,f=`cancelled`,p=`task.id`,m=`delegation.request_id`,h=`delegation.agent_name`,g=`delegation.context_present`,_=`delegation.context_file_count`,v=`delegation.context_notes_length`,y=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,b=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,x=`Subagent did not acknowledge the cancel request`;function S(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function C(e){return e instanceof Error?e.message:String(e)}function w(e,t){if(!o.default.isAbsolute(e))return o.default.normalize(e);let n=o.default.relative(t,e);return n&&!n.startsWith(`..`)?n:e}function T(e,t){let n=new Set;for(let r of e.relevantFiles??[]){if(n.size>=12)break;let e=w(r.trim(),t);e&&e!==`.`&&n.add(e)}return{files:[...n],notes:S(e.priorFindings?.trim(),1500)}}function E(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
|
|
2
|
+
`))}return r.push(`Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.`),r.join(`
|
|
2
3
|
|
|
3
4
|
`)}var D=class e{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];protocol;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get env(){return this.options.env??process.env}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.env.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}start(){if(this.subscriptions.length>0)return;let e=this.options.getSessionId?.();e&&(this.protocol=(0,c.createProtocolRuntime)({bus:this.options.events,source:`@agimon-ai/doompi-task`,sessionId:e}),this.subscriptions.push(this.protocol.onNotification(s.DelegationAccepted,e=>{this.handleAccepted(e)}),this.protocol.onNotification(s.DelegationStarted,e=>{this.handleStarted(e)}),this.protocol.onNotification(s.DelegationUpdated,e=>{this.handleUpdate(e)}),this.protocol.onNotification(s.DelegationFinished,e=>{this.handleResponse(e).catch(n=>{this.report(t.TASK_EVENT.delegationResponseFailed,n,{[m]:e.requestId})})})))}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(){let{value:e}=await this.options.store.mutate(e=>{let t=r.reconcileOrphanedDelegations(e,this.now(),void 0,{pid:process.pid,liveRequestIds:new Set(this.pendingTasks.keys())});return t.orphaned.length===0?{value:[]}:{document:t.document,value:t.orphaned}});for(let n of e)this.options.report?.warn(t.TASK_EVENT.delegationOrphaned,Error(n.delegation?.result?.error??``),{[p]:n.id,...n.delegation?.agent?{[h]:n.delegation.agent}:{},...n.delegation?.pid===void 0?{}:{"delegation.pid":n.delegation.pid}});return e.length>0&&this.options.onChange?.(),e}async assign(e,r){let o=r.agent?.trim();if(!o)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:b};if(r.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let c=(0,a.randomUUID)(),l=this.now(),f=T(r,this.options.cwd),{value:x}=await this.options.store.mutate(t=>{let a=t.tasks.findIndex(t=>t.id===e);if(a===-1)return{value:{ok:!1,message:`#${e} not found`}};let s=t.tasks[a];if(s.status===`deleted`)return{value:{ok:!1,message:`#${e} is deleted`}};if(s.status===u)return{value:{ok:!1,message:`#${e} is already completed`}};if(n.isDelegationActive(s))return{value:{ok:!1,message:`#${e} is already delegated to ${s.delegation?.agent}`}};if(i.isBlocked(t.tasks,s))return{value:{ok:!1,message:`#${e} is blocked by ${(s.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let d={requestId:c,agent:o,state:`requested`,pid:process.pid,startedAt:l,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...r.model?{model:r.model}:{}},f=[...t.tasks];return f[a]={...s,owner:o,updatedAt:l,delegation:d},{document:{...t,tasks:f},value:{ok:!0,message:``,task:f[a]}}});if(!x.ok||!x.task)return{ok:!1,message:x.message};let S=f.notes?.length??0;this.pendingTasks.set(c,e),this.progress.set(c,{agent:o,contextFileCount:f.files.length,contextNotesLength:S}),this.armStartedTimeout(c);let w={requestId:c,taskId:e,agent:o,...r.inlineAgent?{inlineAgent:r.inlineAgent}:{},prompt:E(x.task,r.instructions,f),...r.context?{context:r.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(x.task.id),subject:x.task.subject},...r.model?{model:r.model}:{}};try{if(!this.protocol)throw Error(y);this.protocol.notify(s.DelegationRequested,w)}catch(n){this.report(t.TASK_EVENT.delegationRequestFailed,n,{[p]:e,[m]:c,[h]:o});let r=C(n);return await this.settle(c,d,{status:d,error:`Delegation request failed: ${r}`}),{ok:!1,message:`Could not dispatch #${e} to ${o}: ${r}`}}return this.options.report?.event(t.TASK_EVENT.delegationAssigned,{[p]:e,[m]:c,[h]:o,[g]:f.files.length>0||S>0,[_]:f.files.length,[v]:S,"delegation.brief_length":w.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${e} to ${o} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!n.isDelegationActive(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:r}=t.delegation;return this.protocol?.notify(s.DelegationCancelled,{requestId:r}),this.armCancelTimeout(r),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,n,r,i=t.TASK_EVENT.delegationSettleFailed){this.settle(e,n,r).catch(t=>{this.report(i,t,{[m]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,d,{status:d,error:y})})}armRunTimeout(e){let n=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+n,()=>{let n=this.pendingTasks.get(e),r=this.progress.get(e)?.agent,i=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(t.TASK_EVENT.delegationTimedOut,i,{...n===void 0?{}:{[p]:n},[m]:e,...r?{[h]:r}:{}}),this.protocol?.notify(s.DelegationCancelled,{requestId:e,reason:i.message}),this.settleDetached(e,d,{status:`timed_out`,error:i.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,f,{status:f,error:x})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:n}=e,r=this.pendingTasks.get(e.requestId);if(r===void 0)return;this.armRunTimeout(e.requestId);let i=this.progress.get(e.requestId);i&&this.progress.set(e.requestId,{...i,durationMs:i.durationMs??0,durationObservedAt:i.durationObservedAt??this.nowMs()}),this.options.store.mutate(t=>this.patchDelegation(t,e.requestId,(e,t)=>({...e,status:e.status===u?e.status:`in_progress`,delegation:{...t,state:`running`,startedAt:t.startedAt??this.now(),...n?{runId:n}:{}}}))).then(()=>this.options.onChange?.()).catch(n=>{this.report(t.TASK_EVENT.delegationStartFailed,n,{[p]:r,[m]:e.requestId})})}handleUpdate(t){let n=this.progress.get(t.requestId);if(!n)return;let r=this.nowMs(),i=e.elapsedMs(n,r),a=t.durationMs!==void 0;this.progress.set(t.requestId,{...n,currentTool:t.currentTool??n.currentTool,toolCount:t.toolCount===void 0?n.toolCount:Math.max(n.toolCount??0,t.toolCount),tokens:t.tokens===void 0?n.tokens:Math.max(n.tokens??0,t.tokens),durationMs:a?Math.max(i,t.durationMs):n.durationMs,durationObservedAt:a?r:n.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===u&&!e.error?u:e.status===f?f:d;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:S(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,n,r){let a=this.pendingTasks.get(e);if(a===void 0)return;this.pendingTasks.delete(e),this.clearTimer(e);let o=this.progress.get(e);this.progress.delete(e);let s=this.now(),c;try{let{value:t}=await this.options.store.mutate(t=>this.patchDelegation(t,e,(e,t)=>({...e,status:n===u?u:n===f?`pending`:d,updatedAt:s,delegation:{...t,state:n,endedAt:s,...r?{result:r}:{}}})));c=t}catch(n){this.report(t.TASK_EVENT.delegationSettleFailed,n,{[p]:a,[m]:e})}this.options.onChange?.();let l=c?.delegation?.agent??o?.agent??`subagent`,y=c?.subject??`#${a}`;this.options.report?.event(t.TASK_EVENT.delegationCompleted,{[p]:a,[m]:e,[h]:l,"delegation.outcome":n,[g]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[_]:o?.contextFileCount??0,[v]:o?.contextNotesLength??0,...r?.toolCount===void 0?{}:{"delegation.tool_count":r.toolCount},...r?.durationMs===void 0?{}:{"delegation.duration_ms":r.durationMs}});let b=n===u&&c!==void 0&&i.isTaskListComplete(this.options.store.snapshot.tasks);this.notifyModel(n,a,y,l,r,b)}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let s=[e===u?`Subagent ${r} completed task #${t}: ${n}`:e===f?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&s.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&s.push(`Error: ${i.error}`),i?.output&&s.push(``,i.output),i?.outputPath&&s.push(``,`Full output: ${i.outputPath}`);try{o({customType:l,content:s.join(`
|
|
4
5
|
`),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,r){let i=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!n.isDelegationActive(a))return{value:a};let o=r(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){for(let e of this.subscriptions)e();this.subscriptions.length=0,this.protocol=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};exports.BACKGROUND_WORK_PROVIDER=`doom-task`,exports.DelegationManager=D,exports.ERR_CANCEL_UNACKNOWLEDGED=x,exports.ERR_CHILD_SESSION=b,exports.ERR_NO_RUNTIME=y,exports.MAX_BRIEF_FILES=12,exports.NOTIFY_CUSTOM_TYPE=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.cjs","names":["path","createProtocolRuntime","DelegationAccepted","DelegationStarted","DelegationUpdated","DelegationFinished","TASK_EVENT","reconcileOrphanedDelegations","randomUUID","isDelegationActive","isBlocked","DelegationRequested","DelegationCancelled","isTaskListComplete"],"sources":["../../src/delegation/manager.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport {\n DelegationAccepted,\n DelegationCancelled,\n DelegationFinished,\n DelegationRequested,\n DelegationStarted,\n DelegationUpdated,\n type DelegationAccepted as DelegationAcceptedPayload,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport {\n createProtocolRuntime,\n type EventBusLike,\n type ProtocolRuntime,\n} from '@agimon-ai/doompi-extension-contracts/protocol';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../store/taskStore.ts';\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nexport const MAX_BRIEF_FILES = 12;\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport interface DelegationNotifier {\n (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n ): void;\n}\n\nexport interface DelegationManagerOptions {\n events: EventBusLike;\n store: TaskStore;\n cwd: string;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n env?: NodeJS.ProcessEnv;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/**\n * Render a supplied path the way the child will see it, from `cwd`.\n *\n * Existence is deliberately not checked: an fs probe here duplicates the read\n * the child performs anyway, and it cannot detect the failure that actually\n * matters — a path that exists but is no longer the right one.\n */\nfunction briefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\nfunction briefContext(options: AssignOptions, cwd: string): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = briefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's discovery handed over. Both lines are\n * omitted entirely when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0) {\n sections.push(`Start here (main already located these, the list may be incomplete): ${context.files.join(', ')}`);\n }\n if (context.notes) sections.push(`Already established by main, do not re-derive: ${context.notes}`);\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides the Doom Team event bus rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that runtime is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly subscriptions: Array<() => void> = [];\n private protocol: ProtocolRuntime | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get env(): NodeJS.ProcessEnv {\n return this.options.env ?? process.env;\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.env.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Idempotent: a session restart re-subscribes without stacking handlers. */\n start(): void {\n if (this.subscriptions.length > 0) return;\n const sessionId = this.options.getSessionId?.();\n if (!sessionId) return;\n this.protocol = createProtocolRuntime({\n bus: this.options.events,\n source: '@agimon-ai/doompi-task',\n sessionId,\n });\n this.subscriptions.push(\n this.protocol.onNotification(DelegationAccepted, (event) => {\n this.handleAccepted(event);\n }),\n this.protocol.onNotification(DelegationStarted, (event) => {\n this.handleStarted(event);\n }),\n this.protocol.onNotification(DelegationUpdated, (event) => {\n this.handleUpdate(event);\n }),\n this.protocol.onNotification(DelegationFinished, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: process.pid,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = randomUUID();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: process.pid,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n if (!this.protocol) throw new Error(ERR_NO_RUNTIME);\n this.protocol.notify(DelegationRequested, request);\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Emitted only after the notify succeeds, so it means \"a brief of this\n // shape actually went out\" rather than \"one was assembled\".\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.protocol?.notify(DelegationCancelled, { requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * The bus cannot be probed for listeners, so silence is the only available\n * signal that the subagents runtime is absent. Without this the task would\n * sit in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.protocol?.notify(DelegationCancelled, { requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Emitting the cancel event is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n for (const unsubscribe of this.subscriptions) unsubscribe();\n this.subscriptions.length = 0;\n this.protocol = undefined;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.progress.clear();\n }\n}\n"],"mappings":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M,KAAK,UAAU,EAAO,OAAO,EAClD,GAAQ,QAAQ,EAAM,KAAK,GAAI,EAAO,MAAM,EAC5C,GAAQ,YAAY,EAAM,KAAK,GAAI,gBAAgB,EAAO,YAAY,EAE1E,GAAI,CACF,EACE,CAAE,WAAY,EAAoB,QAAS,EAAM,KAAK;CAAI,EAAG,QAAS,EAAK,EAC3E,CAAE,YAAa,GAAM,UAAW,OAAQ,CAC1C,CACF,OAAS,EAAO,CAId,KAAK,QAAQ,cAAc,EAAO,CAAM,CAC1C,CACF,CAWA,gBACE,EACA,EACA,EACsD,CACtD,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,YAAY,YAAc,CAAS,EACzF,GAAI,IAAU,GAAI,MAAO,CAAE,MAAO,IAAA,EAAU,EAE5C,IAAM,EAAO,EAAS,MAAM,GAC5B,GAAI,CAACJ,EAAAA,mBAAmB,CAAI,EAAG,MAAO,CAAE,MAAO,CAAK,EAEpD,IAAM,EAAU,EAAM,EAAM,EAAK,UAAW,EAC5C,GAAI,IAAY,EAAM,MAAO,CAAE,MAAO,CAAK,EAC3C,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,EACR,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,MAAO,CAAQ,CAC5D,CAEA,SAAgB,CACd,IAAK,IAAM,KAAe,KAAK,cAAe,EAAY,EAC1D,KAAK,cAAc,OAAS,EAC5B,KAAK,SAAW,IAAA,GAChB,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
|
|
1
|
+
{"version":3,"file":"manager.cjs","names":["path","createProtocolRuntime","DelegationAccepted","DelegationStarted","DelegationUpdated","DelegationFinished","TASK_EVENT","reconcileOrphanedDelegations","randomUUID","isDelegationActive","isBlocked","DelegationRequested","DelegationCancelled","isTaskListComplete"],"sources":["../../src/delegation/manager.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport {\n DelegationAccepted,\n DelegationCancelled,\n DelegationFinished,\n DelegationRequested,\n DelegationStarted,\n DelegationUpdated,\n type DelegationAccepted as DelegationAcceptedPayload,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport {\n createProtocolRuntime,\n type EventBusLike,\n type ProtocolRuntime,\n} from '@agimon-ai/doompi-extension-contracts/protocol';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../store/taskStore.ts';\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nexport const MAX_BRIEF_FILES = 12;\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport interface DelegationNotifier {\n (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n ): void;\n}\n\nexport interface DelegationManagerOptions {\n events: EventBusLike;\n store: TaskStore;\n cwd: string;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n env?: NodeJS.ProcessEnv;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/**\n * Render a supplied path the way the child will see it, from `cwd`.\n *\n * Existence is deliberately not checked: an fs probe here duplicates the read\n * the child performs anyway, and it cannot detect the failure that actually\n * matters — a path that exists but is no longer the right one.\n */\nfunction briefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\nfunction briefContext(options: AssignOptions, cwd: string): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = briefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides the Doom Team event bus rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that runtime is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly subscriptions: Array<() => void> = [];\n private protocol: ProtocolRuntime | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get env(): NodeJS.ProcessEnv {\n return this.options.env ?? process.env;\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.env.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Idempotent: a session restart re-subscribes without stacking handlers. */\n start(): void {\n if (this.subscriptions.length > 0) return;\n const sessionId = this.options.getSessionId?.();\n if (!sessionId) return;\n this.protocol = createProtocolRuntime({\n bus: this.options.events,\n source: '@agimon-ai/doompi-task',\n sessionId,\n });\n this.subscriptions.push(\n this.protocol.onNotification(DelegationAccepted, (event) => {\n this.handleAccepted(event);\n }),\n this.protocol.onNotification(DelegationStarted, (event) => {\n this.handleStarted(event);\n }),\n this.protocol.onNotification(DelegationUpdated, (event) => {\n this.handleUpdate(event);\n }),\n this.protocol.onNotification(DelegationFinished, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: process.pid,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = randomUUID();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: process.pid,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n if (!this.protocol) throw new Error(ERR_NO_RUNTIME);\n this.protocol.notify(DelegationRequested, request);\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Emitted only after the notify succeeds, so it means \"a brief of this\n // shape actually went out\" rather than \"one was assembled\".\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.protocol?.notify(DelegationCancelled, { requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * The bus cannot be probed for listeners, so silence is the only available\n * signal that the subagents runtime is absent. Without this the task would\n * sit in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.protocol?.notify(DelegationCancelled, { requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Emitting the cancel event is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n for (const unsubscribe of this.subscriptions) unsubscribe();\n this.subscriptions.length = 0;\n this.protocol = undefined;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.progress.clear();\n }\n}\n"],"mappings":"wcA0BA,MAAa,EAAqB,mBAc5B,EAAkB,YAClB,EAAe,SACf,EAAkB,YAIlB,EAAoB,UACpB,EAAuB,wBAGvB,EAAkB,wBAElB,EAA4B,6BAC5B,EAA+B,gCAC/B,EAAiC,kCAQ1B,EACX,kHACW,EACX,uGACW,EAA4B,kDAwEzC,SAAS,EAAS,EAA2B,EAAQ,IAAuC,CACrF,KACL,OAAO,EAAM,QAAU,EAAQ,EAAQ,GAAG,EAAM,MAAM,EAAG,CAAK,EAAE,gBAClE,CAEA,SAAS,EAAU,EAAwB,CACzC,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CAeA,SAAS,EAAU,EAAe,EAAqB,CACrD,GAAI,CAACA,EAAAA,QAAK,WAAW,CAAK,EAAG,OAAOA,EAAAA,Q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A,EACA,EACsD,CACtD,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,YAAY,YAAc,CAAS,EACzF,GAAI,IAAU,GAAI,MAAO,CAAE,MAAO,IAAA,EAAU,EAE5C,IAAM,EAAO,EAAS,MAAM,GAC5B,GAAI,CAACJ,EAAAA,mBAAmB,CAAI,EAAG,MAAO,CAAE,MAAO,CAAK,EAEpD,IAAM,EAAU,EAAM,EAAM,EAAK,UAAW,EAC5C,GAAI,IAAY,EAAM,MAAO,CAAE,MAAO,CAAK,EAC3C,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,EACR,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,MAAO,CAAQ,CAC5D,CAEA,SAAgB,CACd,IAAK,IAAM,KAAe,KAAK,cAAe,EAAY,EAC1D,KAAK,cAAc,OAAS,EAC5B,KAAK,SAAW,IAAA,GAChB,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.cts","names":[],"sources":["../../src/delegation/manager.ts"],"mappings":";;;;;;cA0Ba;cACA;;;;;cAWA;cAwBA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;UAGe;GAEb;IAAW;IAAoB;IAAiB;KAChD;IAAY;IAAuB;;;UAItB;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT;EACA,MAAM,OAAO;EACb;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"manager.d.cts","names":[],"sources":["../../src/delegation/manager.ts"],"mappings":";;;;;;cA0Ba;cACA;;;;;cAWA;cAwBA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;UAGe;GAEb;IAAW;IAAoB;IAAiB;KAChD;IAAY;IAAuB;;;UAItB;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT;EACA,MAAM,OAAO;EACb;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;cA+FW;mBACM;mBACA;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,SAAS;UAIb;UAIA;cAII;cAIA;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C;;EA4BA,kBAAkB;IAAQ;IAAY;;;;;;;;EAchC,aAAa,QAAQ;EAsBrB,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAwGxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAmDN;;;;;;;;;;UAmDA;EAkBR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.mts","names":[],"sources":["../../src/delegation/manager.ts"],"mappings":";;;;;;cA0Ba;cACA;;;;;cAWA;cAwBA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;UAGe;GAEb;IAAW;IAAoB;IAAiB;KAChD;IAAY;IAAuB;;;UAItB;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT;EACA,MAAM,OAAO;EACb;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"manager.d.mts","names":[],"sources":["../../src/delegation/manager.ts"],"mappings":";;;;;;cA0Ba;cACA;;;;;cAWA;cAwBA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;UAGe;GAEb;IAAW;IAAoB;IAAiB;KAChD;IAAY;IAAuB;;;UAItB;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT;EACA,MAAM,OAAO;EACb;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;cA+FW;mBACM;mBACA;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,SAAS;UAIb;UAIA;cAII;cAIA;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C;;EA4BA,kBAAkB;IAAQ;IAAY;;;;;;;;EAchC,aAAa,QAAQ;EAsBrB,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAwGxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAmDN;;;;;;;;;;UAmDA;EAkBR"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{TASK_EVENT as e}from"../logSinkTelemetry.mjs";import{isDelegationActive as t}from"../store/types.mjs";import{reconcileOrphanedDelegations as n}from"../store/reconcile.mjs";import{isBlocked as r,isTaskListComplete as i}from"../store/taskGraph.mjs";import{randomUUID as a}from"node:crypto";import o from"node:path";import{DelegationAccepted as s,DelegationCancelled as c,DelegationFinished as l,DelegationRequested as u,DelegationStarted as d,DelegationUpdated as f}from"@agimon-ai/doompi-extension-contracts/delegation";import{createProtocolRuntime as p}from"@agimon-ai/doompi-extension-contracts/protocol";const m=`doom-task-notify`,h=`doom-task`,g=12,_=`completed`,v=`failed`,y=`cancelled`,b=`task.id`,x=`delegation.request_id`,S=`delegation.agent_name`,C=`delegation.context_present`,w=`delegation.context_file_count`,T=`delegation.context_notes_length`,E=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,D=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,O=`Subagent did not acknowledge the cancel request`;function k(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function A(e){return e instanceof Error?e.message:String(e)}function j(e,t){if(!o.isAbsolute(e))return o.normalize(e);let n=o.relative(t,e);return n&&!n.startsWith(`..`)?n:e}function M(e,t){let n=new Set;for(let r of e.relevantFiles??[]){if(n.size>=12)break;let e=j(r.trim(),t);e&&e!==`.`&&n.add(e)}return{files:[...n],notes:k(e.priorFindings?.trim(),1500)}}function N(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];
|
|
1
|
+
import{TASK_EVENT as e}from"../logSinkTelemetry.mjs";import{isDelegationActive as t}from"../store/types.mjs";import{reconcileOrphanedDelegations as n}from"../store/reconcile.mjs";import{isBlocked as r,isTaskListComplete as i}from"../store/taskGraph.mjs";import{randomUUID as a}from"node:crypto";import o from"node:path";import{DelegationAccepted as s,DelegationCancelled as c,DelegationFinished as l,DelegationRequested as u,DelegationStarted as d,DelegationUpdated as f}from"@agimon-ai/doompi-extension-contracts/delegation";import{createProtocolRuntime as p}from"@agimon-ai/doompi-extension-contracts/protocol";const m=`doom-task-notify`,h=`doom-task`,g=12,_=`completed`,v=`failed`,y=`cancelled`,b=`task.id`,x=`delegation.request_id`,S=`delegation.agent_name`,C=`delegation.context_present`,w=`delegation.context_file_count`,T=`delegation.context_notes_length`,E=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,D=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,O=`Subagent did not acknowledge the cancel request`;function k(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function A(e){return e instanceof Error?e.message:String(e)}function j(e,t){if(!o.isAbsolute(e))return o.normalize(e);let n=o.relative(t,e);return n&&!n.startsWith(`..`)?n:e}function M(e,t){let n=new Set;for(let r of e.relevantFiles??[]){if(n.size>=12)break;let e=j(r.trim(),t);e&&e!==`.`&&n.add(e)}return{files:[...n],notes:k(e.priorFindings?.trim(),1500)}}function N(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
|
|
2
|
+
`))}return r.push(`Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.`),r.join(`
|
|
2
3
|
|
|
3
4
|
`)}var P=class o{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];protocol;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get env(){return this.options.env??process.env}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.env.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}start(){if(this.subscriptions.length>0)return;let t=this.options.getSessionId?.();t&&(this.protocol=p({bus:this.options.events,source:`@agimon-ai/doompi-task`,sessionId:t}),this.subscriptions.push(this.protocol.onNotification(s,e=>{this.handleAccepted(e)}),this.protocol.onNotification(d,e=>{this.handleStarted(e)}),this.protocol.onNotification(f,e=>{this.handleUpdate(e)}),this.protocol.onNotification(l,t=>{this.handleResponse(t).catch(n=>{this.report(e.delegationResponseFailed,n,{[x]:t.requestId})})})))}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(){let{value:t}=await this.options.store.mutate(e=>{let t=n(e,this.now(),void 0,{pid:process.pid,liveRequestIds:new Set(this.pendingTasks.keys())});return t.orphaned.length===0?{value:[]}:{document:t.document,value:t.orphaned}});for(let n of t)this.options.report?.warn(e.delegationOrphaned,Error(n.delegation?.result?.error??``),{[b]:n.id,...n.delegation?.agent?{[S]:n.delegation.agent}:{},...n.delegation?.pid===void 0?{}:{"delegation.pid":n.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(n,i){let o=i.agent?.trim();if(!o)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:D};if(i.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let s=a(),c=this.now(),l=M(i,this.options.cwd),{value:d}=await this.options.store.mutate(e=>{let a=e.tasks.findIndex(e=>e.id===n);if(a===-1)return{value:{ok:!1,message:`#${n} not found`}};let l=e.tasks[a];if(l.status===`deleted`)return{value:{ok:!1,message:`#${n} is deleted`}};if(l.status===_)return{value:{ok:!1,message:`#${n} is already completed`}};if(t(l))return{value:{ok:!1,message:`#${n} is already delegated to ${l.delegation?.agent}`}};if(r(e.tasks,l))return{value:{ok:!1,message:`#${n} is blocked by ${(l.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let u={requestId:s,agent:o,state:`requested`,pid:process.pid,startedAt:c,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...i.model?{model:i.model}:{}},d=[...e.tasks];return d[a]={...l,owner:o,updatedAt:c,delegation:u},{document:{...e,tasks:d},value:{ok:!0,message:``,task:d[a]}}});if(!d.ok||!d.task)return{ok:!1,message:d.message};let f=l.notes?.length??0;this.pendingTasks.set(s,n),this.progress.set(s,{agent:o,contextFileCount:l.files.length,contextNotesLength:f}),this.armStartedTimeout(s);let p={requestId:s,taskId:n,agent:o,...i.inlineAgent?{inlineAgent:i.inlineAgent}:{},prompt:N(d.task,i.instructions,l),...i.context?{context:i.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(d.task.id),subject:d.task.subject},...i.model?{model:i.model}:{}};try{if(!this.protocol)throw Error(E);this.protocol.notify(u,p)}catch(t){this.report(e.delegationRequestFailed,t,{[b]:n,[x]:s,[S]:o});let r=A(t);return await this.settle(s,v,{status:v,error:`Delegation request failed: ${r}`}),{ok:!1,message:`Could not dispatch #${n} to ${o}: ${r}`}}return this.options.report?.event(e.delegationAssigned,{[b]:n,[x]:s,[S]:o,[C]:l.files.length>0||f>0,[w]:l.files.length,[T]:f,"delegation.brief_length":p.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${n} to ${o} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`}}async cancel(e){let n=this.options.store.read().tasks.find(t=>t.id===e);if(!n)return{ok:!1,message:`#${e} not found`};if(!n.delegation||!t(n))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:r}=n.delegation;return this.protocol?.notify(c,{requestId:r}),this.armCancelTimeout(r),{ok:!0,message:`Cancelling delegation for #${e} (${n.delegation.agent})`}}settleDetached(t,n,r,i=e.delegationSettleFailed){this.settle(t,n,r).catch(e=>{this.report(i,e,{[x]:t})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,v,{status:v,error:E})})}armRunTimeout(t){let n=Math.min(6e4,this.runTimeoutMs);this.armTimer(t,this.runTimeoutMs+n,()=>{let n=this.pendingTasks.get(t),r=this.progress.get(t)?.agent,i=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(e.delegationTimedOut,i,{...n===void 0?{}:{[b]:n},[x]:t,...r?{[S]:r}:{}}),this.protocol?.notify(c,{requestId:t,reason:i.message}),this.settleDetached(t,v,{status:`timed_out`,error:i.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,y,{status:y,error:O})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(t){let{runId:n}=t,r=this.pendingTasks.get(t.requestId);if(r===void 0)return;this.armRunTimeout(t.requestId);let i=this.progress.get(t.requestId);i&&this.progress.set(t.requestId,{...i,durationMs:i.durationMs??0,durationObservedAt:i.durationObservedAt??this.nowMs()}),this.options.store.mutate(e=>this.patchDelegation(e,t.requestId,(e,t)=>({...e,status:e.status===_?e.status:`in_progress`,delegation:{...t,state:`running`,startedAt:t.startedAt??this.now(),...n?{runId:n}:{}}}))).then(()=>this.options.onChange?.()).catch(n=>{this.report(e.delegationStartFailed,n,{[b]:r,[x]:t.requestId})})}handleUpdate(e){let t=this.progress.get(e.requestId);if(!t)return;let n=this.nowMs(),r=o.elapsedMs(t,n),i=e.durationMs!==void 0;this.progress.set(e.requestId,{...t,currentTool:e.currentTool??t.currentTool,toolCount:e.toolCount===void 0?t.toolCount:Math.max(t.toolCount??0,e.toolCount),tokens:e.tokens===void 0?t.tokens:Math.max(t.tokens??0,e.tokens),durationMs:i?Math.max(r,e.durationMs):t.durationMs,durationObservedAt:i?n:t.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===_&&!e.error?_:e.status===y?y:v;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:k(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(t,n,r){let a=this.pendingTasks.get(t);if(a===void 0)return;this.pendingTasks.delete(t),this.clearTimer(t);let o=this.progress.get(t);this.progress.delete(t);let s=this.now(),c;try{let{value:e}=await this.options.store.mutate(e=>this.patchDelegation(e,t,(e,t)=>({...e,status:n===_?_:n===y?`pending`:v,updatedAt:s,delegation:{...t,state:n,endedAt:s,...r?{result:r}:{}}})));c=e}catch(n){this.report(e.delegationSettleFailed,n,{[b]:a,[x]:t})}this.options.onChange?.();let l=c?.delegation?.agent??o?.agent??`subagent`,u=c?.subject??`#${a}`;this.options.report?.event(e.delegationCompleted,{[b]:a,[x]:t,[S]:l,"delegation.outcome":n,[C]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[w]:o?.contextFileCount??0,[T]:o?.contextNotesLength??0,...r?.toolCount===void 0?{}:{"delegation.tool_count":r.toolCount},...r?.durationMs===void 0?{}:{"delegation.duration_ms":r.durationMs}});let d=n===_&&c!==void 0&&i(this.options.store.snapshot.tasks);this.notifyModel(n,a,u,l,r,d)}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let s=[e===_?`Subagent ${r} completed task #${t}: ${n}`:e===y?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&s.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&s.push(`Error: ${i.error}`),i?.output&&s.push(``,i.output),i?.outputPath&&s.push(``,`Full output: ${i.outputPath}`);try{o({customType:m,content:s.join(`
|
|
4
5
|
`),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,n,r){let i=e.tasks.findIndex(e=>e.delegation?.requestId===n);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!t(a))return{value:a};let o=r(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){for(let e of this.subscriptions)e();this.subscriptions.length=0,this.protocol=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};export{h as BACKGROUND_WORK_PROVIDER,P as DelegationManager,O as ERR_CANCEL_UNACKNOWLEDGED,D as ERR_CHILD_SESSION,E as ERR_NO_RUNTIME,g as MAX_BRIEF_FILES,m as NOTIFY_CUSTOM_TYPE};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.mjs","names":[],"sources":["../../src/delegation/manager.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport {\n DelegationAccepted,\n DelegationCancelled,\n DelegationFinished,\n DelegationRequested,\n DelegationStarted,\n DelegationUpdated,\n type DelegationAccepted as DelegationAcceptedPayload,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport {\n createProtocolRuntime,\n type EventBusLike,\n type ProtocolRuntime,\n} from '@agimon-ai/doompi-extension-contracts/protocol';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../store/taskStore.ts';\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nexport const MAX_BRIEF_FILES = 12;\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport interface DelegationNotifier {\n (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n ): void;\n}\n\nexport interface DelegationManagerOptions {\n events: EventBusLike;\n store: TaskStore;\n cwd: string;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n env?: NodeJS.ProcessEnv;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/**\n * Render a supplied path the way the child will see it, from `cwd`.\n *\n * Existence is deliberately not checked: an fs probe here duplicates the read\n * the child performs anyway, and it cannot detect the failure that actually\n * matters — a path that exists but is no longer the right one.\n */\nfunction briefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\nfunction briefContext(options: AssignOptions, cwd: string): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = briefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's discovery handed over. Both lines are\n * omitted entirely when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0) {\n sections.push(`Start here (main already located these, the list may be incomplete): ${context.files.join(', ')}`);\n }\n if (context.notes) sections.push(`Already established by main, do not re-derive: ${context.notes}`);\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides the Doom Team event bus rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that runtime is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly subscriptions: Array<() => void> = [];\n private protocol: ProtocolRuntime | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get env(): NodeJS.ProcessEnv {\n return this.options.env ?? process.env;\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.env.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Idempotent: a session restart re-subscribes without stacking handlers. */\n start(): void {\n if (this.subscriptions.length > 0) return;\n const sessionId = this.options.getSessionId?.();\n if (!sessionId) return;\n this.protocol = createProtocolRuntime({\n bus: this.options.events,\n source: '@agimon-ai/doompi-task',\n sessionId,\n });\n this.subscriptions.push(\n this.protocol.onNotification(DelegationAccepted, (event) => {\n this.handleAccepted(event);\n }),\n this.protocol.onNotification(DelegationStarted, (event) => {\n this.handleStarted(event);\n }),\n this.protocol.onNotification(DelegationUpdated, (event) => {\n this.handleUpdate(event);\n }),\n this.protocol.onNotification(DelegationFinished, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: process.pid,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = randomUUID();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: process.pid,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n if (!this.protocol) throw new Error(ERR_NO_RUNTIME);\n this.protocol.notify(DelegationRequested, request);\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Emitted only after the notify succeeds, so it means \"a brief of this\n // shape actually went out\" rather than \"one was assembled\".\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.protocol?.notify(DelegationCancelled, { requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * The bus cannot be probed for listeners, so silence is the only available\n * signal that the subagents runtime is absent. Without this the task would\n * sit in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.protocol?.notify(DelegationCancelled, { requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Emitting the cancel event is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n for (const unsubscribe of this.subscriptions) unsubscribe();\n this.subscriptions.length = 0;\n this.protocol = undefined;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.progress.clear();\n }\n}\n"],"mappings":"qmBA0BA,MAAa,EAAqB,mBACrB,EAA2B,YAW3B,EAAkB,GAEzB,EAAkB,YAClB,EAAe,SACf,EAAkB,YAIlB,EAAoB,UACpB,EAAuB,wBAGvB,EAAkB,wBAElB,EAA4B,6BAC5B,EAA+B,gCAC/B,EAAiC,kCAQ1B,EACX,kHACW,EACX,uGACW,EAA4B,kDAwEzC,SAAS,EAAS,EAA2B,EAAQ,IAAuC,CACrF,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AAO,EAAS,MAAM,GAC5B,GAAI,CAAC,EAAmB,CAAI,EAAG,MAAO,CAAE,MAAO,CAAK,EAEpD,IAAM,EAAU,EAAM,EAAM,EAAK,UAAW,EAC5C,GAAI,IAAY,EAAM,MAAO,CAAE,MAAO,CAAK,EAC3C,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,EACR,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,MAAO,CAAQ,CAC5D,CAEA,SAAgB,CACd,IAAK,IAAM,KAAe,KAAK,cAAe,EAAY,EAC1D,KAAK,cAAc,OAAS,EAC5B,KAAK,SAAW,IAAA,GAChB,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
|
|
1
|
+
{"version":3,"file":"manager.mjs","names":[],"sources":["../../src/delegation/manager.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport {\n DelegationAccepted,\n DelegationCancelled,\n DelegationFinished,\n DelegationRequested,\n DelegationStarted,\n DelegationUpdated,\n type DelegationAccepted as DelegationAcceptedPayload,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport {\n createProtocolRuntime,\n type EventBusLike,\n type ProtocolRuntime,\n} from '@agimon-ai/doompi-extension-contracts/protocol';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../store/taskStore.ts';\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nexport const MAX_BRIEF_FILES = 12;\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport interface DelegationNotifier {\n (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n ): void;\n}\n\nexport interface DelegationManagerOptions {\n events: EventBusLike;\n store: TaskStore;\n cwd: string;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n env?: NodeJS.ProcessEnv;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/**\n * Render a supplied path the way the child will see it, from `cwd`.\n *\n * Existence is deliberately not checked: an fs probe here duplicates the read\n * the child performs anyway, and it cannot detect the failure that actually\n * matters — a path that exists but is no longer the right one.\n */\nfunction briefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\nfunction briefContext(options: AssignOptions, cwd: string): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = briefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides the Doom Team event bus rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that runtime is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly subscriptions: Array<() => void> = [];\n private protocol: ProtocolRuntime | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get env(): NodeJS.ProcessEnv {\n return this.options.env ?? process.env;\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.env.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Idempotent: a session restart re-subscribes without stacking handlers. */\n start(): void {\n if (this.subscriptions.length > 0) return;\n const sessionId = this.options.getSessionId?.();\n if (!sessionId) return;\n this.protocol = createProtocolRuntime({\n bus: this.options.events,\n source: '@agimon-ai/doompi-task',\n sessionId,\n });\n this.subscriptions.push(\n this.protocol.onNotification(DelegationAccepted, (event) => {\n this.handleAccepted(event);\n }),\n this.protocol.onNotification(DelegationStarted, (event) => {\n this.handleStarted(event);\n }),\n this.protocol.onNotification(DelegationUpdated, (event) => {\n this.handleUpdate(event);\n }),\n this.protocol.onNotification(DelegationFinished, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: process.pid,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = randomUUID();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: process.pid,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n if (!this.protocol) throw new Error(ERR_NO_RUNTIME);\n this.protocol.notify(DelegationRequested, request);\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Emitted only after the notify succeeds, so it means \"a brief of this\n // shape actually went out\" rather than \"one was assembled\".\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end the turn and wait.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.protocol?.notify(DelegationCancelled, { requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * The bus cannot be probed for listeners, so silence is the only available\n * signal that the subagents runtime is absent. Without this the task would\n * sit in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.protocol?.notify(DelegationCancelled, { requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Emitting the cancel event is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n for (const unsubscribe of this.subscriptions) unsubscribe();\n this.subscriptions.length = 0;\n this.protocol = undefined;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,GAAQ,OAAO,EAAM,KAAK,UAAU,EAAO,OAAO,EAClD,GAAQ,QAAQ,EAAM,KAAK,GAAI,EAAO,MAAM,EAC5C,GAAQ,YAAY,EAAM,KAAK,GAAI,gBAAgB,EAAO,YAAY,EAE1E,GAAI,CACF,EACE,CAAE,WAAY,EAAoB,QAAS,EAAM,KAAK;CAAI,EAAG,QAAS,EAAK,EAC3E,CAAE,YAAa,GAAM,UAAW,OAAQ,CAC1C,CACF,OAAS,EAAO,CAId,KAAK,QAAQ,cAAc,EAAO,CAAM,CAC1C,CACF,CAWA,gBACE,EACA,EACA,EACsD,CACtD,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,YAAY,YAAc,CAAS,EACzF,GAAI,IAAU,GAAI,MAAO,CAAE,MAAO,IAAA,EAAU,EAE5C,IAAM,EAAO,EAAS,MAAM,GAC5B,GAAI,CAAC,EAAmB,CAAI,EAAG,MAAO,CAAE,MAAO,CAAK,EAEpD,IAAM,EAAU,EAAM,EAAM,EAAK,UAAW,EAC5C,GAAI,IAAY,EAAM,MAAO,CAAE,MAAO,CAAK,EAC3C,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,EACR,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,MAAO,CAAQ,CAC5D,CAEA,SAAgB,CACd,IAAK,IAAM,KAAe,KAAK,cAAe,EAAY,EAC1D,KAAK,cAAc,OAAS,EAC5B,KAAK,SAAW,IAAA,GAChB,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config.cjs"),t=require("./store/types.cjs"),n=require("./store/reconcile.cjs"),r=require("./store/taskGraph.cjs"),i=require("./delegation/manager.cjs"),a=require("./tool/schema.cjs"),o=require("./store/reducer.cjs"),s=require("./tui/selectors.cjs"),c=require("./store/paths.cjs"),l=require("./store/taskStore.cjs"),u=require("./tool/responseEnvelope.cjs"),d=require("./tool/promptGuidelines.cjs"),f=require("./tool/taskTool.cjs"),p=require("./extension.cjs");exports.BACKGROUND_WORK_PROVIDER=i.BACKGROUND_WORK_PROVIDER,exports.COLLAPSE_KEY_ENV=e.COLLAPSE_KEY_ENV,exports.COLLAPSE_KEY_OFF=e.COLLAPSE_KEY_OFF,exports.COMMAND_NAME=a.COMMAND_NAME,exports.DEFAULT_COLLAPSE_KEY=e.DEFAULT_COLLAPSE_KEY,exports.DEFAULT_DELEGATION_TIMEOUT_MS=e.DEFAULT_DELEGATION_TIMEOUT_MS,exports.DEFAULT_MAX_WIDGET_LINES=e.DEFAULT_MAX_WIDGET_LINES,exports.DEFAULT_PROMPT_GUIDELINES=d.DEFAULT_PROMPT_GUIDELINES,exports.DEFAULT_PROMPT_SNIPPET=f.DEFAULT_PROMPT_SNIPPET,exports.DEFAULT_STORE_TTL_MS=e.DEFAULT_STORE_TTL_MS,exports.DELEGATION_TIMEOUT_MS_ENV=e.DELEGATION_TIMEOUT_MS_ENV,exports.DELETED_STATUS=t.DELETED_STATUS,exports.DelegationManager=i.DelegationManager,exports.ERR_CANCEL_UNACKNOWLEDGED=i.ERR_CANCEL_UNACKNOWLEDGED,exports.ERR_CHILD_SESSION=i.ERR_CHILD_SESSION,exports.ERR_NO_RUNTIME=i.ERR_NO_RUNTIME,exports.ERR_ORPHANED_BY_RESTART=n.ERR_ORPHANED_BY_RESTART,exports.ERR_ORPHANED_BY_SESSION=n.ERR_ORPHANED_BY_SESSION,exports.ERR_REQUIRES_INTERACTIVE=a.ERR_REQUIRES_INTERACTIVE,exports.MAX_BRIEF_FILES=i.MAX_BRIEF_FILES,exports.MAX_UPSERT_ITEMS=o.MAX_UPSERT_ITEMS,exports.MAX_WIDGET_LINES_ENV=e.MAX_WIDGET_LINES_ENV,exports.MSG_ALL_COMPLETE_CLEAR=u.MSG_ALL_COMPLETE_CLEAR,exports.MSG_NO_TASKS=a.MSG_NO_TASKS,exports.MSG_UPSERT_FIELD_MISPLACED=a.MSG_UPSERT_FIELD_MISPLACED,exports.MSG_UPSERT_NONE_APPLIED=u.MSG_UPSERT_NONE_APPLIED,exports.MSG_UPSERT_PARTIAL=u.MSG_UPSERT_PARTIAL,exports.NOTIFY_CUSTOM_TYPE=i.NOTIFY_CUSTOM_TYPE,exports.REF_PATTERN=o.REF_PATTERN,exports.STORE_PATH_ENV=c.STORE_PATH_ENV,exports.STORE_SCHEMA_VERSION=t.STORE_SCHEMA_VERSION,exports.STORE_TTL_MS_ENV=e.STORE_TTL_MS_ENV,exports.TASK_ACTIONS=a.TASK_ACTIONS,exports.TASK_ACTION_FIELDS=a.TASK_ACTION_FIELDS,exports.TASK_CONTEXTS=a.TASK_CONTEXTS,exports.TASK_STATUSES=a.TASK_STATUSES,exports.TOOL_LABEL=a.TOOL_LABEL,exports.TOOL_NAME=a.TOOL_NAME,exports.TaskItemSchema=a.TaskItemSchema,exports.TaskParamsSchema=a.TaskParamsSchema,exports.TaskStore=l.TaskStore,exports.applyTaskMutation=o.applyTaskMutation,exports.buildTextResult=u.buildTextResult,exports.buildToolResult=u.buildToolResult,exports.countTasks=s.countTasks,exports.deriveBlocks=r.deriveBlocks,exports.detectCycle=r.detectCycle,exports.emptyDocument=t.emptyDocument,exports.formatContent=u.formatContent,exports.formatUpsertFailure=o.formatUpsertFailure,exports.formatUpsertFailureText=u.formatUpsertFailureText,exports.getDelegationTimeoutMs=e.getDelegationTimeoutMs,exports.getMaxWidgetLines=e.getMaxWidgetLines,exports.getStoreTtlMs=e.getStoreTtlMs,exports.groupTasks=s.groupTasks,exports.hasActiveWork=s.hasActiveWork,exports.hasStorePathOverride=c.hasStorePathOverride,exports.isBlocked=r.isBlocked,exports.isCommittingOp=o.isCommittingOp,exports.isDelegationActive=t.isDelegationActive,exports.isTaskListComplete=r.isTaskListComplete,exports.lockPathFor=c.lockPathFor,exports.parsePiTaskConfig=e.parsePiTaskConfig,exports.reconcileOrphanedDelegations=n.reconcileOrphanedDelegations,exports.registerTaskTool=f.registerTaskTool,exports.removeLegacyStoreDirectory=c.removeLegacyStoreDirectory,exports.resolveCollapseKey=e.resolveCollapseKey,exports.resolveLegacyStoreDirectory=c.resolveLegacyStoreDirectory,exports.resolveSessionKey=c.resolveSessionKey,exports.resolveStorePath=c.resolveStorePath,exports.selectOverlayLayout=s.selectOverlayLayout,exports.shouldShowIds=s.shouldShowIds,exports.singleItemOutcome=o.singleItemOutcome,exports.sweepStoreFiles=c.sweepStoreFiles,exports.taskActionAcceptsField=a.taskActionAcceptsField,exports.taskExtension=p.default,exports.tempPathFor=c.tempPathFor,exports.unresolvedBlockers=r.unresolvedBlockers,exports.visibleTasks=s.visibleTasks;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config.cjs"),t=require("./store/types.cjs"),n=require("./store/reconcile.cjs"),r=require("./store/taskGraph.cjs"),i=require("./delegation/manager.cjs"),a=require("./tool/schema.cjs"),o=require("./store/reducer.cjs"),s=require("./tui/selectors.cjs"),c=require("./store/paths.cjs"),l=require("./store/taskStore.cjs"),u=require("./tool/responseEnvelope.cjs"),d=require("./tool/promptGuidelines.cjs"),f=require("./tool/taskTool.cjs"),p=require("./extension.cjs");exports.BACKGROUND_WORK_PROVIDER=i.BACKGROUND_WORK_PROVIDER,exports.COLLAPSE_KEY_ENV=e.COLLAPSE_KEY_ENV,exports.COLLAPSE_KEY_OFF=e.COLLAPSE_KEY_OFF,exports.COMMAND_NAME=a.COMMAND_NAME,exports.DEFAULT_COLLAPSE_KEY=e.DEFAULT_COLLAPSE_KEY,exports.DEFAULT_DELEGATION_TIMEOUT_MS=e.DEFAULT_DELEGATION_TIMEOUT_MS,exports.DEFAULT_MAX_WIDGET_LINES=e.DEFAULT_MAX_WIDGET_LINES,exports.DEFAULT_PROMPT_GUIDELINES=d.DEFAULT_PROMPT_GUIDELINES,exports.DEFAULT_PROMPT_SNIPPET=f.DEFAULT_PROMPT_SNIPPET,exports.DEFAULT_STORE_TTL_MS=e.DEFAULT_STORE_TTL_MS,exports.DELEGATION_TIMEOUT_MS_ENV=e.DELEGATION_TIMEOUT_MS_ENV,exports.DELETED_STATUS=t.DELETED_STATUS,exports.DelegationManager=i.DelegationManager,exports.ERR_CANCEL_UNACKNOWLEDGED=i.ERR_CANCEL_UNACKNOWLEDGED,exports.ERR_CHILD_SESSION=i.ERR_CHILD_SESSION,exports.ERR_NO_RUNTIME=i.ERR_NO_RUNTIME,exports.ERR_ORPHANED_BY_RESTART=n.ERR_ORPHANED_BY_RESTART,exports.ERR_ORPHANED_BY_SESSION=n.ERR_ORPHANED_BY_SESSION,exports.ERR_REQUIRES_INTERACTIVE=a.ERR_REQUIRES_INTERACTIVE,exports.MAX_BRIEF_FILES=i.MAX_BRIEF_FILES,exports.MAX_UPSERT_ITEMS=o.MAX_UPSERT_ITEMS,exports.MAX_WIDGET_LINES_ENV=e.MAX_WIDGET_LINES_ENV,exports.MSG_ALL_COMPLETE_CLEAR=u.MSG_ALL_COMPLETE_CLEAR,exports.MSG_NO_TASKS=a.MSG_NO_TASKS,exports.MSG_UPSERT_FIELD_MISPLACED=a.MSG_UPSERT_FIELD_MISPLACED,exports.MSG_UPSERT_NONE_APPLIED=u.MSG_UPSERT_NONE_APPLIED,exports.MSG_UPSERT_PARTIAL=u.MSG_UPSERT_PARTIAL,exports.NOTIFY_CUSTOM_TYPE=i.NOTIFY_CUSTOM_TYPE,exports.REF_PATTERN=o.REF_PATTERN,exports.STORE_PATH_ENV=c.STORE_PATH_ENV,exports.STORE_SCHEMA_VERSION=t.STORE_SCHEMA_VERSION,exports.STORE_TTL_MS_ENV=e.STORE_TTL_MS_ENV,exports.TASK_ACTIONS=a.TASK_ACTIONS,exports.TASK_ACTION_FIELDS=a.TASK_ACTION_FIELDS,exports.TASK_CONTEXTS=a.TASK_CONTEXTS,exports.TASK_STATUSES=a.TASK_STATUSES,exports.TOOL_LABEL=a.TOOL_LABEL,exports.TOOL_NAME=a.TOOL_NAME,exports.TaskItemSchema=a.TaskItemSchema,exports.TaskParamsSchema=a.TaskParamsSchema,exports.TaskStore=l.TaskStore,exports.applyTaskMutation=o.applyTaskMutation,exports.buildTextResult=u.buildTextResult,exports.buildToolResult=u.buildToolResult,exports.countTasks=s.countTasks,exports.deriveBlocks=r.deriveBlocks,exports.deriveTaskProjection=s.deriveTaskProjection,exports.detectCycle=r.detectCycle,exports.emptyDocument=t.emptyDocument,exports.formatContent=u.formatContent,exports.formatUpsertFailure=o.formatUpsertFailure,exports.formatUpsertFailureText=u.formatUpsertFailureText,exports.getDelegationTimeoutMs=e.getDelegationTimeoutMs,exports.getMaxWidgetLines=e.getMaxWidgetLines,exports.getStoreTtlMs=e.getStoreTtlMs,exports.groupTasks=s.groupTasks,exports.hasActiveWork=s.hasActiveWork,exports.hasStorePathOverride=c.hasStorePathOverride,exports.isBlocked=r.isBlocked,exports.isCommittingOp=o.isCommittingOp,exports.isDelegationActive=t.isDelegationActive,exports.isTaskListComplete=r.isTaskListComplete,exports.lockPathFor=c.lockPathFor,exports.parsePiTaskConfig=e.parsePiTaskConfig,exports.reconcileOrphanedDelegations=n.reconcileOrphanedDelegations,exports.registerTaskTool=f.registerTaskTool,exports.removeLegacyStoreDirectory=c.removeLegacyStoreDirectory,exports.resolveCollapseKey=e.resolveCollapseKey,exports.resolveLegacyStoreDirectory=c.resolveLegacyStoreDirectory,exports.resolveSessionKey=c.resolveSessionKey,exports.resolveStorePath=c.resolveStorePath,exports.selectOverlayLayout=s.selectOverlayLayout,exports.selectOverlayLayoutFromProjection=s.selectOverlayLayoutFromProjection,exports.shouldShowIds=s.shouldShowIds,exports.singleItemOutcome=o.singleItemOutcome,exports.sweepStoreFiles=c.sweepStoreFiles,exports.taskActionAcceptsField=a.taskActionAcceptsField,exports.taskExtension=p.default,exports.tempPathFor=c.tempPathFor,exports.unresolvedBlockers=r.unresolvedBlockers,exports.visibleTasks=s.visibleTasks;
|
package/dist/index.d.cts
CHANGED
|
@@ -11,5 +11,5 @@ import { MSG_ALL_COMPLETE_CLEAR, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, To
|
|
|
11
11
|
import { COMMAND_NAME, ERR_REQUIRES_INTERACTIVE, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, TaskItemParams, TaskItemSchema, TaskParams, TaskParamsSchema, taskActionAcceptsField } from "./tool/schema.cjs";
|
|
12
12
|
import { DEFAULT_PROMPT_GUIDELINES } from "./tool/promptGuidelines.cjs";
|
|
13
13
|
import { DEFAULT_PROMPT_SNIPPET, TaskToolDependencies, registerTaskTool } from "./tool/taskTool.cjs";
|
|
14
|
-
import { OverlayLayout, TaskCounts, TaskGroups, countTasks, groupTasks, hasActiveWork, selectOverlayLayout, shouldShowIds, visibleTasks } from "./tui/selectors.cjs";
|
|
15
|
-
export { ApplyResult, AssignOptions, BACKGROUND_WORK_PROVIDER, COLLAPSE_KEY_ENV, COLLAPSE_KEY_OFF, COMMAND_NAME, DEFAULT_COLLAPSE_KEY, DEFAULT_DELEGATION_TIMEOUT_MS, DEFAULT_MAX_WIDGET_LINES, DEFAULT_PROMPT_GUIDELINES, DEFAULT_PROMPT_SNIPPET, DEFAULT_STORE_TTL_MS, DELEGATION_TIMEOUT_MS_ENV, DELETED_STATUS, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, DelegationResult, DelegationState, DepToken, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ERR_REQUIRES_INTERACTIVE, MAX_BRIEF_FILES, MAX_UPSERT_ITEMS, MAX_WIDGET_LINES_ENV, MSG_ALL_COMPLETE_CLEAR, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, NOTIFY_CUSTOM_TYPE, Op, OverlayLayout, PiTaskConfig, REF_PATTERN, ReconcileResult, ReconcileSelf, ReducerAction, STORE_PATH_ENV, STORE_SCHEMA_VERSION, STORE_TTL_MS_ENV, StoreSweepResult, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, Task, TaskAction, TaskCounts, TaskDelegation, TaskDetails, TaskDocument, TaskGroups, TaskItemMutation, TaskItemParams, TaskItemSchema, TaskMutationParams, TaskParams, TaskParamsSchema, TaskStatus, TaskStore, TaskStoreOptions, TaskToolDependencies, ToolResult, UpsertItemOutcome, UpsertSummary, applyTaskMutation, buildTextResult, buildToolResult, countTasks, deriveBlocks, detectCycle, emptyDocument, formatContent, formatUpsertFailure, formatUpsertFailureText, getDelegationTimeoutMs, getMaxWidgetLines, getStoreTtlMs, groupTasks, hasActiveWork, hasStorePathOverride, isBlocked, isCommittingOp, isDelegationActive, isTaskListComplete, lockPathFor, parsePiTaskConfig, reconcileOrphanedDelegations, registerTaskTool, removeLegacyStoreDirectory, resolveCollapseKey, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, selectOverlayLayout, shouldShowIds, singleItemOutcome, sweepStoreFiles, taskActionAcceptsField, taskExtension, tempPathFor, unresolvedBlockers, visibleTasks };
|
|
14
|
+
import { OverlayLayout, TaskCounts, TaskGroups, TaskProjection, countTasks, deriveTaskProjection, groupTasks, hasActiveWork, selectOverlayLayout, selectOverlayLayoutFromProjection, shouldShowIds, visibleTasks } from "./tui/selectors.cjs";
|
|
15
|
+
export { ApplyResult, AssignOptions, BACKGROUND_WORK_PROVIDER, COLLAPSE_KEY_ENV, COLLAPSE_KEY_OFF, COMMAND_NAME, DEFAULT_COLLAPSE_KEY, DEFAULT_DELEGATION_TIMEOUT_MS, DEFAULT_MAX_WIDGET_LINES, DEFAULT_PROMPT_GUIDELINES, DEFAULT_PROMPT_SNIPPET, DEFAULT_STORE_TTL_MS, DELEGATION_TIMEOUT_MS_ENV, DELETED_STATUS, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, DelegationResult, DelegationState, DepToken, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ERR_REQUIRES_INTERACTIVE, MAX_BRIEF_FILES, MAX_UPSERT_ITEMS, MAX_WIDGET_LINES_ENV, MSG_ALL_COMPLETE_CLEAR, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, NOTIFY_CUSTOM_TYPE, Op, OverlayLayout, PiTaskConfig, REF_PATTERN, ReconcileResult, ReconcileSelf, ReducerAction, STORE_PATH_ENV, STORE_SCHEMA_VERSION, STORE_TTL_MS_ENV, StoreSweepResult, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, Task, TaskAction, TaskCounts, TaskDelegation, TaskDetails, TaskDocument, TaskGroups, TaskItemMutation, TaskItemParams, TaskItemSchema, TaskMutationParams, TaskParams, TaskParamsSchema, TaskProjection, TaskStatus, TaskStore, TaskStoreOptions, TaskToolDependencies, ToolResult, UpsertItemOutcome, UpsertSummary, applyTaskMutation, buildTextResult, buildToolResult, countTasks, deriveBlocks, deriveTaskProjection, detectCycle, emptyDocument, formatContent, formatUpsertFailure, formatUpsertFailureText, getDelegationTimeoutMs, getMaxWidgetLines, getStoreTtlMs, groupTasks, hasActiveWork, hasStorePathOverride, isBlocked, isCommittingOp, isDelegationActive, isTaskListComplete, lockPathFor, parsePiTaskConfig, reconcileOrphanedDelegations, registerTaskTool, removeLegacyStoreDirectory, resolveCollapseKey, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, selectOverlayLayout, selectOverlayLayoutFromProjection, shouldShowIds, singleItemOutcome, sweepStoreFiles, taskActionAcceptsField, taskExtension, tempPathFor, unresolvedBlockers, visibleTasks };
|
package/dist/index.d.mts
CHANGED
|
@@ -11,5 +11,5 @@ import { MSG_ALL_COMPLETE_CLEAR, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, To
|
|
|
11
11
|
import { COMMAND_NAME, ERR_REQUIRES_INTERACTIVE, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, TaskItemParams, TaskItemSchema, TaskParams, TaskParamsSchema, taskActionAcceptsField } from "./tool/schema.mjs";
|
|
12
12
|
import { DEFAULT_PROMPT_GUIDELINES } from "./tool/promptGuidelines.mjs";
|
|
13
13
|
import { DEFAULT_PROMPT_SNIPPET, TaskToolDependencies, registerTaskTool } from "./tool/taskTool.mjs";
|
|
14
|
-
import { OverlayLayout, TaskCounts, TaskGroups, countTasks, groupTasks, hasActiveWork, selectOverlayLayout, shouldShowIds, visibleTasks } from "./tui/selectors.mjs";
|
|
15
|
-
export { ApplyResult, AssignOptions, BACKGROUND_WORK_PROVIDER, COLLAPSE_KEY_ENV, COLLAPSE_KEY_OFF, COMMAND_NAME, DEFAULT_COLLAPSE_KEY, DEFAULT_DELEGATION_TIMEOUT_MS, DEFAULT_MAX_WIDGET_LINES, DEFAULT_PROMPT_GUIDELINES, DEFAULT_PROMPT_SNIPPET, DEFAULT_STORE_TTL_MS, DELEGATION_TIMEOUT_MS_ENV, DELETED_STATUS, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, DelegationResult, DelegationState, DepToken, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ERR_REQUIRES_INTERACTIVE, MAX_BRIEF_FILES, MAX_UPSERT_ITEMS, MAX_WIDGET_LINES_ENV, MSG_ALL_COMPLETE_CLEAR, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, NOTIFY_CUSTOM_TYPE, Op, OverlayLayout, PiTaskConfig, REF_PATTERN, ReconcileResult, ReconcileSelf, ReducerAction, STORE_PATH_ENV, STORE_SCHEMA_VERSION, STORE_TTL_MS_ENV, StoreSweepResult, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, Task, TaskAction, TaskCounts, TaskDelegation, TaskDetails, TaskDocument, TaskGroups, TaskItemMutation, TaskItemParams, TaskItemSchema, TaskMutationParams, TaskParams, TaskParamsSchema, TaskStatus, TaskStore, TaskStoreOptions, TaskToolDependencies, ToolResult, UpsertItemOutcome, UpsertSummary, applyTaskMutation, buildTextResult, buildToolResult, countTasks, deriveBlocks, detectCycle, emptyDocument, formatContent, formatUpsertFailure, formatUpsertFailureText, getDelegationTimeoutMs, getMaxWidgetLines, getStoreTtlMs, groupTasks, hasActiveWork, hasStorePathOverride, isBlocked, isCommittingOp, isDelegationActive, isTaskListComplete, lockPathFor, parsePiTaskConfig, reconcileOrphanedDelegations, registerTaskTool, removeLegacyStoreDirectory, resolveCollapseKey, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, selectOverlayLayout, shouldShowIds, singleItemOutcome, sweepStoreFiles, taskActionAcceptsField, taskExtension, tempPathFor, unresolvedBlockers, visibleTasks };
|
|
14
|
+
import { OverlayLayout, TaskCounts, TaskGroups, TaskProjection, countTasks, deriveTaskProjection, groupTasks, hasActiveWork, selectOverlayLayout, selectOverlayLayoutFromProjection, shouldShowIds, visibleTasks } from "./tui/selectors.mjs";
|
|
15
|
+
export { ApplyResult, AssignOptions, BACKGROUND_WORK_PROVIDER, COLLAPSE_KEY_ENV, COLLAPSE_KEY_OFF, COMMAND_NAME, DEFAULT_COLLAPSE_KEY, DEFAULT_DELEGATION_TIMEOUT_MS, DEFAULT_MAX_WIDGET_LINES, DEFAULT_PROMPT_GUIDELINES, DEFAULT_PROMPT_SNIPPET, DEFAULT_STORE_TTL_MS, DELEGATION_TIMEOUT_MS_ENV, DELETED_STATUS, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, DelegationResult, DelegationState, DepToken, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ERR_REQUIRES_INTERACTIVE, MAX_BRIEF_FILES, MAX_UPSERT_ITEMS, MAX_WIDGET_LINES_ENV, MSG_ALL_COMPLETE_CLEAR, MSG_NO_TASKS, MSG_UPSERT_FIELD_MISPLACED, MSG_UPSERT_NONE_APPLIED, MSG_UPSERT_PARTIAL, NOTIFY_CUSTOM_TYPE, Op, OverlayLayout, PiTaskConfig, REF_PATTERN, ReconcileResult, ReconcileSelf, ReducerAction, STORE_PATH_ENV, STORE_SCHEMA_VERSION, STORE_TTL_MS_ENV, StoreSweepResult, TASK_ACTIONS, TASK_ACTION_FIELDS, TASK_CONTEXTS, TASK_STATUSES, TOOL_LABEL, TOOL_NAME, Task, TaskAction, TaskCounts, TaskDelegation, TaskDetails, TaskDocument, TaskGroups, TaskItemMutation, TaskItemParams, TaskItemSchema, TaskMutationParams, TaskParams, TaskParamsSchema, TaskProjection, TaskStatus, TaskStore, TaskStoreOptions, TaskToolDependencies, ToolResult, UpsertItemOutcome, UpsertSummary, applyTaskMutation, buildTextResult, buildToolResult, countTasks, deriveBlocks, deriveTaskProjection, detectCycle, emptyDocument, formatContent, formatUpsertFailure, formatUpsertFailureText, getDelegationTimeoutMs, getMaxWidgetLines, getStoreTtlMs, groupTasks, hasActiveWork, hasStorePathOverride, isBlocked, isCommittingOp, isDelegationActive, isTaskListComplete, lockPathFor, parsePiTaskConfig, reconcileOrphanedDelegations, registerTaskTool, removeLegacyStoreDirectory, resolveCollapseKey, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, selectOverlayLayout, selectOverlayLayoutFromProjection, shouldShowIds, singleItemOutcome, sweepStoreFiles, taskActionAcceptsField, taskExtension, tempPathFor, unresolvedBlockers, visibleTasks };
|