@agimon-ai/po-task 0.0.0-alpha.7 → 0.0.0-alpha.71

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 (93) hide show
  1. package/LICENSE +149 -21
  2. package/README.md +12 -2
  3. package/dist/apiContracts.cjs +1 -0
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.mjs +1 -0
  6. package/dist/apiContracts.mjs.map +1 -1
  7. package/dist/{delegation-Dsqf7fUM.mjs → delegation-5TOl_dEq.mjs} +4 -3
  8. package/dist/delegation-5TOl_dEq.mjs.map +1 -0
  9. package/dist/{delegation-frvEXhIz.cjs → delegation-BJtAUTVg.cjs} +4 -3
  10. package/dist/delegation-BJtAUTVg.cjs.map +1 -0
  11. package/dist/delegationManager.cjs +1 -1
  12. package/dist/delegationManager.d.mts +1 -1
  13. package/dist/delegationManager.mjs +1 -1
  14. package/dist/extensions/mcp.cjs +60 -61
  15. package/dist/extensions/mcp.cjs.map +1 -1
  16. package/dist/extensions/mcp.mjs +60 -61
  17. package/dist/extensions/mcp.mjs.map +1 -1
  18. package/dist/extensions/native.mjs +420 -315
  19. package/dist/extensions/native.mjs.map +1 -1
  20. package/dist/extensions/server.cjs +398 -136
  21. package/dist/extensions/server.cjs.map +1 -1
  22. package/dist/extensions/server.d.mts +2 -2
  23. package/dist/extensions/server.d.mts.map +1 -1
  24. package/dist/extensions/server.mjs +397 -135
  25. package/dist/extensions/server.mjs.map +1 -1
  26. package/dist/extensions/web.mjs +254 -206
  27. package/dist/extensions/web.mjs.map +1 -1
  28. package/dist/{index-DlmXKyhQ.d.mts → index-CdJx5tdI.d.mts} +2 -2
  29. package/dist/{index-DlmXKyhQ.d.mts.map → index-CdJx5tdI.d.mts.map} +1 -1
  30. package/dist/{index-B1JPJdpZ.d.mts → index-DrE00rrP.d.mts} +3 -3
  31. package/dist/{index-B1JPJdpZ.d.mts.map → index-DrE00rrP.d.mts.map} +1 -1
  32. package/dist/{index-qQGWsPum.d.mts → index-DuT-Lbxy.d.mts} +2 -3
  33. package/dist/index-DuT-Lbxy.d.mts.map +1 -0
  34. package/dist/{index-CUWCvh-E.d.mts → index-nx0ueNkm.d.mts} +2 -2
  35. package/dist/{index-CUWCvh-E.d.mts.map → index-nx0ueNkm.d.mts.map} +1 -1
  36. package/dist/{index-B9QNwUBr.d.mts → index-sahNy7Hg.d.mts} +3 -3
  37. package/dist/{index-B9QNwUBr.d.mts.map → index-sahNy7Hg.d.mts.map} +1 -1
  38. package/dist/{index-CA4Opp4r.d.mts → index-tAu1TIyi.d.mts} +4 -6
  39. package/dist/index-tAu1TIyi.d.mts.map +1 -0
  40. package/dist/index.cjs +3 -5
  41. package/dist/index.d.mts +10 -10
  42. package/dist/index.mjs +4 -4
  43. package/dist/{logSinkTelemetry-BhbKdn-x.mjs → logSinkTelemetry-3GMazFYa.mjs} +2 -2
  44. package/dist/logSinkTelemetry-3GMazFYa.mjs.map +1 -0
  45. package/dist/{logSinkTelemetry-BGb8WQBz.cjs → logSinkTelemetry-DhzIQMsV.cjs} +3 -3
  46. package/dist/logSinkTelemetry-DhzIQMsV.cjs.map +1 -0
  47. package/dist/logSinkTelemetry.cjs +1 -1
  48. package/dist/logSinkTelemetry.d.mts +1 -1
  49. package/dist/logSinkTelemetry.mjs +1 -1
  50. package/dist/{paths-P-XvOUuH.cjs → paths-CWVDY8Yd.cjs} +12 -78
  51. package/dist/paths-CWVDY8Yd.cjs.map +1 -0
  52. package/dist/{paths-DajceJig.mjs → paths-CjATVpi8.mjs} +12 -66
  53. package/dist/paths-CjATVpi8.mjs.map +1 -0
  54. package/dist/storeInvariants.d.mts +1 -1
  55. package/dist/storePaths.cjs +1 -3
  56. package/dist/storePaths.d.mts +2 -2
  57. package/dist/storePaths.mjs +1 -1
  58. package/dist/storeReconcile.d.mts +1 -1
  59. package/dist/storeReducer.d.mts +1 -1
  60. package/dist/storeTaskGraph.d.mts +1 -1
  61. package/dist/storeTaskStore.cjs +1 -1
  62. package/dist/storeTaskStore.d.mts +1 -1
  63. package/dist/storeTaskStore.mjs +1 -1
  64. package/dist/storeTypes.d.mts +1 -1
  65. package/dist/{task-4HeGAS8o.d.mts → task--hlnpS7L.d.mts} +2 -2
  66. package/dist/{task-4HeGAS8o.d.mts.map → task--hlnpS7L.d.mts.map} +1 -1
  67. package/dist/task-CXF9VULl.cjs.map +1 -1
  68. package/dist/{task-DJpTteeJ.d.mts → task-DdTKZNtU.d.mts} +3 -1
  69. package/dist/task-DdTKZNtU.d.mts.map +1 -0
  70. package/dist/task-giCbpKzV.mjs.map +1 -1
  71. package/dist/{taskGraph-D0zFHF2p.d.mts → taskGraph-CB8ffMCz.d.mts} +2 -2
  72. package/dist/{taskGraph-D0zFHF2p.d.mts.map → taskGraph-CB8ffMCz.d.mts.map} +1 -1
  73. package/dist/{taskStore-C4vcUOzA.cjs → taskStore-B-BbY2Ci.cjs} +30 -36
  74. package/dist/taskStore-B-BbY2Ci.cjs.map +1 -0
  75. package/dist/{taskStore-BAi54FKL.mjs → taskStore-wuXXFCZT.mjs} +29 -35
  76. package/dist/taskStore-wuXXFCZT.mjs.map +1 -0
  77. package/dist/toolResponseEnvelope.d.mts +1 -1
  78. package/dist/toolSchema.d.mts +1 -1
  79. package/llms.txt +11 -0
  80. package/package.json +18 -17
  81. package/src/prompts/codemode-how-to-task/SKILL.md +40 -0
  82. package/src/types/webTasks.ts +1 -0
  83. package/dist/delegation-Dsqf7fUM.mjs.map +0 -1
  84. package/dist/delegation-frvEXhIz.cjs.map +0 -1
  85. package/dist/index-CA4Opp4r.d.mts.map +0 -1
  86. package/dist/index-qQGWsPum.d.mts.map +0 -1
  87. package/dist/logSinkTelemetry-BGb8WQBz.cjs.map +0 -1
  88. package/dist/logSinkTelemetry-BhbKdn-x.mjs.map +0 -1
  89. package/dist/paths-DajceJig.mjs.map +0 -1
  90. package/dist/paths-P-XvOUuH.cjs.map +0 -1
  91. package/dist/task-DJpTteeJ.d.mts.map +0 -1
  92. package/dist/taskStore-BAi54FKL.mjs.map +0 -1
  93. package/dist/taskStore-C4vcUOzA.cjs.map +0 -1
