@agimon-ai/doompi-task 0.0.1-alpha.121 → 0.0.1-alpha.122

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.
Files changed (46) hide show
  1. package/dist/commands.cjs +1 -1
  2. package/dist/commands.d.mts +1 -1
  3. package/dist/commands.mjs +1 -1
  4. package/dist/extensions/mcp.cjs +208 -922
  5. package/dist/extensions/mcp.cjs.map +1 -1
  6. package/dist/extensions/mcp.mjs +208 -922
  7. package/dist/extensions/mcp.mjs.map +1 -1
  8. package/dist/extensions/pi.cjs +4 -4
  9. package/dist/extensions/pi.mjs +4 -4
  10. package/dist/extensions/server.cjs +2 -1
  11. package/dist/extensions/server.cjs.map +1 -1
  12. package/dist/extensions/server.mjs +2 -1
  13. package/dist/extensions/server.mjs.map +1 -1
  14. package/dist/index.cjs +4 -2
  15. package/dist/index.d.mts +3 -3
  16. package/dist/index.mjs +3 -3
  17. package/dist/{root.cli-swHZqusx.d.mts → root.cli-Brg0bUuN.d.mts} +2 -2
  18. package/dist/{root.cli-swHZqusx.d.mts.map → root.cli-Brg0bUuN.d.mts.map} +1 -1
  19. package/dist/{task-DKHKuems.mjs → task-BBy5LoRL.mjs} +15 -2
  20. package/dist/{task-DKHKuems.mjs.map → task-BBy5LoRL.mjs.map} +1 -1
  21. package/dist/{task-Dqy88_rr.cjs → task-BF91oQcx.cjs} +26 -1
  22. package/dist/{task-Dqy88_rr.cjs.map → task-BF91oQcx.cjs.map} +1 -1
  23. package/dist/{task-DHSvdK6E.d.mts → task-lCI3ZCI6.d.mts} +23 -2
  24. package/dist/task-lCI3ZCI6.d.mts.map +1 -0
  25. package/dist/{task-space.cli-BH4Iy_7m.cjs → task-space.cli-BJcRZleT.cjs} +2 -2
  26. package/dist/{task-space.cli-BH4Iy_7m.cjs.map → task-space.cli-BJcRZleT.cjs.map} +1 -1
  27. package/dist/{task-space.cli-CMYNjgOW.mjs → task-space.cli-DH6bLqsD.mjs} +2 -2
  28. package/dist/{task-space.cli-CMYNjgOW.mjs.map → task-space.cli-DH6bLqsD.mjs.map} +1 -1
  29. package/dist/{task.cli-CiTkjUaX.cjs → task.cli-CHZG08JZ.cjs} +2 -2
  30. package/dist/{task.cli-CiTkjUaX.cjs.map → task.cli-CHZG08JZ.cjs.map} +1 -1
  31. package/dist/{task.cli-BM34E7GG.mjs → task.cli-Co6KD4vF.mjs} +2 -2
  32. package/dist/{task.cli-BM34E7GG.mjs.map → task.cli-Co6KD4vF.mjs.map} +1 -1
  33. package/dist/{tasks.cli-BZj83YD_.mjs → tasks.cli-C6j3syEo.mjs} +2 -2
  34. package/dist/{tasks.cli-BZj83YD_.mjs.map → tasks.cli-C6j3syEo.mjs.map} +1 -1
  35. package/dist/{tasks.cli-8VvuN9YQ.cjs → tasks.cli-Ed2QpAyo.cjs} +2 -2
  36. package/dist/{tasks.cli-8VvuN9YQ.cjs.map → tasks.cli-Ed2QpAyo.cjs.map} +1 -1
  37. package/dist/toolSchema.cjs +3 -1
  38. package/dist/toolSchema.d.mts +2 -2
  39. package/dist/toolSchema.mjs +2 -2
  40. package/dist/toolTaskTool.cjs +1 -1
  41. package/dist/toolTaskTool.d.mts +1 -1
  42. package/dist/toolTaskTool.mjs +1 -1
  43. package/dist/tuiTaskSpace.cjs +1 -1
  44. package/dist/tuiTaskSpace.mjs +1 -1
  45. package/package.json +4 -4
  46. package/dist/task-DHSvdK6E.d.mts.map +0 -1
@@ -1,839 +1,110 @@
1
1
  import { defineMcpPlugin, defineMcpTool } from "@agimon-ai/doompi-core/mcpFacet";
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";
2
+ import { InlineAgentSchema } from "@agimon-ai/doompi-core/delegation";
3
+ import { Type } from "typebox";
5
4
  import fs from "node:fs";
6
5
  import os from "node:os";
