@agimon-ai/po-task 0.0.0-alpha.0

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 (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/dist/apiContracts.cjs +54 -0
  4. package/dist/apiContracts.cjs.map +1 -0
  5. package/dist/apiContracts.d.mts +53 -0
  6. package/dist/apiContracts.d.mts.map +1 -0
  7. package/dist/apiContracts.mjs +49 -0
  8. package/dist/apiContracts.mjs.map +1 -0
  9. package/dist/config-CFSs3iku.mjs +72 -0
  10. package/dist/config-CFSs3iku.mjs.map +1 -0
  11. package/dist/config-CdX-Bv8q.cjs +173 -0
  12. package/dist/config-CdX-Bv8q.cjs.map +1 -0
  13. package/dist/config.cjs +19 -0
  14. package/dist/config.d.mts +2 -0
  15. package/dist/config.mjs +2 -0
  16. package/dist/delegation-BiOy3_7g.mjs +7 -0
  17. package/dist/delegation-BiOy3_7g.mjs.map +1 -0
  18. package/dist/delegation-CdMqOZB4.mjs +626 -0
  19. package/dist/delegation-CdMqOZB4.mjs.map +1 -0
  20. package/dist/delegation-DsnKjMbJ.cjs +661 -0
  21. package/dist/delegation-DsnKjMbJ.cjs.map +1 -0
  22. package/dist/delegation-LDpHP2CC.cjs +12 -0
  23. package/dist/delegation-LDpHP2CC.cjs.map +1 -0
  24. package/dist/delegationManager.cjs +10 -0
  25. package/dist/delegationManager.d.mts +2 -0
  26. package/dist/delegationManager.mjs +3 -0
  27. package/dist/extensions/mcp-ui.mjs +23 -0
  28. package/dist/extensions/mcp-ui.mjs.map +1 -0
  29. package/dist/extensions/mcp.cjs +1144 -0
  30. package/dist/extensions/mcp.cjs.map +1 -0
  31. package/dist/extensions/mcp.d.mts +5 -0
  32. package/dist/extensions/mcp.d.mts.map +1 -0
  33. package/dist/extensions/mcp.mjs +1115 -0
  34. package/dist/extensions/mcp.mjs.map +1 -0
  35. package/dist/extensions/native.mjs +1175 -0
  36. package/dist/extensions/native.mjs.map +1 -0
  37. package/dist/extensions/server.cjs +569 -0
  38. package/dist/extensions/server.cjs.map +1 -0
  39. package/dist/extensions/server.d.mts +5 -0
  40. package/dist/extensions/server.d.mts.map +1 -0
  41. package/dist/extensions/server.mjs +563 -0
  42. package/dist/extensions/server.mjs.map +1 -0
  43. package/dist/extensions/web.mjs +1018 -0
  44. package/dist/extensions/web.mjs.map +1 -0
  45. package/dist/index-B-3sCF2S.d.mts +43 -0
  46. package/dist/index-B-3sCF2S.d.mts.map +1 -0
  47. package/dist/index-B1JPJdpZ.d.mts +51 -0
  48. package/dist/index-B1JPJdpZ.d.mts.map +1 -0
  49. package/dist/index-CUWCvh-E.d.mts +72 -0
  50. package/dist/index-CUWCvh-E.d.mts.map +1 -0
  51. package/dist/index-DlmXKyhQ.d.mts +34 -0
  52. package/dist/index-DlmXKyhQ.d.mts.map +1 -0
  53. package/dist/index-Dvb8X_qB.d.mts +67 -0
  54. package/dist/index-Dvb8X_qB.d.mts.map +1 -0
  55. package/dist/index-XY9VPmfm.d.mts +26 -0
  56. package/dist/index-XY9VPmfm.d.mts.map +1 -0
  57. package/dist/index-teIf67qQ.d.mts +196 -0
  58. package/dist/index-teIf67qQ.d.mts.map +1 -0
  59. package/dist/index.cjs +93 -0
  60. package/dist/index.d.mts +11 -0
  61. package/dist/index.mjs +12 -0
  62. package/dist/invariants-DhjEjBPU.cjs +79 -0
  63. package/dist/invariants-DhjEjBPU.cjs.map +1 -0
  64. package/dist/invariants-q_UamF7D.mjs +62 -0
  65. package/dist/invariants-q_UamF7D.mjs.map +1 -0
  66. package/dist/logSinkTelemetry-B23qGiP-.cjs +52 -0
  67. package/dist/logSinkTelemetry-B23qGiP-.cjs.map +1 -0
  68. package/dist/logSinkTelemetry-BMBsC54p.mjs +41 -0
  69. package/dist/logSinkTelemetry-BMBsC54p.mjs.map +1 -0
  70. package/dist/logSinkTelemetry.cjs +6 -0
  71. package/dist/logSinkTelemetry.d.mts +23 -0
  72. package/dist/logSinkTelemetry.d.mts.map +1 -0
  73. package/dist/logSinkTelemetry.mjs +3 -0
  74. package/dist/paths-CSya2l9_.cjs +308 -0
  75. package/dist/paths-CSya2l9_.cjs.map +1 -0
  76. package/dist/paths-Cah1vFGv.mjs +207 -0
  77. package/dist/paths-Cah1vFGv.mjs.map +1 -0
  78. package/dist/processLiveness-Ccd9wenT.mjs +20 -0
  79. package/dist/processLiveness-Ccd9wenT.mjs.map +1 -0
  80. package/dist/processLiveness-umpNgsPR.cjs +25 -0
  81. package/dist/processLiveness-umpNgsPR.cjs.map +1 -0
  82. package/dist/reconcile-BcD-hTbd.mjs +63 -0
  83. package/dist/reconcile-BcD-hTbd.mjs.map +1 -0
  84. package/dist/reconcile-cRL0NjDr.cjs +80 -0
  85. package/dist/reconcile-cRL0NjDr.cjs.map +1 -0
  86. package/dist/reducer-BEfJFM5L.mjs +345 -0
  87. package/dist/reducer-BEfJFM5L.mjs.map +1 -0
  88. package/dist/reducer-BV0YIZ2o.cjs +380 -0
  89. package/dist/reducer-BV0YIZ2o.cjs.map +1 -0
  90. package/dist/storeInvariants.cjs +5 -0
  91. package/dist/storeInvariants.d.mts +23 -0
  92. package/dist/storeInvariants.d.mts.map +1 -0
  93. package/dist/storeInvariants.mjs +2 -0
  94. package/dist/storePaths.cjs +14 -0
  95. package/dist/storePaths.d.mts +2 -0
  96. package/dist/storePaths.mjs +2 -0
  97. package/dist/storeProcessLiveness.cjs +3 -0
  98. package/dist/storeProcessLiveness.d.mts +11 -0
  99. package/dist/storeProcessLiveness.d.mts.map +1 -0
  100. package/dist/storeProcessLiveness.mjs +2 -0
  101. package/dist/storeReconcile.cjs +5 -0
  102. package/dist/storeReconcile.d.mts +2 -0
  103. package/dist/storeReconcile.mjs +2 -0
  104. package/dist/storeReducer.cjs +8 -0
  105. package/dist/storeReducer.d.mts +2 -0
  106. package/dist/storeReducer.mjs +2 -0
  107. package/dist/storeTaskGraph.cjs +7 -0
  108. package/dist/storeTaskGraph.d.mts +2 -0
  109. package/dist/storeTaskGraph.mjs +2 -0
  110. package/dist/storeTaskStore.cjs +3 -0
  111. package/dist/storeTaskStore.d.mts +2 -0
  112. package/dist/storeTaskStore.mjs +2 -0
  113. package/dist/storeTypes.cjs +6 -0
  114. package/dist/storeTypes.d.mts +2 -0
  115. package/dist/storeTypes.mjs +2 -0
  116. package/dist/task-CXF9VULl.cjs +49 -0
  117. package/dist/task-CXF9VULl.cjs.map +1 -0
  118. package/dist/task-DJpTteeJ.d.mts +187 -0
  119. package/dist/task-DJpTteeJ.d.mts.map +1 -0
  120. package/dist/task-DO0TwZ0z.mjs +132 -0
  121. package/dist/task-DO0TwZ0z.mjs.map +1 -0
  122. package/dist/task-Dhta7JyA.d.mts +126 -0
  123. package/dist/task-Dhta7JyA.d.mts.map +1 -0
  124. package/dist/task-UvW877Ez.cjs +227 -0
  125. package/dist/task-UvW877Ez.cjs.map +1 -0
  126. package/dist/task-giCbpKzV.mjs +26 -0
  127. package/dist/task-giCbpKzV.mjs.map +1 -0
  128. package/dist/taskGraph-BOQvT0-M.mjs +63 -0
  129. package/dist/taskGraph-BOQvT0-M.mjs.map +1 -0
  130. package/dist/taskGraph-BskRslrr.cjs +92 -0
  131. package/dist/taskGraph-BskRslrr.cjs.map +1 -0
  132. package/dist/taskGraph-D0zFHF2p.d.mts +25 -0
  133. package/dist/taskGraph-D0zFHF2p.d.mts.map +1 -0
  134. package/dist/taskResult-D2G7b4w-.cjs +224 -0
  135. package/dist/taskResult-D2G7b4w-.cjs.map +1 -0
  136. package/dist/taskResult-edBAAKSH.mjs +165 -0
  137. package/dist/taskResult-edBAAKSH.mjs.map +1 -0
  138. package/dist/taskStore-DjU60rMm.cjs +215 -0
  139. package/dist/taskStore-DjU60rMm.cjs.map +1 -0
  140. package/dist/taskStore-pAJ971Ml.mjs +208 -0
  141. package/dist/taskStore-pAJ971Ml.mjs.map +1 -0
  142. package/dist/telemetry-Ca0I3Tqo.cjs +30 -0
  143. package/dist/telemetry-Ca0I3Tqo.cjs.map +1 -0
  144. package/dist/telemetry-DyS44zAD.mjs +25 -0
  145. package/dist/telemetry-DyS44zAD.mjs.map +1 -0
  146. package/dist/telemetry-FMGRovb4.d.mts +35 -0
  147. package/dist/telemetry-FMGRovb4.d.mts.map +1 -0
  148. package/dist/toolPromptGuidelines.cjs +27 -0
  149. package/dist/toolPromptGuidelines.cjs.map +1 -0
  150. package/dist/toolPromptGuidelines.d.mts +13 -0
  151. package/dist/toolPromptGuidelines.d.mts.map +1 -0
  152. package/dist/toolPromptGuidelines.mjs +26 -0
  153. package/dist/toolPromptGuidelines.mjs.map +1 -0
  154. package/dist/toolResponseEnvelope.cjs +12 -0
  155. package/dist/toolResponseEnvelope.d.mts +2 -0
  156. package/dist/toolResponseEnvelope.mjs +2 -0
  157. package/dist/toolSchema.cjs +18 -0
  158. package/dist/toolSchema.d.mts +2 -0
  159. package/dist/toolSchema.mjs +2 -0
  160. package/package.json +223 -0
  161. package/src/types/webTasks.ts +24 -0
@@ -0,0 +1,1144 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let _agimon_ai_po_core_mcpFacet = require("@agimon-ai/po-core/mcpFacet");
28
+ let _agimon_ai_po_core_delegation = require("@agimon-ai/po-core/delegation");
29
+ let typebox = require("typebox");
30
+ let node_fs = require("node:fs");
31
+ node_fs = __toESM(node_fs, 1);
32
+ let node_path = require("node:path");
33
+ node_path = __toESM(node_path, 1);
34
+ let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
35
+ let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
36
+ let typebox_value = require("typebox/value");
37
+ //#region src/schemas/task.ts
38
+ const TASK_ACTIONS = [
39
+ "upsert",
40
+ "list",
41
+ "get",
42
+ "delete",
43
+ "clear",
44
+ "assign",
45
+ "cancel"
46
+ ];
47
+ const TASK_STATUSES = [
48
+ "pending",
49
+ "in_progress",
50
+ "completed",
51
+ "failed",
52
+ "deleted"
53
+ ];
54
+ const TASK_CONTEXTS = ["fresh", "fork"];
55
+ /**
56
+ * A dependency target: an existing task id, or the `ref` of a task created
57
+ * earlier in the same call.
58
+ */
59
+ const DepTokenSchema = typebox.Type.Union([typebox.Type.Integer(), typebox.Type.String()]);
60
+ /**
61
+ * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
62
+ * validates tool arguments against this schema before `execute` runs, so a
63
+ * stray `{"action":"update"}` inside an entry is rejected at the boundary.
64
+ */
65
+ const TaskItemSchema = typebox.Type.Object({
66
+ 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." })),
67
+ 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." })),
68
+ 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." })),
69
+ description: typebox.Type.Optional(typebox.Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
70
+ activeForm: typebox.Type.Optional(typebox.Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
71
+ status: typebox.Type.Optional(typebox.Type.String({
72
+ enum: [...TASK_STATUSES],
73
+ description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
74
+ })),
75
+ 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." })),
76
+ addBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
77
+ removeBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
78
+ owner: typebox.Type.Optional(typebox.Type.String({ description: "Owner label; assign sets it to the subagent name." })),
79
+ metadata: typebox.Type.Optional(typebox.Type.Record(typebox.Type.String(), typebox.Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
80
+ }, { additionalProperties: false });
81
+ /** One task-to-agent handoff in a native assignment batch. */
82
+ const TaskAssignmentSchema = typebox.Type.Object({
83
+ id: typebox.Type.Integer({ description: "Pending, unblocked task id to delegate" }),
84
+ agent: typebox.Type.String({ description: "Exact discovered subagent name" }),
85
+ inlineAgent: typebox.Type.Optional(_agimon_ai_po_core_delegation.InlineAgentSchema),
86
+ instructions: typebox.Type.Optional(typebox.Type.String({ description: "Extra instructions appended to this delegated brief" })),
87
+ 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.` })),
88
+ priorFindings: typebox.Type.Optional(typebox.Type.String({ description: "Established facts this child should consume rather than re-derive" })),
89
+ model: typebox.Type.Optional(typebox.Type.String({ description: "Model override for this delegated run" })),
90
+ context: typebox.Type.Optional(typebox.Type.String({
91
+ enum: [...TASK_CONTEXTS],
92
+ description: "Starting context for this child: 'fresh' or 'fork'"
93
+ }))
94
+ }, { additionalProperties: false });
95
+ /**
96
+ * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
97
+ * wording changes here change model behaviour.
98
+ */
99
+ const TaskParamsSchema = typebox.Type.Object({
100
+ action: typebox.Type.String({ enum: [...TASK_ACTIONS] }),
101
+ tasks: typebox.Type.Optional(typebox.Type.Array(TaskItemSchema, {
102
+ minItems: 1,
103
+ 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."
104
+ })),
105
+ assignments: typebox.Type.Optional(typebox.Type.Array(TaskAssignmentSchema, {
106
+ minItems: 1,
107
+ description: "Required for assign, one entry per task, including when there is only one."
108
+ })),
109
+ 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." })),
110
+ status: typebox.Type.Optional(typebox.Type.String({
111
+ enum: [...TASK_STATUSES],
112
+ description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
113
+ })),
114
+ includeDeleted: typebox.Type.Optional(typebox.Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
115
+ });
116
+ /** Remote MCP connections track tasks only; delegation stays with the local agent. */
117
+ const REMOTE_TASK_ACTIONS = [
118
+ "upsert",
119
+ "list",
120
+ "get",
121
+ "delete",
122
+ "clear"
123
+ ];
124
+ const { assignments: _assignments, ...remoteTaskProperties } = TaskParamsSchema.properties;
125
+ const RemoteTaskParamsSchema = typebox.Type.Object({
126
+ ...remoteTaskProperties,
127
+ action: typebox.Type.String({ enum: [...REMOTE_TASK_ACTIONS] })
128
+ });
129
+ //#endregion
130
+ //#region src/services/config/index.ts
131
+ const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
132
+ /** Maximum number of non-deleted tasks retained on one board. */
133
+ function getMaxTasks(env = process.env) {
134
+ const raw = Number(env[MAX_TASKS_ENV]);
135
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
136
+ }
137
+ //#endregion
138
+ //#region src/services/paths/index.ts
139
+ const STORE_PATH_ENV = "DOOM_TASK_STORE";
140
+ const STORE_DIR_NAME = "doom-task";
141
+ const STORE_FILE_NAME = "tasks.json";
142
+ /** Resolve the tree root without relying on extension startup order. */
143
+ function resolveSessionKey(rootSessionId, env = process.env) {
144
+ if (!env[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) return rootSessionId;
145
+ const parentSessionId = env[_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV]?.trim();
146
+ if (!parentSessionId) throw new Error(`${_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);
147
+ return parentSessionId;
148
+ }
149
+ /** Resolve one root session tree to a task document under the Pi agent directory. */
150
+ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey = "standalone") {
151
+ const override = env[STORE_PATH_ENV]?.trim();
152
+ if (override) return node_path.default.resolve(override);
153
+ const trimmedSessionKey = sessionKey.trim();
154
+ if (!trimmedSessionKey) throw new Error("doom-task session id cannot be blank");
155
+ return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
156
+ }
157
+ function lockPathFor(storePath) {
158
+ return `${storePath}.lock`;
159
+ }
160
+ function tempPathFor(storePath, pid = process.pid) {
161
+ return `${storePath}.tmp.${pid}`;
162
+ }
163
+ //#endregion
164
+ //#region src/models/task.ts
165
+ const DELETED_STATUS$1 = "deleted";
166
+ function emptyDocument() {
167
+ return {
168
+ version: 1,
169
+ rev: 0,
170
+ nextId: 1,
171
+ tasks: []
172
+ };
173
+ }
174
+ /**
175
+ * A delegation is "live" while the owning run may still produce a response.
176
+ *
177
+ * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
178
+ * which carries the state as a plain string, answers the question the same way
179
+ * the store does.
180
+ */
181
+ function isDelegationActive(task) {
182
+ const state = task.delegation?.state;
183
+ return state === "requested" || state === "running";
184
+ }
185
+ //#endregion
186
+ //#region src/types/telemetry.ts
187
+ const TASK_EVENT = {
188
+ notificationFailed: "doom_task.notification_failed",
189
+ storeReadFailed: "doom_task.store_read_failed",
190
+ storeLockTimeout: "doom_task.store_lock_timeout",
191
+ storeLockBreakFailed: "doom_task.store_lock_break_failed",
192
+ storeWatchFailed: "doom_task.store_watch_failed",
193
+ storeListenerFailed: "doom_task.store_listener_failed",
194
+ storeSweepFailed: "doom_task.store_sweep_failed",
195
+ sessionStartFailed: "doom_task.session_start_failed",
196
+ sessionStartDegraded: "doom_task.session_start_degraded",
197
+ toolFailed: "doom_task.tool_failed",
198
+ delegationRequestFailed: "doom_task.delegation_request_failed",
199
+ delegationStartFailed: "doom_task.delegation_start_failed",
200
+ delegationResponseFailed: "doom_task.delegation_response_failed",
201
+ delegationSettleFailed: "doom_task.delegation_settle_failed",
202
+ delegationTimedOut: "doom_task.delegation_timed_out",
203
+ delegationOrphaned: "doom_task.delegation_orphaned",
204
+ delegationAssigned: "doom_task.delegation_assigned",
205
+ delegationCompleted: "doom_task.delegation_completed"
206
+ };
207
+ //#endregion
208
+ //#region src/services/invariants/index.ts
209
+ /**
210
+ * Collapse a malformed snapshot to one row per task id.
211
+ *
212
+ * Normal writes replace tasks in place, but older or externally edited stores
213
+ * can contain both a stale and a current copy. Prefer the copy with the newest
214
+ * ISO update timestamp; equal or missing timestamps use the later array entry.
215
+ * The winning row keeps the id's original position so repair does not reorder
216
+ * an otherwise stable task list.
217
+ */
218
+ function canonicalizeTasks(tasks) {
219
+ const canonical = [];
220
+ const indexById = /* @__PURE__ */ new Map();
221
+ for (const task of tasks) {
222
+ const existingIndex = indexById.get(task.id);
223
+ if (existingIndex === void 0) {
224
+ indexById.set(task.id, canonical.length);
225
+ canonical.push(task);
226
+ continue;
227
+ }
228
+ const existing = canonical[existingIndex];
229
+ if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) canonical[existingIndex] = task;
230
+ }
231
+ return canonical;
232
+ }
233
+ /**
234
+ * Allowed forward transitions per source status.
235
+ *
236
+ * `failed` is recoverable (a delegation can be retried) so it may return to
237
+ * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a
238
+ * terminal tombstone.
239
+ */
240
+ const VALID_TRANSITIONS = {
241
+ pending: /* @__PURE__ */ new Set([
242
+ "in_progress",
243
+ "completed",
244
+ "failed",
245
+ "deleted"
246
+ ]),
247
+ in_progress: /* @__PURE__ */ new Set([
248
+ "pending",
249
+ "completed",
250
+ "failed",
251
+ "deleted"
252
+ ]),
253
+ failed: /* @__PURE__ */ new Set([
254
+ "pending",
255
+ "in_progress",
256
+ "completed",
257
+ "deleted"
258
+ ]),
259
+ completed: /* @__PURE__ */ new Set(["deleted"]),
260
+ deleted: /* @__PURE__ */ new Set()
261
+ };
262
+ function isTransitionValid(from, to) {
263
+ if (from === to) return true;
264
+ return VALID_TRANSITIONS[from].has(to);
265
+ }
266
+ //#endregion
267
+ //#region src/services/processLiveness/index.ts
268
+ /**
269
+ * Is a process still running?
270
+ *
271
+ * Signal 0 performs the permission and existence check without delivering a
272
+ * signal. EPERM means the process exists but belongs to another user, which
273
+ * still counts as alive.
274
+ */
275
+ function isProcessAlive(pid) {
276
+ try {
277
+ process.kill(pid, 0);
278
+ return true;
279
+ } catch (error) {
280
+ return error.code === "EPERM";
281
+ }
282
+ }
283
+ //#endregion
284
+ //#region src/services/taskStore/index.ts
285
+ const LOCK_TIMEOUT_MS = 2e3;
286
+ const LOCK_STALE_MS = 1e4;
287
+ const LOCK_RETRY_BASE_MS = 10;
288
+ const LOCK_RETRY_MAX_MS = 60;
289
+ const UTF8_ENCODING = "utf8";
290
+ const MISSING_FILE_CODE = "ENOENT";
291
+ const LOCK_EXISTS_CODE = "EEXIST";
292
+ const STORE_PATH_ATTRIBUTE = "store.path";
293
+ function sleep(ms) {
294
+ return new Promise((resolve) => setTimeout(resolve, ms));
295
+ }
296
+ /**
297
+ * Coerce arbitrary parsed JSON into a valid document.
298
+ *
299
+ * A corrupt or truncated store must not take the session down: the worst
300
+ * acceptable outcome is starting from an empty list, never a crash on startup.
301
+ */
302
+ function normalizeDocument(parsed) {
303
+ if (!parsed || typeof parsed !== "object") return emptyDocument();
304
+ const candidate = parsed;
305
+ if (!Array.isArray(candidate.tasks)) return emptyDocument();
306
+ const tasks = canonicalizeTasks(candidate.tasks.filter((task) => Boolean(task) && typeof task === "object" && typeof task.id === "number"));
307
+ const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);
308
+ return {
309
+ version: typeof candidate.version === "number" ? candidate.version : 1,
310
+ rev: typeof candidate.rev === "number" ? candidate.rev : 0,
311
+ nextId: typeof candidate.nextId === "number" && candidate.nextId > maxId ? candidate.nextId : maxId + 1,
312
+ tasks
313
+ };
314
+ }
315
+ /**
316
+ * File-backed task store shared by one root session and its delegated children.
317
+ *
318
+ * Durability model: the JSON file is the source of truth. Mutations are
319
+ * read-modify-write under an advisory lock so concurrent delegated processes
320
+ * cannot clobber each other, and writes land via temp-file rename so a
321
+ * crash mid-write can never leave a partial document behind.
322
+ */
323
+ var TaskStore = class {
324
+ storePath;
325
+ cwd;
326
+ env;
327
+ cached = emptyDocument();
328
+ listeners = /* @__PURE__ */ new Set();
329
+ lockTimeoutMs;
330
+ report;
331
+ constructor(options = {}) {
332
+ this.cwd = options.cwd ?? process.cwd();
333
+ this.env = options.env ?? process.env;
334
+ this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);
335
+ this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;
336
+ this.report = options.report;
337
+ }
338
+ /** Bind a default store to the current session tree before reading it. */
339
+ configureSession(sessionKey) {
340
+ if (this.env["DOOM_TASK_STORE"]?.trim()) return;
341
+ this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);
342
+ this.cached = emptyDocument();
343
+ }
344
+ /** Last document read from disk, without hitting the filesystem. */
345
+ get snapshot() {
346
+ return this.cached;
347
+ }
348
+ read() {
349
+ try {
350
+ const raw = node_fs.default.readFileSync(this.storePath, UTF8_ENCODING);
351
+ this.cached = normalizeDocument(JSON.parse(raw));
352
+ } catch (error) {
353
+ if (error.code !== MISSING_FILE_CODE) this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
354
+ this.cached = emptyDocument();
355
+ }
356
+ return this.cached;
357
+ }
358
+ async readAsync(shouldApply = () => true, onReadError) {
359
+ const storePath = this.storePath;
360
+ const document = await this.readDocumentAsync(storePath, onReadError);
361
+ if (!shouldApply()) return document;
362
+ this.cached = document;
363
+ return document;
364
+ }
365
+ async readDocumentAsync(storePath = this.storePath, onReadError) {
366
+ try {
367
+ const raw = await node_fs.default.promises.readFile(storePath, UTF8_ENCODING);
368
+ return normalizeDocument(JSON.parse(raw));
369
+ } catch (error) {
370
+ if (error.code !== MISSING_FILE_CODE) {
371
+ this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });
372
+ try {
373
+ onReadError?.(error);
374
+ } catch {}
375
+ }
376
+ return emptyDocument();
377
+ }
378
+ }
379
+ /**
380
+ * Apply a mutation under the store lock.
381
+ *
382
+ * `mutate` receives the freshest on-disk document and returns either the next
383
+ * document to commit or `undefined` for a read-only action (list/get), which
384
+ * skips the write entirely so queries never bump `rev`.
385
+ */
386
+ async mutate(mutate) {
387
+ const release = await this.acquireLock();
388
+ const outcome = (() => {
389
+ try {
390
+ const current = this.read();
391
+ const mutation = mutate(current);
392
+ if (!mutation.document) return { result: {
393
+ document: current,
394
+ value: mutation.value
395
+ } };
396
+ const committed = this.write(mutation.document);
397
+ return {
398
+ result: {
399
+ document: committed,
400
+ value: mutation.value
401
+ },
402
+ notification: committed
403
+ };
404
+ } finally {
405
+ release();
406
+ }
407
+ })();
408
+ if (outcome.notification) this.notifyCommitted(outcome.notification);
409
+ return outcome.result;
410
+ }
411
+ notifyCommitted(committed) {
412
+ for (const listener of this.listeners) try {
413
+ listener(committed);
414
+ } catch (error) {
415
+ this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
416
+ }
417
+ }
418
+ write(document) {
419
+ const next = {
420
+ ...document,
421
+ version: 1,
422
+ rev: document.rev + 1
423
+ };
424
+ node_fs.default.mkdirSync(node_path.default.dirname(this.storePath), { recursive: true });
425
+ const temp = tempPathFor(this.storePath);
426
+ node_fs.default.writeFileSync(temp, `${JSON.stringify(next, void 0, 2)}\n`, UTF8_ENCODING);
427
+ node_fs.default.renameSync(temp, this.storePath);
428
+ this.cached = next;
429
+ return next;
430
+ }
431
+ async acquireLock() {
432
+ const lockPath = lockPathFor(this.storePath);
433
+ node_fs.default.mkdirSync(node_path.default.dirname(this.storePath), { recursive: true });
434
+ const deadline = Date.now() + this.lockTimeoutMs;
435
+ for (;;) try {
436
+ const handle = node_fs.default.openSync(lockPath, "wx");
437
+ node_fs.default.writeSync(handle, JSON.stringify({
438
+ pid: process.pid,
439
+ time: Date.now()
440
+ }));
441
+ node_fs.default.closeSync(handle);
442
+ return () => node_fs.default.rmSync(lockPath, { force: true });
443
+ } catch (error) {
444
+ if (error.code !== LOCK_EXISTS_CODE) throw error;
445
+ if (Date.now() >= deadline) {
446
+ this.report?.warn(TASK_EVENT.storeLockTimeout, /* @__PURE__ */ new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`), { [STORE_PATH_ATTRIBUTE]: this.storePath });
447
+ return () => {};
448
+ }
449
+ this.breakStaleLock(lockPath);
450
+ await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);
451
+ }
452
+ }
453
+ /** Remove a lock left behind by a dead process or one held implausibly long. */
454
+ breakStaleLock(lockPath) {
455
+ try {
456
+ const holder = JSON.parse(node_fs.default.readFileSync(lockPath, UTF8_ENCODING));
457
+ const expired = typeof holder.time === "number" && Date.now() - holder.time > LOCK_STALE_MS;
458
+ const dead = typeof holder.pid === "number" && !isProcessAlive(holder.pid);
459
+ if (!expired && !dead) return false;
460
+ node_fs.default.unlinkSync(lockPath);
461
+ return true;
462
+ } catch (error) {
463
+ if (error.code !== MISSING_FILE_CODE) this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });
464
+ return false;
465
+ }
466
+ }
467
+ /**
468
+ * Listen for commits made through this store instance.
469
+ *
470
+ * Live cross-process updates use the owning session's direct event bus. This
471
+ * listener publishes local commits to that bus and never watches the filesystem.
472
+ */
473
+ onExternalChange(listener) {
474
+ this.listeners.add(listener);
475
+ return () => this.listeners.delete(listener);
476
+ }
477
+ dispose() {
478
+ this.listeners.clear();
479
+ }
480
+ };
481
+ //#endregion
482
+ //#region src/models/taskGraph.ts
483
+ const COMPLETED_STATUS = "completed";
484
+ const DELETED_STATUS = "deleted";
485
+ /** True when a non-empty list has no visible work left to finish. */
486
+ function isTaskListComplete(taskList) {
487
+ const visible = taskList.filter((task) => task.status !== DELETED_STATUS);
488
+ return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
489
+ }
490
+ /**
491
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
492
+ *
493
+ * Takes the proposed additions explicitly so the reducer can ask the question
494
+ * before mutating anything.
495
+ */
496
+ function detectCycle(taskList, taskId, newBlockedBy) {
497
+ const edges = /* @__PURE__ */ new Map();
498
+ for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
499
+ else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
500
+ const visiting = /* @__PURE__ */ new Set();
501
+ const visited = /* @__PURE__ */ new Set();
502
+ const hasCycleFrom = (node) => {
503
+ if (visiting.has(node)) return true;
504
+ if (visited.has(node)) return false;
505
+ visiting.add(node);
506
+ for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
507
+ visiting.delete(node);
508
+ visited.add(node);
509
+ return false;
510
+ };
511
+ for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
512
+ return false;
513
+ }
514
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
515
+ function deriveBlocks(taskList) {
516
+ const blocks = /* @__PURE__ */ new Map();
517
+ for (const task of taskList) for (const dep of task.blockedBy ?? []) {
518
+ const dependents = blocks.get(dep) ?? [];
519
+ dependents.push(task.id);
520
+ blocks.set(dep, dependents);
521
+ }
522
+ return blocks;
523
+ }
524
+ //#endregion
525
+ //#region src/services/reducer/index.ts
526
+ /** Default board capacity when a caller does not provide a configured limit. */
527
+ const DEFAULT_REDUCER_MAX_TASKS = 15;
528
+ /**
529
+ * A ref must start with a letter, which makes it structurally unconfusable with
530
+ * a stringified id. That is why resolving a dependency token is just a `typeof`
531
+ * check with no coercion heuristics.
532
+ */
533
+ const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
534
+ /**
535
+ * Does this op represent state that must reach disk?
536
+ *
537
+ * The exhaustive switch is the point: a future `Op` variant cannot be added
538
+ * without declaring its persistence intent, so nothing silently starts or stops
539
+ * bumping `rev`.
540
+ */
541
+ function isCommittingOp(op) {
542
+ switch (op.kind) {
543
+ case "error":
544
+ case "list":
545
+ case "get": return false;
546
+ case "upsert": return op.items.some((item) => item.kind === "created" || item.kind === "updated");
547
+ case "delete":
548
+ case "clear": return true;
549
+ }
550
+ }
551
+ function errorResult(document, message) {
552
+ return {
553
+ document,
554
+ op: {
555
+ kind: "error",
556
+ message
557
+ }
558
+ };
559
+ }
560
+ function sameNumberList(a, b) {
561
+ const x = a ?? [];
562
+ const y = b ?? [];
563
+ return x.length === y.length && x.every((value, index) => value === y[index]);
564
+ }
565
+ function sameRecord(a, b) {
566
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
567
+ }
568
+ /**
569
+ * Did this update change anything? A no-effect update (status re-set to its
570
+ * current value, fields re-sent unchanged) reports "No change" rather than
571
+ * "Updated #N" — without the distinction a model can loop re-issuing the same
572
+ * call believing it never landed.
573
+ */
574
+ function taskChanged(before, after) {
575
+ return before.subject !== after.subject || before.status !== after.status || before.description !== after.description || before.activeForm !== after.activeForm || before.owner !== after.owner || !sameNumberList(before.blockedBy, after.blockedBy) || !sameRecord(before.metadata, after.metadata);
576
+ }
577
+ function withTasks(document, tasks, nextId = document.nextId) {
578
+ return {
579
+ ...document,
580
+ tasks,
581
+ nextId
582
+ };
583
+ }
584
+ /** Merge incoming metadata over a base; a `null` value deletes its key. */
585
+ function mergeMetadata(base, incoming) {
586
+ const merged = { ...base };
587
+ for (const [key, value] of Object.entries(incoming)) if (value === null) delete merged[key];
588
+ else merged[key] = value;
589
+ return Object.keys(merged).length ? merged : void 0;
590
+ }
591
+ /** Copy the optional scalar fields an item may set onto a task, in place. */
592
+ function assignScalars(target, item) {
593
+ if (item.subject !== void 0) target.subject = item.subject;
594
+ if (item.description !== void 0) target.description = item.description;
595
+ if (item.activeForm !== void 0) target.activeForm = item.activeForm;
596
+ if (item.owner !== void 0) target.owner = item.owner;
597
+ if (item.metadata !== void 0) {
598
+ const merged = mergeMetadata(target.metadata, item.metadata);
599
+ if (merged === void 0) delete target.metadata;
600
+ else target.metadata = merged;
601
+ }
602
+ }
603
+ function resolveDep(context, field, token) {
604
+ if (typeof token === "number") return {
605
+ ok: true,
606
+ id: token
607
+ };
608
+ if (!REF_PATTERN.test(token)) return {
609
+ ok: false,
610
+ message: `${field}: "${token}" is not a valid ref; pass an existing task id as a number`
611
+ };
612
+ const id = context.refIds.get(token);
613
+ if (id !== void 0) return {
614
+ ok: true,
615
+ id
616
+ };
617
+ const failedAt = context.failedRefs.get(token);
618
+ if (failedAt !== void 0) return {
619
+ ok: false,
620
+ message: `${field}: ref "${token}" refers to item[${failedAt}], which failed`
621
+ };
622
+ return {
623
+ ok: false,
624
+ message: `${field}: unknown ref "${token}" — a ref must be declared by an earlier entry in the same call`
625
+ };
626
+ }
627
+ function fail(message) {
628
+ return {
629
+ ok: false,
630
+ message
631
+ };
632
+ }
633
+ /** Structural checks that apply to every entry, whichever kind it is. */
634
+ function checkShape(context, item) {
635
+ if (item.ref !== void 0) {
636
+ if (item.id !== void 0) return "ref is only valid when creating a task; drop the id, or drop the ref";
637
+ if (!REF_PATTERN.test(item.ref)) return `ref "${item.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;
638
+ if (context.refIds.get(item.ref) !== void 0 || context.failedRefs.has(item.ref)) return `duplicate ref "${item.ref}": it was already declared by an earlier entry`;
639
+ }
640
+ }
641
+ function applyCreateItem(context, item, index, now) {
642
+ if (item.subject === void 0) return fail("subject is required when the entry has no id");
643
+ if (!item.subject.trim()) return fail("subject must not be blank");
644
+ if (item.addBlockedBy !== void 0 || item.removeBlockedBy !== void 0) return fail("addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy");
645
+ if (item.status === "deleted") return fail("cannot create a task with status deleted; create it, then use action delete");
646
+ if (context.tasks.filter((task) => task.status !== "deleted").length >= context.maxTasks) return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);
647
+ const blockedBy = [];
648
+ for (const token of item.blockedBy ?? []) {
649
+ const resolved = resolveDep(context, "blockedBy", token);
650
+ if (!resolved.ok) return fail(resolved.message);
651
+ const dep = context.tasks.find((task) => task.id === resolved.id);
652
+ if (!dep) return fail(`blockedBy: #${resolved.id} not found`);
653
+ if (dep.status === "deleted") return fail(`blockedBy: #${resolved.id} is deleted`);
654
+ if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);
655
+ }
656
+ const created = {
657
+ id: context.nextId,
658
+ subject: item.subject,
659
+ status: item.status ?? "pending",
660
+ createdAt: now,
661
+ updatedAt: now
662
+ };
663
+ assignScalars(created, item);
664
+ if (blockedBy.length) created.blockedBy = blockedBy;
665
+ context.nextId += 1;
666
+ context.tasks.push(created);
667
+ if (item.ref) context.refIds.set(item.ref, created.id);
668
+ return {
669
+ ok: true,
670
+ outcome: {
671
+ index,
672
+ kind: "created",
673
+ id: created.id,
674
+ subject: created.subject,
675
+ status: created.status,
676
+ ...item.ref ? { ref: item.ref } : {},
677
+ ...blockedBy.length ? { blockedBy } : {}
678
+ }
679
+ };
680
+ }
681
+ function applyUpdateItem(context, item, index, now) {
682
+ const id = item.id;
683
+ const at = context.tasks.findIndex((task) => task.id === id);
684
+ if (at === -1) return fail(`#${id} not found`);
685
+ if (item.blockedBy !== void 0) return fail("blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id");
686
+ if (!(item.subject !== void 0 || item.description !== void 0 || item.activeForm !== void 0 || item.status !== void 0 || item.owner !== void 0 || item.metadata !== void 0 || Boolean(item.addBlockedBy?.length) || Boolean(item.removeBlockedBy?.length))) return fail("nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy");
687
+ const current = context.tasks[at];
688
+ if (item.subject !== void 0 && !item.subject.trim()) return fail("subject must not be blank");
689
+ let newStatus = current.status;
690
+ if (item.status !== void 0) {
691
+ if (!isTransitionValid(current.status, item.status)) return fail(`illegal transition ${current.status} -> ${item.status}`);
692
+ newStatus = item.status;
693
+ }
694
+ let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];
695
+ for (const token of item.removeBlockedBy ?? []) {
696
+ const resolved = resolveDep(context, "removeBlockedBy", token);
697
+ if (!resolved.ok) return fail(resolved.message);
698
+ newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);
699
+ }
700
+ for (const token of item.addBlockedBy ?? []) {
701
+ const resolved = resolveDep(context, "addBlockedBy", token);
702
+ if (!resolved.ok) return fail(resolved.message);
703
+ if (resolved.id === id) return fail(`cannot block #${id} on itself`);
704
+ const dep = context.tasks.find((task) => task.id === resolved.id);
705
+ if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);
706
+ if (dep.status === "deleted") return fail(`addBlockedBy: #${resolved.id} is deleted`);
707
+ if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);
708
+ }
709
+ const updated = {
710
+ ...current,
711
+ status: newStatus
712
+ };
713
+ assignScalars(updated, item);
714
+ if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
715
+ else delete updated.blockedBy;
716
+ const candidate = [...context.tasks];
717
+ candidate[at] = updated;
718
+ if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) return fail("addBlockedBy would create a cycle in the blockedBy graph");
719
+ const changed = taskChanged(current, updated);
720
+ if (changed) updated.updatedAt = now;
721
+ context.tasks = candidate;
722
+ return {
723
+ ok: true,
724
+ outcome: changed ? {
725
+ index,
726
+ kind: "updated",
727
+ id,
728
+ fromStatus: current.status,
729
+ toStatus: newStatus
730
+ } : {
731
+ index,
732
+ kind: "unchanged",
733
+ id,
734
+ status: newStatus
735
+ }
736
+ };
737
+ }
738
+ /**
739
+ * Apply every entry in request order, threading the document.
740
+ *
741
+ * Each entry lands completely or not at all: a create whose dependencies fail
742
+ * is not kept dependency-free, because handing back an unblocked task the
743
+ * caller asked to be blocked is a lie it may immediately act on.
744
+ */
745
+ function applyUpsert(document, items, now, maxTasks) {
746
+ const context = {
747
+ tasks: [...document.tasks],
748
+ nextId: document.nextId,
749
+ maxTasks,
750
+ refIds: /* @__PURE__ */ new Map(),
751
+ failedRefs: /* @__PURE__ */ new Map()
752
+ };
753
+ const outcomes = [];
754
+ let applied = 0;
755
+ for (const [index, item] of items.entries()) {
756
+ const shapeError = checkShape(context, item);
757
+ const result = shapeError ? fail(shapeError) : item.id === void 0 ? applyCreateItem(context, item, index, now) : applyUpdateItem(context, item, index, now);
758
+ if (result.ok) {
759
+ outcomes.push(result.outcome);
760
+ applied += 1;
761
+ continue;
762
+ }
763
+ if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) context.failedRefs.set(item.ref, index);
764
+ outcomes.push({
765
+ index,
766
+ kind: "failed",
767
+ message: result.message,
768
+ ...item.id === void 0 ? {} : { id: item.id },
769
+ ...item.ref ? { ref: item.ref } : {}
770
+ });
771
+ }
772
+ return {
773
+ document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,
774
+ op: {
775
+ kind: "upsert",
776
+ items: outcomes,
777
+ applied,
778
+ failed: outcomes.length - applied
779
+ }
780
+ };
781
+ }
782
+ /**
783
+ * Pure reducer: (document, action, params) -> (document, op).
784
+ *
785
+ * All validation is in-line: structural guards plus state-aware checks
786
+ * (transition legality, dangling or deleted blockedBy, self-block, cycles,
787
+ * in-flight delegations). The caller owns persistence and formatting.
788
+ */
789
+ function applyTaskMutation(document, action, params, now = (/* @__PURE__ */ new Date()).toISOString(), maxTasks = DEFAULT_REDUCER_MAX_TASKS) {
790
+ switch (action) {
791
+ case "upsert": {
792
+ const items = params.tasks;
793
+ if (!Array.isArray(items) || items.length === 0) return errorResult(document, "upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}");
794
+ if (items.length > 100) return errorResult(document, `upsert accepts at most 100 entries per call (received ${items.length})`);
795
+ return applyUpsert(document, items, now, maxTasks);
796
+ }
797
+ case "list": return {
798
+ document,
799
+ op: {
800
+ kind: "list",
801
+ includeDeleted: params.includeDeleted === true,
802
+ ...params.status !== void 0 ? { statusFilter: params.status } : {}
803
+ }
804
+ };
805
+ case "get": {
806
+ if (params.id === void 0) return errorResult(document, "id required for get");
807
+ const task = document.tasks.find((candidate) => candidate.id === params.id);
808
+ if (!task) return errorResult(document, `#${params.id} not found`);
809
+ return {
810
+ document,
811
+ op: {
812
+ kind: "get",
813
+ task
814
+ }
815
+ };
816
+ }
817
+ case "delete": {
818
+ if (params.id === void 0) return errorResult(document, "id required for delete");
819
+ const index = document.tasks.findIndex((task) => task.id === params.id);
820
+ if (index === -1) return errorResult(document, `#${params.id} not found`);
821
+ const current = document.tasks[index];
822
+ if (current.status === "deleted") return errorResult(document, `#${current.id} is already deleted`);
823
+ if (isDelegationActive(current)) return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);
824
+ const tasks = [...document.tasks];
825
+ tasks[index] = {
826
+ ...current,
827
+ status: DELETED_STATUS$1,
828
+ updatedAt: now
829
+ };
830
+ return {
831
+ document: withTasks(document, tasks),
832
+ op: {
833
+ kind: "delete",
834
+ id: current.id,
835
+ subject: current.subject
836
+ }
837
+ };
838
+ }
839
+ case "clear": {
840
+ const active = document.tasks.filter(isDelegationActive);
841
+ if (active.length > 0) return errorResult(document, `cannot clear while delegations are running (${active.map((task) => `#${task.id}`).join(", ")}) — cancel them first`);
842
+ const count = document.tasks.length;
843
+ return {
844
+ document: withTasks(document, [], 1),
845
+ op: {
846
+ kind: "clear",
847
+ count
848
+ }
849
+ };
850
+ }
851
+ }
852
+ }
853
+ //#endregion
854
+ //#region src/services/taskResult/index.ts
855
+ const MSG_ALL_COMPLETE_CLEAR = "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.";
856
+ /**
857
+ * Steering for a mixed batch. Unlike a batch of spawned subagents, a failed
858
+ * entry here had no side effect at all, so retrying the failures is the safe
859
+ * move and the model must be told so or it will do nothing. The hazard is the
860
+ * other half: resending an applied create would make a second task.
861
+ */
862
+ const MSG_UPSERT_PARTIAL = "The applied entries are committed. Resend only the failed entries, corrected — a failed entry changed nothing, so a corrected retry is safe. Do not resend an entry that already applied: an entry without an id creates a second task.";
863
+ const MSG_ASSIGN_PARTIAL = "Successful assignments are already running. Retry only the failed entries after correcting their task state or arguments; do not resend successful entries.";
864
+ /** LLM-facing report for a native assignment batch. */
865
+ function formatAssignmentResults(items) {
866
+ if (items.length === 1) return items[0].message;
867
+ const succeeded = items.filter((item) => item.ok).length;
868
+ const failed = items.length - succeeded;
869
+ const lines = [`Assigned ${succeeded}/${items.length} tasks${failed > 0 ? `; ${failed} failed` : ""}.`, ...items.map((item) => item.ok ? `- [${item.index}] Delegated #${item.id} to ${item.agent}` : `- [${item.index}] Failed #${item.id} → ${item.agent}: ${item.message}`)];
870
+ if (failed > 0 && succeeded > 0) lines.push("", MSG_ASSIGN_PARTIAL);
871
+ if (failed === 0) lines.push("", "All assignments are running independently in the background. Continue non-overlapping work, or end your turn.");
872
+ return lines.join("\n");
873
+ }
874
+ /** `[status] #id subject (activeForm) [agent] ⛓ #dep` — the `list` line format. */
875
+ function formatListLine(task) {
876
+ const block = task.blockedBy?.length ? ` ⛓ ${task.blockedBy.map((id) => `#${id}`).join(",")}` : "";
877
+ const form = task.status === "in_progress" && task.activeForm ? ` (${task.activeForm})` : "";
878
+ const delegated = task.delegation && task.delegation.state !== "cancelled" ? ` [${task.delegation.agent}]` : "";
879
+ return `[${task.status}] #${task.id} ${task.subject}${form}${delegated}${block}`;
880
+ }
881
+ function formatDelegationLines(task) {
882
+ const delegation = task.delegation;
883
+ if (!delegation) return [];
884
+ const lines = [` delegated to: ${delegation.agent} (${delegation.state})`];
885
+ if (delegation.model) lines.push(` model: ${delegation.model}`);
886
+ if (delegation.result?.error) lines.push(` error: ${delegation.result.error}`);
887
+ if (delegation.result?.outputPath) lines.push(` output file: ${delegation.result.outputPath}`);
888
+ if (delegation.result?.output) lines.push(` output: ${delegation.result.output}`);
889
+ return lines;
890
+ }
891
+ function formatGetLines(task, document) {
892
+ const blocks = deriveBlocks(document.tasks).get(task.id) ?? [];
893
+ const lines = [`#${task.id} [${task.status}] ${task.subject}`];
894
+ if (task.description) lines.push(` description: ${task.description}`);
895
+ if (task.activeForm) lines.push(` activeForm: ${task.activeForm}`);
896
+ if (task.blockedBy?.length) lines.push(` blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`);
897
+ if (blocks.length) lines.push(` blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
898
+ if (task.owner) lines.push(` owner: ${task.owner}`);
899
+ lines.push(...formatDelegationLines(task));
900
+ return lines.join("\n");
901
+ }
902
+ /** One entry's outcome. Batch lines prefix this with `- [n] `. */
903
+ function formatUpsertItem(item) {
904
+ switch (item.kind) {
905
+ case "created": {
906
+ const ref = item.ref ? ` (ref "${item.ref}")` : "";
907
+ const deps = item.blockedBy?.length ? ` — blocked by ${item.blockedBy.map((id) => `#${id}`).join(", ")}` : "";
908
+ return `Created #${item.id}${ref}: ${item.subject} (${item.status})${deps}`;
909
+ }
910
+ case "updated": {
911
+ const transition = item.fromStatus === item.toStatus ? "" : ` (${item.fromStatus} -> ${item.toStatus})`;
912
+ return `Updated #${item.id}${transition}`;
913
+ }
914
+ case "unchanged": return `No change: #${item.id} already matches the requested values (status: ${item.status})`;
915
+ case "failed": return `Failed${item.id === void 0 ? "" : ` #${item.id}`}: ${item.message}`;
916
+ }
917
+ }
918
+ /**
919
+ * Pure formatter: `(op, document) -> string`. The switch is closed over `Op`,
920
+ * so a new reducer variant fails to compile until it is handled here.
921
+ */
922
+ function formatContent(op, document) {
923
+ switch (op.kind) {
924
+ case "upsert": {
925
+ const lines = op.items.length === 1 ? [formatUpsertItem(op.items[0])] : [
926
+ `Upsert applied ${op.applied}/${op.items.length} entries${op.failed > 0 ? `; ${op.failed} failed` : ""}.`,
927
+ ...op.items.map((item) => `- [${item.index}] ${formatUpsertItem(item)}`),
928
+ ...op.failed > 0 ? ["", MSG_UPSERT_PARTIAL] : []
929
+ ];
930
+ if (op.applied > 0 && isTaskListComplete(document.tasks)) lines.push(MSG_ALL_COMPLETE_CLEAR);
931
+ return lines.join("\n");
932
+ }
933
+ case "delete": return `Deleted #${op.id}: ${op.subject}`;
934
+ case "clear": return `Closed task list (cleared ${op.count} tasks)`;
935
+ case "list": {
936
+ let view = document.tasks;
937
+ if (!op.includeDeleted) view = view.filter((task) => task.status !== "deleted");
938
+ if (op.statusFilter) view = view.filter((task) => task.status === op.statusFilter);
939
+ return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
940
+ }
941
+ case "get": return formatGetLines(op.task, document);
942
+ case "error": return `Error: ${op.message}`;
943
+ }
944
+ }
945
+ /** Build the LLM-facing envelope. `details` carries the post-mutation snapshot. */
946
+ function buildToolResult(action, params, document, op) {
947
+ return {
948
+ content: [{
949
+ type: "text",
950
+ text: formatContent(op, document)
951
+ }],
952
+ details: {
953
+ action,
954
+ params,
955
+ tasks: document.tasks,
956
+ nextId: document.nextId,
957
+ rev: document.rev,
958
+ ...op.kind === "error" ? { error: op.message } : {},
959
+ ...op.kind === "upsert" ? { upsert: {
960
+ applied: op.items.flatMap((item) => item.kind === "failed" ? [] : [item.id]),
961
+ failed: op.failed
962
+ } } : {}
963
+ }
964
+ };
965
+ }
966
+ /** Envelope for a native assignment batch, including ids used by the consolidated TUI result. */
967
+ function buildAssignmentResult(params, document, text, assignment) {
968
+ return {
969
+ content: [{
970
+ type: "text",
971
+ text
972
+ }],
973
+ details: {
974
+ action: "assign",
975
+ params,
976
+ tasks: document.tasks,
977
+ nextId: document.nextId,
978
+ rev: document.rev,
979
+ assignment
980
+ }
981
+ };
982
+ }
983
+ /** Envelope for delegation actions, which do not flow through the reducer. */
984
+ function buildTextResult(action, params, document, text, error) {
985
+ return {
986
+ content: [{
987
+ type: "text",
988
+ text: error ? `Error: ${error}` : text
989
+ }],
990
+ details: {
991
+ action,
992
+ params,
993
+ tasks: document.tasks,
994
+ nextId: document.nextId,
995
+ rev: document.rev,
996
+ ...error ? { error } : {}
997
+ }
998
+ };
999
+ }
1000
+ //#endregion
1001
+ //#region src/services/taskTool/index.ts
1002
+ function output(value) {
1003
+ if (typeof value === "object" && value !== null && "content" in value) return value;
1004
+ return {
1005
+ content: [{
1006
+ type: "text",
1007
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
1008
+ }],
1009
+ details: value
1010
+ };
1011
+ }
1012
+ function failure(error) {
1013
+ return {
1014
+ content: [{
1015
+ type: "text",
1016
+ text: error instanceof Error ? error.message : String(error)
1017
+ }],
1018
+ isError: true
1019
+ };
1020
+ }
1021
+ async function reducerAction(store, action, params, maxTasks) {
1022
+ const { document, value } = await store.mutate((current) => {
1023
+ const result = applyTaskMutation(current, action, params, void 0, maxTasks);
1024
+ return {
1025
+ ...isCommittingOp(result.op) ? { document: result.document } : {},
1026
+ value: result
1027
+ };
1028
+ });
1029
+ if (value.op.kind === "error") throw new Error(value.op.message);
1030
+ return buildToolResult(action, params, document, value.op);
1031
+ }
1032
+ async function assignmentBatch(manager, assignments, signal) {
1033
+ const result = [];
1034
+ for (const [index, assignment] of assignments.entries()) try {
1035
+ const outcome = await manager.assign(assignment.id, {
1036
+ agent: assignment.agent,
1037
+ inlineAgent: assignment.inlineAgent,
1038
+ instructions: assignment.instructions,
1039
+ relevantFiles: assignment.relevantFiles,
1040
+ priorFindings: assignment.priorFindings,
1041
+ model: assignment.model,
1042
+ ...assignment.context === "fork" || assignment.context === "fresh" ? { context: assignment.context } : {},
1043
+ signal
1044
+ });
1045
+ result.push({
1046
+ index,
1047
+ id: assignment.id,
1048
+ agent: assignment.agent,
1049
+ ...outcome
1050
+ });
1051
+ } catch (error) {
1052
+ result.push({
1053
+ index,
1054
+ id: assignment.id,
1055
+ agent: assignment.agent,
1056
+ ok: false,
1057
+ message: String(error)
1058
+ });
1059
+ }
1060
+ return result;
1061
+ }
1062
+ function createHeadlessTaskTool(store, manager, maxTasks) {
1063
+ return {
1064
+ name: "task",
1065
+ label: "Task",
1066
+ description: "Maintain a persistent task graph and delegate ready tasks to background agents.",
1067
+ parameters: TaskParamsSchema,
1068
+ promptSnippet: "Track complex work persistently and delegate ready tasks",
1069
+ executionMode: "serial",
1070
+ async execute(_toolCallId, rawParams, signal, onUpdate) {
1071
+ if (!(0, typebox_value.Check)(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
1072
+ const params = rawParams;
1073
+ try {
1074
+ if ((params.action === "assign" || params.action === "cancel") && !manager) throw new Error("Delegation is not available on this connection.");
1075
+ if (params.action === "assign") {
1076
+ if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
1077
+ onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
1078
+ const items = await assignmentBatch(manager, params.assignments, signal);
1079
+ const assigned = items.filter((item) => item.ok).map((item) => item.id);
1080
+ const text = formatAssignmentResults(items);
1081
+ if (assigned.length === 0) throw new Error(text);
1082
+ return buildAssignmentResult(params, store.snapshot, text, {
1083
+ assigned,
1084
+ failed: items.length - assigned.length
1085
+ });
1086
+ }
1087
+ if (params.action === "cancel") {
1088
+ const outcome = await manager.cancel(params.id ?? NaN);
1089
+ if (!outcome.ok) throw new Error(outcome.message);
1090
+ return buildTextResult("cancel", params, store.snapshot, outcome.message);
1091
+ }
1092
+ return reducerAction(store, params.action, params, maxTasks);
1093
+ } catch (error) {
1094
+ return failure(error);
1095
+ }
1096
+ }
1097
+ };
1098
+ }
1099
+ //#endregion
1100
+ //#region src/extensions/workspaces/sessions/(backend)/tool/task.mcp.ts
1101
+ var task_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpTool)(({ execution }) => {
1102
+ const store = new TaskStore({
1103
+ cwd: execution.cwd,
1104
+ env: execution.environment
1105
+ });
1106
+ store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));
1107
+ const tool = createHeadlessTaskTool(store, void 0, getMaxTasks(execution.environment));
1108
+ let initialized;
1109
+ return {
1110
+ ...tool,
1111
+ parameters: RemoteTaskParamsSchema,
1112
+ description: "Track multi-step work in the Po session as a persistent task list (todo, plan, task graph). Delegating to background agents is not available here.",
1113
+ async execute(...args) {
1114
+ initialized ??= store.readAsync().then(() => void 0);
1115
+ await initialized;
1116
+ return tool.execute(...args);
1117
+ }
1118
+ };
1119
+ });
1120
+ //#endregion
1121
+ //#region generated/mcp.ts
1122
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
1123
+ const via = (identity, value) => value === void 0 ? void 0 : {
1124
+ ...identity,
1125
+ ...value
1126
+ };
1127
+ const withWidget = (key, value) => value === void 0 ? value : {
1128
+ ...value,
1129
+ _meta: {
1130
+ ...value._meta,
1131
+ ["po/widget"]: key
1132
+ }
1133
+ };
1134
+ const mcp = (0, _agimon_ai_po_core_mcpFacet.defineMcpPlugin)({
1135
+ name: "@agimon-ai/po-task",
1136
+ session: (context) => ({ get tools() {
1137
+ return [withWidget("@agimon-ai/po-task/task", via({ name: "task" }, at(task_mcp_default, context)))];
1138
+ } })
1139
+ });
1140
+ //#endregion
1141
+ exports.default = mcp;
1142
+ exports.mcp = mcp;
1143
+
1144
+ //# sourceMappingURL=mcp.cjs.map