@agimon-ai/doompi-task 0.0.1-alpha.76 → 0.0.1-alpha.77

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.
@@ -0,0 +1,1836 @@
1
+ import { defineMcpPlugin, defineMcpTool } from "@agimon-ai/doompi-core/mcp-facet";
2
+ import { DOOM_DELEGATION_ACCEPTED_EVENT, DOOM_DELEGATION_FINISHED_EVENT, DOOM_DELEGATION_STARTED_EVENT, DOOM_DELEGATION_UPDATED_EVENT, InlineAgentSchema } from "@agimon-ai/doompi-core/delegation";
3
+ import { randomUUID } from "node:crypto";
4
+ import path from "node:path";
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "@agimon-ai/doompi-core/child-process";
8
+ import { Check } from "typebox/value";
9
+ import { Type } from "typebox";
10
+ //#region src/services/config/index.ts
11
+ const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
12
+ const DELEGATION_TIMEOUT_MS_ENV = "DOOM_TASK_DELEGATION_TIMEOUT_MS";
13
+ /** Deliberately under the subagents auto-drain ceiling (30 min) so a headless
14
+ * session still gets the failure and a model turn before draining gives up. */
15
+ const DEFAULT_DELEGATION_TIMEOUT_MS = 12e5;
16
+ /** Maximum number of non-deleted tasks retained on one board. */
17
+ function getMaxTasks(env = process.env) {
18
+ const raw = Number(env[MAX_TASKS_ENV]);
19
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
20
+ }
21
+ /** How long a delegated run may go without reporting a result. */
22
+ function getDelegationTimeoutMs(env = process.env) {
23
+ const raw = Number(env[DELEGATION_TIMEOUT_MS_ENV]);
24
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_DELEGATION_TIMEOUT_MS;
25
+ }
26
+ //#endregion
27
+ //#region src/models/taskGraph.ts
28
+ const COMPLETED_STATUS = "completed";
29
+ const DELETED_STATUS$2 = "deleted";
30
+ /** True when a non-empty list has no visible work left to finish. */
31
+ function isTaskListComplete(taskList) {
32
+ const visible = taskList.filter((task) => task.status !== DELETED_STATUS$2);
33
+ return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
34
+ }
35
+ /**
36
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
37
+ *
38
+ * Takes the proposed additions explicitly so the reducer can ask the question
39
+ * before mutating anything.
40
+ */
41
+ function detectCycle(taskList, taskId, newBlockedBy) {
42
+ const edges = /* @__PURE__ */ new Map();
43
+ for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
44
+ else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
45
+ const visiting = /* @__PURE__ */ new Set();
46
+ const visited = /* @__PURE__ */ new Set();
47
+ const hasCycleFrom = (node) => {
48
+ if (visiting.has(node)) return true;
49
+ if (visited.has(node)) return false;
50
+ visiting.add(node);
51
+ for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
52
+ visiting.delete(node);
53
+ visited.add(node);
54
+ return false;
55
+ };
56
+ for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
57
+ return false;
58
+ }
59
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
60
+ function deriveBlocks(taskList) {
61
+ const blocks = /* @__PURE__ */ new Map();
62
+ for (const task of taskList) for (const dep of task.blockedBy ?? []) {
63
+ const dependents = blocks.get(dep) ?? [];
64
+ dependents.push(task.id);
65
+ blocks.set(dep, dependents);
66
+ }
67
+ return blocks;
68
+ }
69
+ /**
70
+ * Blocking dependencies of a task that are not yet resolved.
71
+ *
72
+ * `completed` clears a dependency; `failed` deliberately does not, so a failed
73
+ * delegation keeps its dependents blocked instead of silently releasing work
74
+ * that was never actually finished.
75
+ */
76
+ function unresolvedBlockers(taskList, task) {
77
+ return (task.blockedBy ?? []).filter((dep) => {
78
+ const blocker = taskList.find((candidate) => candidate.id === dep);
79
+ if (!blocker) return false;
80
+ return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS$2;
81
+ });
82
+ }
83
+ function isBlocked(taskList, task) {
84
+ return unresolvedBlockers(taskList, task).length > 0;
85
+ }
86
+ //#endregion
87
+ //#region src/types/telemetry.ts
88
+ const TASK_EVENT = {
89
+ notificationFailed: "doom_task.notification_failed",
90
+ storeReadFailed: "doom_task.store_read_failed",
91
+ storeLockTimeout: "doom_task.store_lock_timeout",
92
+ storeLockBreakFailed: "doom_task.store_lock_break_failed",
93
+ storeWatchFailed: "doom_task.store_watch_failed",
94
+ storeListenerFailed: "doom_task.store_listener_failed",
95
+ storeCommitListenerFailed: "doom_task.store_commit_listener_failed",
96
+ storeSweepFailed: "doom_task.store_sweep_failed",
97
+ sessionStartFailed: "doom_task.session_start_failed",
98
+ sessionStartDegraded: "doom_task.session_start_degraded",
99
+ toolFailed: "doom_task.tool_failed",
100
+ delegationRequestFailed: "doom_task.delegation_request_failed",
101
+ delegationStartFailed: "doom_task.delegation_start_failed",
102
+ delegationResponseFailed: "doom_task.delegation_response_failed",
103
+ delegationSettleFailed: "doom_task.delegation_settle_failed",
104
+ delegationTimedOut: "doom_task.delegation_timed_out",
105
+ delegationOrphaned: "doom_task.delegation_orphaned",
106
+ delegationAssigned: "doom_task.delegation_assigned",
107
+ delegationCompleted: "doom_task.delegation_completed"
108
+ };
109
+ //#endregion
110
+ //#region src/models/task.ts
111
+ const DELETED_STATUS$1 = "deleted";
112
+ function emptyDocument() {
113
+ return {
114
+ version: 1,
115
+ rev: 0,
116
+ nextId: 1,
117
+ tasks: []
118
+ };
119
+ }
120
+ /**
121
+ * A delegation is "live" while the owning run may still produce a response.
122
+ *
123
+ * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
124
+ * which carries the state as a plain string, answers the question the same way
125
+ * the store does.
126
+ */
127
+ function isDelegationActive(task) {
128
+ const state = task.delegation?.state;
129
+ return state === "requested" || state === "running";
130
+ }
131
+ //#endregion
132
+ //#region src/services/processLiveness/index.ts
133
+ /**
134
+ * Is a process still running?
135
+ *
136
+ * Signal 0 performs the permission and existence check without delivering a
137
+ * signal. EPERM means the process exists but belongs to another user, which
138
+ * still counts as alive.
139
+ */
140
+ function isProcessAlive(pid) {
141
+ try {
142
+ process.kill(pid, 0);
143
+ return true;
144
+ } catch (error) {
145
+ return error.code === "EPERM";
146
+ }
147
+ }
148
+ //#endregion
149
+ //#region src/services/reconcile/index.ts
150
+ const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
151
+ const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
152
+ /**
153
+ * Recover tasks that no longer have anyone able to finish them.
154
+ *
155
+ * A subagent run dies with the harness that spawned it, but the store file
156
+ * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
157
+ * kinds of delegation qualify as dead:
158
+ *
159
+ * - the owning pid is gone, so nothing is left to report a result;
160
+ * - the owning pid is *this* process, yet the request is absent from the live
161
+ * set. Settling requires an in-memory record, so an in-process session
162
+ * restart (which clears that map without writing to the store) leaves rows
163
+ * nothing can ever resolve. Checking pid liveness alone misses these, because
164
+ * the pid is our own and very much alive.
165
+ *
166
+ * Delegations owned by a different, still-running pid belong to a parallel
167
+ * session and are left untouched.
168
+ */
169
+ function reconcileOrphanedDelegations(document, now = (/* @__PURE__ */ new Date()).toISOString(), isAlive = isProcessAlive, self) {
170
+ const orphaned = [];
171
+ const tasks = document.tasks.map((task) => {
172
+ if (!isDelegationActive(task)) return task;
173
+ const pid = task.delegation?.pid;
174
+ if (pid === void 0) return task;
175
+ const abandonedHere = self !== void 0 && pid === self.pid && !self.liveRequestIds.has(task.delegation.requestId);
176
+ if (!abandonedHere && isAlive(pid)) return task;
177
+ const recovered = {
178
+ ...task,
179
+ status: "pending",
180
+ updatedAt: now,
181
+ delegation: {
182
+ ...task.delegation,
183
+ state: "failed",
184
+ endedAt: now,
185
+ result: {
186
+ status: "failed",
187
+ error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART
188
+ }
189
+ }
190
+ };
191
+ orphaned.push(recovered);
192
+ return recovered;
193
+ });
194
+ if (orphaned.length === 0) return {
195
+ document,
196
+ orphaned
197
+ };
198
+ return {
199
+ document: {
200
+ ...document,
201
+ tasks
202
+ },
203
+ orphaned
204
+ };
205
+ }
206
+ //#endregion
207
+ //#region src/services/delegation/index.ts
208
+ const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
209
+ const DEFAULT_STARTED_TIMEOUT_MS = 5e3;
210
+ const DEFAULT_RUN_TIMEOUT_MS = 12e5;
211
+ const DEFAULT_CANCEL_TIMEOUT_MS = 1e4;
212
+ const MAX_RUN_TIMEOUT_GRACE_MS = 6e4;
213
+ const MAX_STORED_OUTPUT = 4e3;
214
+ /**
215
+ * Cap on files rendered into a brief. Exported so the tool schema can state the
216
+ * same number to the model rather than restating it and drifting.
217
+ */
218
+ const MAX_BRIEF_NOTES = 1500;
219
+ const COMPLETED_STATE = "completed";
220
+ const FAILED_STATE = "failed";
221
+ const CANCELLED_STATE = "cancelled";
222
+ const TIMED_OUT_STATUS = "timed_out";
223
+ const DELETED_STATUS = "deleted";
224
+ const TASK_ID_ATTRIBUTE = "task.id";
225
+ const REQUEST_ID_ATTRIBUTE = "delegation.request_id";
226
+ const AGENT_ATTRIBUTE = "delegation.agent_name";
227
+ const PID_ATTRIBUTE = "delegation.pid";
228
+ const CONTEXT_PRESENT_ATTRIBUTE = "delegation.context_present";
229
+ const CONTEXT_FILE_COUNT_ATTRIBUTE = "delegation.context_file_count";
230
+ const CONTEXT_NOTES_LENGTH_ATTRIBUTE = "delegation.context_notes_length";
231
+ const BRIEF_LENGTH_ATTRIBUTE = "delegation.brief_length";
232
+ const TOOL_COUNT_ATTRIBUTE = "delegation.tool_count";
233
+ const DURATION_MS_ATTRIBUTE = "delegation.duration_ms";
234
+ const OUTCOME_ATTRIBUTE = "delegation.outcome";
235
+ const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
236
+ const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
237
+ const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
238
+ function truncate(value, limit = MAX_STORED_OUTPUT) {
239
+ if (!value) return void 0;
240
+ return value.length <= limit ? value : `${value.slice(0, limit)}\n… (truncated)`;
241
+ }
242
+ function messageOf(error) {
243
+ return error instanceof Error ? error.message : String(error);
244
+ }
245
+ /** Normalize the parent context with host-owned path semantics. */
246
+ function briefContext(options, cwd, platform) {
247
+ const files = /* @__PURE__ */ new Set();
248
+ for (const entry of options.relevantFiles ?? []) {
249
+ if (files.size >= 12) break;
250
+ const normalized = platform.formatBriefPath(entry.trim(), cwd);
251
+ if (normalized && normalized !== ".") files.add(normalized);
252
+ }
253
+ return {
254
+ files: [...files],
255
+ notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES)
256
+ };
257
+ }
258
+ /**
259
+ * Build the brief handed to the subagent.
260
+ *
261
+ * Doom Team owns the child tool surface and the parent owns the task record.
262
+ * Keeping those responsibilities explicit prevents a child from attempting to
263
+ * call a task tool that is not loaded in its runtime, while still giving it a
264
+ * reliable path to ask the parent for a decision.
265
+ *
266
+ * The context pack is the parent's verified discovery handed over. The whole
267
+ * block is omitted when nothing was supplied: this brief is the child's whole
268
+ * starting context, so an empty section header is pure token cost.
269
+ */
270
+ function buildBrief(task, instructions, context) {
271
+ const sections = [`Task #${task.id}: ${task.subject}`];
272
+ if (task.description) sections.push(task.description);
273
+ if (instructions) sections.push(instructions);
274
+ if (context.files.length > 0 || context.notes) {
275
+ const contextLines = ["Parent context — consume before repository discovery:"];
276
+ if (context.files.length > 0) contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(", ")}`);
277
+ if (context.notes) contextLines.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`);
278
+ contextLines.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.");
279
+ sections.push(contextLines.join("\n"));
280
+ }
281
+ sections.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.");
282
+ return sections.join("\n\n");
283
+ }
284
+ /**
285
+ * Owns the lifecycle of tasks delegated to subagents.
286
+ *
287
+ * Delegation rides Team's injected Cordis service rather than spawning
288
+ * processes directly, so doom-task stays decoupled from the subagent runtime
289
+ * and degrades to a clear error when that service is not loaded.
290
+ *
291
+ * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
292
+ * a delegation always has a deadline no matter which phase it is in. Losing
293
+ * that pairing is what previously left tasks running forever.
294
+ */
295
+ var DelegationManager = class DelegationManager {
296
+ options;
297
+ progress = /* @__PURE__ */ new Map();
298
+ pendingTasks = /* @__PURE__ */ new Map();
299
+ settlingRequests = /* @__PURE__ */ new Set();
300
+ timers = /* @__PURE__ */ new Map();
301
+ subscriptions = [];
302
+ service;
303
+ constructor(options) {
304
+ this.options = options;
305
+ }
306
+ now() {
307
+ return this.options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
308
+ }
309
+ nowMs() {
310
+ return this.options.nowMs?.() ?? Date.now();
311
+ }
312
+ get runTimeoutMs() {
313
+ return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
314
+ }
315
+ report(event, error, attributes) {
316
+ this.options.report?.error(event, error, attributes);
317
+ }
318
+ /** True in a session that is itself a subagent child. */
319
+ get isChildSession() {
320
+ return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);
321
+ }
322
+ /** Live progress for a task, for the overlay to render. */
323
+ progressFor(task) {
324
+ const requestId = task.delegation?.requestId;
325
+ return requestId ? this.progress.get(requestId) : void 0;
326
+ }
327
+ /** Displayed runtime duration, rebased from the latest child observation. */
328
+ static elapsedMs(progress, nowMs = Date.now()) {
329
+ const baseline = progress.durationMs ?? 0;
330
+ const observedAt = progress.durationObservedAt ?? nowMs;
331
+ return baseline + Math.max(0, nowMs - observedAt);
332
+ }
333
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
334
+ bind(ctx, service) {
335
+ this.unbind();
336
+ this.service = service;
337
+ this.subscriptions.push(ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {
338
+ this.handleAccepted(event);
339
+ }), ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {
340
+ this.handleStarted(event);
341
+ }), ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {
342
+ this.handleUpdate(event);
343
+ }), ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {
344
+ this.handleResponse(event).catch((error) => {
345
+ this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });
346
+ });
347
+ }));
348
+ return () => {
349
+ if (this.service === service) this.unbind();
350
+ };
351
+ }
352
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
353
+ unbind() {
354
+ for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
355
+ this.service = void 0;
356
+ }
357
+ /** Items still in flight, surfaced so auto-stop will not kill the harness. */
358
+ listActiveWork() {
359
+ return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) => pending.sessionId ? [{
360
+ id: `task-${pending.taskId}:${requestId}`,
361
+ sessionId: pending.sessionId
362
+ }] : []);
363
+ }
364
+ /**
365
+ * Return tasks nothing can finish to `pending`.
366
+ *
367
+ * The live request set is read inside the mutation so a delegation assigned
368
+ * while the lock was contended is not mistaken for a leftover.
369
+ */
370
+ async reconcile(isCurrent = () => true) {
371
+ const { value } = await this.options.store.mutate((document) => {
372
+ if (!isCurrent()) return { value: [] };
373
+ const result = reconcileOrphanedDelegations(document, this.now(), void 0, {
374
+ pid: this.options.platform.processId,
375
+ liveRequestIds: new Set(this.pendingTasks.keys())
376
+ });
377
+ if (result.orphaned.length === 0) return { value: [] };
378
+ return {
379
+ document: result.document,
380
+ value: result.orphaned
381
+ };
382
+ });
383
+ if (!isCurrent()) return [];
384
+ for (const task of value) this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ""), {
385
+ [TASK_ID_ATTRIBUTE]: task.id,
386
+ ...task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {},
387
+ ...task.delegation?.pid === void 0 ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }
388
+ });
389
+ if (value.length > 0) this.options.onChange?.();
390
+ return value;
391
+ }
392
+ async assign(taskId, options) {
393
+ const agent = options.agent?.trim();
394
+ if (!agent) return {
395
+ ok: false,
396
+ message: "agent required for assign"
397
+ };
398
+ if (this.isChildSession) return {
399
+ ok: false,
400
+ message: ERR_CHILD_SESSION
401
+ };
402
+ if (options.signal?.aborted) return {
403
+ ok: false,
404
+ message: "delegation cancelled before it started"
405
+ };
406
+ const requestId = this.options.platform.createRequestId();
407
+ const startedAt = this.now();
408
+ const sessionId = this.options.getSessionId?.();
409
+ const context = briefContext(options, this.options.cwd, this.options.platform);
410
+ const { value: outcome } = await this.options.store.mutate((current) => {
411
+ const index = current.tasks.findIndex((task) => task.id === taskId);
412
+ if (index === -1) return { value: {
413
+ ok: false,
414
+ message: `#${taskId} not found`
415
+ } };
416
+ const task = current.tasks[index];
417
+ if (task.status === DELETED_STATUS) return { value: {
418
+ ok: false,
419
+ message: `#${taskId} is deleted`
420
+ } };
421
+ if (task.status === COMPLETED_STATE) return { value: {
422
+ ok: false,
423
+ message: `#${taskId} is already completed`
424
+ } };
425
+ if (isDelegationActive(task)) return { value: {
426
+ ok: false,
427
+ message: `#${taskId} is already delegated to ${task.delegation?.agent}`
428
+ } };
429
+ if (isBlocked(current.tasks, task)) return { value: {
430
+ ok: false,
431
+ message: `#${taskId} is blocked by ${(task.blockedBy ?? []).map((id) => `#${id}`).join(", ")}`
432
+ } };
433
+ const delegation = {
434
+ requestId,
435
+ agent,
436
+ state: "requested",
437
+ pid: this.options.platform.processId,
438
+ startedAt,
439
+ ...sessionId ? { sessionId } : {},
440
+ ...options.model ? { model: options.model } : {}
441
+ };
442
+ const tasks = [...current.tasks];
443
+ tasks[index] = {
444
+ ...task,
445
+ owner: agent,
446
+ updatedAt: startedAt,
447
+ delegation
448
+ };
449
+ return {
450
+ document: {
451
+ ...current,
452
+ tasks
453
+ },
454
+ value: {
455
+ ok: true,
456
+ message: "",
457
+ task: tasks[index]
458
+ }
459
+ };
460
+ });
461
+ if (!outcome.ok || !outcome.task) return {
462
+ ok: false,
463
+ message: outcome.message
464
+ };
465
+ const contextNotesLength = context.notes?.length ?? 0;
466
+ this.pendingTasks.set(requestId, {
467
+ taskId,
468
+ sessionId
469
+ });
470
+ this.progress.set(requestId, {
471
+ agent,
472
+ contextFileCount: context.files.length,
473
+ contextNotesLength
474
+ });
475
+ this.armStartedTimeout(requestId);
476
+ this.options.onChange?.();
477
+ const request = {
478
+ requestId,
479
+ taskId,
480
+ agent,
481
+ ...options.inlineAgent ? { inlineAgent: options.inlineAgent } : {},
482
+ prompt: buildBrief(outcome.task, options.instructions, context),
483
+ ...options.context ? { context: options.context } : {},
484
+ cwd: this.options.cwd,
485
+ artifacts: true,
486
+ timeoutMs: this.runTimeoutMs,
487
+ runMode: "detached",
488
+ teamTask: {
489
+ id: String(outcome.task.id),
490
+ subject: outcome.task.subject
491
+ },
492
+ ...options.model ? { model: options.model } : {}
493
+ };
494
+ try {
495
+ const service = this.service;
496
+ if (!service) throw new Error(ERR_NO_RUNTIME);
497
+ service.request(request).catch((error) => {
498
+ this.report(TASK_EVENT.delegationRequestFailed, error, {
499
+ [TASK_ID_ATTRIBUTE]: taskId,
500
+ [REQUEST_ID_ATTRIBUTE]: requestId,
501
+ [AGENT_ATTRIBUTE]: agent
502
+ });
503
+ this.settleDetached(requestId, FAILED_STATE, {
504
+ status: FAILED_STATE,
505
+ error: `Delegation request failed: ${messageOf(error)}`
506
+ });
507
+ });
508
+ } catch (error) {
509
+ this.report(TASK_EVENT.delegationRequestFailed, error, {
510
+ [TASK_ID_ATTRIBUTE]: taskId,
511
+ [REQUEST_ID_ATTRIBUTE]: requestId,
512
+ [AGENT_ATTRIBUTE]: agent
513
+ });
514
+ const detail = messageOf(error);
515
+ await this.settle(requestId, FAILED_STATE, {
516
+ status: FAILED_STATE,
517
+ error: `Delegation request failed: ${detail}`
518
+ });
519
+ return {
520
+ ok: false,
521
+ message: `Could not dispatch #${taskId} to ${agent}: ${detail}`
522
+ };
523
+ }
524
+ this.options.report?.event(TASK_EVENT.delegationAssigned, {
525
+ [TASK_ID_ATTRIBUTE]: taskId,
526
+ [REQUEST_ID_ATTRIBUTE]: requestId,
527
+ [AGENT_ATTRIBUTE]: agent,
528
+ [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,
529
+ [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,
530
+ [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,
531
+ [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length
532
+ });
533
+ return {
534
+ ok: true,
535
+ 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 your turn.`
536
+ };
537
+ }
538
+ async cancel(taskId) {
539
+ const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
540
+ if (!task) return {
541
+ ok: false,
542
+ message: `#${taskId} not found`
543
+ };
544
+ if (!task.delegation || !isDelegationActive(task)) return {
545
+ ok: false,
546
+ message: `#${taskId} has no running delegation`
547
+ };
548
+ const { requestId } = task.delegation;
549
+ this.service?.cancel({ requestId });
550
+ this.armCancelTimeout(requestId);
551
+ return {
552
+ ok: true,
553
+ message: `Cancelling delegation for #${taskId} (${task.delegation.agent})`
554
+ };
555
+ }
556
+ /** Settle without awaiting, reporting rather than dropping a failure. */
557
+ settleDetached(requestId, state, result, event = TASK_EVENT.delegationSettleFailed) {
558
+ this.settle(requestId, state, result).catch((error) => {
559
+ this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });
560
+ });
561
+ }
562
+ /**
563
+ * Fail a delegation that nobody acknowledged.
564
+ *
565
+ * Provider loss or a stalled Team runtime can still leave a dispatched
566
+ * request silent. Without this acknowledgement deadline the task would sit
567
+ * in `requested` forever.
568
+ */
569
+ armStartedTimeout(requestId) {
570
+ this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {
571
+ this.settleDetached(requestId, FAILED_STATE, {
572
+ status: FAILED_STATE,
573
+ error: ERR_NO_RUNTIME
574
+ });
575
+ });
576
+ }
577
+ /**
578
+ * Bound a run that already started.
579
+ *
580
+ * The request carries the same budget, so in the normal case the runtime ends
581
+ * the run itself and reports a richer result. The grace period biases toward
582
+ * that answer; this timer only covers a runtime that goes silent, which is
583
+ * precisely the case where no response event will ever arrive.
584
+ */
585
+ armRunTimeout(requestId) {
586
+ const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);
587
+ this.armTimer(requestId, this.runTimeoutMs + grace, () => {
588
+ const taskId = this.pendingTasks.get(requestId)?.taskId;
589
+ const agent = this.progress.get(requestId)?.agent;
590
+ const error = /* @__PURE__ */ new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);
591
+ this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {
592
+ ...taskId === void 0 ? {} : { [TASK_ID_ATTRIBUTE]: taskId },
593
+ [REQUEST_ID_ATTRIBUTE]: requestId,
594
+ ...agent ? { [AGENT_ATTRIBUTE]: agent } : {}
595
+ });
596
+ this.service?.cancel({
597
+ requestId,
598
+ reason: error.message
599
+ });
600
+ this.settleDetached(requestId, FAILED_STATE, {
601
+ status: TIMED_OUT_STATUS,
602
+ error: error.message
603
+ });
604
+ });
605
+ }
606
+ /**
607
+ * Guarantee a cancel reaches a terminal state.
608
+ *
609
+ * Calling the service is a request, not an outcome: a runtime that has
610
+ * already forgotten the request answers nothing at all. The window still
611
+ * favours a real response, which carries the run's partial output.
612
+ */
613
+ armCancelTimeout(requestId) {
614
+ if (!this.pendingTasks.has(requestId)) return;
615
+ this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {
616
+ this.settleDetached(requestId, CANCELLED_STATE, {
617
+ status: CANCELLED_STATE,
618
+ error: ERR_CANCEL_UNACKNOWLEDGED
619
+ });
620
+ });
621
+ }
622
+ armTimer(requestId, delayMs, onFire) {
623
+ this.clearTimer(requestId);
624
+ const timer = setTimeout(onFire, delayMs);
625
+ timer.unref?.();
626
+ this.timers.set(requestId, timer);
627
+ }
628
+ clearTimer(requestId) {
629
+ const timer = this.timers.get(requestId);
630
+ if (timer) clearTimeout(timer);
631
+ this.timers.delete(requestId);
632
+ }
633
+ /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */
634
+ handleAccepted(event) {
635
+ if (!this.pendingTasks.has(event.requestId)) return;
636
+ this.armRunTimeout(event.requestId);
637
+ }
638
+ handleStarted(event) {
639
+ const { runId } = event;
640
+ const taskId = this.pendingTasks.get(event.requestId)?.taskId;
641
+ if (taskId === void 0) return;
642
+ this.armRunTimeout(event.requestId);
643
+ const existing = this.progress.get(event.requestId);
644
+ if (existing) this.progress.set(event.requestId, {
645
+ ...existing,
646
+ durationMs: existing.durationMs ?? 0,
647
+ durationObservedAt: existing.durationObservedAt ?? this.nowMs()
648
+ });
649
+ this.options.store.mutate((document) => this.patchDelegation(document, event.requestId, (task, delegation) => ({
650
+ ...task,
651
+ status: task.status === COMPLETED_STATE ? task.status : "in_progress",
652
+ delegation: {
653
+ ...delegation,
654
+ state: "running",
655
+ startedAt: delegation.startedAt ?? this.now(),
656
+ ...runId ? { runId } : {}
657
+ }
658
+ }))).then(() => this.options.onChange?.()).catch((error) => {
659
+ this.report(TASK_EVENT.delegationStartFailed, error, {
660
+ [TASK_ID_ATTRIBUTE]: taskId,
661
+ [REQUEST_ID_ATTRIBUTE]: event.requestId
662
+ });
663
+ });
664
+ }
665
+ handleUpdate(event) {
666
+ const existing = this.progress.get(event.requestId);
667
+ if (!existing) return;
668
+ const observedAt = this.nowMs();
669
+ const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);
670
+ const hasDuration = event.durationMs !== void 0;
671
+ this.progress.set(event.requestId, {
672
+ ...existing,
673
+ currentTool: event.currentTool ?? existing.currentTool,
674
+ toolCount: event.toolCount === void 0 ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),
675
+ tokens: event.tokens === void 0 ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),
676
+ durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs) : existing.durationMs,
677
+ durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt
678
+ });
679
+ this.options.onChange?.();
680
+ }
681
+ async handleResponse(event) {
682
+ if (!this.pendingTasks.has(event.requestId)) return;
683
+ const state = event.status === COMPLETED_STATE && !event.error ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;
684
+ await this.settle(event.requestId, state, {
685
+ status: event.status,
686
+ error: event.error,
687
+ output: truncate(event.output),
688
+ outputPath: event.outputPath,
689
+ sessionFile: event.sessionFile,
690
+ durationMs: event.durationMs,
691
+ toolCount: event.toolCount
692
+ });
693
+ }
694
+ /**
695
+ * Apply the terminal state of a delegation and tell the model about it.
696
+ *
697
+ * A cancelled run returns the task to `pending` (the work is still wanted,
698
+ * just not by that agent); a failure marks it `failed` so it stays visible
699
+ * rather than silently rejoining the backlog.
700
+ *
701
+ * The request is claimed in `settlingRequests` while it remains published as
702
+ * active work. It is removed only after the terminal state and model notification
703
+ * have been handed off, so an auto-stop observer cannot end the session between
704
+ * receiving the result and delivering it to the model.
705
+ */
706
+ async settle(requestId, state, result) {
707
+ const pending = this.pendingTasks.get(requestId);
708
+ if (!pending || this.settlingRequests.has(requestId)) return;
709
+ this.settlingRequests.add(requestId);
710
+ this.clearTimer(requestId);
711
+ const { taskId } = pending;
712
+ const progress = this.progress.get(requestId);
713
+ try {
714
+ const endedAt = this.now();
715
+ let task;
716
+ try {
717
+ const { value } = await this.options.store.mutate((document) => this.patchDelegation(document, requestId, (current, delegation) => ({
718
+ ...current,
719
+ status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? "pending" : FAILED_STATE,
720
+ updatedAt: endedAt,
721
+ delegation: {
722
+ ...delegation,
723
+ state,
724
+ endedAt,
725
+ ...result ? { result } : {}
726
+ }
727
+ })));
728
+ task = value;
729
+ } catch (error) {
730
+ this.report(TASK_EVENT.delegationSettleFailed, error, {
731
+ [TASK_ID_ATTRIBUTE]: taskId,
732
+ [REQUEST_ID_ATTRIBUTE]: requestId
733
+ });
734
+ }
735
+ const agent = task?.delegation?.agent ?? progress?.agent ?? "subagent";
736
+ const subject = task?.subject ?? `#${taskId}`;
737
+ this.options.report?.event(TASK_EVENT.delegationCompleted, {
738
+ [TASK_ID_ATTRIBUTE]: taskId,
739
+ [REQUEST_ID_ATTRIBUTE]: requestId,
740
+ [AGENT_ATTRIBUTE]: agent,
741
+ [OUTCOME_ATTRIBUTE]: state,
742
+ [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,
743
+ [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,
744
+ [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,
745
+ ...result?.toolCount === void 0 ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount },
746
+ ...result?.durationMs === void 0 ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }
747
+ });
748
+ const listComplete = state === COMPLETED_STATE && task !== void 0 && isTaskListComplete(this.options.store.snapshot.tasks);
749
+ this.notifyModel(state, taskId, subject, agent, result, listComplete);
750
+ } finally {
751
+ this.pendingTasks.delete(requestId);
752
+ this.progress.delete(requestId);
753
+ this.settlingRequests.delete(requestId);
754
+ this.options.onChange?.();
755
+ }
756
+ }
757
+ notifyModel(state, taskId, subject, agent, result, listComplete) {
758
+ const notify = this.options.notify;
759
+ if (!notify) return;
760
+ const lines = [state === COMPLETED_STATE ? `Subagent ${agent} completed task #${taskId}: ${subject}` : state === CANCELLED_STATE ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)` : `Subagent ${agent} failed task #${taskId}: ${subject}`];
761
+ if (listComplete) lines.push("", "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.");
762
+ if (result?.error) lines.push(`Error: ${result.error}`);
763
+ if (result?.output) lines.push("", result.output);
764
+ if (result?.outputPath) lines.push("", `Full output: ${result.outputPath}`);
765
+ try {
766
+ notify({
767
+ customType: NOTIFY_CUSTOM_TYPE,
768
+ content: lines.join("\n"),
769
+ display: true
770
+ }, {
771
+ triggerTurn: true,
772
+ deliverAs: "steer"
773
+ });
774
+ } catch (error) {
775
+ this.options.onNotifyError(error, taskId);
776
+ }
777
+ }
778
+ /**
779
+ * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.
780
+ *
781
+ * Terminal delegations are left alone. The document here is the freshest one,
782
+ * read under the store lock, which is the only place the check is meaningful:
783
+ * a `started` event can land after a cancel already settled the run, and
784
+ * without this guard its write would resurrect a delegation that nothing is
785
+ * tracking any more.
786
+ */
787
+ patchDelegation(document, requestId, patch) {
788
+ const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);
789
+ if (index === -1) return { value: void 0 };
790
+ const task = document.tasks[index];
791
+ if (!isDelegationActive(task)) return { value: task };
792
+ const updated = patch(task, task.delegation);
793
+ if (updated === task) return { value: task };
794
+ const tasks = [...document.tasks];
795
+ tasks[index] = updated;
796
+ return {
797
+ document: {
798
+ ...document,
799
+ tasks
800
+ },
801
+ value: updated
802
+ };
803
+ }
804
+ dispose() {
805
+ this.unbind();
806
+ this.reset();
807
+ }
808
+ /** Clear one Pi session's transient delegation state without losing service injection. */
809
+ reset() {
810
+ const changed = this.pendingTasks.size > 0 || this.progress.size > 0;
811
+ for (const timer of this.timers.values()) clearTimeout(timer);
812
+ this.timers.clear();
813
+ this.pendingTasks.clear();
814
+ this.settlingRequests.clear();
815
+ this.progress.clear();
816
+ if (changed) this.options.onChange?.();
817
+ }
818
+ };
819
+ //#endregion
820
+ //#region src/services/delegationPlatform/index.ts
821
+ function formatBriefPath(entry, cwd) {
822
+ if (!path.isAbsolute(entry)) return path.normalize(entry);
823
+ const relative = path.relative(cwd, entry);
824
+ return relative && !relative.startsWith("..") ? relative : entry;
825
+ }
826
+ /** Supply Node-owned process and path facilities to the host-neutral manager. */
827
+ function createNodeDelegationPlatform(environment = process.env) {
828
+ return {
829
+ environment,
830
+ processId: process.pid,
831
+ createRequestId: randomUUID,
832
+ formatBriefPath
833
+ };
834
+ }
835
+ //#endregion
836
+ //#region src/services/paths/index.ts
837
+ const STORE_PATH_ENV = "DOOM_TASK_STORE";
838
+ const STORE_DIR_NAME = "doom-task";
839
+ const STORE_FILE_NAME = "tasks.json";
840
+ const DEFAULT_CONFIG_DIR_NAME = ".pi";
841
+ const AGENT_DIR_NAME = "agent";
842
+ const PI_CODING_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
843
+ const HOME_ALIAS = "~";
844
+ const HOME_ALIAS_PREFIX = "~/";
845
+ function resolveAgentDirectory(env) {
846
+ const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();
847
+ if (configured === HOME_ALIAS) return os.homedir();
848
+ if (configured?.startsWith(HOME_ALIAS_PREFIX)) return path.join(os.homedir(), configured.slice(2));
849
+ return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);
850
+ }
851
+ /** Resolve the tree root without relying on extension startup order. */
852
+ function resolveSessionKey(rootSessionId, env = process.env) {
853
+ if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;
854
+ const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();
855
+ if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);
856
+ return parentSessionId;
857
+ }
858
+ /** Resolve one root session tree to a task document under the Pi agent directory. */
859
+ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey = "standalone") {
860
+ const override = env[STORE_PATH_ENV]?.trim();
861
+ if (override) return path.resolve(override);
862
+ const trimmedSessionKey = sessionKey.trim();
863
+ if (!trimmedSessionKey) throw new Error("doom-task session id cannot be blank");
864
+ return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
865
+ }
866
+ function lockPathFor(storePath) {
867
+ return `${storePath}.lock`;
868
+ }
869
+ function tempPathFor(storePath, pid = process.pid) {
870
+ return `${storePath}.tmp.${pid}`;
871
+ }
872
+ //#endregion
873
+ //#region src/services/invariants/index.ts
874
+ /**
875
+ * Collapse a malformed snapshot to one row per task id.
876
+ *
877
+ * Normal writes replace tasks in place, but older or externally edited stores
878
+ * can contain both a stale and a current copy. Prefer the copy with the newest
879
+ * ISO update timestamp; equal or missing timestamps use the later array entry.
880
+ * The winning row keeps the id's original position so repair does not reorder
881
+ * an otherwise stable task list.
882
+ */
883
+ function canonicalizeTasks(tasks) {
884
+ const canonical = [];
885
+ const indexById = /* @__PURE__ */ new Map();
886
+ for (const task of tasks) {
887
+ const existingIndex = indexById.get(task.id);
888
+ if (existingIndex === void 0) {
889
+ indexById.set(task.id, canonical.length);
890
+ canonical.push(task);
891
+ continue;
892
+ }
893
+ const existing = canonical[existingIndex];
894
+ if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) canonical[existingIndex] = task;
895
+ }
896
+ return canonical;
897
+ }
898
+ /**
899
+ * Allowed forward transitions per source status.
900
+ *
901
+ * `failed` is recoverable (a delegation can be retried) so it may return to
902
+ * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a
903
+ * terminal tombstone.
904
+ */
905
+ const VALID_TRANSITIONS = {
906
+ pending: /* @__PURE__ */ new Set([
907
+ "in_progress",
908
+ "completed",
909
+ "failed",
910
+ "deleted"
911
+ ]),
912
+ in_progress: /* @__PURE__ */ new Set([
913
+ "pending",
914
+ "completed",
915
+ "failed",
916
+ "deleted"
917
+ ]),
918
+ failed: /* @__PURE__ */ new Set([
919
+ "pending",
920
+ "in_progress",
921
+ "completed",
922
+ "deleted"
923
+ ]),
924
+ completed: /* @__PURE__ */ new Set(["deleted"]),
925
+ deleted: /* @__PURE__ */ new Set()
926
+ };
927
+ function isTransitionValid(from, to) {
928
+ if (from === to) return true;
929
+ return VALID_TRANSITIONS[from].has(to);
930
+ }
931
+ //#endregion
932
+ //#region src/services/taskStore/index.ts
933
+ const LOCK_TIMEOUT_MS = 2e3;
934
+ const LOCK_STALE_MS = 1e4;
935
+ const LOCK_RETRY_BASE_MS = 10;
936
+ const LOCK_RETRY_MAX_MS = 60;
937
+ const UTF8_ENCODING = "utf8";
938
+ const MISSING_FILE_CODE = "ENOENT";
939
+ const LOCK_EXISTS_CODE = "EEXIST";
940
+ const STORE_PATH_ATTRIBUTE = "store.path";
941
+ function sleep(ms) {
942
+ return new Promise((resolve) => setTimeout(resolve, ms));
943
+ }
944
+ /**
945
+ * Coerce arbitrary parsed JSON into a valid document.
946
+ *
947
+ * A corrupt or truncated store must not take the session down: the worst
948
+ * acceptable outcome is starting from an empty list, never a crash on startup.
949
+ */
950
+ function normalizeDocument(parsed) {
951
+ if (!parsed || typeof parsed !== "object") return emptyDocument();
952
+ const candidate = parsed;
953
+ if (!Array.isArray(candidate.tasks)) return emptyDocument();
954
+ const tasks = canonicalizeTasks(candidate.tasks.filter((task) => Boolean(task) && typeof task === "object" && typeof task.id === "number"));
955
+ const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);
956
+ return {
957
+ version: typeof candidate.version === "number" ? candidate.version : 1,
958
+ rev: typeof candidate.rev === "number" ? candidate.rev : 0,
959
+ nextId: typeof candidate.nextId === "number" && candidate.nextId > maxId ? candidate.nextId : maxId + 1,
960
+ tasks
961
+ };
962
+ }
963
+ /**
964
+ * File-backed task store shared by one root session and its delegated children.
965
+ *
966
+ * Durability model: the JSON file is the source of truth. Mutations are
967
+ * read-modify-write under an advisory lock so concurrent delegated processes
968
+ * cannot clobber each other, and writes land via temp-file rename so a
969
+ * crash mid-write can never leave a partial document behind.
970
+ */
971
+ var TaskStore = class {
972
+ storePath;
973
+ cwd;
974
+ env;
975
+ cached = emptyDocument();
976
+ listeners = /* @__PURE__ */ new Set();
977
+ lockTimeoutMs;
978
+ report;
979
+ onCommitted;
980
+ constructor(options = {}) {
981
+ this.cwd = options.cwd ?? process.cwd();
982
+ this.env = options.env ?? process.env;
983
+ this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);
984
+ this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;
985
+ this.report = options.report;
986
+ this.onCommitted = options.onCommitted;
987
+ }
988
+ /** Bind a default store to the current session tree before reading it. */
989
+ configureSession(sessionKey) {
990
+ if (this.env["DOOM_TASK_STORE"]?.trim()) return;
991
+ this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);
992
+ this.cached = emptyDocument();
993
+ }
994
+ /** Last document read from disk, without hitting the filesystem. */
995
+ get snapshot() {
996
+ return this.cached;
997
+ }
998
+ read() {
999
+ try {
1000
+ const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);
1001
+ this.cached = normalizeDocument(JSON.parse(raw));
1002
+ } catch (error) {
1003
+ if (error.code !== MISSING_FILE_CODE) this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1004
+ this.cached = emptyDocument();
1005
+ }
1006
+ return this.cached;
1007
+ }
1008
+ async readAsync(shouldApply = () => true) {
1009
+ const storePath = this.storePath;
1010
+ const document = await this.readDocumentAsync(storePath);
1011
+ if (!shouldApply()) return document;
1012
+ this.cached = document;
1013
+ return document;
1014
+ }
1015
+ async readDocumentAsync(storePath = this.storePath) {
1016
+ try {
1017
+ const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);
1018
+ return normalizeDocument(JSON.parse(raw));
1019
+ } catch (error) {
1020
+ if (error.code !== MISSING_FILE_CODE) this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });
1021
+ return emptyDocument();
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Apply a mutation under the store lock.
1026
+ *
1027
+ * `mutate` receives the freshest on-disk document and returns either the next
1028
+ * document to commit or `undefined` for a read-only action (list/get), which
1029
+ * skips the write entirely so queries never bump `rev`.
1030
+ */
1031
+ async mutate(mutate) {
1032
+ const release = await this.acquireLock();
1033
+ const outcome = (() => {
1034
+ try {
1035
+ const current = this.read();
1036
+ const mutation = mutate(current);
1037
+ if (!mutation.document) return { result: {
1038
+ document: current,
1039
+ value: mutation.value
1040
+ } };
1041
+ const committed = this.write(mutation.document);
1042
+ return {
1043
+ result: {
1044
+ document: committed,
1045
+ value: mutation.value
1046
+ },
1047
+ notification: {
1048
+ previous: current,
1049
+ committed
1050
+ }
1051
+ };
1052
+ } finally {
1053
+ release();
1054
+ }
1055
+ })();
1056
+ if (outcome.notification) this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);
1057
+ return outcome.result;
1058
+ }
1059
+ notifyCommitted(previous, committed) {
1060
+ try {
1061
+ this.onCommitted?.(previous, committed);
1062
+ } catch (error) {
1063
+ this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1064
+ }
1065
+ for (const listener of this.listeners) try {
1066
+ listener(committed);
1067
+ } catch (error) {
1068
+ this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1069
+ }
1070
+ }
1071
+ write(document) {
1072
+ const next = {
1073
+ ...document,
1074
+ version: 1,
1075
+ rev: document.rev + 1
1076
+ };
1077
+ fs.mkdirSync(path.dirname(this.storePath), { recursive: true });
1078
+ const temp = tempPathFor(this.storePath);
1079
+ fs.writeFileSync(temp, `${JSON.stringify(next, void 0, 2)}\n`, UTF8_ENCODING);
1080
+ fs.renameSync(temp, this.storePath);
1081
+ this.cached = next;
1082
+ return next;
1083
+ }
1084
+ async acquireLock() {
1085
+ const lockPath = lockPathFor(this.storePath);
1086
+ fs.mkdirSync(path.dirname(this.storePath), { recursive: true });
1087
+ const deadline = Date.now() + this.lockTimeoutMs;
1088
+ for (;;) try {
1089
+ const handle = fs.openSync(lockPath, "wx");
1090
+ fs.writeSync(handle, JSON.stringify({
1091
+ pid: process.pid,
1092
+ time: Date.now()
1093
+ }));
1094
+ fs.closeSync(handle);
1095
+ return () => fs.rmSync(lockPath, { force: true });
1096
+ } catch (error) {
1097
+ if (error.code !== LOCK_EXISTS_CODE) throw error;
1098
+ if (Date.now() >= deadline) {
1099
+ this.report?.warn(TASK_EVENT.storeLockTimeout, /* @__PURE__ */ new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`), { [STORE_PATH_ATTRIBUTE]: this.storePath });
1100
+ return () => {};
1101
+ }
1102
+ this.breakStaleLock(lockPath);
1103
+ await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);
1104
+ }
1105
+ }
1106
+ /** Remove a lock left behind by a dead process or one held implausibly long. */
1107
+ breakStaleLock(lockPath) {
1108
+ try {
1109
+ const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING));
1110
+ const expired = typeof holder.time === "number" && Date.now() - holder.time > LOCK_STALE_MS;
1111
+ const dead = typeof holder.pid === "number" && !isProcessAlive(holder.pid);
1112
+ if (!expired && !dead) return false;
1113
+ fs.unlinkSync(lockPath);
1114
+ return true;
1115
+ } catch (error) {
1116
+ if (error.code !== MISSING_FILE_CODE) this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });
1117
+ return false;
1118
+ }
1119
+ }
1120
+ /**
1121
+ * Listen for commits made through this store instance.
1122
+ *
1123
+ * Live cross-process updates use the owning session's direct event bus. This
1124
+ * listener remains for local terminal views and never watches the filesystem.
1125
+ */
1126
+ onExternalChange(listener) {
1127
+ this.listeners.add(listener);
1128
+ return () => this.listeners.delete(listener);
1129
+ }
1130
+ dispose() {
1131
+ this.listeners.clear();
1132
+ }
1133
+ };
1134
+ //#endregion
1135
+ //#region src/schemas/task.ts
1136
+ const TASK_ACTIONS = [
1137
+ "upsert",
1138
+ "list",
1139
+ "get",
1140
+ "delete",
1141
+ "clear",
1142
+ "assign",
1143
+ "cancel"
1144
+ ];
1145
+ const TASK_STATUSES = [
1146
+ "pending",
1147
+ "in_progress",
1148
+ "completed",
1149
+ "failed",
1150
+ "deleted"
1151
+ ];
1152
+ const TASK_CONTEXTS = ["fresh", "fork"];
1153
+ /**
1154
+ * A dependency target: an existing task id, or the `ref` of a task created
1155
+ * earlier in the same call.
1156
+ */
1157
+ const DepTokenSchema = Type.Union([Type.Integer(), Type.String()]);
1158
+ /**
1159
+ * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
1160
+ * validates tool arguments against this schema before `execute` runs, so a
1161
+ * stray `{"action":"update"}` inside an entry is rejected at the boundary.
1162
+ */
1163
+ const TaskItemSchema = Type.Object({
1164
+ id: Type.Optional(Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
1165
+ ref: Type.Optional(Type.String({ description: "Temporary name for a task created by this entry, so a LATER entry in this array can list it in blockedBy. Must start with a letter; never stored." })),
1166
+ subject: Type.Optional(Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
1167
+ description: Type.Optional(Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
1168
+ activeForm: Type.Optional(Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
1169
+ status: Type.Optional(Type.String({
1170
+ enum: [...TASK_STATUSES],
1171
+ description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
1172
+ })),
1173
+ blockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies for a NEW entry: task ids, or refs of tasks created EARLIER in this array. On an entry with an id use addBlockedBy / removeBlockedBy instead." })),
1174
+ addBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
1175
+ removeBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
1176
+ owner: Type.Optional(Type.String({ description: "Owner label; assign sets it to the subagent name." })),
1177
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
1178
+ }, { additionalProperties: false });
1179
+ /** One task-to-agent handoff in a native assignment batch. */
1180
+ const TaskAssignmentSchema = Type.Object({
1181
+ id: Type.Integer({ description: "Pending, unblocked task id to delegate" }),
1182
+ agent: Type.String({ description: "Exact discovered subagent name" }),
1183
+ inlineAgent: Type.Optional(InlineAgentSchema),
1184
+ instructions: Type.Optional(Type.String({ description: "Extra instructions appended to this delegated brief" })),
1185
+ relevantFiles: Type.Optional(Type.Array(Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
1186
+ priorFindings: Type.Optional(Type.String({ description: "Established facts this child should consume rather than re-derive" })),
1187
+ model: Type.Optional(Type.String({ description: "Model override for this delegated run" })),
1188
+ context: Type.Optional(Type.String({
1189
+ enum: [...TASK_CONTEXTS],
1190
+ description: "Starting context for this child: 'fresh' or 'fork'"
1191
+ }))
1192
+ }, { additionalProperties: false });
1193
+ /**
1194
+ * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
1195
+ * wording changes here change model behaviour.
1196
+ */
1197
+ const TaskParamsSchema = Type.Object({
1198
+ action: Type.String({ enum: [...TASK_ACTIONS] }),
1199
+ tasks: Type.Optional(Type.Array(TaskItemSchema, {
1200
+ minItems: 1,
1201
+ description: "upsert only. An entry with an id changes that task, an entry without an id creates one. Entries apply in array order, so a later entry can depend on an earlier one by ref."
1202
+ })),
1203
+ assignments: Type.Optional(Type.Array(TaskAssignmentSchema, {
1204
+ minItems: 1,
1205
+ description: "Required for assign, one entry per task, including when there is only one."
1206
+ })),
1207
+ id: Type.Optional(Type.Integer({ description: "Task id, for get, delete and cancel. Not accepted by upsert or assign: those carry ids inside tasks[] and assignments[] entries." })),
1208
+ status: Type.Optional(Type.String({
1209
+ enum: [...TASK_STATUSES],
1210
+ description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
1211
+ })),
1212
+ includeDeleted: Type.Optional(Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
1213
+ });
1214
+ //#endregion
1215
+ //#region src/services/reducer/index.ts
1216
+ /** Default board capacity when a caller does not provide a configured limit. */
1217
+ const DEFAULT_REDUCER_MAX_TASKS = 15;
1218
+ /**
1219
+ * A ref must start with a letter, which makes it structurally unconfusable with
1220
+ * a stringified id. That is why resolving a dependency token is just a `typeof`
1221
+ * check with no coercion heuristics.
1222
+ */
1223
+ const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
1224
+ /**
1225
+ * Does this op represent state that must reach disk?
1226
+ *
1227
+ * The exhaustive switch is the point: a future `Op` variant cannot be added
1228
+ * without declaring its persistence intent, so nothing silently starts or stops
1229
+ * bumping `rev`.
1230
+ */
1231
+ function isCommittingOp(op) {
1232
+ switch (op.kind) {
1233
+ case "error":
1234
+ case "list":
1235
+ case "get": return false;
1236
+ case "upsert": return op.items.some((item) => item.kind === "created" || item.kind === "updated");
1237
+ case "delete":
1238
+ case "clear": return true;
1239
+ }
1240
+ }
1241
+ function errorResult(document, message) {
1242
+ return {
1243
+ document,
1244
+ op: {
1245
+ kind: "error",
1246
+ message
1247
+ }
1248
+ };
1249
+ }
1250
+ function sameNumberList(a, b) {
1251
+ const x = a ?? [];
1252
+ const y = b ?? [];
1253
+ return x.length === y.length && x.every((value, index) => value === y[index]);
1254
+ }
1255
+ function sameRecord(a, b) {
1256
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
1257
+ }
1258
+ /**
1259
+ * Did this update change anything? A no-effect update (status re-set to its
1260
+ * current value, fields re-sent unchanged) reports "No change" rather than
1261
+ * "Updated #N" — without the distinction a model can loop re-issuing the same
1262
+ * call believing it never landed.
1263
+ */
1264
+ function taskChanged(before, after) {
1265
+ return before.subject !== after.subject || before.status !== after.status || before.description !== after.description || before.activeForm !== after.activeForm || before.owner !== after.owner || !sameNumberList(before.blockedBy, after.blockedBy) || !sameRecord(before.metadata, after.metadata);
1266
+ }
1267
+ function withTasks(document, tasks, nextId = document.nextId) {
1268
+ return {
1269
+ ...document,
1270
+ tasks,
1271
+ nextId
1272
+ };
1273
+ }
1274
+ /** Merge incoming metadata over a base; a `null` value deletes its key. */
1275
+ function mergeMetadata(base, incoming) {
1276
+ const merged = { ...base };
1277
+ for (const [key, value] of Object.entries(incoming)) if (value === null) delete merged[key];
1278
+ else merged[key] = value;
1279
+ return Object.keys(merged).length ? merged : void 0;
1280
+ }
1281
+ /** Copy the optional scalar fields an item may set onto a task, in place. */
1282
+ function assignScalars(target, item) {
1283
+ if (item.subject !== void 0) target.subject = item.subject;
1284
+ if (item.description !== void 0) target.description = item.description;
1285
+ if (item.activeForm !== void 0) target.activeForm = item.activeForm;
1286
+ if (item.owner !== void 0) target.owner = item.owner;
1287
+ if (item.metadata !== void 0) {
1288
+ const merged = mergeMetadata(target.metadata, item.metadata);
1289
+ if (merged === void 0) delete target.metadata;
1290
+ else target.metadata = merged;
1291
+ }
1292
+ }
1293
+ function resolveDep(context, field, token) {
1294
+ if (typeof token === "number") return {
1295
+ ok: true,
1296
+ id: token
1297
+ };
1298
+ if (!REF_PATTERN.test(token)) return {
1299
+ ok: false,
1300
+ message: `${field}: "${token}" is not a valid ref; pass an existing task id as a number`
1301
+ };
1302
+ const id = context.refIds.get(token);
1303
+ if (id !== void 0) return {
1304
+ ok: true,
1305
+ id
1306
+ };
1307
+ const failedAt = context.failedRefs.get(token);
1308
+ if (failedAt !== void 0) return {
1309
+ ok: false,
1310
+ message: `${field}: ref "${token}" refers to item[${failedAt}], which failed`
1311
+ };
1312
+ return {
1313
+ ok: false,
1314
+ message: `${field}: unknown ref "${token}" — a ref must be declared by an earlier entry in the same call`
1315
+ };
1316
+ }
1317
+ function fail(message) {
1318
+ return {
1319
+ ok: false,
1320
+ message
1321
+ };
1322
+ }
1323
+ /** Structural checks that apply to every entry, whichever kind it is. */
1324
+ function checkShape(context, item) {
1325
+ if (item.ref !== void 0) {
1326
+ if (item.id !== void 0) return "ref is only valid when creating a task; drop the id, or drop the ref";
1327
+ if (!REF_PATTERN.test(item.ref)) return `ref "${item.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;
1328
+ if (context.refIds.get(item.ref) !== void 0 || context.failedRefs.has(item.ref)) return `duplicate ref "${item.ref}": it was already declared by an earlier entry`;
1329
+ }
1330
+ }
1331
+ function applyCreateItem(context, item, index, now) {
1332
+ if (item.subject === void 0) return fail("subject is required when the entry has no id");
1333
+ if (!item.subject.trim()) return fail("subject must not be blank");
1334
+ if (item.addBlockedBy !== void 0 || item.removeBlockedBy !== void 0) return fail("addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy");
1335
+ if (item.status === "deleted") return fail("cannot create a task with status deleted; create it, then use action delete");
1336
+ if (context.tasks.filter((task) => task.status !== "deleted").length >= context.maxTasks) return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);
1337
+ const blockedBy = [];
1338
+ for (const token of item.blockedBy ?? []) {
1339
+ const resolved = resolveDep(context, "blockedBy", token);
1340
+ if (!resolved.ok) return fail(resolved.message);
1341
+ const dep = context.tasks.find((task) => task.id === resolved.id);
1342
+ if (!dep) return fail(`blockedBy: #${resolved.id} not found`);
1343
+ if (dep.status === "deleted") return fail(`blockedBy: #${resolved.id} is deleted`);
1344
+ if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);
1345
+ }
1346
+ const created = {
1347
+ id: context.nextId,
1348
+ subject: item.subject,
1349
+ status: item.status ?? "pending",
1350
+ createdAt: now,
1351
+ updatedAt: now
1352
+ };
1353
+ assignScalars(created, item);
1354
+ if (blockedBy.length) created.blockedBy = blockedBy;
1355
+ context.nextId += 1;
1356
+ context.tasks.push(created);
1357
+ if (item.ref) context.refIds.set(item.ref, created.id);
1358
+ return {
1359
+ ok: true,
1360
+ outcome: {
1361
+ index,
1362
+ kind: "created",
1363
+ id: created.id,
1364
+ subject: created.subject,
1365
+ status: created.status,
1366
+ ...item.ref ? { ref: item.ref } : {},
1367
+ ...blockedBy.length ? { blockedBy } : {}
1368
+ }
1369
+ };
1370
+ }
1371
+ function applyUpdateItem(context, item, index, now) {
1372
+ const id = item.id;
1373
+ const at = context.tasks.findIndex((task) => task.id === id);
1374
+ if (at === -1) return fail(`#${id} not found`);
1375
+ if (item.blockedBy !== void 0) return fail("blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id");
1376
+ if (!(item.subject !== void 0 || item.description !== void 0 || item.activeForm !== void 0 || item.status !== void 0 || item.owner !== void 0 || item.metadata !== void 0 || Boolean(item.addBlockedBy?.length) || Boolean(item.removeBlockedBy?.length))) return fail("nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy");
1377
+ const current = context.tasks[at];
1378
+ if (item.subject !== void 0 && !item.subject.trim()) return fail("subject must not be blank");
1379
+ let newStatus = current.status;
1380
+ if (item.status !== void 0) {
1381
+ if (!isTransitionValid(current.status, item.status)) return fail(`illegal transition ${current.status} -> ${item.status}`);
1382
+ newStatus = item.status;
1383
+ }
1384
+ let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];
1385
+ for (const token of item.removeBlockedBy ?? []) {
1386
+ const resolved = resolveDep(context, "removeBlockedBy", token);
1387
+ if (!resolved.ok) return fail(resolved.message);
1388
+ newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);
1389
+ }
1390
+ for (const token of item.addBlockedBy ?? []) {
1391
+ const resolved = resolveDep(context, "addBlockedBy", token);
1392
+ if (!resolved.ok) return fail(resolved.message);
1393
+ if (resolved.id === id) return fail(`cannot block #${id} on itself`);
1394
+ const dep = context.tasks.find((task) => task.id === resolved.id);
1395
+ if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);
1396
+ if (dep.status === "deleted") return fail(`addBlockedBy: #${resolved.id} is deleted`);
1397
+ if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);
1398
+ }
1399
+ const updated = {
1400
+ ...current,
1401
+ status: newStatus
1402
+ };
1403
+ assignScalars(updated, item);
1404
+ if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
1405
+ else delete updated.blockedBy;
1406
+ const candidate = [...context.tasks];
1407
+ candidate[at] = updated;
1408
+ if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) return fail("addBlockedBy would create a cycle in the blockedBy graph");
1409
+ const changed = taskChanged(current, updated);
1410
+ if (changed) updated.updatedAt = now;
1411
+ context.tasks = candidate;
1412
+ return {
1413
+ ok: true,
1414
+ outcome: changed ? {
1415
+ index,
1416
+ kind: "updated",
1417
+ id,
1418
+ fromStatus: current.status,
1419
+ toStatus: newStatus
1420
+ } : {
1421
+ index,
1422
+ kind: "unchanged",
1423
+ id,
1424
+ status: newStatus
1425
+ }
1426
+ };
1427
+ }
1428
+ /**
1429
+ * Apply every entry in request order, threading the document.
1430
+ *
1431
+ * Each entry lands completely or not at all: a create whose dependencies fail
1432
+ * is not kept dependency-free, because handing back an unblocked task the
1433
+ * caller asked to be blocked is a lie it may immediately act on.
1434
+ */
1435
+ function applyUpsert(document, items, now, maxTasks) {
1436
+ const context = {
1437
+ tasks: [...document.tasks],
1438
+ nextId: document.nextId,
1439
+ maxTasks,
1440
+ refIds: /* @__PURE__ */ new Map(),
1441
+ failedRefs: /* @__PURE__ */ new Map()
1442
+ };
1443
+ const outcomes = [];
1444
+ let applied = 0;
1445
+ for (const [index, item] of items.entries()) {
1446
+ const shapeError = checkShape(context, item);
1447
+ const result = shapeError ? fail(shapeError) : item.id === void 0 ? applyCreateItem(context, item, index, now) : applyUpdateItem(context, item, index, now);
1448
+ if (result.ok) {
1449
+ outcomes.push(result.outcome);
1450
+ applied += 1;
1451
+ continue;
1452
+ }
1453
+ if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) context.failedRefs.set(item.ref, index);
1454
+ outcomes.push({
1455
+ index,
1456
+ kind: "failed",
1457
+ message: result.message,
1458
+ ...item.id === void 0 ? {} : { id: item.id },
1459
+ ...item.ref ? { ref: item.ref } : {}
1460
+ });
1461
+ }
1462
+ return {
1463
+ document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,
1464
+ op: {
1465
+ kind: "upsert",
1466
+ items: outcomes,
1467
+ applied,
1468
+ failed: outcomes.length - applied
1469
+ }
1470
+ };
1471
+ }
1472
+ /**
1473
+ * Pure reducer: (document, action, params) -> (document, op).
1474
+ *
1475
+ * All validation is in-line: structural guards plus state-aware checks
1476
+ * (transition legality, dangling or deleted blockedBy, self-block, cycles,
1477
+ * in-flight delegations). The caller owns persistence and formatting.
1478
+ */
1479
+ function applyTaskMutation(document, action, params, now = (/* @__PURE__ */ new Date()).toISOString(), maxTasks = DEFAULT_REDUCER_MAX_TASKS) {
1480
+ switch (action) {
1481
+ case "upsert": {
1482
+ const items = params.tasks;
1483
+ if (!Array.isArray(items) || items.length === 0) return errorResult(document, "upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}");
1484
+ if (items.length > 100) return errorResult(document, `upsert accepts at most 100 entries per call (received ${items.length})`);
1485
+ return applyUpsert(document, items, now, maxTasks);
1486
+ }
1487
+ case "list": return {
1488
+ document,
1489
+ op: {
1490
+ kind: "list",
1491
+ includeDeleted: params.includeDeleted === true,
1492
+ ...params.status !== void 0 ? { statusFilter: params.status } : {}
1493
+ }
1494
+ };
1495
+ case "get": {
1496
+ if (params.id === void 0) return errorResult(document, "id required for get");
1497
+ const task = document.tasks.find((candidate) => candidate.id === params.id);
1498
+ if (!task) return errorResult(document, `#${params.id} not found`);
1499
+ return {
1500
+ document,
1501
+ op: {
1502
+ kind: "get",
1503
+ task
1504
+ }
1505
+ };
1506
+ }
1507
+ case "delete": {
1508
+ if (params.id === void 0) return errorResult(document, "id required for delete");
1509
+ const index = document.tasks.findIndex((task) => task.id === params.id);
1510
+ if (index === -1) return errorResult(document, `#${params.id} not found`);
1511
+ const current = document.tasks[index];
1512
+ if (current.status === "deleted") return errorResult(document, `#${current.id} is already deleted`);
1513
+ if (isDelegationActive(current)) return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);
1514
+ const tasks = [...document.tasks];
1515
+ tasks[index] = {
1516
+ ...current,
1517
+ status: DELETED_STATUS$1,
1518
+ updatedAt: now
1519
+ };
1520
+ return {
1521
+ document: withTasks(document, tasks),
1522
+ op: {
1523
+ kind: "delete",
1524
+ id: current.id,
1525
+ subject: current.subject
1526
+ }
1527
+ };
1528
+ }
1529
+ case "clear": {
1530
+ const active = document.tasks.filter(isDelegationActive);
1531
+ if (active.length > 0) return errorResult(document, `cannot clear while delegations are running (${active.map((task) => `#${task.id}`).join(", ")}) — cancel them first`);
1532
+ const count = document.tasks.length;
1533
+ return {
1534
+ document: withTasks(document, [], 1),
1535
+ op: {
1536
+ kind: "clear",
1537
+ count
1538
+ }
1539
+ };
1540
+ }
1541
+ }
1542
+ }
1543
+ //#endregion
1544
+ //#region src/services/taskResult/index.ts
1545
+ const MSG_ALL_COMPLETE_CLEAR = "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.";
1546
+ /**
1547
+ * Steering for a mixed batch. Unlike a batch of spawned subagents, a failed
1548
+ * entry here had no side effect at all, so retrying the failures is the safe
1549
+ * move and the model must be told so or it will do nothing. The hazard is the
1550
+ * other half: resending an applied create would make a second task.
1551
+ */
1552
+ const MSG_UPSERT_PARTIAL = "The applied entries are committed. Resend only the failed entries, corrected — a failed entry changed nothing, so a corrected retry is safe. Do not resend an entry that already applied: an entry without an id creates a second task.";
1553
+ const MSG_ASSIGN_PARTIAL = "Successful assignments are already running. Retry only the failed entries after correcting their task state or arguments; do not resend successful entries.";
1554
+ /** LLM-facing report for a native assignment batch. */
1555
+ function formatAssignmentResults(items) {
1556
+ if (items.length === 1) return items[0].message;
1557
+ const succeeded = items.filter((item) => item.ok).length;
1558
+ const failed = items.length - succeeded;
1559
+ const lines = [`Assigned ${succeeded}/${items.length} tasks${failed > 0 ? `; ${failed} failed` : ""}.`, ...items.map((item) => item.ok ? `- [${item.index}] Delegated #${item.id} to ${item.agent}` : `- [${item.index}] Failed #${item.id} → ${item.agent}: ${item.message}`)];
1560
+ if (failed > 0 && succeeded > 0) lines.push("", MSG_ASSIGN_PARTIAL);
1561
+ if (failed === 0) lines.push("", "All assignments are running independently in the background. Continue non-overlapping work, or end your turn.");
1562
+ return lines.join("\n");
1563
+ }
1564
+ /** `[status] #id subject (activeForm) [agent] ⛓ #dep` — the `list` line format. */
1565
+ function formatListLine(task) {
1566
+ const block = task.blockedBy?.length ? ` ⛓ ${task.blockedBy.map((id) => `#${id}`).join(",")}` : "";
1567
+ const form = task.status === "in_progress" && task.activeForm ? ` (${task.activeForm})` : "";
1568
+ const delegated = task.delegation && task.delegation.state !== "cancelled" ? ` [${task.delegation.agent}]` : "";
1569
+ return `[${task.status}] #${task.id} ${task.subject}${form}${delegated}${block}`;
1570
+ }
1571
+ function formatDelegationLines(task) {
1572
+ const delegation = task.delegation;
1573
+ if (!delegation) return [];
1574
+ const lines = [` delegated to: ${delegation.agent} (${delegation.state})`];
1575
+ if (delegation.model) lines.push(` model: ${delegation.model}`);
1576
+ if (delegation.result?.error) lines.push(` error: ${delegation.result.error}`);
1577
+ if (delegation.result?.outputPath) lines.push(` output file: ${delegation.result.outputPath}`);
1578
+ if (delegation.result?.output) lines.push(` output: ${delegation.result.output}`);
1579
+ return lines;
1580
+ }
1581
+ function formatGetLines(task, document) {
1582
+ const blocks = deriveBlocks(document.tasks).get(task.id) ?? [];
1583
+ const lines = [`#${task.id} [${task.status}] ${task.subject}`];
1584
+ if (task.description) lines.push(` description: ${task.description}`);
1585
+ if (task.activeForm) lines.push(` activeForm: ${task.activeForm}`);
1586
+ if (task.blockedBy?.length) lines.push(` blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`);
1587
+ if (blocks.length) lines.push(` blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
1588
+ if (task.owner) lines.push(` owner: ${task.owner}`);
1589
+ lines.push(...formatDelegationLines(task));
1590
+ return lines.join("\n");
1591
+ }
1592
+ /** One entry's outcome. Batch lines prefix this with `- [n] `. */
1593
+ function formatUpsertItem(item) {
1594
+ switch (item.kind) {
1595
+ case "created": {
1596
+ const ref = item.ref ? ` (ref "${item.ref}")` : "";
1597
+ const deps = item.blockedBy?.length ? ` — blocked by ${item.blockedBy.map((id) => `#${id}`).join(", ")}` : "";
1598
+ return `Created #${item.id}${ref}: ${item.subject} (${item.status})${deps}`;
1599
+ }
1600
+ case "updated": {
1601
+ const transition = item.fromStatus === item.toStatus ? "" : ` (${item.fromStatus} -> ${item.toStatus})`;
1602
+ return `Updated #${item.id}${transition}`;
1603
+ }
1604
+ case "unchanged": return `No change: #${item.id} already matches the requested values (status: ${item.status})`;
1605
+ case "failed": return `Failed${item.id === void 0 ? "" : ` #${item.id}`}: ${item.message}`;
1606
+ }
1607
+ }
1608
+ /**
1609
+ * Pure formatter: `(op, document) -> string`. The switch is closed over `Op`,
1610
+ * so a new reducer variant fails to compile until it is handled here.
1611
+ */
1612
+ function formatContent(op, document) {
1613
+ switch (op.kind) {
1614
+ case "upsert": {
1615
+ const lines = op.items.length === 1 ? [formatUpsertItem(op.items[0])] : [
1616
+ `Upsert applied ${op.applied}/${op.items.length} entries${op.failed > 0 ? `; ${op.failed} failed` : ""}.`,
1617
+ ...op.items.map((item) => `- [${item.index}] ${formatUpsertItem(item)}`),
1618
+ ...op.failed > 0 ? ["", MSG_UPSERT_PARTIAL] : []
1619
+ ];
1620
+ if (op.applied > 0 && isTaskListComplete(document.tasks)) lines.push(MSG_ALL_COMPLETE_CLEAR);
1621
+ return lines.join("\n");
1622
+ }
1623
+ case "delete": return `Deleted #${op.id}: ${op.subject}`;
1624
+ case "clear": return `Closed task list (cleared ${op.count} tasks)`;
1625
+ case "list": {
1626
+ let view = document.tasks;
1627
+ if (!op.includeDeleted) view = view.filter((task) => task.status !== "deleted");
1628
+ if (op.statusFilter) view = view.filter((task) => task.status === op.statusFilter);
1629
+ return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
1630
+ }
1631
+ case "get": return formatGetLines(op.task, document);
1632
+ case "error": return `Error: ${op.message}`;
1633
+ }
1634
+ }
1635
+ /** Build the LLM-facing envelope. `details` carries the post-mutation snapshot. */
1636
+ function buildToolResult(action, params, document, op) {
1637
+ return {
1638
+ content: [{
1639
+ type: "text",
1640
+ text: formatContent(op, document)
1641
+ }],
1642
+ details: {
1643
+ action,
1644
+ params,
1645
+ tasks: document.tasks,
1646
+ nextId: document.nextId,
1647
+ rev: document.rev,
1648
+ ...op.kind === "error" ? { error: op.message } : {},
1649
+ ...op.kind === "upsert" ? { upsert: {
1650
+ applied: op.items.flatMap((item) => item.kind === "failed" ? [] : [item.id]),
1651
+ failed: op.failed
1652
+ } } : {}
1653
+ }
1654
+ };
1655
+ }
1656
+ /** Envelope for a native assignment batch, including ids used by the consolidated TUI result. */
1657
+ function buildAssignmentResult(params, document, text, assignment) {
1658
+ return {
1659
+ content: [{
1660
+ type: "text",
1661
+ text
1662
+ }],
1663
+ details: {
1664
+ action: "assign",
1665
+ params,
1666
+ tasks: document.tasks,
1667
+ nextId: document.nextId,
1668
+ rev: document.rev,
1669
+ assignment
1670
+ }
1671
+ };
1672
+ }
1673
+ /** Envelope for delegation actions, which do not flow through the reducer. */
1674
+ function buildTextResult(action, params, document, text, error) {
1675
+ return {
1676
+ content: [{
1677
+ type: "text",
1678
+ text: error ? `Error: ${error}` : text
1679
+ }],
1680
+ details: {
1681
+ action,
1682
+ params,
1683
+ tasks: document.tasks,
1684
+ nextId: document.nextId,
1685
+ rev: document.rev,
1686
+ ...error ? { error } : {}
1687
+ }
1688
+ };
1689
+ }
1690
+ //#endregion
1691
+ //#region src/services/taskTool/index.ts
1692
+ function output(value) {
1693
+ if (typeof value === "object" && value !== null && "content" in value) return value;
1694
+ return {
1695
+ content: [{
1696
+ type: "text",
1697
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
1698
+ }],
1699
+ details: value
1700
+ };
1701
+ }
1702
+ function failure(error) {
1703
+ return {
1704
+ content: [{
1705
+ type: "text",
1706
+ text: error instanceof Error ? error.message : String(error)
1707
+ }],
1708
+ isError: true
1709
+ };
1710
+ }
1711
+ async function reducerAction(store, action, params, maxTasks) {
1712
+ const { document, value } = await store.mutate((current) => {
1713
+ const result = applyTaskMutation(current, action, params, void 0, maxTasks);
1714
+ return {
1715
+ ...isCommittingOp(result.op) ? { document: result.document } : {},
1716
+ value: result
1717
+ };
1718
+ });
1719
+ if (value.op.kind === "error") throw new Error(value.op.message);
1720
+ return buildToolResult(action, params, document, value.op);
1721
+ }
1722
+ async function assignmentBatch(manager, assignments, signal) {
1723
+ const result = [];
1724
+ for (const [index, assignment] of assignments.entries()) try {
1725
+ const outcome = await manager.assign(assignment.id, {
1726
+ agent: assignment.agent,
1727
+ inlineAgent: assignment.inlineAgent,
1728
+ instructions: assignment.instructions,
1729
+ relevantFiles: assignment.relevantFiles,
1730
+ priorFindings: assignment.priorFindings,
1731
+ model: assignment.model,
1732
+ ...assignment.context === "fork" || assignment.context === "fresh" ? { context: assignment.context } : {},
1733
+ signal
1734
+ });
1735
+ result.push({
1736
+ index,
1737
+ id: assignment.id,
1738
+ agent: assignment.agent,
1739
+ ...outcome
1740
+ });
1741
+ } catch (error) {
1742
+ result.push({
1743
+ index,
1744
+ id: assignment.id,
1745
+ agent: assignment.agent,
1746
+ ok: false,
1747
+ message: String(error)
1748
+ });
1749
+ }
1750
+ return result;
1751
+ }
1752
+ function createHeadlessTaskTool(store, manager, maxTasks) {
1753
+ return {
1754
+ name: "task",
1755
+ label: "Task",
1756
+ description: "Maintain a persistent task graph and delegate ready tasks to background agents.",
1757
+ parameters: TaskParamsSchema,
1758
+ promptSnippet: "Track complex work persistently and delegate ready tasks",
1759
+ executionMode: "serial",
1760
+ async execute(_toolCallId, rawParams, signal, onUpdate) {
1761
+ if (!Check(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
1762
+ const params = rawParams;
1763
+ try {
1764
+ if (params.action === "assign") {
1765
+ if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
1766
+ onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
1767
+ const items = await assignmentBatch(manager, params.assignments, signal);
1768
+ const assigned = items.filter((item) => item.ok).map((item) => item.id);
1769
+ const text = formatAssignmentResults(items);
1770
+ if (assigned.length === 0) throw new Error(text);
1771
+ return buildAssignmentResult(params, store.snapshot, text, {
1772
+ assigned,
1773
+ failed: items.length - assigned.length
1774
+ });
1775
+ }
1776
+ if (params.action === "cancel") {
1777
+ const outcome = await manager.cancel(params.id ?? NaN);
1778
+ if (!outcome.ok) throw new Error(outcome.message);
1779
+ return buildTextResult("cancel", params, store.snapshot, outcome.message);
1780
+ }
1781
+ return reducerAction(store, params.action, params, maxTasks);
1782
+ } catch (error) {
1783
+ return failure(error);
1784
+ }
1785
+ }
1786
+ };
1787
+ }
1788
+ //#endregion
1789
+ //#region src/extensions/workspaces/sessions/(backend)/tool/task.mcp.ts
1790
+ var task_mcp_default = defineMcpTool(({ execution }) => {
1791
+ const store = new TaskStore({
1792
+ cwd: execution.cwd,
1793
+ env: execution.environment
1794
+ });
1795
+ store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));
1796
+ const manager = new DelegationManager({
1797
+ store,
1798
+ cwd: execution.cwd,
1799
+ platform: createNodeDelegationPlatform(execution.environment),
1800
+ getSessionId: () => execution.sessionId,
1801
+ runTimeoutMs: getDelegationTimeoutMs(execution.environment),
1802
+ onNotifyError: (error) => void execution.client.notify({
1803
+ body: String(error),
1804
+ level: "warning"
1805
+ })
1806
+ });
1807
+ const tool = createHeadlessTaskTool(store, manager, getMaxTasks(execution.environment));
1808
+ let initialized;
1809
+ return {
1810
+ ...tool,
1811
+ async execute(...args) {
1812
+ initialized ??= store.readAsync().then(async () => {
1813
+ await manager.reconcile();
1814
+ });
1815
+ await initialized;
1816
+ return tool.execute(...args);
1817
+ }
1818
+ };
1819
+ });
1820
+ //#endregion
1821
+ //#region generated/mcp.ts
1822
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
1823
+ const via = (identity, value) => ({
1824
+ ...identity,
1825
+ ...value
1826
+ });
1827
+ const mcp = defineMcpPlugin({
1828
+ name: "@agimon-ai/doompi-task",
1829
+ session: (context) => ({ get tools() {
1830
+ return [via({ name: "task" }, at(task_mcp_default, context))];
1831
+ } })
1832
+ });
1833
+ //#endregion
1834
+ export { mcp as default, mcp };
1835
+
1836
+ //# sourceMappingURL=mcp.mjs.map