@@ -1,23 +1,24 @@
1
1
  import { f as getDelegationTimeoutMs, h as getStoreTtlMs, p as getMaxTasks } from "../config-BTadoGeF.mjs";
2
2
  import { r as isBlocked } from "../taskGraph-BOQvT0-M.mjs";
3
3
  import { t as TASK_EVENT } from "../telemetry-gEGWTaMI.mjs";
4
- import { n as DelegationManager, t as BACKGROUND_WORK_PROVIDER } from "../delegation-Dsqf7fUM.mjs";
4
+ import { n as DelegationManager, t as BACKGROUND_WORK_PROVIDER } from "../delegation-5TOl_dEq.mjs";
5
5
  import { a as buildAssignmentResult, c as formatAssignmentResults, o as buildTextResult, s as buildToolResult } from "../taskResult-edBAAKSH.mjs";
6
6
  import { g as COMMAND_NAME, m as TaskParamsSchema } from "../task-DO0TwZ0z.mjs";
7
- import { a as removeLegacyStoreDirectoryAsync, c as resolveSessionKey, d as sweepStoreFilesAsync, l as resolveStorePath, n as hasStorePathOverride } from "../paths-DajceJig.mjs";
7
+ import { c as resolveStorePath, i as removeLegacyStoreDirectory, l as sweepStoreFiles, n as hasStorePathOverride, s as resolveSessionKey } from "../paths-CjATVpi8.mjs";
8
8
  import { a as isCommittingOp, r as applyTaskMutation } from "../reducer-BEfJFM5L.mjs";
9
- import { t as TaskStore } from "../taskStore-BAi54FKL.mjs";
10
- import { n as toFailureReporter, t as createTaskErrorReporter } from "../logSinkTelemetry-BhbKdn-x.mjs";
9
+ import { t as TaskStore } from "../taskStore-wuXXFCZT.mjs";
10
+ import { n as toFailureReporter, t as createTaskErrorReporter } from "../logSinkTelemetry-3GMazFYa.mjs";
11
11
  import { PO_DELEGATION_SERVICE, readPoDelegationService } from "@agimon-ai/po-core/delegation";
12
12
  import path from "node:path";
