@agimon-ai/doompi-task 0.0.1-alpha.120 → 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
@@ -26,843 +26,114 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  //#endregion
27
27
  let _agimon_ai_doompi_core_mcpFacet = require("@agimon-ai/doompi-core/mcpFacet");
28
28
  let _agimon_ai_doompi_core_delegation = require("@agimon-ai/doompi-core/delegation");
29
- let node_crypto = require("node:crypto");
30
- let node_path = require("node:path");
31
- node_path = __toESM(node_path, 1);
29
+ let typebox = require("typebox");
32
30
  let node_fs = require("node:fs");
33
31
  node_fs = __toESM(node_fs, 1);
34
32
  let node_os = require("node:os");
35
33
  node_os = __toESM(node_os, 1);
34
+ let node_path = require("node:path");
35
+ node_path = __toESM(node_path, 1);
36
36
  let _agimon_ai_doompi_core_childProcess = require("@agimon-ai/doompi-core/childProcess");
37
37
  let typebox_value = require("typebox/value");
38
- let typebox = require("typebox");
39
- //#region src/services/config/index.ts
40
- const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
41
- const DELEGATION_TIMEOUT_MS_ENV = "DOOM_TASK_DELEGATION_TIMEOUT_MS";
42
- /** Deliberately under the subagents auto-drain ceiling (30 min) so a headless
43
- * session still gets the failure and a model turn before draining gives up. */
44
- const DEFAULT_DELEGATION_TIMEOUT_MS = 12e5;
45
- /** Maximum number of non-deleted tasks retained on one board. */
46
- function getMaxTasks(env = process.env) {
47
- const raw = Number(env[MAX_TASKS_ENV]);
48
- return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
49
- }
50
- /** How long a delegated run may go without reporting a result. */
51
- function getDelegationTimeoutMs(env = process.env) {
52
- const raw = Number(env[DELEGATION_TIMEOUT_MS_ENV]);
53
- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_DELEGATION_TIMEOUT_MS;
54
- }
55
- //#endregion
56
- //#region src/models/taskGraph.ts
57
- const COMPLETED_STATUS = "completed";
58
- const DELETED_STATUS$2 = "deleted";
59
- /** True when a non-empty list has no visible work left to finish. */
60
- function isTaskListComplete(taskList) {
61
- const visible = taskList.filter((task) => task.status !== DELETED_STATUS$2);
62
- return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
63
- }
64
- /**
65
- * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
66
- *
67
- * Takes the proposed additions explicitly so the reducer can ask the question
68
- * before mutating anything.
69
- */
70
- function detectCycle(taskList, taskId, newBlockedBy) {
71
- const edges = /* @__PURE__ */ new Map();
72
- for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
73
- else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
74
- const visiting = /* @__PURE__ */ new Set();
75
- const visited = /* @__PURE__ */ new Set();
76
- const hasCycleFrom = (node) => {
77
- if (visiting.has(node)) return true;
78
- if (visited.has(node)) return false;
79
- visiting.add(node);
80
- for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
81
- visiting.delete(node);
82
- visited.add(node);
83
- return false;
84
- };
85
- for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
86
- return false;
87
- }
88
- /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
89
- function deriveBlocks(taskList) {
90
- const blocks = /* @__PURE__ */ new Map();
91
- for (const task of taskList) for (const dep of task.blockedBy ?? []) {
92
- const dependents = blocks.get(dep) ?? [];
93
- dependents.push(task.id);
94
- blocks.set(dep, dependents);
95
- }
96
- return blocks;
97
- }
98
- /**
99
- * Blocking dependencies of a task that are not yet resolved.
100
- *
101
- * `completed` clears a dependency; `failed` deliberately does not, so a failed
102
- * delegation keeps its dependents blocked instead of silently releasing work
103
- * that was never actually finished.
104
- */
105
- function unresolvedBlockers(taskList, task) {
106
- return (task.blockedBy ?? []).filter((dep) => {
107
- const blocker = taskList.find((candidate) => candidate.id === dep);
108
- if (!blocker) return false;
109
- return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS$2;
110
- });
111
- }
112
- function isBlocked(taskList, task) {
113
- return unresolvedBlockers(taskList, task).length > 0;
114
- }
115
- //#endregion
116
- //#region src/types/telemetry.ts
117
- const TASK_EVENT = {
118
- notificationFailed: "doom_task.notification_failed",
119
- storeReadFailed: "doom_task.store_read_failed",
120
- storeLockTimeout: "doom_task.store_lock_timeout",
121
- storeLockBreakFailed: "doom_task.store_lock_break_failed",
122
- storeWatchFailed: "doom_task.store_watch_failed",
123
- storeListenerFailed: "doom_task.store_listener_failed",
124
- storeCommitListenerFailed: "doom_task.store_commit_listener_failed",
125
- storeSweepFailed: "doom_task.store_sweep_failed",
126
- sessionStartFailed: "doom_task.session_start_failed",
127
- sessionStartDegraded: "doom_task.session_start_degraded",
128
- toolFailed: "doom_task.tool_failed",
129
- delegationRequestFailed: "doom_task.delegation_request_failed",
130
- delegationStartFailed: "doom_task.delegation_start_failed",
131
- delegationResponseFailed: "doom_task.delegation_response_failed",
132
- delegationSettleFailed: "doom_task.delegation_settle_failed",
133
- delegationTimedOut: "doom_task.delegation_timed_out",
134
- delegationOrphaned: "doom_task.delegation_orphaned",
135
- delegationAssigned: "doom_task.delegation_assigned",
136
- delegationCompleted: "doom_task.delegation_completed"
137
- };
138
- //#endregion
139
- //#region src/models/task.ts
140
- const DELETED_STATUS$1 = "deleted";
141
- function emptyDocument() {
142
- return {
143
- version: 1,
144
- rev: 0,
145
- nextId: 1,
146
- tasks: []
147
- };
148
- }
149
- /**
150
- * A delegation is "live" while the owning run may still produce a response.
151
- *
152
- * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
153
- * which carries the state as a plain string, answers the question the same way
154
- * the store does.
155
- */
156
- function isDelegationActive(task) {
157
- const state = task.delegation?.state;
158
- return state === "requested" || state === "running";
159
- }
160
- //#endregion
161
- //#region src/services/processLiveness/index.ts
162
- /**
163
- * Is a process still running?
164
- *
165
- * Signal 0 performs the permission and existence check without delivering a
166
- * signal. EPERM means the process exists but belongs to another user, which
167
- * still counts as alive.
168
- */
169
- function isProcessAlive(pid) {
170
- try {
171
- process.kill(pid, 0);
172
- return true;
173
- } catch (error) {
174
- return error.code === "EPERM";
175
- }
176
- }
177
- //#endregion
178
- //#region src/services/reconcile/index.ts
179
- const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
180
- const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
181
- /**
182
- * Recover tasks that no longer have anyone able to finish them.
183
- *
184
- * A subagent run dies with the harness that spawned it, but the store file
185
- * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
186
- * kinds of delegation qualify as dead:
187
- *
188
- * - the owning pid is gone, so nothing is left to report a result;
189
- * - the owning pid is *this* process, yet the request is absent from the live
190
- * set. Settling requires an in-memory record, so an in-process session
191
- * restart (which clears that map without writing to the store) leaves rows
192
- * nothing can ever resolve. Checking pid liveness alone misses these, because
193
- * the pid is our own and very much alive.
194
- *
195
- * Delegations owned by a different, still-running pid belong to a parallel
196
- * session and are left untouched.
197
- */
198
- function reconcileOrphanedDelegations(document, now = (/* @__PURE__ */ new Date()).toISOString(), isAlive = isProcessAlive, self) {
199
- const orphaned = [];
200
- const tasks = document.tasks.map((task) => {
201
- if (!isDelegationActive(task)) return task;
202
- const pid = task.delegation?.pid;
203
- if (pid === void 0) return task;
204
- const abandonedHere = self !== void 0 && pid === self.pid && !self.liveRequestIds.has(task.delegation.requestId);
205
- if (!abandonedHere && isAlive(pid)) return task;
206
- const recovered = {
207
- ...task,
208
- status: "pending",
209
- updatedAt: now,
210
- delegation: {
211
- ...task.delegation,
212
- state: "failed",
213
- endedAt: now,
214
- result: {
215
- status: "failed",
216
- error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART
217
- }
218
- }
219
- };
220
- orphaned.push(recovered);
221
- return recovered;
222
- });
223
- if (orphaned.length === 0) return {
224
- document,
225
- orphaned
226
- };
227
- return {
228
- document: {
229
- ...document,
230
- tasks
231
- },
232
- orphaned
233
- };
234
- }
235
- //#endregion
236
- //#region src/services/delegation/index.ts
237
- const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
238
- const DEFAULT_STARTED_TIMEOUT_MS = 5e3;
239
- const DEFAULT_RUN_TIMEOUT_MS = 12e5;
240
- const DEFAULT_CANCEL_TIMEOUT_MS = 1e4;
241
- const MAX_RUN_TIMEOUT_GRACE_MS = 6e4;
242
- const MAX_STORED_OUTPUT = 4e3;
243
- /**
244
- * Cap on files rendered into a brief. Exported so the tool schema can state the
245
- * same number to the model rather than restating it and drifting.
246
- */
247
- const MAX_BRIEF_NOTES = 1500;
248
- const COMPLETED_STATE = "completed";
249
- const FAILED_STATE = "failed";
250
- const CANCELLED_STATE = "cancelled";
251
- const TIMED_OUT_STATUS = "timed_out";
252
- const DELETED_STATUS = "deleted";
253
- const TASK_ID_ATTRIBUTE = "task.id";
254
- const REQUEST_ID_ATTRIBUTE = "delegation.request_id";
255
- const AGENT_ATTRIBUTE = "delegation.agent_name";
256
- const PID_ATTRIBUTE = "delegation.pid";
257
- const CONTEXT_PRESENT_ATTRIBUTE = "delegation.context_present";
258
- const CONTEXT_FILE_COUNT_ATTRIBUTE = "delegation.context_file_count";
259
- const CONTEXT_NOTES_LENGTH_ATTRIBUTE = "delegation.context_notes_length";
260
- const BRIEF_LENGTH_ATTRIBUTE = "delegation.brief_length";
261
- const TOOL_COUNT_ATTRIBUTE = "delegation.tool_count";
262
- const DURATION_MS_ATTRIBUTE = "delegation.duration_ms";
263
- const OUTCOME_ATTRIBUTE = "delegation.outcome";
264
- const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
265
- const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
266
- const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
267
- function truncate(value, limit = MAX_STORED_OUTPUT) {
268
- if (!value) return void 0;
269
- return value.length <= limit ? value : `${value.slice(0, limit)}\n… (truncated)`;
270
- }
271
- function messageOf(error) {
272
- return error instanceof Error ? error.message : String(error);
273
- }
274
- /** Normalize the parent context with host-owned path semantics. */
275
- function briefContext(options, cwd, platform) {
276
- const files = /* @__PURE__ */ new Set();
277
- for (const entry of options.relevantFiles ?? []) {
278
- if (files.size >= 12) break;
279
- const normalized = platform.formatBriefPath(entry.trim(), cwd);
280
- if (normalized && normalized !== ".") files.add(normalized);
281
- }
282
- return {
283
- files: [...files],
284
- notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES)
285
- };
286
- }
287
- /**
288
- * Build the brief handed to the subagent.
289
- *
290
- * Doom Team owns the child tool surface and the parent owns the task record.
291
- * Keeping those responsibilities explicit prevents a child from attempting to
292
- * call a task tool that is not loaded in its runtime, while still giving it a
293
- * reliable path to ask the parent for a decision.
294
- *
295
- * The context pack is the parent's verified discovery handed over. The whole
296
- * block is omitted when nothing was supplied: this brief is the child's whole
297
- * starting context, so an empty section header is pure token cost.
298
- */
299
- function buildBrief(task, instructions, context) {
300
- const sections = [`Task #${task.id}: ${task.subject}`];
301
- if (task.description) sections.push(task.description);
302
- if (instructions) sections.push(instructions);
303
- if (context.files.length > 0 || context.notes) {
304
- const contextLines = ["Parent context — consume before repository discovery:"];
305
- if (context.files.length > 0) contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(", ")}`);
306
- if (context.notes) contextLines.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`);
307
- 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.");
308
- sections.push(contextLines.join("\n"));
309
- }
310
- 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.");
311
- return sections.join("\n\n");
312
- }
313
- /**
314
- * Owns the lifecycle of tasks delegated to subagents.
315
- *
316
- * Delegation rides Team's injected Cordis service rather than spawning
317
- * processes directly, so doom-task stays decoupled from the subagent runtime
318
- * and degrades to a clear error when that service is not loaded.
319
- *
320
- * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
321
- * a delegation always has a deadline no matter which phase it is in. Losing
322
- * that pairing is what previously left tasks running forever.
323
- */
324
- var DelegationManager = class DelegationManager {
325
- options;
326
- progress = /* @__PURE__ */ new Map();
327
- pendingTasks = /* @__PURE__ */ new Map();
328
- settlingRequests = /* @__PURE__ */ new Set();
329
- timers = /* @__PURE__ */ new Map();
330
- subscriptions = [];
331
- service;
332
- constructor(options) {
333
- this.options = options;
334
- }
335
- setCwd(cwd) {
336
- this.options.cwd = cwd;
337
- }
338
- now() {
339
- return this.options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
340
- }
341
- nowMs() {
342
- return this.options.nowMs?.() ?? Date.now();
343
- }
344
- get runTimeoutMs() {
345
- return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
346
- }
347
- report(event, error, attributes) {
348
- this.options.report?.error(event, error, attributes);
349
- }
350
- /** True in a session that is itself a subagent child. */
351
- get isChildSession() {
352
- return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);
353
- }
354
- /** Live progress for a task, for the overlay to render. */
355
- progressFor(task) {
356
- const requestId = task.delegation?.requestId;
357
- return requestId ? this.progress.get(requestId) : void 0;
358
- }
359
- /** Displayed runtime duration, rebased from the latest child observation. */
360
- static elapsedMs(progress, nowMs = Date.now()) {
361
- const baseline = progress.durationMs ?? 0;
362
- const observedAt = progress.durationObservedAt ?? nowMs;
363
- return baseline + Math.max(0, nowMs - observedAt);
364
- }
365
- /** Rebind to the active Team service without stacking lifecycle listeners. */
366
- bind(ctx, service) {
367
- this.unbind();
368
- this.service = service;
369
- this.subscriptions.push(ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {
370
- this.handleAccepted(event);
371
- }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_STARTED_EVENT, (event) => {
372
- this.handleStarted(event);
373
- }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_UPDATED_EVENT, (event) => {
374
- this.handleUpdate(event);
375
- }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_FINISHED_EVENT, (event) => {
376
- this.handleResponse(event).catch((error) => {
377
- this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });
378
- });
379
- }));
380
- return () => {
381
- if (this.service === service) this.unbind();
382
- };
383
- }
384
- /** Remove only the cross-package binding; task state and watchdogs remain live. */
385
- unbind() {
386
- for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
387
- this.service = void 0;
388
- }
389
- /** Items still in flight, surfaced so auto-stop will not kill the harness. */
390
- listActiveWork() {
391
- return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) => pending.sessionId ? [{
392
- id: `task-${pending.taskId}:${requestId}`,
393
- sessionId: pending.sessionId
394
- }] : []);
395
- }
396
- /**
397
- * Return tasks nothing can finish to `pending`.
398
- *
399
- * The live request set is read inside the mutation so a delegation assigned
400
- * while the lock was contended is not mistaken for a leftover.
401
- */
402
- async reconcile(isCurrent = () => true) {
403
- const { value } = await this.options.store.mutate((document) => {
404
- if (!isCurrent()) return { value: [] };
405
- const result = reconcileOrphanedDelegations(document, this.now(), void 0, {
406
- pid: this.options.platform.processId,
407
- liveRequestIds: new Set(this.pendingTasks.keys())
408
- });
409
- if (result.orphaned.length === 0) return { value: [] };
410
- return {
411
- document: result.document,
412
- value: result.orphaned
413
- };
414
- });
415
- if (!isCurrent()) return [];
416
- for (const task of value) this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ""), {
417
- [TASK_ID_ATTRIBUTE]: task.id,
418
- ...task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {},
419
- ...task.delegation?.pid === void 0 ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }
420
- });
421
- if (value.length > 0) this.options.onChange?.();
422
- return value;
423
- }
424
- async assign(taskId, options) {
425
- const agent = options.agent?.trim();
426
- if (!agent) return {
427
- ok: false,
428
- message: "agent required for assign"
429
- };
430
- if (this.isChildSession) return {
431
- ok: false,
432
- message: ERR_CHILD_SESSION
433
- };
434
- if (options.signal?.aborted) return {
435
- ok: false,
436
- message: "delegation cancelled before it started"
437
- };
438
- const requestId = this.options.platform.createRequestId();
439
- const startedAt = this.now();
440
- const sessionId = this.options.getSessionId?.();
441
- const context = briefContext(options, this.options.cwd, this.options.platform);
442
- const { value: outcome } = await this.options.store.mutate((current) => {
443
- const index = current.tasks.findIndex((task) => task.id === taskId);
444
- if (index === -1) return { value: {
445
- ok: false,
446
- message: `#${taskId} not found`
447
- } };
448
- const task = current.tasks[index];
449
- if (task.status === DELETED_STATUS) return { value: {
450
- ok: false,
451
- message: `#${taskId} is deleted`
452
- } };
453
- if (task.status === COMPLETED_STATE) return { value: {
454
- ok: false,
455
- message: `#${taskId} is already completed`
456
- } };
457
- if (isDelegationActive(task)) return { value: {
458
- ok: false,
459
- message: `#${taskId} is already delegated to ${task.delegation?.agent}`
460
- } };
461
- if (isBlocked(current.tasks, task)) return { value: {
462
- ok: false,
463
- message: `#${taskId} is blocked by ${(task.blockedBy ?? []).map((id) => `#${id}`).join(", ")}`
464
- } };
465
- const delegation = {
466
- requestId,
467
- agent,
468
- state: "requested",
469
- pid: this.options.platform.processId,
470
- startedAt,
471
- ...sessionId ? { sessionId } : {},
472
- ...options.model ? { model: options.model } : {}
473
- };
474
- const tasks = [...current.tasks];
475
- tasks[index] = {
476
- ...task,
477
- owner: agent,
478
- updatedAt: startedAt,
479
- delegation
480
- };
481
- return {
482
- document: {
483
- ...current,
484
- tasks
485
- },
486
- value: {
487
- ok: true,
488
- message: "",
489
- task: tasks[index]
490
- }
491
- };
492
- });
493
- if (!outcome.ok || !outcome.task) return {
494
- ok: false,
495
- message: outcome.message
496
- };
497
- const contextNotesLength = context.notes?.length ?? 0;
498
- this.pendingTasks.set(requestId, {
499
- taskId,
500
- sessionId
501
- });
502
- this.progress.set(requestId, {
503
- agent,
504
- contextFileCount: context.files.length,
505
- contextNotesLength
506
- });
507
- this.armStartedTimeout(requestId);
508
- this.options.onChange?.();
509
- const request = {
510
- requestId,
511
- taskId,
512
- agent,
513
- ...options.inlineAgent ? { inlineAgent: options.inlineAgent } : {},
514
- prompt: buildBrief(outcome.task, options.instructions, context),
515
- ...options.context ? { context: options.context } : {},
516
- cwd: this.options.cwd,
517
- artifacts: true,
518
- timeoutMs: this.runTimeoutMs,
519
- runMode: "detached",
520
- teamTask: {
521
- id: String(outcome.task.id),
522
- subject: outcome.task.subject
523
- },
524
- ...options.model ? { model: options.model } : {}
525
- };
526
- try {
527
- const service = this.service;
528
- if (!service) throw new Error(ERR_NO_RUNTIME);
529
- service.request(request).catch((error) => {
530
- this.report(TASK_EVENT.delegationRequestFailed, error, {
531
- [TASK_ID_ATTRIBUTE]: taskId,
532
- [REQUEST_ID_ATTRIBUTE]: requestId,
533
- [AGENT_ATTRIBUTE]: agent
534
- });
535
- this.settleDetached(requestId, FAILED_STATE, {
536
- status: FAILED_STATE,
537
- error: `Delegation request failed: ${messageOf(error)}`
538
- });
539
- });
540
- } catch (error) {
541
- this.report(TASK_EVENT.delegationRequestFailed, error, {
542
- [TASK_ID_ATTRIBUTE]: taskId,
543
- [REQUEST_ID_ATTRIBUTE]: requestId,
544
- [AGENT_ATTRIBUTE]: agent
545
- });
546
- const detail = messageOf(error);
547
- await this.settle(requestId, FAILED_STATE, {
548
- status: FAILED_STATE,
549
- error: `Delegation request failed: ${detail}`
550
- });
551
- return {
552
- ok: false,
553
- message: `Could not dispatch #${taskId} to ${agent}: ${detail}`
554
- };
555
- }
556
- this.options.report?.event(TASK_EVENT.delegationAssigned, {
557
- [TASK_ID_ATTRIBUTE]: taskId,
558
- [REQUEST_ID_ATTRIBUTE]: requestId,
559
- [AGENT_ATTRIBUTE]: agent,
560
- [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,
561
- [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,
562
- [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,
563
- [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length
564
- });
565
- return {
566
- ok: true,
567
- 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.`
568
- };
569
- }
570
- async cancel(taskId) {
571
- const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
572
- if (!task) return {
573
- ok: false,
574
- message: `#${taskId} not found`
575
- };
576
- if (!task.delegation || !isDelegationActive(task)) return {
577
- ok: false,
578
- message: `#${taskId} has no running delegation`
579
- };
580
- const { requestId } = task.delegation;
581
- this.service?.cancel({ requestId });
582
- this.armCancelTimeout(requestId);
583
- return {
584
- ok: true,
585
- message: `Cancelling delegation for #${taskId} (${task.delegation.agent})`
586
- };
587
- }
588
- /** Settle without awaiting, reporting rather than dropping a failure. */
589
- settleDetached(requestId, state, result, event = TASK_EVENT.delegationSettleFailed) {
590
- this.settle(requestId, state, result).catch((error) => {
591
- this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });
592
- });
593
- }
594
- /**
595
- * Fail a delegation that nobody acknowledged.
596
- *
597
- * Provider loss or a stalled Team runtime can still leave a dispatched
598
- * request silent. Without this acknowledgement deadline the task would sit
599
- * in `requested` forever.
600
- */
601
- armStartedTimeout(requestId) {
602
- this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {
603
- this.settleDetached(requestId, FAILED_STATE, {
604
- status: FAILED_STATE,
605
- error: ERR_NO_RUNTIME
606
- });
607
- });
608
- }
609
- /**
610
- * Bound a run that already started.
611
- *
612
- * The request carries the same budget, so in the normal case the runtime ends
613
- * the run itself and reports a richer result. The grace period biases toward
614
- * that answer; this timer only covers a runtime that goes silent, which is
615
- * precisely the case where no response event will ever arrive.
616
- */
617
- armRunTimeout(requestId) {
618
- const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);
619
- this.armTimer(requestId, this.runTimeoutMs + grace, () => {
620
- const taskId = this.pendingTasks.get(requestId)?.taskId;
621
- const agent = this.progress.get(requestId)?.agent;
622
- const error = /* @__PURE__ */ new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);
623
- this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {
624
- ...taskId === void 0 ? {} : { [TASK_ID_ATTRIBUTE]: taskId },
625
- [REQUEST_ID_ATTRIBUTE]: requestId,
626
- ...agent ? { [AGENT_ATTRIBUTE]: agent } : {}
627
- });
628
- this.service?.cancel({
629
- requestId,
630
- reason: error.message
631
- });
632
- this.settleDetached(requestId, FAILED_STATE, {
633
- status: TIMED_OUT_STATUS,
634
- error: error.message
635
- });
636
- });
637
- }
638
- /**
639
- * Guarantee a cancel reaches a terminal state.
640
- *
641
- * Calling the service is a request, not an outcome: a runtime that has
642
- * already forgotten the request answers nothing at all. The window still
643
- * favours a real response, which carries the run's partial output.
644
- */
645
- armCancelTimeout(requestId) {
646
- if (!this.pendingTasks.has(requestId)) return;
647
- this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {
648
- this.settleDetached(requestId, CANCELLED_STATE, {
649
- status: CANCELLED_STATE,
650
- error: ERR_CANCEL_UNACKNOWLEDGED
651
- });
652
- });
653
- }
654
- armTimer(requestId, delayMs, onFire) {
655
- this.clearTimer(requestId);
656
- const timer = setTimeout(onFire, delayMs);
657
- timer.unref?.();
658
- this.timers.set(requestId, timer);
659
- }
660
- clearTimer(requestId) {
661
- const timer = this.timers.get(requestId);
662
- if (timer) clearTimeout(timer);
663
- this.timers.delete(requestId);
664
- }
665
- /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */
666
- handleAccepted(event) {
667
- if (!this.pendingTasks.has(event.requestId)) return;
668
- this.armRunTimeout(event.requestId);
669
- }
670
- handleStarted(event) {
671
- const { runId } = event;
672
- const taskId = this.pendingTasks.get(event.requestId)?.taskId;
673
- if (taskId === void 0) return;
674
- this.armRunTimeout(event.requestId);
675
- const existing = this.progress.get(event.requestId);
676
- if (existing) this.progress.set(event.requestId, {
677
- ...existing,
678
- durationMs: existing.durationMs ?? 0,
679
- durationObservedAt: existing.durationObservedAt ?? this.nowMs()
680
- });
681
- this.options.store.mutate((document) => this.patchDelegation(document, event.requestId, (task, delegation) => ({
682
- ...task,
683
- status: task.status === COMPLETED_STATE ? task.status : "in_progress",
684
- delegation: {
685
- ...delegation,
686
- state: "running",
687
- startedAt: delegation.startedAt ?? this.now(),
688
- ...runId ? { runId } : {}
689
- }
690
- }))).then(() => this.options.onChange?.()).catch((error) => {
691
- this.report(TASK_EVENT.delegationStartFailed, error, {
692
- [TASK_ID_ATTRIBUTE]: taskId,
693
- [REQUEST_ID_ATTRIBUTE]: event.requestId
694
- });
695
- });
696
- }
697
- handleUpdate(event) {
698
- const existing = this.progress.get(event.requestId);
699
- if (!existing) return;
700
- const observedAt = this.nowMs();
701
- const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);
702
- const hasDuration = event.durationMs !== void 0;
703
- this.progress.set(event.requestId, {
704
- ...existing,
705
- currentTool: event.currentTool ?? existing.currentTool,
706
- toolCount: event.toolCount === void 0 ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),
707
- tokens: event.tokens === void 0 ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),
708
- durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs) : existing.durationMs,
709
- durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt
710
- });
711
- this.options.onChange?.();
712
- }
713
- async handleResponse(event) {
714
- if (!this.pendingTasks.has(event.requestId)) return;
715
- const state = event.status === COMPLETED_STATE && !event.error ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;
716
- await this.settle(event.requestId, state, {
717
- status: event.status,
718
- error: event.error,
719
- output: truncate(event.output),
720
- outputPath: event.outputPath,
721
- sessionFile: event.sessionFile,
722
- durationMs: event.durationMs,
723
- toolCount: event.toolCount
724
- });
725
- }
726
- /**
727
- * Apply the terminal state of a delegation and tell the model about it.
728
- *
729
- * A cancelled run returns the task to `pending` (the work is still wanted,
730
- * just not by that agent); a failure marks it `failed` so it stays visible
731
- * rather than silently rejoining the backlog.
732
- *
733
- * The request is claimed in `settlingRequests` while it remains published as
734
- * active work. It is removed only after the terminal state and model notification
735
- * have been handed off, so an auto-stop observer cannot end the session between
736
- * receiving the result and delivering it to the model.
737
- */
738
- async settle(requestId, state, result) {
739
- const pending = this.pendingTasks.get(requestId);
740
- if (!pending || this.settlingRequests.has(requestId)) return;
741
- this.settlingRequests.add(requestId);
742
- this.clearTimer(requestId);
743
- const { taskId } = pending;
744
- const progress = this.progress.get(requestId);
745
- try {
746
- const endedAt = this.now();
747
- let task;
748
- try {
749
- const { value } = await this.options.store.mutate((document) => this.patchDelegation(document, requestId, (current, delegation) => ({
750
- ...current,
751
- status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? "pending" : FAILED_STATE,
752
- updatedAt: endedAt,
753
- delegation: {
754
- ...delegation,
755
- state,
756
- endedAt,
757
- ...result ? { result } : {}
758
- }
759
- })));
760
- task = value;
761
- } catch (error) {
762
- this.report(TASK_EVENT.delegationSettleFailed, error, {
763
- [TASK_ID_ATTRIBUTE]: taskId,
764
- [REQUEST_ID_ATTRIBUTE]: requestId
765
- });
766
- }
767
- const agent = task?.delegation?.agent ?? progress?.agent ?? "subagent";
768
- const subject = task?.subject ?? `#${taskId}`;
769
- this.options.report?.event(TASK_EVENT.delegationCompleted, {
770
- [TASK_ID_ATTRIBUTE]: taskId,
771
- [REQUEST_ID_ATTRIBUTE]: requestId,
772
- [AGENT_ATTRIBUTE]: agent,
773
- [OUTCOME_ATTRIBUTE]: state,
774
- [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,
775
- [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,
776
- [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,
777
- ...result?.toolCount === void 0 ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount },
778
- ...result?.durationMs === void 0 ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }
779
- });
780
- const listComplete = state === COMPLETED_STATE && task !== void 0 && isTaskListComplete(this.options.store.snapshot.tasks);
781
- this.notifyModel(state, taskId, subject, agent, result, listComplete);
782
- } finally {
783
- this.pendingTasks.delete(requestId);
784
- this.progress.delete(requestId);
785
- this.settlingRequests.delete(requestId);
786
- this.options.onChange?.();
787
- }
788
- }
789
- notifyModel(state, taskId, subject, agent, result, listComplete) {
790
- const notify = this.options.notify;
791
- if (!notify) return;
792
- 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}`];
793
- if (listComplete) lines.push("", "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.");
794
- if (result?.error) lines.push(`Error: ${result.error}`);
795
- if (result?.output) lines.push("", result.output);
796
- if (result?.outputPath) lines.push("", `Full output: ${result.outputPath}`);
797
- try {
798
- notify({
799
- customType: NOTIFY_CUSTOM_TYPE,
800
- content: lines.join("\n"),
801
- display: true
802
- }, {
803
- triggerTurn: true,
804
- deliverAs: "steer"
805
- });
806
- } catch (error) {
807
- this.options.onNotifyError(error, taskId);
808
- }
809
- }
810
- /**
811
- * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.
812
- *
813
- * Terminal delegations are left alone. The document here is the freshest one,
814
- * read under the store lock, which is the only place the check is meaningful:
815
- * a `started` event can land after a cancel already settled the run, and
816
- * without this guard its write would resurrect a delegation that nothing is
817
- * tracking any more.
818
- */
819
- patchDelegation(document, requestId, patch) {
820
- const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);
821
- if (index === -1) return { value: void 0 };
822
- const task = document.tasks[index];
823
- if (!isDelegationActive(task)) return { value: task };
824
- const updated = patch(task, task.delegation);
825
- if (updated === task) return { value: task };
826
- const tasks = [...document.tasks];
827
- tasks[index] = updated;
828
- return {
829
- document: {
830
- ...document,
831
- tasks
832
- },
833
- value: updated
834
- };
835
- }
836
- dispose() {
837
- this.unbind();
838
- this.reset();
839
- }
840
- /** Clear one Pi session's transient delegation state without losing service injection. */
841
- reset() {
842
- const changed = this.pendingTasks.size > 0 || this.progress.size > 0;
843
- for (const timer of this.timers.values()) clearTimeout(timer);
844
- this.timers.clear();
845
- this.pendingTasks.clear();
846
- this.settlingRequests.clear();
847
- this.progress.clear();
848
- if (changed) this.options.onChange?.();
849
- }
850
- };
38
+ //#region src/schemas/task.ts
39
+ const TASK_ACTIONS = [
40
+ "upsert",
41
+ "list",
42
+ "get",
43
+ "delete",
44
+ "clear",
45
+ "assign",
46
+ "cancel"
47
+ ];
48
+ const TASK_STATUSES = [
49
+ "pending",
50
+ "in_progress",
51
+ "completed",
52
+ "failed",
53
+ "deleted"
54
+ ];
55
+ const TASK_CONTEXTS = ["fresh", "fork"];
56
+ /**
57
+ * A dependency target: an existing task id, or the `ref` of a task created
58
+ * earlier in the same call.
59
+ */
60
+ const DepTokenSchema = typebox.Type.Union([typebox.Type.Integer(), typebox.Type.String()]);
61
+ /**
62
+ * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
63
+ * validates tool arguments against this schema before `execute` runs, so a
64
+ * stray `{"action":"update"}` inside an entry is rejected at the boundary.
65
+ */
66
+ const TaskItemSchema = typebox.Type.Object({
67
+ id: typebox.Type.Optional(typebox.Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
68
+ ref: typebox.Type.Optional(typebox.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." })),
69
+ subject: typebox.Type.Optional(typebox.Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
70
+ description: typebox.Type.Optional(typebox.Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
71
+ activeForm: typebox.Type.Optional(typebox.Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
72
+ status: typebox.Type.Optional(typebox.Type.String({
73
+ enum: [...TASK_STATUSES],
74
+ description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
75
+ })),
76
+ blockedBy: typebox.Type.Optional(typebox.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." })),
77
+ addBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
78
+ removeBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
79
+ owner: typebox.Type.Optional(typebox.Type.String({ description: "Owner label; assign sets it to the subagent name." })),
80
+ metadata: typebox.Type.Optional(typebox.Type.Record(typebox.Type.String(), typebox.Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
81
+ }, { additionalProperties: false });
82
+ /** One task-to-agent handoff in a native assignment batch. */
83
+ const TaskAssignmentSchema = typebox.Type.Object({
84
+ id: typebox.Type.Integer({ description: "Pending, unblocked task id to delegate" }),
85
+ agent: typebox.Type.String({ description: "Exact discovered subagent name" }),
86
+ inlineAgent: typebox.Type.Optional(_agimon_ai_doompi_core_delegation.InlineAgentSchema),
87
+ instructions: typebox.Type.Optional(typebox.Type.String({ description: "Extra instructions appended to this delegated brief" })),
88
+ relevantFiles: typebox.Type.Optional(typebox.Type.Array(typebox.Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
89
+ priorFindings: typebox.Type.Optional(typebox.Type.String({ description: "Established facts this child should consume rather than re-derive" })),
90
+ model: typebox.Type.Optional(typebox.Type.String({ description: "Model override for this delegated run" })),
91
+ context: typebox.Type.Optional(typebox.Type.String({
92
+ enum: [...TASK_CONTEXTS],
93
+ description: "Starting context for this child: 'fresh' or 'fork'"
94
+ }))
95
+ }, { additionalProperties: false });
96
+ /**
97
+ * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
98
+ * wording changes here change model behaviour.
99
+ */
100
+ const TaskParamsSchema = typebox.Type.Object({
101
+ action: typebox.Type.String({ enum: [...TASK_ACTIONS] }),
102
+ tasks: typebox.Type.Optional(typebox.Type.Array(TaskItemSchema, {
103
+ minItems: 1,
104
+ 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."
105
+ })),
106
+ assignments: typebox.Type.Optional(typebox.Type.Array(TaskAssignmentSchema, {
107
+ minItems: 1,
108
+ description: "Required for assign, one entry per task, including when there is only one."
109
+ })),
110
+ id: typebox.Type.Optional(typebox.Type.Integer({ description: "Task id, for get, delete and cancel. Not accepted by upsert or assign: those carry ids inside tasks[] and assignments[] entries." })),
111
+ status: typebox.Type.Optional(typebox.Type.String({
112
+ enum: [...TASK_STATUSES],
113
+ description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
114
+ })),
115
+ includeDeleted: typebox.Type.Optional(typebox.Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
116
+ });
117
+ /** Remote MCP connections track tasks only; delegation stays with the local agent. */
118
+ const REMOTE_TASK_ACTIONS = [
119
+ "upsert",
120
+ "list",
121
+ "get",
122
+ "delete",
123
+ "clear"
124
+ ];
125
+ const { assignments: _assignments, ...remoteTaskProperties } = TaskParamsSchema.properties;
126
+ const RemoteTaskParamsSchema = typebox.Type.Object({
127
+ ...remoteTaskProperties,
128
+ action: typebox.Type.String({ enum: [...REMOTE_TASK_ACTIONS] })
129
+ });
851
130
  //#endregion
852
- //#region src/services/delegationPlatform/index.ts
853
- function formatBriefPath(entry, cwd) {
854
- if (!node_path.default.isAbsolute(entry)) return node_path.default.normalize(entry);
855
- const relative = node_path.default.relative(cwd, entry);
856
- return relative && !relative.startsWith("..") ? relative : entry;
857
- }
858
- /** Supply Node-owned process and path facilities to the host-neutral manager. */
859
- function createNodeDelegationPlatform(environment = process.env) {
860
- return {
861
- environment,
862
- processId: process.pid,
863
- createRequestId: node_crypto.randomUUID,
864
- formatBriefPath
865
- };
131
+ //#region src/services/config/index.ts
132
+ const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
133
+ /** Maximum number of non-deleted tasks retained on one board. */
134
+ function getMaxTasks(env = process.env) {
135
+ const raw = Number(env[MAX_TASKS_ENV]);
136
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
866
137
  }
867
138
  //#endregion
868
139
  //#region src/services/paths/index.ts
@@ -902,6 +173,51 @@ function tempPathFor(storePath, pid = process.pid) {
902
173
  return `${storePath}.tmp.${pid}`;
903
174
  }
904
175
  //#endregion
176
+ //#region src/models/task.ts
177
+ const DELETED_STATUS$1 = "deleted";
178
+ function emptyDocument() {
179
+ return {
180
+ version: 1,
181
+ rev: 0,
182
+ nextId: 1,
183
+ tasks: []
184
+ };
185
+ }
186
+ /**
187
+ * A delegation is "live" while the owning run may still produce a response.
188
+ *
189
+ * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
190
+ * which carries the state as a plain string, answers the question the same way
191
+ * the store does.
192
+ */
193
+ function isDelegationActive(task) {
194
+ const state = task.delegation?.state;
195
+ return state === "requested" || state === "running";
196
+ }
197
+ //#endregion
198
+ //#region src/types/telemetry.ts
199
+ const TASK_EVENT = {
200
+ notificationFailed: "doom_task.notification_failed",
201
+ storeReadFailed: "doom_task.store_read_failed",
202
+ storeLockTimeout: "doom_task.store_lock_timeout",
203
+ storeLockBreakFailed: "doom_task.store_lock_break_failed",
204
+ storeWatchFailed: "doom_task.store_watch_failed",
205
+ storeListenerFailed: "doom_task.store_listener_failed",
206
+ storeCommitListenerFailed: "doom_task.store_commit_listener_failed",
207
+ storeSweepFailed: "doom_task.store_sweep_failed",
208
+ sessionStartFailed: "doom_task.session_start_failed",
209
+ sessionStartDegraded: "doom_task.session_start_degraded",
210
+ toolFailed: "doom_task.tool_failed",
211
+ delegationRequestFailed: "doom_task.delegation_request_failed",
212
+ delegationStartFailed: "doom_task.delegation_start_failed",
213
+ delegationResponseFailed: "doom_task.delegation_response_failed",
214
+ delegationSettleFailed: "doom_task.delegation_settle_failed",
215
+ delegationTimedOut: "doom_task.delegation_timed_out",
216
+ delegationOrphaned: "doom_task.delegation_orphaned",
217
+ delegationAssigned: "doom_task.delegation_assigned",
218
+ delegationCompleted: "doom_task.delegation_completed"
219
+ };
220
+ //#endregion
905
221
  //#region src/services/invariants/index.ts
906
222
  /**
907
223
  * Collapse a malformed snapshot to one row per task id.
@@ -961,6 +277,23 @@ function isTransitionValid(from, to) {
961
277
  return VALID_TRANSITIONS[from].has(to);
962
278
  }
963
279
  //#endregion
280
+ //#region src/services/processLiveness/index.ts
281
+ /**
282
+ * Is a process still running?
283
+ *
284
+ * Signal 0 performs the permission and existence check without delivering a
285
+ * signal. EPERM means the process exists but belongs to another user, which
286
+ * still counts as alive.
287
+ */
288
+ function isProcessAlive(pid) {
289
+ try {
290
+ process.kill(pid, 0);
291
+ return true;
292
+ } catch (error) {
293
+ return error.code === "EPERM";
294
+ }
295
+ }
296
+ //#endregion
964
297
  //#region src/services/taskStore/index.ts
965
298
  const LOCK_TIMEOUT_MS = 2e3;
966
299
  const LOCK_STALE_MS = 1e4;
@@ -1164,85 +497,48 @@ var TaskStore = class {
1164
497
  }
1165
498
  };
1166
499
  //#endregion
1167
- //#region src/schemas/task.ts
1168
- const TASK_ACTIONS = [
1169
- "upsert",
1170
- "list",
1171
- "get",
1172
- "delete",
1173
- "clear",
1174
- "assign",
1175
- "cancel"
1176
- ];
1177
- const TASK_STATUSES = [
1178
- "pending",
1179
- "in_progress",
1180
- "completed",
1181
- "failed",
1182
- "deleted"
1183
- ];
1184
- const TASK_CONTEXTS = ["fresh", "fork"];
1185
- /**
1186
- * A dependency target: an existing task id, or the `ref` of a task created
1187
- * earlier in the same call.
1188
- */
1189
- const DepTokenSchema = typebox.Type.Union([typebox.Type.Integer(), typebox.Type.String()]);
1190
- /**
1191
- * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
1192
- * validates tool arguments against this schema before `execute` runs, so a
1193
- * stray `{"action":"update"}` inside an entry is rejected at the boundary.
1194
- */
1195
- const TaskItemSchema = typebox.Type.Object({
1196
- id: typebox.Type.Optional(typebox.Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
1197
- ref: typebox.Type.Optional(typebox.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." })),
1198
- subject: typebox.Type.Optional(typebox.Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
1199
- description: typebox.Type.Optional(typebox.Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
1200
- activeForm: typebox.Type.Optional(typebox.Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
1201
- status: typebox.Type.Optional(typebox.Type.String({
1202
- enum: [...TASK_STATUSES],
1203
- description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
1204
- })),
1205
- blockedBy: typebox.Type.Optional(typebox.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." })),
1206
- addBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
1207
- removeBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
1208
- owner: typebox.Type.Optional(typebox.Type.String({ description: "Owner label; assign sets it to the subagent name." })),
1209
- metadata: typebox.Type.Optional(typebox.Type.Record(typebox.Type.String(), typebox.Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
1210
- }, { additionalProperties: false });
1211
- /** One task-to-agent handoff in a native assignment batch. */
1212
- const TaskAssignmentSchema = typebox.Type.Object({
1213
- id: typebox.Type.Integer({ description: "Pending, unblocked task id to delegate" }),
1214
- agent: typebox.Type.String({ description: "Exact discovered subagent name" }),
1215
- inlineAgent: typebox.Type.Optional(_agimon_ai_doompi_core_delegation.InlineAgentSchema),
1216
- instructions: typebox.Type.Optional(typebox.Type.String({ description: "Extra instructions appended to this delegated brief" })),
1217
- relevantFiles: typebox.Type.Optional(typebox.Type.Array(typebox.Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
1218
- priorFindings: typebox.Type.Optional(typebox.Type.String({ description: "Established facts this child should consume rather than re-derive" })),
1219
- model: typebox.Type.Optional(typebox.Type.String({ description: "Model override for this delegated run" })),
1220
- context: typebox.Type.Optional(typebox.Type.String({
1221
- enum: [...TASK_CONTEXTS],
1222
- description: "Starting context for this child: 'fresh' or 'fork'"
1223
- }))
1224
- }, { additionalProperties: false });
500
+ //#region src/models/taskGraph.ts
501
+ const COMPLETED_STATUS = "completed";
502
+ const DELETED_STATUS = "deleted";
503
+ /** True when a non-empty list has no visible work left to finish. */
504
+ function isTaskListComplete(taskList) {
505
+ const visible = taskList.filter((task) => task.status !== DELETED_STATUS);
506
+ return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
507
+ }
1225
508
  /**
1226
- * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
1227
- * wording changes here change model behaviour.
509
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
510
+ *
511
+ * Takes the proposed additions explicitly so the reducer can ask the question
512
+ * before mutating anything.
1228
513
  */
1229
- const TaskParamsSchema = typebox.Type.Object({
1230
- action: typebox.Type.String({ enum: [...TASK_ACTIONS] }),
1231
- tasks: typebox.Type.Optional(typebox.Type.Array(TaskItemSchema, {
1232
- minItems: 1,
1233
- 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."
1234
- })),
1235
- assignments: typebox.Type.Optional(typebox.Type.Array(TaskAssignmentSchema, {
1236
- minItems: 1,
1237
- description: "Required for assign, one entry per task, including when there is only one."
1238
- })),
1239
- id: typebox.Type.Optional(typebox.Type.Integer({ description: "Task id, for get, delete and cancel. Not accepted by upsert or assign: those carry ids inside tasks[] and assignments[] entries." })),
1240
- status: typebox.Type.Optional(typebox.Type.String({
1241
- enum: [...TASK_STATUSES],
1242
- description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
1243
- })),
1244
- includeDeleted: typebox.Type.Optional(typebox.Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
1245
- });
514
+ function detectCycle(taskList, taskId, newBlockedBy) {
515
+ const edges = /* @__PURE__ */ new Map();
516
+ for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
517
+ else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
518
+ const visiting = /* @__PURE__ */ new Set();
519
+ const visited = /* @__PURE__ */ new Set();
520
+ const hasCycleFrom = (node) => {
521
+ if (visiting.has(node)) return true;
522
+ if (visited.has(node)) return false;
523
+ visiting.add(node);
524
+ for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
525
+ visiting.delete(node);
526
+ visited.add(node);
527
+ return false;
528
+ };
529
+ for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
530
+ return false;
531
+ }
532
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
533
+ function deriveBlocks(taskList) {
534
+ const blocks = /* @__PURE__ */ new Map();
535
+ for (const task of taskList) for (const dep of task.blockedBy ?? []) {
536
+ const dependents = blocks.get(dep) ?? [];
537
+ dependents.push(task.id);
538
+ blocks.set(dep, dependents);
539
+ }
540
+ return blocks;
541
+ }
1246
542
  //#endregion
1247
543
  //#region src/services/reducer/index.ts
1248
544
  /** Default board capacity when a caller does not provide a configured limit. */
@@ -1793,6 +1089,7 @@ function createHeadlessTaskTool(store, manager, maxTasks) {
1793
1089
  if (!(0, typebox_value.Check)(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
1794
1090
  const params = rawParams;
1795
1091
  try {
1092
+ if ((params.action === "assign" || params.action === "cancel") && !manager) throw new Error("Delegation is not available on this connection.");
1796
1093
  if (params.action === "assign") {
1797
1094
  if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
1798
1095
  onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
@@ -1825,25 +1122,14 @@ var task_mcp_default = (0, _agimon_ai_doompi_core_mcpFacet.defineMcpTool)(({ exe
1825
1122
  env: execution.environment
1826
1123
  });
1827
1124
  store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));
1828
- const manager = new DelegationManager({
1829
- store,
1830
- cwd: execution.cwd,
1831
- platform: createNodeDelegationPlatform(execution.environment),
1832
- getSessionId: () => execution.sessionId,
1833
- runTimeoutMs: getDelegationTimeoutMs(execution.environment),
1834
- onNotifyError: (error) => void execution.client.notify({
1835
- body: String(error),
1836
- level: "warning"
1837
- })
1838
- });
1839
- const tool = createHeadlessTaskTool(store, manager, getMaxTasks(execution.environment));
1125
+ const tool = createHeadlessTaskTool(store, void 0, getMaxTasks(execution.environment));
1840
1126
  let initialized;
1841
1127
  return {
1842
1128
  ...tool,
1129
+ parameters: RemoteTaskParamsSchema,
1130
+ 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.",
1843
1131
  async execute(...args) {
1844
- initialized ??= store.readAsync().then(async () => {
1845
- await manager.reconcile();
1846
- });
1132
+ initialized ??= store.readAsync().then(() => void 0);
1847
1133
  await initialized;
1848
1134
  return tool.execute(...args);
1849
1135
  }