6
+ import path from "node:path";
7
7
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "@agimon-ai/doompi-core/childProcess";
8
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
- setCwd(cwd) {
307
- this.options.cwd = cwd;
308
- }
309
- now() {
310
- return this.options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
311
- }
312
- nowMs() {
313
- return this.options.nowMs?.() ?? Date.now();
314
- }
315
- get runTimeoutMs() {
316
- return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
317
- }
318
- report(event, error, attributes) {
319
- this.options.report?.error(event, error, attributes);
320
- }
321
- /** True in a session that is itself a subagent child. */
322
- get isChildSession() {
323
- return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);
324
- }
325
- /** Live progress for a task, for the overlay to render. */
326
- progressFor(task) {
327
- const requestId = task.delegation?.requestId;
328
- return requestId ? this.progress.get(requestId) : void 0;
329
- }
330
- /** Displayed runtime duration, rebased from the latest child observation. */
331
- static elapsedMs(progress, nowMs = Date.now()) {
332
- const baseline = progress.durationMs ?? 0;
333
- const observedAt = progress.durationObservedAt ?? nowMs;
334
- return baseline + Math.max(0, nowMs - observedAt);
335
- }
336
- /** Rebind to the active Team service without stacking lifecycle listeners. */
337
- bind(ctx, service) {
338
- this.unbind();
339
- this.service = service;
340
- this.subscriptions.push(ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {
341
- this.handleAccepted(event);
342
- }), ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {
343
- this.handleStarted(event);
344
- }), ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {
345
- this.handleUpdate(event);
346
- }), ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {
347
- this.handleResponse(event).catch((error) => {
348
- this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });
349
- });
350
- }));
351
- return () => {
352
- if (this.service === service) this.unbind();
353
- };
354
- }
355
- /** Remove only the cross-package binding; task state and watchdogs remain live. */
356
- unbind() {
357
- for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
358
- this.service = void 0;
359
- }
360
- /** Items still in flight, surfaced so auto-stop will not kill the harness. */
361
- listActiveWork() {
362
- return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) => pending.sessionId ? [{
363
- id: `task-${pending.taskId}:${requestId}`,
364
- sessionId: pending.sessionId
365
- }] : []);
366
- }
367
- /**
368
- * Return tasks nothing can finish to `pending`.
369
- *
370
- * The live request set is read inside the mutation so a delegation assigned
371
- * while the lock was contended is not mistaken for a leftover.
372
- */
373
- async reconcile(isCurrent = () => true) {
374
- const { value } = await this.options.store.mutate((document) => {
375
- if (!isCurrent()) return { value: [] };
376
- const result = reconcileOrphanedDelegations(document, this.now(), void 0, {
377
- pid: this.options.platform.processId,
378
- liveRequestIds: new Set(this.pendingTasks.keys())
379
- });
380
- if (result.orphaned.length === 0) return { value: [] };
381
- return {
382
- document: result.document,
383
- value: result.orphaned
384
- };
385
- });
386
- if (!isCurrent()) return [];
387
- for (const task of value) this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ""), {
388
- [TASK_ID_ATTRIBUTE]: task.id,
389
- ...task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {},
390
- ...task.delegation?.pid === void 0 ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }
391
- });
392
- if (value.length > 0) this.options.onChange?.();
393
- return value;
394
- }
395
- async assign(taskId, options) {
396
- const agent = options.agent?.trim();
397
- if (!agent) return {
398
- ok: false,
399
- message: "agent required for assign"
400
- };
401
- if (this.isChildSession) return {
402
- ok: false,
403
- message: ERR_CHILD_SESSION
404
- };
405
- if (options.signal?.aborted) return {
406
- ok: false,
407
- message: "delegation cancelled before it started"
408
- };
409
- const requestId = this.options.platform.createRequestId();
410
- const startedAt = this.now();
411
- const sessionId = this.options.getSessionId?.();
412
- const context = briefContext(options, this.options.cwd, this.options.platform);
413
- const { value: outcome } = await this.options.store.mutate((current) => {
414
- const index = current.tasks.findIndex((task) => task.id === taskId);
415
- if (index === -1) return { value: {
416
- ok: false,
417
- message: `#${taskId} not found`
418
- } };
419
- const task = current.tasks[index];
420
- if (task.status === DELETED_STATUS) return { value: {
421
- ok: false,
422
- message: `#${taskId} is deleted`
423
- } };
424
- if (task.status === COMPLETED_STATE) return { value: {
425
- ok: false,
426
- message: `#${taskId} is already completed`
427
- } };
428
- if (isDelegationActive(task)) return { value: {
429
- ok: false,
430
- message: `#${taskId} is already delegated to ${task.delegation?.agent}`
431
- } };
432
- if (isBlocked(current.tasks, task)) return { value: {
433
- ok: false,
434
- message: `#${taskId} is blocked by ${(task.blockedBy ?? []).map((id) => `#${id}`).join(", ")}`
435
- } };
436
- const delegation = {
437
- requestId,
438
- agent,
439
- state: "requested",
440
- pid: this.options.platform.processId,
441
- startedAt,
442
- ...sessionId ? { sessionId } : {},
443
- ...options.model ? { model: options.model } : {}
444
- };
445
- const tasks = [...current.tasks];
446
- tasks[index] = {
447
- ...task,
448
- owner: agent,
449
- updatedAt: startedAt,
450
- delegation
451
- };
452
- return {
453
- document: {
454
- ...current,
455
- tasks
456
- },
457
- value: {
458
- ok: true,
459
- message: "",
460
- task: tasks[index]
461
- }
462
- };
463
- });
464
- if (!outcome.ok || !outcome.task) return {
465
- ok: false,
466
- message: outcome.message
467
- };
468
- const contextNotesLength = context.notes?.length ?? 0;
469
- this.pendingTasks.set(requestId, {
470
- taskId,
471
- sessionId
472
- });
473
- this.progress.set(requestId, {
474
- agent,
475
- contextFileCount: context.files.length,
476
- contextNotesLength
477
- });
478
- this.armStartedTimeout(requestId);
479
- this.options.onChange?.();
480
- const request = {
481
- requestId,
482
- taskId,
483
- agent,
484
- ...options.inlineAgent ? { inlineAgent: options.inlineAgent } : {},
485
- prompt: buildBrief(outcome.task, options.instructions, context),
486
- ...options.context ? { context: options.context } : {},
487
- cwd: this.options.cwd,
488
- artifacts: true,
489
- timeoutMs: this.runTimeoutMs,
490
- runMode: "detached",
491
- teamTask: {
492
- id: String(outcome.task.id),
493
- subject: outcome.task.subject
494
- },
495
- ...options.model ? { model: options.model } : {}
496
- };
497
- try {
498
- const service = this.service;
499
- if (!service) throw new Error(ERR_NO_RUNTIME);
500
- service.request(request).catch((error) => {
501
- this.report(TASK_EVENT.delegationRequestFailed, error, {
502
- [TASK_ID_ATTRIBUTE]: taskId,
503
- [REQUEST_ID_ATTRIBUTE]: requestId,
504
- [AGENT_ATTRIBUTE]: agent
505
- });
506
- this.settleDetached(requestId, FAILED_STATE, {
507
- status: FAILED_STATE,
508
- error: `Delegation request failed: ${messageOf(error)}`
509
- });
510
- });
511
- } catch (error) {
512
- this.report(TASK_EVENT.delegationRequestFailed, error, {
513
- [TASK_ID_ATTRIBUTE]: taskId,
514
- [REQUEST_ID_ATTRIBUTE]: requestId,
515
- [AGENT_ATTRIBUTE]: agent
516
- });
517
- const detail = messageOf(error);
518
- await this.settle(requestId, FAILED_STATE, {
519
- status: FAILED_STATE,
520
- error: `Delegation request failed: ${detail}`
521
- });
522
- return {
523
- ok: false,
524
- message: `Could not dispatch #${taskId} to ${agent}: ${detail}`
525
- };
526
- }
527
- this.options.report?.event(TASK_EVENT.delegationAssigned, {
528
- [TASK_ID_ATTRIBUTE]: taskId,
529
- [REQUEST_ID_ATTRIBUTE]: requestId,
530
- [AGENT_ATTRIBUTE]: agent,
531
- [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,
532
- [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,
533
- [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,
534
- [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length
535
- });
536
- return {
537
- ok: true,
538
- 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.`
539
- };
540
- }
541
- async cancel(taskId) {
542
- const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
543
- if (!task) return {
544
- ok: false,
545
- message: `#${taskId} not found`
546
- };
547
- if (!task.delegation || !isDelegationActive(task)) return {
548
- ok: false,
549
- message: `#${taskId} has no running delegation`
550
- };
551
- const { requestId } = task.delegation;
552
- this.service?.cancel({ requestId });
553
- this.armCancelTimeout(requestId);
554
- return {
555
- ok: true,
556
- message: `Cancelling delegation for #${taskId} (${task.delegation.agent})`
557
- };
558
- }
559
- /** Settle without awaiting, reporting rather than dropping a failure. */
560
- settleDetached(requestId, state, result, event = TASK_EVENT.delegationSettleFailed) {
561
- this.settle(requestId, state, result).catch((error) => {
562
- this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });
563
- });
564
- }
565
- /**
566
- * Fail a delegation that nobody acknowledged.
567
- *
568
- * Provider loss or a stalled Team runtime can still leave a dispatched
569
- * request silent. Without this acknowledgement deadline the task would sit
570
- * in `requested` forever.
571
- */
572
- armStartedTimeout(requestId) {
573
- this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {
574
- this.settleDetached(requestId, FAILED_STATE, {
575
- status: FAILED_STATE,
576
- error: ERR_NO_RUNTIME
577
- });
578
- });
579
- }
580
- /**
581
- * Bound a run that already started.
582
- *
583
- * The request carries the same budget, so in the normal case the runtime ends
584
- * the run itself and reports a richer result. The grace period biases toward
585
- * that answer; this timer only covers a runtime that goes silent, which is
586
- * precisely the case where no response event will ever arrive.
587
- */
588
- armRunTimeout(requestId) {
589
- const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);
590
- this.armTimer(requestId, this.runTimeoutMs + grace, () => {
591
- const taskId = this.pendingTasks.get(requestId)?.taskId;
592
- const agent = this.progress.get(requestId)?.agent;
593
- const error = /* @__PURE__ */ new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);
594
- this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {
595
- ...taskId === void 0 ? {} : { [TASK_ID_ATTRIBUTE]: taskId },
596
- [REQUEST_ID_ATTRIBUTE]: requestId,
597
- ...agent ? { [AGENT_ATTRIBUTE]: agent } : {}
598
- });
599
- this.service?.cancel({
600
- requestId,
601
- reason: error.message
602
- });
603
- this.settleDetached(requestId, FAILED_STATE, {
604
- status: TIMED_OUT_STATUS,
605
- error: error.message
606
- });
607
- });
608
- }
609
- /**
610
- * Guarantee a cancel reaches a terminal state.
611
- *
612
- * Calling the service is a request, not an outcome: a runtime that has
613
- * already forgotten the request answers nothing at all. The window still
614
- * favours a real response, which carries the run's partial output.
615
- */
616
- armCancelTimeout(requestId) {
617
- if (!this.pendingTasks.has(requestId)) return;
618
- this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {
619
- this.settleDetached(requestId, CANCELLED_STATE, {
620
- status: CANCELLED_STATE,
621
- error: ERR_CANCEL_UNACKNOWLEDGED
622
- });
623
- });
624
- }
625
- armTimer(requestId, delayMs, onFire) {
626
- this.clearTimer(requestId);
627
- const timer = setTimeout(onFire, delayMs);
628
- timer.unref?.();
629
- this.timers.set(requestId, timer);
630
- }
631
- clearTimer(requestId) {
632
- const timer = this.timers.get(requestId);
633
- if (timer) clearTimeout(timer);
634
- this.timers.delete(requestId);
635
- }
636
- /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */
637
- handleAccepted(event) {
638
- if (!this.pendingTasks.has(event.requestId)) return;
639
- this.armRunTimeout(event.requestId);
640
- }
641
- handleStarted(event) {
642
- const { runId } = event;
643
- const taskId = this.pendingTasks.get(event.requestId)?.taskId;
644
- if (taskId === void 0) return;
645
- this.armRunTimeout(event.requestId);
646
- const existing = this.progress.get(event.requestId);
647
- if (existing) this.progress.set(event.requestId, {
648
- ...existing,
649
- durationMs: existing.durationMs ?? 0,
650
- durationObservedAt: existing.durationObservedAt ?? this.nowMs()
651
- });
652
- this.options.store.mutate((document) => this.patchDelegation(document, event.requestId, (task, delegation) => ({
653
- ...task,
654
- status: task.status === COMPLETED_STATE ? task.status : "in_progress",
655
- delegation: {
656
- ...delegation,
657
- state: "running",
658
- startedAt: delegation.startedAt ?? this.now(),
659
- ...runId ? { runId } : {}
660
- }
661
- }))).then(() => this.options.onChange?.()).catch((error) => {
662
- this.report(TASK_EVENT.delegationStartFailed, error, {
663
- [TASK_ID_ATTRIBUTE]: taskId,
664
- [REQUEST_ID_ATTRIBUTE]: event.requestId
665
- });
666
- });
667
- }
668
- handleUpdate(event) {
669
- const existing = this.progress.get(event.requestId);
670
- if (!existing) return;
671
- const observedAt = this.nowMs();
672
- const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);
673
- const hasDuration = event.durationMs !== void 0;
674
- this.progress.set(event.requestId, {
675
- ...existing,
676
- currentTool: event.currentTool ?? existing.currentTool,
677
- toolCount: event.toolCount === void 0 ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),
678
- tokens: event.tokens === void 0 ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),
679
- durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs) : existing.durationMs,
680
- durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt
681
- });
682
- this.options.onChange?.();
683
- }
684
- async handleResponse(event) {
685
- if (!this.pendingTasks.has(event.requestId)) return;
686
- const state = event.status === COMPLETED_STATE && !event.error ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;
687
- await this.settle(event.requestId, state, {
688
- status: event.status,
689
- error: event.error,
690
- output: truncate(event.output),
691
- outputPath: event.outputPath,
692
- sessionFile: event.sessionFile,
693
- durationMs: event.durationMs,
694
- toolCount: event.toolCount
695
- });
696
- }
697
- /**
698
- * Apply the terminal state of a delegation and tell the model about it.
699
- *
700
- * A cancelled run returns the task to `pending` (the work is still wanted,
701
- * just not by that agent); a failure marks it `failed` so it stays visible
702
- * rather than silently rejoining the backlog.
703
- *
704
- * The request is claimed in `settlingRequests` while it remains published as
705
- * active work. It is removed only after the terminal state and model notification
706
- * have been handed off, so an auto-stop observer cannot end the session between
707
- * receiving the result and delivering it to the model.
708
- */
709
- async settle(requestId, state, result) {
710
- const pending = this.pendingTasks.get(requestId);
711
- if (!pending || this.settlingRequests.has(requestId)) return;
712
- this.settlingRequests.add(requestId);
713
- this.clearTimer(requestId);
714
- const { taskId } = pending;
715
- const progress = this.progress.get(requestId);
716
- try {
717
- const endedAt = this.now();
718
- let task;
719
- try {
720
- const { value } = await this.options.store.mutate((document) => this.patchDelegation(document, requestId, (current, delegation) => ({
721
- ...current,
722
- status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? "pending" : FAILED_STATE,
723
- updatedAt: endedAt,
724
- delegation: {
725
- ...delegation,
726
- state,
727
- endedAt,
728
- ...result ? { result } : {}
729
- }
730
- })));
731
- task = value;
732
- } catch (error) {
733
- this.report(TASK_EVENT.delegationSettleFailed, error, {
734
- [TASK_ID_ATTRIBUTE]: taskId,
735
- [REQUEST_ID_ATTRIBUTE]: requestId
736
- });
737
- }
738
- const agent = task?.delegation?.agent ?? progress?.agent ?? "subagent";
739
- const subject = task?.subject ?? `#${taskId}`;
740
- this.options.report?.event(TASK_EVENT.delegationCompleted, {
741
- [TASK_ID_ATTRIBUTE]: taskId,
742
- [REQUEST_ID_ATTRIBUTE]: requestId,
743
- [AGENT_ATTRIBUTE]: agent,
744
- [OUTCOME_ATTRIBUTE]: state,
745
- [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,
746
- [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,
747
- [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,
748
- ...result?.toolCount === void 0 ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount },
749
- ...result?.durationMs === void 0 ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }
750
- });
751
- const listComplete = state === COMPLETED_STATE && task !== void 0 && isTaskListComplete(this.options.store.snapshot.tasks);
752
- this.notifyModel(state, taskId, subject, agent, result, listComplete);
753
- } finally {
754
- this.pendingTasks.delete(requestId);
755
- this.progress.delete(requestId);
756
- this.settlingRequests.delete(requestId);
757
- this.options.onChange?.();
758
- }
759
- }
760
- notifyModel(state, taskId, subject, agent, result, listComplete) {
761
- const notify = this.options.notify;
762
- if (!notify) return;
763
- 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}`];
764
- if (listComplete) lines.push("", "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.");
765
- if (result?.error) lines.push(`Error: ${result.error}`);
766
- if (result?.output) lines.push("", result.output);
767
- if (result?.outputPath) lines.push("", `Full output: ${result.outputPath}`);
768
- try {
769
- notify({
770
- customType: NOTIFY_CUSTOM_TYPE,
771
- content: lines.join("\n"),
772
- display: true
773
- }, {
774
- triggerTurn: true,
775
- deliverAs: "steer"
776
- });
777
- } catch (error) {
778
- this.options.onNotifyError(error, taskId);
779
- }
780
- }
781
- /**
782
- * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.
783
- *
784
- * Terminal delegations are left alone. The document here is the freshest one,
785
- * read under the store lock, which is the only place the check is meaningful:
786
- * a `started` event can land after a cancel already settled the run, and
787
- * without this guard its write would resurrect a delegation that nothing is
788
- * tracking any more.
789
- */
790
- patchDelegation(document, requestId, patch) {
791
- const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);
792
- if (index === -1) return { value: void 0 };
793
- const task = document.tasks[index];
794
- if (!isDelegationActive(task)) return { value: task };
795
- const updated = patch(task, task.delegation);
796
- if (updated === task) return { value: task };
797
- const tasks = [...document.tasks];
798
- tasks[index] = updated;
799
- return {
800
- document: {
801
- ...document,
802
- tasks
803
- },
804
- value: updated
805
- };
806
- }
807
- dispose() {
808
- this.unbind();
809
- this.reset();
810
- }
811
- /** Clear one Pi session's transient delegation state without losing service injection. */
812
- reset() {
813
- const changed = this.pendingTasks.size > 0 || this.progress.size > 0;
814
- for (const timer of this.timers.values()) clearTimeout(timer);
815
- this.timers.clear();
816
- this.pendingTasks.clear();
817
- this.settlingRequests.clear();
818
- this.progress.clear();
819
- if (changed) this.options.onChange?.();
820
- }
821
- };
9
+ //#region src/schemas/task.ts
10
+ const TASK_ACTIONS = [
11
+ "upsert",
12
+ "list",
13
+ "get",
14
+ "delete",
15
+ "clear",
16
+ "assign",
17
+ "cancel"
18
+ ];
19
+ const TASK_STATUSES = [
20
+ "pending",
21
+ "in_progress",
22
+ "completed",
23
+ "failed",
24
+ "deleted"
25
+ ];
26
+ const TASK_CONTEXTS = ["fresh", "fork"];
27
+ /**
28
+ * A dependency target: an existing task id, or the `ref` of a task created
29
+ * earlier in the same call.
30
+ */
31
+ const DepTokenSchema = Type.Union([Type.Integer(), Type.String()]);
32
+ /**
33
+ * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
34
+ * validates tool arguments against this schema before `execute` runs, so a
35
+ * stray `{"action":"update"}` inside an entry is rejected at the boundary.
36
+ */
37
+ const TaskItemSchema = Type.Object({
38
+ id: Type.Optional(Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
39
+ 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." })),
40
+ subject: Type.Optional(Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
41
+ description: Type.Optional(Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
42
+ activeForm: Type.Optional(Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
43
+ status: Type.Optional(Type.String({
44
+ enum: [...TASK_STATUSES],
45
+ description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
46
+ })),
47
+ 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." })),
48
+ addBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
49
+ removeBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
50
+ owner: Type.Optional(Type.String({ description: "Owner label; assign sets it to the subagent name." })),
51
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
52
+ }, { additionalProperties: false });
53
+ /** One task-to-agent handoff in a native assignment batch. */
54
+ const TaskAssignmentSchema = Type.Object({
55
+ id: Type.Integer({ description: "Pending, unblocked task id to delegate" }),
56
+ agent: Type.String({ description: "Exact discovered subagent name" }),
57
+ inlineAgent: Type.Optional(InlineAgentSchema),
58
+ instructions: Type.Optional(Type.String({ description: "Extra instructions appended to this delegated brief" })),
59
+ relevantFiles: Type.Optional(Type.Array(Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
60
+ priorFindings: Type.Optional(Type.String({ description: "Established facts this child should consume rather than re-derive" })),
61
+ model: Type.Optional(Type.String({ description: "Model override for this delegated run" })),
62
+ context: Type.Optional(Type.String({
63
+ enum: [...TASK_CONTEXTS],
64
+ description: "Starting context for this child: 'fresh' or 'fork'"
65
+ }))
66
+ }, { additionalProperties: false });
67
+ /**
68
+ * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
69
+ * wording changes here change model behaviour.
70
+ */
71
+ const TaskParamsSchema = Type.Object({
72
+ action: Type.String({ enum: [...TASK_ACTIONS] }),
73
+ tasks: Type.Optional(Type.Array(TaskItemSchema, {
74
+ minItems: 1,
75
+ 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."
76
+ })),
77
+ assignments: Type.Optional(Type.Array(TaskAssignmentSchema, {
78
+ minItems: 1,
79
+ description: "Required for assign, one entry per task, including when there is only one."
80
+ })),
81
+ 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." })),
82
+ status: Type.Optional(Type.String({
83
+ enum: [...TASK_STATUSES],
84
+ description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
85
+ })),
86
+ includeDeleted: Type.Optional(Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
87
+ });
88
+ /** Remote MCP connections track tasks only; delegation stays with the local agent. */
89
+ const REMOTE_TASK_ACTIONS = [
90
+ "upsert",
91
+ "list",
92
+ "get",
93
+ "delete",
94
+ "clear"
95
+ ];
96
+ const { assignments: _assignments, ...remoteTaskProperties } = TaskParamsSchema.properties;
97
+ const RemoteTaskParamsSchema = Type.Object({
98
+ ...remoteTaskProperties,
99
+ action: Type.String({ enum: [...REMOTE_TASK_ACTIONS] })
100
+ });
822
101
  //#endregion
823
- //#region src/services/delegationPlatform/index.ts
824
- function formatBriefPath(entry, cwd) {
825
- if (!path.isAbsolute(entry)) return path.normalize(entry);
826
- const relative = path.relative(cwd, entry);
827
- return relative && !relative.startsWith("..") ? relative : entry;
828
- }
829
- /** Supply Node-owned process and path facilities to the host-neutral manager. */
830
- function createNodeDelegationPlatform(environment = process.env) {
831
- return {
832
- environment,
833
- processId: process.pid,
834
- createRequestId: randomUUID,
835
- formatBriefPath
836
- };
102
+ //#region src/services/config/index.ts
103
+ const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
104
+ /** Maximum number of non-deleted tasks retained on one board. */
105
+ function getMaxTasks(env = process.env) {
106
+ const raw = Number(env[MAX_TASKS_ENV]);
107
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
837
108
  }
838
109
  //#endregion
839
110
  //#region src/services/paths/index.ts
@@ -873,6 +144,51 @@ function tempPathFor(storePath, pid = process.pid) {
873
144
  return `${storePath}.tmp.${pid}`;
874
145
  }
875
146
  //#endregion
147
+ //#region src/models/task.ts
148
+ const DELETED_STATUS$1 = "deleted";
149
+ function emptyDocument() {
150
+ return {
151
+ version: 1,
152
+ rev: 0,
153
+ nextId: 1,
154
+ tasks: []
155
+ };
156
+ }
157
+ /**
158
+ * A delegation is "live" while the owning run may still produce a response.
159
+ *
160
+ * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
161
+ * which carries the state as a plain string, answers the question the same way
162
+ * the store does.
163
+ */
164
+ function isDelegationActive(task) {
165
+ const state = task.delegation?.state;
166
+ return state === "requested" || state === "running";
167
+ }
168
+ //#endregion
169
+ //#region src/types/telemetry.ts
170
+ const TASK_EVENT = {
171
+ notificationFailed: "doom_task.notification_failed",
172
+ storeReadFailed: "doom_task.store_read_failed",
173
+ storeLockTimeout: "doom_task.store_lock_timeout",
174
+ storeLockBreakFailed: "doom_task.store_lock_break_failed",
175
+ storeWatchFailed: "doom_task.store_watch_failed",
176
+ storeListenerFailed: "doom_task.store_listener_failed",
177
+ storeCommitListenerFailed: "doom_task.store_commit_listener_failed",
178
+ storeSweepFailed: "doom_task.store_sweep_failed",
179
+ sessionStartFailed: "doom_task.session_start_failed",
180
+ sessionStartDegraded: "doom_task.session_start_degraded",
181
+ toolFailed: "doom_task.tool_failed",
182
+ delegationRequestFailed: "doom_task.delegation_request_failed",
183
+ delegationStartFailed: "doom_task.delegation_start_failed",
184
+ delegationResponseFailed: "doom_task.delegation_response_failed",
185
+ delegationSettleFailed: "doom_task.delegation_settle_failed",
186
+ delegationTimedOut: "doom_task.delegation_timed_out",
187
+ delegationOrphaned: "doom_task.delegation_orphaned",
188
+ delegationAssigned: "doom_task.delegation_assigned",
189
+ delegationCompleted: "doom_task.delegation_completed"
190
+ };
191
+ //#endregion
876
192
  //#region src/services/invariants/index.ts
877
193
  /**
878
194
  * Collapse a malformed snapshot to one row per task id.
@@ -932,6 +248,23 @@ function isTransitionValid(from, to) {
932
248
  return VALID_TRANSITIONS[from].has(to);
933
249
  }
934
250
  //#endregion
251
+ //#region src/services/processLiveness/index.ts
252
+ /**
253
+ * Is a process still running?
254
+ *
255
+ * Signal 0 performs the permission and existence check without delivering a
256
+ * signal. EPERM means the process exists but belongs to another user, which
257
+ * still counts as alive.
258
+ */
259
+ function isProcessAlive(pid) {
260
+ try {
261
+ process.kill(pid, 0);
262
+ return true;
263
+ } catch (error) {
264
+ return error.code === "EPERM";
265
+ }
266
+ }
267
+ //#endregion
935
268
  //#region src/services/taskStore/index.ts
936
269
  const LOCK_TIMEOUT_MS = 2e3;
937
270
  const LOCK_STALE_MS = 1e4;
@@ -1135,85 +468,48 @@ var TaskStore = class {
1135
468
  }
1136
469
  };
1137
470
  //#endregion
1138
- //#region src/schemas/task.ts
1139
- const TASK_ACTIONS = [
1140
- "upsert",
1141
- "list",
1142
- "get",
1143
- "delete",
1144
- "clear",
1145
- "assign",
1146
- "cancel"
1147
- ];
1148
- const TASK_STATUSES = [
1149
- "pending",
1150
- "in_progress",
1151
- "completed",
1152
- "failed",
1153
- "deleted"
1154
- ];
1155
- const TASK_CONTEXTS = ["fresh", "fork"];
1156
- /**
1157
- * A dependency target: an existing task id, or the `ref` of a task created
1158
- * earlier in the same call.
1159
- */
1160
- const DepTokenSchema = Type.Union([Type.Integer(), Type.String()]);
1161
- /**
1162
- * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
1163
- * validates tool arguments against this schema before `execute` runs, so a
1164
- * stray `{"action":"update"}` inside an entry is rejected at the boundary.
1165
- */
1166
- const TaskItemSchema = Type.Object({
1167
- id: Type.Optional(Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
1168
- 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." })),
1169
- subject: Type.Optional(Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
1170
- description: Type.Optional(Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
1171
- activeForm: Type.Optional(Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
1172
- status: Type.Optional(Type.String({
1173
- enum: [...TASK_STATUSES],
1174
- description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
1175
- })),
1176
- 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." })),
1177
- addBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
1178
- removeBlockedBy: Type.Optional(Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
1179
- owner: Type.Optional(Type.String({ description: "Owner label; assign sets it to the subagent name." })),
1180
- metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
1181
- }, { additionalProperties: false });
1182
- /** One task-to-agent handoff in a native assignment batch. */
1183
- const TaskAssignmentSchema = Type.Object({
1184
- id: Type.Integer({ description: "Pending, unblocked task id to delegate" }),
1185
- agent: Type.String({ description: "Exact discovered subagent name" }),
1186
- inlineAgent: Type.Optional(InlineAgentSchema),
1187
- instructions: Type.Optional(Type.String({ description: "Extra instructions appended to this delegated brief" })),
1188
- relevantFiles: Type.Optional(Type.Array(Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
1189
- priorFindings: Type.Optional(Type.String({ description: "Established facts this child should consume rather than re-derive" })),
1190
- model: Type.Optional(Type.String({ description: "Model override for this delegated run" })),
1191
- context: Type.Optional(Type.String({
1192
- enum: [...TASK_CONTEXTS],
1193
- description: "Starting context for this child: 'fresh' or 'fork'"
1194
- }))
1195
- }, { additionalProperties: false });
471
+ //#region src/models/taskGraph.ts
472
+ const COMPLETED_STATUS = "completed";
473
+ const DELETED_STATUS = "deleted";
474
+ /** True when a non-empty list has no visible work left to finish. */
475
+ function isTaskListComplete(taskList) {
476
+ const visible = taskList.filter((task) => task.status !== DELETED_STATUS);
477
+ return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
478
+ }
1196
479
  /**
1197
- * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
1198
- * wording changes here change model behaviour.
480
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
481
+ *
482
+ * Takes the proposed additions explicitly so the reducer can ask the question
483
+ * before mutating anything.
1199
484
  */
1200
- const TaskParamsSchema = Type.Object({
1201
- action: Type.String({ enum: [...TASK_ACTIONS] }),
1202
- tasks: Type.Optional(Type.Array(TaskItemSchema, {
1203
- minItems: 1,
1204
- 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."
1205
- })),
1206
- assignments: Type.Optional(Type.Array(TaskAssignmentSchema, {
1207
- minItems: 1,
1208
- description: "Required for assign, one entry per task, including when there is only one."
1209
- })),
1210
- 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." })),
1211
- status: Type.Optional(Type.String({
1212
- enum: [...TASK_STATUSES],
1213
- description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
1214
- })),
1215
- includeDeleted: Type.Optional(Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
1216
- });
485
+ function detectCycle(taskList, taskId, newBlockedBy) {
486
+ const edges = /* @__PURE__ */ new Map();
487
+ for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
488
+ else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
489
+ const visiting = /* @__PURE__ */ new Set();
490
+ const visited = /* @__PURE__ */ new Set();
491
+ const hasCycleFrom = (node) => {
492
+ if (visiting.has(node)) return true;
493
+ if (visited.has(node)) return false;
494
+ visiting.add(node);
495
+ for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
496
+ visiting.delete(node);
497
+ visited.add(node);
498
+ return false;
499
+ };
500
+ for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
501
+ return false;
502
+ }
503
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
504
+ function deriveBlocks(taskList) {
505
+ const blocks = /* @__PURE__ */ new Map();
506
+ for (const task of taskList) for (const dep of task.blockedBy ?? []) {
507
+ const dependents = blocks.get(dep) ?? [];
508
+ dependents.push(task.id);
509
+ blocks.set(dep, dependents);
510
+ }
511
+ return blocks;
512
+ }
1217
513
  //#endregion
1218
514
  //#region src/services/reducer/index.ts
1219
515
  /** Default board capacity when a caller does not provide a configured limit. */
@@ -1764,6 +1060,7 @@ function createHeadlessTaskTool(store, manager, maxTasks) {
1764
1060
  if (!Check(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
1765
1061
  const params = rawParams;
1766
1062
  try {
1063
+ if ((params.action === "assign" || params.action === "cancel") && !manager) throw new Error("Delegation is not available on this connection.");
1767
1064
  if (params.action === "assign") {
1768
1065
  if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
1769
1066
  onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
@@ -1796,25 +1093,14 @@ var task_mcp_default = defineMcpTool(({ execution }) => {
1796
1093
  env: execution.environment
1797
1094
  });
1798
1095
  store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));
1799
- const manager = new DelegationManager({
1800
- store,
1801
- cwd: execution.cwd,
1802
- platform: createNodeDelegationPlatform(execution.environment),
1803
- getSessionId: () => execution.sessionId,
1804
- runTimeoutMs: getDelegationTimeoutMs(execution.environment),
1805
- onNotifyError: (error) => void execution.client.notify({
1806
- body: String(error),
1807
- level: "warning"
1808
- })
1809
- });
1810
- const tool = createHeadlessTaskTool(store, manager, getMaxTasks(execution.environment));
1096
+ const tool = createHeadlessTaskTool(store, void 0, getMaxTasks(execution.environment));
1811
1097
  let initialized;
1812
1098
  return {
1813
1099
  ...tool,
1100
+ parameters: RemoteTaskParamsSchema,
1101
+ description: "Track multi-step work in the DoomPi session as a persistent task list (todo, plan, task graph). Delegating to background agents is not available here.",
1814
1102
  async execute(...args) {
1815
- initialized ??= store.readAsync().then(async () => {
1816
- await manager.reconcile();
1817
- });
1103
+ initialized ??= store.readAsync().then(() => void 0);
1818
1104
  await initialized;
1819
1105
  return tool.execute(...args);
1820
1106
  }