13
- import { composeServerProviderOverrides, defineServerPlugin } from "@agimon-ai/po-core/serverFacet";
14
- import { composeRootHooks, defineChannel, defineResource, defineRoot, defineServerCommand, defineServerTool } from "@agimon-ai/po-core/extensionFile";
13
+ import { composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
14
+ import { composeRootHooks, composeRootInjects, defineChannel, defineResource, defineRoot, defineServerCommand, defineServerTool, runCleanups } from "@agimon-ai/po-core/extensionFile";
15
15
  import { PO_BACKGROUND_WORK_SERVICE, readPoBackgroundWorkService } from "@agimon-ai/po-core/backgroundWork";
16
+ import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
16
17
  import { PO_CONTEXT_CONTRIBUTIONS_SERVICE, requirePoContextContributions } from "@agimon-ai/po-core/contextContributions";
17
18
  import { createPoReadinessCoordinator, readPoReadinessCoordinator } from "@agimon-ai/po-core/readiness";
18
19
  import { createHash, randomUUID } from "node:crypto";
20
+ import { Check, Errors } from "typebox/value";
19
21
  import { HOME_ENTITY_LIMIT } from "@agimon-ai/po-core/hubChannel";
20
- import { Check } from "typebox/value";
21
22
  //#region src/services/contextContribution/index.ts
22
23
  const TASK_CONTEXT_CONTRIBUTION_SOURCE = "@agimon-ai/po-task";
23
24
  const TASK_CONTEXT_CONTRIBUTION_ID = "active-tasks";
@@ -77,6 +78,315 @@ function createNodeDelegationPlatform(environment = process.env) {
77
78
  };
78
79
  }
79
80
  //#endregion
81
+ //#region src/services/taskTool/index.ts
82
+ function output(value) {
83
+ if (typeof value === "object" && value !== null && "content" in value) return value;
84
+ return {
85
+ content: [{
86
+ type: "text",
87
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
88
+ }],
89
+ details: value
90
+ };
91
+ }
92
+ function failure(error) {
93
+ return {
94
+ content: [{
95
+ type: "text",
96
+ text: error instanceof Error ? error.message : String(error)
97
+ }],
98
+ isError: true
99
+ };
100
+ }
101
+ async function reducerAction(store, action, params, maxTasks) {
102
+ const { document, value } = await store.mutate((current) => {
103
+ const result = applyTaskMutation(current, action, params, void 0, maxTasks);
104
+ return {
105
+ ...isCommittingOp(result.op) ? { document: result.document } : {},
106
+ value: result
107
+ };
108
+ });
109
+ if (value.op.kind === "error") throw new Error(value.op.message);
110
+ return buildToolResult(action, params, document, value.op);
111
+ }
112
+ async function assignmentBatch(manager, assignments, signal) {
113
+ const result = [];
114
+ for (const [index, assignment] of assignments.entries()) try {
115
+ const outcome = await manager.assign(assignment.id, {
116
+ agent: assignment.agent,
117
+ inlineAgent: assignment.inlineAgent,
118
+ instructions: assignment.instructions,
119
+ relevantFiles: assignment.relevantFiles,
120
+ priorFindings: assignment.priorFindings,
121
+ model: assignment.model,
122
+ ...assignment.context === "fork" || assignment.context === "fresh" ? { context: assignment.context } : {},
123
+ signal
124
+ });
125
+ result.push({
126
+ index,
127
+ id: assignment.id,
128
+ agent: assignment.agent,
129
+ ...outcome
130
+ });
131
+ } catch (error) {
132
+ result.push({
133
+ index,
134
+ id: assignment.id,
135
+ agent: assignment.agent,
136
+ ok: false,
137
+ message: String(error)
138
+ });
139
+ }
140
+ return result;
141
+ }
142
+ /** One task action against the session store, shared by the `task` tool and the `tasks` code-mode namespace. */
143
+ async function runTaskAction(store, manager, maxTasks, rawParams, signal, onUpdate) {
144
+ if (!Check(TaskParamsSchema, rawParams)) {
145
+ const [first] = Errors(TaskParamsSchema, rawParams);
146
+ return failure(`Invalid task parameters${first ? `: ${first.instancePath || "/"} ${first.message}` : ""}.`);
147
+ }
148
+ const params = rawParams;
149
+ try {
150
+ if ((params.action === "assign" || params.action === "cancel") && !manager) throw new Error("Delegation is not available on this connection.");
151
+ if (params.action === "assign") {
152
+ if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
153
+ onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
154
+ const items = await assignmentBatch(manager, params.assignments, signal);
155
+ const assigned = items.filter((item) => item.ok).map((item) => item.id);
156
+ const text = formatAssignmentResults(items);
157
+ if (assigned.length === 0) throw new Error(text);
158
+ return buildAssignmentResult(params, store.snapshot, text, {
159
+ assigned,
160
+ failed: items.length - assigned.length
161
+ });
162
+ }
163
+ if (params.action === "cancel") {
164
+ const outcome = await manager.cancel(params.id ?? NaN);
165
+ if (!outcome.ok) throw new Error(outcome.message);
166
+ return buildTextResult("cancel", params, store.snapshot, outcome.message);
167
+ }
168
+ return reducerAction(store, params.action, params, maxTasks);
169
+ } catch (error) {
170
+ return failure(error);
171
+ }
172
+ }
173
+ function createHeadlessTaskTool(store, manager, maxTasks) {
174
+ return {
175
+ name: "task",
176
+ label: "Task",
177
+ description: "Maintain a persistent task graph and delegate ready tasks to background agents.",
178
+ parameters: TaskParamsSchema,
179
+ promptSnippet: "Track complex work persistently and delegate ready tasks",
180
+ executionMode: "serial",
181
+ execute: (_toolCallId, rawParams, signal, onUpdate) => runTaskAction(store, manager, maxTasks, rawParams, signal, onUpdate)
182
+ };
183
+ }
184
+ //#endregion
185
+ //#region src/services/taskNamespace/index.ts
186
+ const DECLARATIONS = `type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'deleted';
187
+
188
+ type DelegationState = 'requested' | 'running' | 'completed' | 'failed' | 'cancelled';
189
+
190
+ interface DelegationResult {
191
+ status: string;
192
+ output?: string;
193
+ outputPath?: string;
194
+ sessionFile?: string;
195
+ error?: string;
196
+ durationMs?: number;
197
+ toolCount?: number;
198
+ }
199
+
200
+ interface TaskDelegation {
201
+ requestId: string;
202
+ agent: string;
203
+ identity?: string;
204
+ state: DelegationState;
205
+ sessionId?: string;
206
+ pid?: number;
207
+ runId?: string;
208
+ model?: string;
209
+ startedAt?: string;
210
+ endedAt?: string;
211
+ result?: DelegationResult;
212
+ }
213
+
214
+ interface Task {
215
+ id: number;
216
+ subject: string;
217
+ description?: string;
218
+ activeForm?: string;
219
+ status: TaskStatus;
220
+ blockedBy?: number[];
221
+ owner?: string;
222
+ metadata?: Record<string, unknown>;
223
+ createdAt?: string;
224
+ updatedAt?: string;
225
+ delegation?: TaskDelegation;
226
+ }
227
+
228
+ interface TaskDocument {
229
+ version: number;
230
+ rev: number;
231
+ nextId: number;
232
+ tasks: Task[];
233
+ }
234
+ interface TaskItem {
235
+ /** Existing task id to change. Omit to create; an unknown id fails only that entry. */
236
+ id?: number;
237
+ /** Temporary name so a LATER entry in the same call can list it in blockedBy. Never stored. */
238
+ ref?: string;
239
+ /** Short and imperative. Required when creating. */
240
+ subject?: string;
241
+ /** The durable brief handed to a subagent on assign. */
242
+ description?: string;
243
+ /** Present-continuous label shown while in_progress, such as 'writing tests'. */
244
+ activeForm?: string;
245
+ status?: TaskStatus;
246
+ /** For a NEW entry: task ids or earlier refs. */
247
+ blockedBy?: (number | string)[];
248
+ /** For an entry with an id: dependencies to add or remove. */
249
+ addBlockedBy?: (number | string)[];
250
+ removeBlockedBy?: (number | string)[];
251
+ owner?: string;
252
+ /** Merged into the task; a null value deletes that key. */
253
+ metadata?: Record<string, unknown>;
254
+ }
255
+
256
+ interface TaskAssignment {
257
+ /** A pending, unblocked task. */
258
+ id: number;
259
+ /** Exact name from subagent({ action: 'agents' }). */
260
+ agent: string;
261
+ instructions?: string;
262
+ /** Only files you actually read or located. */
263
+ relevantFiles?: string[];
264
+ /** Only verified facts, not directives. */
265
+ priorFindings?: string;
266
+ model?: string;
267
+ context?: 'fresh' | 'fork';
268
+ }
269
+
270
+ /** What a write returns: the text the task tool would print, and the graph after the write. */
271
+ interface TaskWrite {
272
+ message: string;
273
+ document: TaskDocument;
274
+ /** upsert only: ids that landed and how many entries failed. Nothing landing throws; a partial failure does not. */
275
+ applied?: number[];
276
+ failed?: number;
277
+ }
278
+ declare const tasks: {
279
+ /** The whole task graph, tombstones included. Filter it in the script. */
280
+ snapshot(): Promise<TaskDocument>;
281
+ /**
282
+ * Create or change tasks, applied in array order. Never mark a task completed while tests fail or the
283
+ * work is partial: use failed, or keep it in_progress and add a task for the blocker in the same call.
284
+ * Status flow is pending, in_progress, completed. failed is recoverable and deleted is a tombstone.
285
+ */
286
+ upsert(tasks: TaskItem[]): Promise<TaskWrite>;
287
+ /** Tombstone one task. Refused while it has a running delegation. */
288
+ delete(id: number): Promise<TaskWrite>;
289
+ /** Remove every task. Refused while a delegation is running. */
290
+ clear(): Promise<TaskWrite>;
291
+ /** Hand ready tasks to background subagents. Batch independent tasks in one call. */
292
+ assign(assignments: TaskAssignment[]): Promise<TaskWrite>;
293
+ /** Cancel a task's running delegation. */
294
+ cancel(id: number): Promise<TaskWrite>;
295
+ };`;
296
+ /** The owning session's task graph: `snapshot` reads without locking, the rest write through the same store as the `task` tool. */
297
+ function createTaskNamespace(options) {
298
+ return {
299
+ name: "tasks",
300
+ summary: "The session task graph: tasks.snapshot() reads it, tasks.upsert/delete/clear change it, tasks.assign/cancel hand tasks to background subagents. Use it to track multi-step work.",
301
+ declarations: DECLARATIONS,
302
+ bind(run) {
303
+ if (run.sessionId !== options.sessionId) throw new Error("Tasks namespace belongs to another session.");
304
+ let disposed = false;
305
+ run.onDispose(() => {
306
+ disposed = true;
307
+ });
308
+ const assertAvailable = () => {
309
+ run.signal.throwIfAborted();
310
+ if (disposed) throw new Error("Tasks namespace run is disposed.");
311
+ options.assertAvailable();
312
+ };
313
+ const members = Object.create(null);
314
+ members.snapshot = async () => {
315
+ assertAvailable();
316
+ const storePath = options.store.storePath;
317
+ const errors = [];
318
+ const document = await options.store.readAsync(() => false, (error) => errors.push(error));
319
+ assertAvailable();
320
+ if (options.store.storePath !== storePath) throw new Error("Task store path changed during snapshot.");
321
+ if (errors.length > 0) throw new Error("Task snapshot read failed.", { cause: errors[0] });
322
+ return JSON.parse(JSON.stringify(document));
323
+ };
324
+ const write = async (params) => {
325
+ assertAvailable();
326
+ const started = Date.now();
327
+ const result = await runTaskAction(options.store, options.manager, options.maxTasks, params, run.signal);
328
+ assertAvailable();
329
+ const message = result.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n");
330
+ const upsert = result.details?.upsert;
331
+ const failure = result.isError || upsert && upsert.applied.length === 0 && upsert.failed > 0 ? message : void 0;
332
+ run.record?.({
333
+ name: `tasks.${String(params.action)}`,
334
+ tool: "task",
335
+ args: params,
336
+ ok: failure === void 0,
337
+ ms: Date.now() - started,
338
+ ...failure === void 0 ? {} : { error: failure },
339
+ result: {
340
+ content: result.content,
341
+ details: result.details
342
+ }
343
+ });
344
+ if (failure !== void 0) throw new Error(failure);
345
+ return {
346
+ message,
347
+ document: JSON.parse(JSON.stringify(options.store.snapshot)),
348
+ ...upsert ? {
349
+ applied: upsert.applied,
350
+ failed: upsert.failed
351
+ } : {}
352
+ };
353
+ };
354
+ members.upsert = (tasks) => write({
355
+ action: "upsert",
356
+ tasks: entriesWithIds(tasks)
357
+ });
358
+ members.list = members.snapshot;
359
+ members.delete = (id) => write({
360
+ action: "delete",
361
+ id: taskId(id)
362
+ });
363
+ members.clear = () => write({ action: "clear" });
364
+ members.assign = (assignments) => write({
365
+ action: "assign",
366
+ assignments: entriesWithIds(assignments)
367
+ });
368
+ members.cancel = (id) => write({
369
+ action: "cancel",
370
+ id: taskId(id)
371
+ });
372
+ return members;
373
+ }
374
+ };
375
+ }
376
+ /** `'3'` becomes `3`, as the `task` tool's argument coercion does; anything else is left for validation to reject. */
377
+ function taskId(value) {
378
+ return typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
379
+ }
380
+ /** One entry becomes a list, and each entry's id goes through `taskId`. The caller's objects are not changed. */
381
+ function entriesWithIds(value) {
382
+ const entries = value !== null && typeof value === "object" && !Array.isArray(value) ? [value] : value;
383
+ if (!Array.isArray(entries)) return entries;
384
+ return entries.map((entry) => entry !== null && typeof entry === "object" && "id" in entry ? {
385
+ ...entry,
386
+ id: taskId(entry.id)
387
+ } : entry);
388
+ }
389
+ //#endregion
80
390
  //#region src/types/webTasks.ts
81
391
  /** Browser-safe task view published by the cockpit hub channel. */
82
392
  const TASKS_CHANNEL_TYPE = "task_graph";
@@ -90,7 +400,7 @@ function headlineOf(content) {
90
400
  const root = defineRoot(({ host: serverHost, agent: host, signal: pluginSignal }) => {
91
401
  if (!host) throw new Error("Task session requires the headless host.");
92
402
  const execution = host.context;
93
- if (serverHost.context.directEvents === void 0) throw new Error("Task headless facet requires the session direct event bus.");
403
+ if (serverHost.context.directEvents === void 0) throw new Error("Task server plugin requires the session direct event bus.");
94
404
  const directEvents = serverHost.context.directEvents;
95
405
  const reporter = createTaskErrorReporter({
96
406
  cwd: execution.cwd,
@@ -175,6 +485,25 @@ const root = defineRoot(({ host: serverHost, agent: host, signal: pluginSignal }
175
485
  },
176
486
  services: [(serviceContextOwner) => {
177
487
  serviceContext = serviceContextOwner;
488
+ const namespace = createTaskNamespace({
489
+ store,
490
+ manager,
491
+ maxTasks,
492
+ sessionId: execution.sessionId,
493
+ assertAvailable: () => {
494
+ if (!active || disposed || pluginSignal?.aborted) throw new Error("Task session is unavailable.");
495
+ }
496
+ });
497
+ serviceContextOwner.inject([PO_CODEMODE_SERVICE], (context) => {
498
+ const codemode = readPoCodemode(context);
499
+ if (!codemode) return void 0;
500
+ const registration = codemode.register(SOURCE, namespace);
501
+ const restriction = host.registerToolRestriction({ excludedTools: ["task"] });
502
+ return () => {
503
+ restriction.dispose();
504
+ registration.dispose();
505
+ };
506
+ });
178
507
  serviceContextOwner.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (context) => {
179
508
  const registration = requirePoContextContributions(context).register(createTaskContextContribution(() => active && !disposed ? store.snapshot.tasks : []));
180
509
  return () => registration.dispose();
@@ -221,9 +550,9 @@ const root = defineRoot(({ host: serverHost, agent: host, signal: pluginSignal }
221
550
  if (!isCurrent()) return { value: void 0 };
222
551
  store.configureSession(resolveSessionKey(activityContext.sessionId, activityContext.environment));
223
552
  manager.setCwd(activityContext.cwd);
224
- const cleanup = await removeLegacyStoreDirectoryAsync(store.storePath, activityContext.cwd);
553
+ const cleanup = await removeLegacyStoreDirectory(store.storePath, activityContext.cwd);
225
554
  if (!isCurrent()) return { value: void 0 };
226
- const sweep = hasStorePathOverride(activityContext.environment) ? { errors: [] } : await sweepStoreFilesAsync(store.storePath, getStoreTtlMs(activityContext.environment));
555
+ const sweep = hasStorePathOverride(activityContext.environment) ? { errors: [] } : await sweepStoreFiles(store.storePath, getStoreTtlMs(activityContext.environment));
227
556
  for (const error of [...cleanup.errors, ...sweep.errors]) {
228
557
  diagnostics.push(error);
229
558
  report.warn(TASK_EVENT.storeSweepFailed, new Error(error));
@@ -277,12 +606,14 @@ const root = defineRoot(({ host: serverHost, agent: host, signal: pluginSignal }
277
606
  generation += 1;
278
607
  startupAbort.abort();
279
608
  await Promise.allSettled([startup]);
280
- unwatch?.();
281
- background?.dispose();
282
- manager.dispose();
283
- store.dispose();
284
- await ownedReadiness.dispose();
285
- await reporter.shutdown();
609
+ await runCleanups([
610
+ () => unwatch?.(),
611
+ () => background?.dispose(),
612
+ () => manager.dispose(),
613
+ () => store.dispose(),
614
+ () => ownedReadiness.dispose(),
615
+ () => reporter.shutdown()
616
+ ], "Task cleanup failed.");
286
617
  }
287
618
  };
288
619
  });
@@ -310,6 +641,7 @@ function present(document) {
310
641
  if (task.updatedAt) view.updatedAt = task.updatedAt;
311
642
  if (task.delegation) view.delegation = {
312
643
  ...task.delegation.agent === void 0 ? {} : { agent: task.delegation.agent },
644
+ ...task.delegation.identity === void 0 ? {} : { identity: task.delegation.identity },
313
645
  ...task.delegation.state === void 0 ? {} : { state: task.delegation.state }
314
646
  };
315
647
  return [view];
@@ -323,8 +655,9 @@ function createTasksChannel(options = {}) {
323
655
  frameType: TASKS_CHANNEL_TYPE,
324
656
  start(host) {
325
657
  const stores = /* @__PURE__ */ new Map();
326
- const open = (scope) => {
327
- if (stores.has(scope.sessionId)) return;
658
+ let closed = false;
659
+ const open = async (scope) => {
660
+ if (closed || stores.has(scope.sessionId)) return;
328
661
  let store = options.storeFor?.(scope);
329
662
  if (store === void 0) {
330
663
  if (scope.environment === void 0) throw new Error(`Task channel requires an admitted environment for session '${scope.sessionId}'.`);
@@ -334,12 +667,21 @@ function createTasksChannel(options = {}) {
334
667
  storePath: resolveStorePath(scope.cwd, scope.environment, resolveSessionKey(scope.sessionId, scope.environment))
335
668
  });
336
669
  }
337
- store.read();
338
670
  const source = {
339
671
  store,
340
- unsubscribe: () => void 0
672
+ unsubscribe: () => void 0,
673
+ ready: false,
674
+ latest: void 0
341
675
  };
342
676
  stores.set(scope.sessionId, source);
677
+ try {
678
+ await store.readAsync();
679
+ } catch (error) {
680
+ if (stores.get(scope.sessionId) === source) close(scope.sessionId);
681
+ throw error;
682
+ }
683
+ if (closed || stores.get(scope.sessionId) !== source) return;
684
+ source.ready = true;
343
685
  source.unsubscribe = host.directEvents.subscribe(TASKS_CHANNEL_TYPE, scope.sessionId, (payload) => {
344
686
  if (!isTaskDocument(payload)) return;
345
687
  const current = stores.get(scope.sessionId);
@@ -347,6 +689,12 @@ function createTasksChannel(options = {}) {
347
689
  current.latest = payload;
348
690
  host.publish(scope.sessionId, present(payload));
349
691
  }, { replayLatest: true });
692
+ if (!source.latest && store.snapshot.tasks.length > 0) host.publish(scope.sessionId, present(store.snapshot));
693
+ };
694
+ const requestOpen = (scope) => {
695
+ open(scope).catch((error) => {
696
+ host.onNotice(`Could not open task store for session '${scope.sessionId}': ${String(error)}`);
697
+ });
350
698
  };
351
699
  const close = (sessionId) => {
352
700
  const source = stores.get(sessionId);
@@ -355,12 +703,11 @@ function createTasksChannel(options = {}) {
355
703
  source.store.dispose();
356
704
  stores.delete(sessionId);
357
705
  };
358
- for (const scope of host.sessions()) open(scope);
706
+ for (const scope of host.sessions()) requestOpen(scope);
359
707
  return {
360
708
  homeFor(scope) {
361
- open(scope);
362
709
  const source = stores.get(scope.sessionId);
363
- const document = source?.latest ?? source?.store.snapshot;
710
+ const document = source?.ready ? source.latest ?? source.store.snapshot : void 0;
364
711
  if (!document) return {
365
712
  coverage: "unavailable",
366
713
  entities: []
@@ -411,14 +758,15 @@ function createTasksChannel(options = {}) {
411
758
  };
412
759
  },
413
760
  payloadFor(scope) {
414
- open(scope);
761
+ requestOpen(scope);
415
762
  const source = stores.get(scope.sessionId);
416
- const document = source?.latest ?? source?.store.snapshot;
763
+ const document = source?.ready ? source.latest ?? source.store.snapshot : void 0;
417
764
  return document === void 0 ? void 0 : present(document);
418
765
  },
419
- sessionAdded: open,
766
+ sessionAdded: requestOpen,
420
767
  sessionRemoved: close,
421
768
  close() {
769
+ closed = true;
422
770
  for (const sessionId of stores.keys()) close(sessionId);
423
771
  }
424
772
  };
@@ -429,105 +777,6 @@ function createTasksChannel(options = {}) {
429
777
  //#region src/extensions/(backend)/channel/task-graph.server.ts
430
778
  var task_graph_server_default = defineChannel(createTasksChannel);
431
779
  //#endregion
432
- //#region src/services/taskTool/index.ts
433
- function output(value) {
434
- if (typeof value === "object" && value !== null && "content" in value) return value;
435
- return {
436
- content: [{
437
- type: "text",
438
- text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
439
- }],
440
- details: value
441
- };
442
- }
443
- function failure(error) {
444
- return {
445
- content: [{
446
- type: "text",
447
- text: error instanceof Error ? error.message : String(error)
448
- }],
449
- isError: true
450
- };
451
- }
452
- async function reducerAction(store, action, params, maxTasks) {
453
- const { document, value } = await store.mutate((current) => {
454
- const result = applyTaskMutation(current, action, params, void 0, maxTasks);
455
- return {
456
- ...isCommittingOp(result.op) ? { document: result.document } : {},
457
- value: result
458
- };
459
- });
460
- if (value.op.kind === "error") throw new Error(value.op.message);
461
- return buildToolResult(action, params, document, value.op);
462
- }
463
- async function assignmentBatch(manager, assignments, signal) {
464
- const result = [];
465
- for (const [index, assignment] of assignments.entries()) try {
466
- const outcome = await manager.assign(assignment.id, {
467
- agent: assignment.agent,
468
- inlineAgent: assignment.inlineAgent,
469
- instructions: assignment.instructions,
470
- relevantFiles: assignment.relevantFiles,
471
- priorFindings: assignment.priorFindings,
472
- model: assignment.model,
473
- ...assignment.context === "fork" || assignment.context === "fresh" ? { context: assignment.context } : {},
474
- signal
475
- });
476
- result.push({
477
- index,
478
- id: assignment.id,
479
- agent: assignment.agent,
480
- ...outcome
481
- });
482
- } catch (error) {
483
- result.push({
484
- index,
485
- id: assignment.id,
486
- agent: assignment.agent,
487
- ok: false,
488
- message: String(error)
489
- });
490
- }
491
- return result;
492
- }
493
- function createHeadlessTaskTool(store, manager, maxTasks) {
494
- return {
495
- name: "task",
496
- label: "Task",
497
- description: "Maintain a persistent task graph and delegate ready tasks to background agents.",
498
- parameters: TaskParamsSchema,
499
- promptSnippet: "Track complex work persistently and delegate ready tasks",
500
- executionMode: "serial",
501
- async execute(_toolCallId, rawParams, signal, onUpdate) {
502
- if (!Check(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
503
- const params = rawParams;
504
- try {
505
- if ((params.action === "assign" || params.action === "cancel") && !manager) throw new Error("Delegation is not available on this connection.");
506
- if (params.action === "assign") {
507
- if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
508
- onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
509
- const items = await assignmentBatch(manager, params.assignments, signal);
510
- const assigned = items.filter((item) => item.ok).map((item) => item.id);
511
- const text = formatAssignmentResults(items);
512
- if (assigned.length === 0) throw new Error(text);
513
- return buildAssignmentResult(params, store.snapshot, text, {
514
- assigned,
515
- failed: items.length - assigned.length
516
- });
517
- }
518
- if (params.action === "cancel") {
519
- const outcome = await manager.cancel(params.id ?? NaN);
520
- if (!outcome.ok) throw new Error(outcome.message);
521
- return buildTextResult("cancel", params, store.snapshot, outcome.message);
522
- }
523
- return reducerAction(store, params.action, params, maxTasks);
524
- } catch (error) {
525
- return failure(error);
526
- }
527
- }
528
- };
529
- }
530
- //#endregion
531
780
  //#region src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.ts
532
781
  var tasks_server_default$1 = (context) => ({
533
782
  name: COMMAND_NAME,
@@ -545,12 +794,22 @@ var tasks_server_default$1 = (context) => ({
545
794
  //#region src/extensions/workspaces/sessions/(backend)/command/tasks.server.ts
546
795
  var tasks_server_default = defineServerCommand(tasks_server_default$1);
547
796
  //#endregion
797
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-task.server.ts
798
+ var codemode_how_to_task_server_default = defineResource({
799
+ name: "codemode-how-to-task",
800
+ description: "Track work as a task list with the tasks namespace, so the plan and its progress survive compaction, and hand tasks to background subagents. Use at the start of any request with three or more steps, when the person gives a list of things to do, or before delegating work.",
801
+ kind: "skill",
802
+ pinned: true,
803
+ path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-task/SKILL.md"),
804
+ read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-task/SKILL.md")
805
+ });
806
+ //#endregion
548
807
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.ts
549
808
  var task_board_server_default$1 = (context) => ({
550
809
  name: "po/task-board",
551
810
  kind: "context",
552
811
  /**
553
- * The same bounded projection the Pi facet renders: open work only, one line each.
812
+ * The same bounded projection the Pi extension renders: open work only, one line each.
554
813
  * Dumping the whole TaskDocument put every completed task plus the store's own
555
814
  * version/rev/nextId bookkeeping in the prompt, and an idle board still cost a
556
815
  * paragraph. '' is dropped by the prompt composer.
@@ -572,21 +831,24 @@ var task_server_default = defineServerTool(task_server_default$1);
572
831
  //#endregion
573
832
  //#region generated/server.ts
574
833
  const at = (value, context) => typeof value === "function" ? value(context) : value;
834
+ /* v8 ignore next -- generated normalization branch */
835
+ const defined = (values) => values.filter((value) => value !== void 0);
575
836
  const via = (identity, value) => value === void 0 ? void 0 : {
576
837
  ...identity,
577
838
  ...value
578
839
  };
579
- const facet = defineServerPlugin({
840
+ const serverPlugin = defineServerPlugin({
580
841
  name: "@agimon-ai/po-task",
581
842
  providerOverrides: composeServerProviderOverrides(root_server_default),
582
- global: () => ({ get channels() {
583
- return [() => via({ frameType: "task_graph" }, task_graph_server_default())];
843
+ injects: composeRootInjects({ session: [root_server_default] }),
844
+ global: (context) => ({ get channels() {
845
+ return [() => via({ frameType: "task_graph" }, at(task_graph_server_default, context))];
584
846
  } }),
585
- workspace: () => ({ get channels() {
586
- return [() => via({ frameType: "task_graph" }, task_graph_server_default())];
847
+ workspace: (context) => ({ get channels() {
848
+ return defined([context.hosted("global") ? void 0 : () => via({ frameType: "task_graph" }, at(task_graph_server_default, context))]);
587
849
  } }),
588
850
  session: async (context) => {
589
- const scopeSession = await root_server_default(context);
851
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
590
852
  const contextSession = {
591
853
  ...context,
592
854
  root: scopeSession.value
@@ -594,13 +856,13 @@ const facet = defineServerPlugin({
594
856
  return {
595
857
  ...composeRootHooks(scopeSession),
596
858
  get channels() {
597
- return [() => via({ frameType: "task_graph" }, task_graph_server_default())];
859
+ return defined([context.hosted("global") ? void 0 : () => via({ frameType: "task_graph" }, at(task_graph_server_default, context))]);
598
860
  },
599
861
  get commands() {
600
862
  return [via({ name: "tasks" }, at(tasks_server_default, contextSession))];
601
863
  },
602
864
  get resources() {
603
- return [at(task_board_server_default, contextSession)];
865
+ return [at(codemode_how_to_task_server_default, contextSession), at(task_board_server_default, contextSession)];
604
866
  },
605
867
  get tools() {
606
868
  return [via({ name: "task" }, at(task_server_default, contextSession))];
@@ -613,6 +875,6 @@ const facet = defineServerPlugin({
613
875
  }
614
876
  });
615
877
  //#endregion
616
- export { facet as default, facet };
878
+ export { serverPlugin as default, serverPlugin };
617
879
 
618
880
  //# sourceMappingURL=server.mjs.map