@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2

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 (110) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/memory/task-digest.js +1 -1
  28. package/dist/paths.d.ts +1 -0
  29. package/dist/paths.js +11 -0
  30. package/dist/playbooks/background-jobs.md +40 -0
  31. package/dist/playbooks/catalog.d.ts +1 -7
  32. package/dist/playbooks/catalog.js +4 -14
  33. package/dist/playbooks/event-scheduling.md +8 -4
  34. package/dist/playbooks/memory-and-learning.md +1 -1
  35. package/dist/playbooks/outbound-media.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +1 -1
  37. package/dist/playbooks/task-closeout.md +12 -11
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +54 -21
  40. package/dist/playbooks/task-planning.md +46 -19
  41. package/dist/runtime/bootstrap.js +29 -4
  42. package/dist/runtime/channel-context.d.ts +33 -0
  43. package/dist/runtime/dingtalk.d.ts +22 -2
  44. package/dist/runtime/dingtalk.js +141 -0
  45. package/dist/runtime/durable-dispatch.d.ts +10 -0
  46. package/dist/runtime/durable-dispatch.js +42 -1
  47. package/dist/runtime/event-validation.d.ts +48 -0
  48. package/dist/runtime/event-validation.js +81 -0
  49. package/dist/runtime/events.d.ts +17 -8
  50. package/dist/runtime/events.js +96 -22
  51. package/dist/runtime/store.d.ts +1 -1
  52. package/dist/runtime/task-commands.js +29 -51
  53. package/dist/runtime/task-driver.d.ts +5 -8
  54. package/dist/runtime/task-driver.js +120 -93
  55. package/dist/runtime/task-migration.d.ts +11 -0
  56. package/dist/runtime/task-migration.js +70 -0
  57. package/dist/settings.d.ts +11 -0
  58. package/dist/settings.js +12 -0
  59. package/dist/shared/recoverable-error.d.ts +26 -0
  60. package/dist/shared/recoverable-error.js +29 -0
  61. package/dist/shared/task-events.d.ts +0 -26
  62. package/dist/shared/task-events.js +0 -15
  63. package/dist/shared/task-ledger.d.ts +32 -8
  64. package/dist/shared/task-ledger.js +66 -17
  65. package/dist/subagents/builtin/explorer.md +16 -0
  66. package/dist/subagents/builtin/researcher.md +17 -0
  67. package/dist/subagents/builtin/verifier.md +17 -0
  68. package/dist/subagents/discovery.d.ts +17 -3
  69. package/dist/subagents/discovery.js +88 -15
  70. package/dist/subagents/tool.d.ts +21 -1
  71. package/dist/subagents/tool.js +140 -12
  72. package/dist/tasks/control.d.ts +4 -0
  73. package/dist/tasks/control.js +3 -0
  74. package/dist/tasks/store.d.ts +28 -1
  75. package/dist/tasks/store.js +63 -6
  76. package/dist/tasks/transitions.d.ts +40 -0
  77. package/dist/tasks/transitions.js +82 -0
  78. package/dist/tools/bash.d.ts +2 -0
  79. package/dist/tools/bash.js +18 -5
  80. package/dist/tools/event-manage.js +28 -77
  81. package/dist/tools/index.d.ts +4 -0
  82. package/dist/tools/index.js +7 -2
  83. package/dist/tools/job.js +2 -2
  84. package/dist/tools/memory-manage.js +0 -1
  85. package/dist/tools/registry.d.ts +29 -8
  86. package/dist/tools/registry.js +39 -22
  87. package/dist/tools/send-media.d.ts +28 -0
  88. package/dist/tools/send-media.js +88 -0
  89. package/dist/tools/task-manage/create.d.ts +2 -0
  90. package/dist/tools/task-manage/create.js +35 -0
  91. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  92. package/dist/tools/task-manage/lifecycle.js +197 -0
  93. package/dist/tools/task-manage/schema.d.ts +43 -0
  94. package/dist/tools/task-manage/schema.js +90 -0
  95. package/dist/tools/task-manage/shared.d.ts +36 -0
  96. package/dist/tools/task-manage/shared.js +247 -0
  97. package/dist/tools/task-manage/types.d.ts +53 -0
  98. package/dist/tools/task-manage/types.js +1 -0
  99. package/dist/tools/task-manage/verification.d.ts +16 -0
  100. package/dist/tools/task-manage/verification.js +112 -0
  101. package/dist/tools/task-manage.d.ts +9 -89
  102. package/dist/tools/task-manage.js +8 -696
  103. package/dist/tools/tool-details.d.ts +44 -0
  104. package/dist/tools/tool-details.js +62 -0
  105. package/dist/tui/app.js +2 -0
  106. package/dist/tui/terminal-media-sender.d.ts +9 -0
  107. package/dist/tui/terminal-media-sender.js +15 -0
  108. package/package.json +2 -2
  109. package/dist/playbooks/task-recurring.md +0 -41
  110. package/dist/playbooks/task-repair.md +0 -45
@@ -1,4 +1,4 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
2
  import { isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { Agent } from "@earendil-works/pi-agent-core";
4
4
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
@@ -8,6 +8,7 @@ import { recallRelevantMemory } from "../memory/recall.js";
8
8
  import { formatModelReference } from "../models/utils.js";
9
9
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
10
  import { splitH1Sections } from "../shared/markdown-sections.js";
11
+ import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
11
12
  import { shellEscape } from "../shared/shell-escape.js";
12
13
  import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
13
14
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
@@ -47,6 +48,19 @@ const subagentSchema = Type.Object({
47
48
  description: '"worktree" runs in a dedicated git worktree.',
48
49
  })),
49
50
  worktreePath: Type.Optional(Type.String({ description: "Reuse an existing task-owned worktree; must be under channel tasks/worktrees/." })),
51
+ returns: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("artifact")], {
52
+ description: 'How the sub-agent should hand back its result. "text" (default) returns the response directly. "artifact" instructs it to write its primary output to a file and end with an ARTIFACT: <filename> marker. Either way the full output is always saved under the artifact directory, and a reply over the size budget is truncated with a pointer to that file.',
53
+ })),
54
+ thinkingLevel: Type.Optional(Type.Union([
55
+ Type.Literal("off"),
56
+ Type.Literal("minimal"),
57
+ Type.Literal("low"),
58
+ Type.Literal("medium"),
59
+ Type.Literal("high"),
60
+ Type.Literal("xhigh"),
61
+ ], {
62
+ description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for purpose=verify, "off" otherwise.',
63
+ })),
50
64
  });
51
65
  const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
52
66
  enabled: true,
@@ -60,6 +74,21 @@ const MAX_SESSION_SECTION_CHARS = 280;
60
74
  const MAX_SESSION_CONTEXT_CHARS = 1800;
61
75
  const MAX_RECALL_CONTEXT_CHARS = 2200;
62
76
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
77
+ /**
78
+ * Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
79
+ * same prompt-unit currency as the system prompt budget (shared/prompt-units.ts). The full
80
+ * output always lands on disk under the artifact directory regardless of this budget — this
81
+ * only caps what gets echoed into the parent's context.
82
+ */
83
+ export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
84
+ const ARTIFACT_TRUNCATION_HEAD_RATIO = 1;
85
+ /**
86
+ * Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
87
+ * tool-free turn to summarize what it already found instead of having its work discarded.
88
+ * This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
89
+ */
90
+ const CONVERGENCE_WALL_CLOCK_MS = 60_000;
91
+ const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
63
92
  class DirectoryExecutor {
64
93
  constructor(base, directory) {
65
94
  this.base = base;
@@ -78,6 +107,15 @@ function safeGitBranchSegment(value) {
78
107
  .replace(/^-+|-+$/g, "")
79
108
  .slice(0, 48) || "run");
80
109
  }
110
+ function getSubAgentArtifactsRoot(channelDir) {
111
+ return join(channelDir, "subagent-artifacts");
112
+ }
113
+ /** Every run gets its own artifact directory (spec 032 D4), independent of `returns` mode. */
114
+ async function prepareArtifactDir(channelDir, runId) {
115
+ const artifactDir = join(getSubAgentArtifactsRoot(channelDir), safeRunSegment(runId));
116
+ await mkdir(artifactDir, { recursive: true });
117
+ return artifactDir;
118
+ }
81
119
  async function prepareRunContext(runId, params, options) {
82
120
  const purpose = params.purpose ?? "work";
83
121
  const taskId = params.taskId?.trim() || undefined;
@@ -89,12 +127,13 @@ async function prepareRunContext(runId, params, options) {
89
127
  if (taskId && !ownedTask) {
90
128
  throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
91
129
  }
130
+ const artifactDir = await prepareArtifactDir(options.channelDir, runId);
92
131
  const isolation = params.isolation ?? "shared";
93
132
  if (isolation === "shared") {
94
133
  if (params.worktreePath)
95
134
  throw new Error("worktreePath requires isolation=worktree.");
96
135
  const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
97
- return { runId, purpose, taskId, isolation, workingDirectory };
136
+ return { runId, purpose, taskId, isolation, workingDirectory, artifactDir };
98
137
  }
99
138
  if (!taskId)
100
139
  throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
@@ -122,6 +161,7 @@ async function prepareRunContext(runId, params, options) {
122
161
  workingDirectory: existing,
123
162
  worktreePath: existing,
124
163
  worktreeBranch: branchResult.code === 0 ? branchResult.stdout.trim() || undefined : undefined,
164
+ artifactDir,
125
165
  };
126
166
  await recordTaskWorktree(options.channelDir, taskId, context);
127
167
  return context;
@@ -149,6 +189,7 @@ async function prepareRunContext(runId, params, options) {
149
189
  workingDirectory: path,
150
190
  worktreePath: path,
151
191
  worktreeBranch: branch,
192
+ artifactDir,
152
193
  };
153
194
  try {
154
195
  await recordTaskWorktree(options.channelDir, taskId, context);
@@ -214,6 +255,42 @@ function buildStoppedText(config, reason, finalText) {
214
255
  }
215
256
  return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
216
257
  }
258
+ const ARTIFACT_MARKER_PATTERN = /(?:^|\n)ARTIFACT:\s*(\S+)\s*$/i;
259
+ function parseArtifactMarker(output) {
260
+ return ARTIFACT_MARKER_PATTERN.exec(output.trim())?.[1];
261
+ }
262
+ /**
263
+ * Spec 032 D4: the full text always lands on disk, independent of `returns` mode and of
264
+ * whether it fits the reply budget. What comes back to the parent is capped at
265
+ * MAX_SUBAGENT_RESULT_UNITS; a reply over budget is truncated with a pointer to the file
266
+ * a chatty sub-agent can no longer blow out the parent's context.
267
+ */
268
+ async function finalizeSubAgentOutput(runContext, finalText, returns) {
269
+ const trimmed = finalText.trim();
270
+ const outputPath = join(runContext.artifactDir, "output.md");
271
+ if (trimmed) {
272
+ await writeFile(outputPath, finalText, "utf-8");
273
+ }
274
+ let artifactPath;
275
+ if (returns === "artifact" && trimmed) {
276
+ const filename = parseArtifactMarker(trimmed);
277
+ if (filename) {
278
+ const candidate = resolve(runContext.artifactDir, filename);
279
+ const rel = relative(runContext.artifactDir, candidate);
280
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
281
+ artifactPath = candidate;
282
+ }
283
+ }
284
+ }
285
+ if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
286
+ return { artifactPath, replyText: finalText, truncated: false };
287
+ }
288
+ const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
289
+ headRatio: ARTIFACT_TRUNCATION_HEAD_RATIO,
290
+ marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
291
+ });
292
+ return { artifactPath, replyText: clipped.text, truncated: true };
293
+ }
217
294
  /**
218
295
  * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
219
296
  * context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
@@ -259,7 +336,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
259
336
  bashDefaultTimeoutSeconds: bashTimeoutSec,
260
337
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
261
338
  }
262
- function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
339
+ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
263
340
  const taskText = task.trim();
264
341
  const lines = [
265
342
  `Runtime context:`,
@@ -268,6 +345,7 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
268
345
  `- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
269
346
  `- Working directory: ${runContext.workingDirectory}`,
270
347
  `- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
348
+ `- Artifact directory: ${runContext.artifactDir}`,
271
349
  `- Your configured role: ${config.name}`,
272
350
  ];
273
351
  for (const block of contextBlocks) {
@@ -281,6 +359,9 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
281
359
  const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
282
360
  lines.push("", "Verification protocol:", `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`, "- You are the checker, not the maker. Do not edit files or fix failures; report them.", "- Run deterministic checks when available and distinguish observed evidence from assumptions.", "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.");
283
361
  }
362
+ else if (returns === "artifact") {
363
+ lines.push("", "Output protocol:", `- Write your primary output as a file under the artifact directory above.`, "- End the response with exactly one final line: ARTIFACT: <filename>");
364
+ }
284
365
  return lines.join("\n");
285
366
  }
286
367
  function buildSessionContextBlock(sessionMarkdown) {
@@ -362,7 +443,7 @@ function filterToolsByName(allTools, names) {
362
443
  const allowed = new Set(names);
363
444
  return allTools.filter((tool) => allowed.has(tool.name));
364
445
  }
365
- function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict) {
446
+ function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict, extras) {
366
447
  return {
367
448
  kind: "subagent",
368
449
  agent: config.name,
@@ -385,6 +466,9 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
385
466
  worktreePath: runContext.worktreePath,
386
467
  worktreeBranch: runContext.worktreeBranch,
387
468
  verificationVerdict,
469
+ artifactDir: runContext.artifactDir,
470
+ artifactPath: extras?.artifactPath,
471
+ resultTruncated: extras?.resultTruncated ?? false,
388
472
  };
389
473
  }
390
474
  function linkAbortSignals(parentSignal, childController) {
@@ -403,7 +487,7 @@ export function createSubAgentTool(options) {
403
487
  return {
404
488
  name: "subagent",
405
489
  label: "subagent",
406
- description: "Delegate a task to a sub-agent with an isolated context. You may use a predefined sub-agent from workspaceDir/sub-agents/ or define a temporary inline sub-agent by providing systemPrompt/tools/model parameters. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
490
+ description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no predefined agent is required. You may instead name a predefined sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
407
491
  parameters: subagentSchema,
408
492
  execute: async (_toolCallId, params, signal, onUpdate) => {
409
493
  const availableModels = options.getAvailableModels();
@@ -417,11 +501,12 @@ export function createSubAgentTool(options) {
417
501
  if (taskLengthError) {
418
502
  throw new Error(taskLengthError);
419
503
  }
420
- const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params);
504
+ const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
421
505
  if (!invocation.config) {
422
506
  throw new Error(`${invocation.error}\n\nAvailable predefined sub-agents:\n${formatSubAgentList(discovery.agents)}`);
423
507
  }
424
508
  const config = invocation.config;
509
+ const returns = params.returns ?? "text";
425
510
  const runContext = await prepareRunContext(_toolCallId, params, options);
426
511
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
427
512
  const apiKey = await options.resolveApiKey(config.model);
@@ -430,6 +515,8 @@ export function createSubAgentTool(options) {
430
515
  let assistantTurns = 0;
431
516
  let toolCalls = 0;
432
517
  let failureReason;
518
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, never for a parent-driven stop. */
519
+ let budgetExceeded = false;
433
520
  let lastUpdateText = "";
434
521
  const emitUpdate = (text) => {
435
522
  const nextText = text.trim();
@@ -454,7 +541,7 @@ export function createSubAgentTool(options) {
454
541
  initialState: {
455
542
  systemPrompt: config.systemPrompt,
456
543
  model: config.model,
457
- thinkingLevel: "off",
544
+ thinkingLevel: config.thinkingLevel,
458
545
  tools: filterToolsByName(availableTools, config.tools),
459
546
  },
460
547
  convertToLlm,
@@ -464,6 +551,7 @@ export function createSubAgentTool(options) {
464
551
  const unlinkAbortSignals = linkAbortSignals(signal, childController);
465
552
  const wallClockTimer = setTimeout(() => {
466
553
  failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
554
+ budgetExceeded = true;
467
555
  worker.abort();
468
556
  }, config.maxWallTimeSec * 1000);
469
557
  const unsubscribe = worker.subscribe((event) => {
@@ -487,6 +575,7 @@ export function createSubAgentTool(options) {
487
575
  emitUpdate(formatStatus(config.name, label));
488
576
  if (toolCalls > config.maxToolCalls) {
489
577
  failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
578
+ budgetExceeded = true;
490
579
  emitUpdate(formatStatus(config.name, "tool budget reached"));
491
580
  worker.abort();
492
581
  }
@@ -496,6 +585,7 @@ export function createSubAgentTool(options) {
496
585
  event.toolResults.length > 0 &&
497
586
  assistantTurns >= config.maxTurns) {
498
587
  failureReason = `Turn budget exceeded (${config.maxTurns})`;
588
+ budgetExceeded = true;
499
589
  emitUpdate(formatStatus(config.name, "turn budget reached"));
500
590
  worker.abort();
501
591
  }
@@ -509,12 +599,43 @@ export function createSubAgentTool(options) {
509
599
  childController.signal.addEventListener("abort", abortWorker, { once: true });
510
600
  try {
511
601
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
512
- await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
602
+ await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
513
603
  await worker.waitForIdle();
514
604
  }
515
605
  finally {
516
606
  childController.signal.removeEventListener("abort", abortWorker);
517
607
  }
608
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
609
+ // conclusion instead of discarding the work outright. A parent-driven /stop
610
+ // (childController already aborted) skips this — the user asked to stop now.
611
+ if (budgetExceeded && !childController.signal.aborted) {
612
+ clearTimeout(wallClockTimer);
613
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
614
+ const preConvergenceMessageCount = worker.state.messages.length;
615
+ worker.state.tools = [];
616
+ let convergenceTimedOut = false;
617
+ const convergenceTimer = setTimeout(() => {
618
+ convergenceTimedOut = true;
619
+ worker.abort();
620
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
621
+ childController.signal.addEventListener("abort", abortWorker, { once: true });
622
+ try {
623
+ await worker.prompt(CONVERGENCE_PROMPT);
624
+ await worker.waitForIdle();
625
+ }
626
+ catch {
627
+ // Best effort: fall through to whatever worker.state.messages holds.
628
+ }
629
+ finally {
630
+ childController.signal.removeEventListener("abort", abortWorker);
631
+ clearTimeout(convergenceTimer);
632
+ }
633
+ if (convergenceTimedOut) {
634
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
635
+ // convergence turn and fall back to whatever came before it.
636
+ worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
637
+ }
638
+ }
518
639
  }
519
640
  finally {
520
641
  unsubscribe();
@@ -575,14 +696,21 @@ export function createSubAgentTool(options) {
575
696
  throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
576
697
  }
577
698
  emitUpdate(formatStatus(config.name, "stopped"));
699
+ const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
578
700
  return {
579
- content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalText) }],
580
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict),
701
+ content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) }],
702
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
581
703
  };
582
704
  }
705
+ const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
583
706
  return {
584
- content: [{ type: "text", text: finalText || `(Sub-agent ${config.name} completed with no text output)` }],
585
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict),
707
+ content: [
708
+ {
709
+ type: "text",
710
+ text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
711
+ },
712
+ ],
713
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
586
714
  };
587
715
  },
588
716
  };
@@ -4,6 +4,8 @@ export type TaskSideEffects = "read-only" | "workspace" | "external";
4
4
  export type TaskVerificationMode = "evidence" | "independent";
5
5
  export type TaskVerificationStatus = "pending" | "passed" | "failed";
6
6
  export type TaskOutcome = "pending" | "running" | "progress" | "blocked" | "failed" | "verified";
7
+ /** Who paused a task: a user via /tasks pause, or the deterministic governor (ex-`escalated`). */
8
+ export type TaskPausedBy = "user" | "governor";
7
9
  export interface TaskBudget {
8
10
  maxAttempts: number;
9
11
  maxTokens?: number;
@@ -52,6 +54,8 @@ export interface TaskControl {
52
54
  lastFinishedAt?: string;
53
55
  /** Identifier of the currently open recurring-task cycle, when applicable. */
54
56
  cycleId?: string;
57
+ /** Present only while status is `paused`; distinguishes a user pause from a governor pause. */
58
+ pausedBy?: TaskPausedBy;
55
59
  }
56
60
  export interface TaskControlPatch {
57
61
  priority?: TaskPriority;
@@ -5,6 +5,7 @@ const SIDE_EFFECTS = ["read-only", "workspace", "external"];
5
5
  const VERIFICATION_MODES = ["evidence", "independent"];
6
6
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
7
7
  const OUTCOMES = ["pending", "running", "progress", "blocked", "failed", "verified"];
8
+ const PAUSED_BY = ["user", "governor"];
8
9
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
9
10
  function isRecord(value) {
10
11
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -154,6 +155,7 @@ export function parseTaskControl(raw) {
154
155
  lastStartedAt: optionalString(value.lastStartedAt),
155
156
  lastFinishedAt: optionalString(value.lastFinishedAt),
156
157
  cycleId: optionalString(value.cycleId),
158
+ pausedBy: value.pausedBy === undefined ? undefined : enumValue(value.pausedBy, PAUSED_BY, "user"),
157
159
  };
158
160
  }
159
161
  /** Reset state which is meaningful only within one recurring task cycle. */
@@ -180,6 +182,7 @@ export function resetTaskControlForCycle(control, cycleId) {
180
182
  lastStartedAt: undefined,
181
183
  lastFinishedAt: undefined,
182
184
  cycleId: normalizedCycleId,
185
+ pausedBy: undefined,
183
186
  };
184
187
  }
185
188
  function patchOptionalString(current, value) {
@@ -1,11 +1,18 @@
1
1
  import { type TaskDocumentFields } from "../shared/task-ledger.js";
2
- import type { TaskControl, TaskOutcome } from "./control.js";
2
+ import { type TaskControl, type TaskOutcome } from "./control.js";
3
3
  export interface StoredTaskDocument {
4
4
  id: string;
5
5
  path: string;
6
6
  fields: TaskDocumentFields;
7
7
  body: string;
8
8
  }
9
+ /**
10
+ * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
11
+ * verification PASS and external approval survive routine Current Cycle / History logging and
12
+ * only break when the contract itself changes (spec 029, D4). Old attestations that hashed the
13
+ * whole body naturally fail this check after upgrade and are re-verified — verification should
14
+ * always reflect current content, so there is no compatibility burden.
15
+ */
9
16
  export declare function taskBodyHash(body: string): string;
10
17
  export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
11
18
  export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
@@ -26,7 +33,27 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
26
33
  silent?: boolean;
27
34
  finishedAt: Date;
28
35
  }): Promise<void>;
36
+ /**
37
+ * A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
38
+ * the former `escalated` status, now `paused` + `pausedBy: "governor"`), records the reason,
39
+ * and clears the wake so no automatic dispatch resumes it until a human intervenes.
40
+ */
29
41
  export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
42
+ /**
43
+ * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
44
+ * with a `-N` suffix when the same task is reopened more than once on the same local day.
45
+ */
46
+ export declare function nextCycleId(previousCycleId: string | undefined, now: Date): string;
47
+ /**
48
+ * Open the next cycle of a done recurring task entirely in the runtime (spec 029, D2):
49
+ * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
50
+ * mark it `active`. This is the deterministic replacement for the retired
51
+ * `task_manage start-cycle` action — no LLM turn is spent just to reopen a cycle.
52
+ */
53
+ export declare function openRecurringTaskCycle(channelDir: string, id: string, now: Date): Promise<{
54
+ document: StoredTaskDocument;
55
+ cycleId: string;
56
+ } | undefined>;
30
57
  export declare function dependencyState(channelDir: string, dependencyIds: readonly string[], ownerId?: string): Promise<{
31
58
  ready: boolean;
32
59
  reason?: string;
@@ -3,9 +3,17 @@ import { existsSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
- import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, taskBody, } from "../shared/task-ledger.js";
6
+ import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, startTaskCycle, taskBody, taskContractSegment, } from "../shared/task-ledger.js";
7
+ import { resetTaskControlForCycle } from "./control.js";
8
+ /**
9
+ * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
10
+ * verification PASS and external approval survive routine Current Cycle / History logging and
11
+ * only break when the contract itself changes (spec 029, D4). Old attestations that hashed the
12
+ * whole body naturally fail this check after upgrade and are re-verified — verification should
13
+ * always reflect current content, so there is no compatibility burden.
14
+ */
7
15
  export function taskBodyHash(body) {
8
- return createHash("sha256").update(body).digest("hex");
16
+ return createHash("sha256").update(taskContractSegment(body)).digest("hex");
9
17
  }
10
18
  export async function readStoredTask(channelDir, idInput, includeArchive = false, allowInvalidControl = false) {
11
19
  const id = normalizeTaskId(idInput);
@@ -29,7 +37,7 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
29
37
  id,
30
38
  path,
31
39
  fields: {
32
- status: frontmatter.status ?? "open",
40
+ status: frontmatter.status ?? "active",
33
41
  wake: frontmatter.wake,
34
42
  schedule: frontmatter.schedule,
35
43
  recurrence: frontmatter.recurrence,
@@ -108,17 +116,59 @@ export async function finishTaskAttempt(channelDir, id, result) {
108
116
  }
109
117
  }, true);
110
118
  }
119
+ /**
120
+ * A governor stop: the deterministic task governor pauses the task (spec 029, D3 — this is
121
+ * the former `escalated` status, now `paused` + `pausedBy: "governor"`), records the reason,
122
+ * and clears the wake so no automatic dispatch resumes it until a human intervenes.
123
+ */
111
124
  export async function escalateTask(channelDir, id, reason) {
112
125
  const document = await updateStoredTask(channelDir, id, (task) => {
113
- task.fields.status = "escalated";
126
+ task.fields.status = "paused";
114
127
  task.fields.wake = undefined;
115
128
  if (task.fields.control) {
129
+ task.fields.control.pausedBy = "governor";
116
130
  task.fields.control.lastOutcome = "blocked";
117
131
  task.fields.control.blockedReason = reason;
118
132
  }
119
133
  });
120
134
  return document !== undefined;
121
135
  }
136
+ /**
137
+ * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
138
+ * with a `-N` suffix when the same task is reopened more than once on the same local day.
139
+ */
140
+ export function nextCycleId(previousCycleId, now) {
141
+ const y = now.getFullYear();
142
+ const m = String(now.getMonth() + 1).padStart(2, "0");
143
+ const d = String(now.getDate()).padStart(2, "0");
144
+ const base = `cycle-${y}-${m}-${d}`;
145
+ if (!previousCycleId || (previousCycleId !== base && !previousCycleId.startsWith(`${base}-`)))
146
+ return base;
147
+ const suffix = previousCycleId.slice(base.length + 1);
148
+ const previousCount = suffix ? Number.parseInt(suffix, 10) : 1;
149
+ const nextCount = Number.isFinite(previousCount) && previousCount >= 1 ? previousCount + 1 : 2;
150
+ return `${base}-${nextCount}`;
151
+ }
152
+ /**
153
+ * Open the next cycle of a done recurring task entirely in the runtime (spec 029, D2):
154
+ * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
155
+ * mark it `active`. This is the deterministic replacement for the retired
156
+ * `task_manage start-cycle` action — no LLM turn is spent just to reopen a cycle.
157
+ */
158
+ export async function openRecurringTaskCycle(channelDir, id, now) {
159
+ let cycleId;
160
+ const document = await updateStoredTask(channelDir, id, (task) => {
161
+ cycleId = nextCycleId(task.fields.control?.cycleId, now);
162
+ task.body = startTaskCycle(task.body, cycleId);
163
+ task.fields.status = "active";
164
+ task.fields.wake = undefined;
165
+ if (task.fields.control)
166
+ task.fields.control = resetTaskControlForCycle(task.fields.control, cycleId);
167
+ });
168
+ if (!document || !cycleId)
169
+ return undefined;
170
+ return { document, cycleId };
171
+ }
122
172
  export async function dependencyState(channelDir, dependencyIds, ownerId) {
123
173
  const detectCycle = async (id, path, active) => {
124
174
  if (id === ownerId || active.has(id))
@@ -143,8 +193,15 @@ export async function dependencyState(channelDir, dependencyIds, ownerId) {
143
193
  const dependency = await readStoredTask(channelDir, dependencyId, true, true);
144
194
  if (!dependency)
145
195
  return { ready: false, reason: `dependency ${dependencyId} is missing` };
146
- if (dependency.fields.status === "cancelled" || dependency.fields.status === "escalated") {
147
- return { ready: false, reason: `dependency ${dependencyId} is ${dependency.fields.status}` };
196
+ if (dependency.fields.status === "cancelled") {
197
+ return { ready: false, reason: `dependency ${dependencyId} is cancelled` };
198
+ }
199
+ // A governor-paused dependency will not self-recover, so it blocks the dependent
200
+ // terminally (matches the retired `escalated` semantics); a user pause is a soft wait.
201
+ if (dependency.fields.status === "paused") {
202
+ return dependency.fields.control?.pausedBy === "governor"
203
+ ? { ready: false, reason: `dependency ${dependencyId} is paused by the governor` }
204
+ : { ready: false, reason: `waiting for dependency ${dependencyId} (paused)` };
148
205
  }
149
206
  if (dependency.fields.status !== "done")
150
207
  return { ready: false, reason: `waiting for dependency ${dependencyId}` };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The task status model and its single transition table (spec 029, D3).
3
+ *
4
+ * There are six canonical statuses. Every status maps to exactly one driver behaviour;
5
+ * statuses that used to differ only for human readers were merged (their nuance now lives
6
+ * in free-text `control.blockedReason`). A single `action × fromStatus → toStatus` table
7
+ * replaces the per-action status guards that used to be scattered across `task_manage` and
8
+ * the `/tasks` command handlers, so an illegal transition always fails the same way.
9
+ *
10
+ * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
11
+ * waiting → sleep until wake, then dispatch
12
+ * verifying → dispatch a checker-only turn
13
+ * paused → never dispatched (excluded at the driver scan layer, zero token)
14
+ * done → recurring: reopen next cycle at wake; otherwise archived
15
+ * cancelled → archived, never
16
+ */
17
+ export declare const TASK_STATUSES: readonly ["active", "waiting", "verifying", "done", "cancelled", "paused"];
18
+ export type TaskStatus = (typeof TASK_STATUSES)[number];
19
+ /** Statuses a user/agent may set directly via create/progress/set. */
20
+ export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "paused"];
21
+ export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
22
+ /** Statuses the driver never dispatches. */
23
+ export declare const TERMINAL_TASK_STATUSES: Set<string>;
24
+ export type TaskLifecycleAction = "create" | "progress" | "candidate" | "verify" | "done" | "cancel" | "set" | "pause" | "resume" | "run";
25
+ /**
26
+ * Map a stored (possibly legacy) status string to a canonical status.
27
+ * Legacy files are read losslessly and written back canonical on the next write;
28
+ * there is no disk migration. `escalated` maps to `paused` — the caller is expected to
29
+ * stamp `control.pausedBy = "governor"` to preserve the "stopped by the governor" nuance.
30
+ */
31
+ export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
32
+ /** True when the stored status was the legacy `escalated` (⇒ paused by the governor). */
33
+ export declare function wasLegacyEscalated(raw: string | undefined): boolean;
34
+ export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
35
+ /**
36
+ * Assert an action is legal from the current status, throwing a uniform error otherwise.
37
+ * Returns the resolved target status: a fixed status, or — for `to: "caller"` actions —
38
+ * `requestedStatus` when supplied (validated as settable) else the unchanged `from`.
39
+ */
40
+ export declare function resolveTaskTransition(action: TaskLifecycleAction, id: string, from: TaskStatus, requestedStatus?: string): TaskStatus;
@@ -0,0 +1,82 @@
1
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
2
+ /**
3
+ * The task status model and its single transition table (spec 029, D3).
4
+ *
5
+ * There are six canonical statuses. Every status maps to exactly one driver behaviour;
6
+ * statuses that used to differ only for human readers were merged (their nuance now lives
7
+ * in free-text `control.blockedReason`). A single `action × fromStatus → toStatus` table
8
+ * replaces the per-action status guards that used to be scattered across `task_manage` and
9
+ * the `/tasks` command handlers, so an illegal transition always fails the same way.
10
+ *
11
+ * active → dispatchable now (wake-gated: not yet due ⇒ sleep until wake)
12
+ * waiting → sleep until wake, then dispatch
13
+ * verifying → dispatch a checker-only turn
14
+ * paused → never dispatched (excluded at the driver scan layer, zero token)
15
+ * done → recurring: reopen next cycle at wake; otherwise archived
16
+ * cancelled → archived, never
17
+ */
18
+ export const TASK_STATUSES = ["active", "waiting", "verifying", "done", "cancelled", "paused"];
19
+ /** Statuses a user/agent may set directly via create/progress/set. */
20
+ export const SETTABLE_TASK_STATUSES = ["active", "waiting", "paused"];
21
+ /** Statuses the driver never dispatches. */
22
+ export const TERMINAL_TASK_STATUSES = new Set(["done", "cancelled", "paused"]);
23
+ const TRANSITIONS = {
24
+ create: { from: [], to: "active" },
25
+ progress: { from: ["active", "waiting", "verifying"], to: "caller" },
26
+ candidate: { from: ["active", "waiting"], to: "verifying" },
27
+ verify: { from: ["verifying"], to: "verifying" },
28
+ done: { from: ["active", "waiting", "verifying"], to: "done" },
29
+ cancel: { from: ["active", "waiting", "verifying", "paused"], to: "cancelled" },
30
+ set: { from: ["active", "waiting", "verifying", "paused", "done"], to: "caller" },
31
+ pause: { from: ["active", "waiting", "verifying"], to: "paused" },
32
+ resume: { from: ["paused"], to: "active" },
33
+ run: { from: ["paused", "active", "waiting"], to: "active" },
34
+ };
35
+ /**
36
+ * Map a stored (possibly legacy) status string to a canonical status.
37
+ * Legacy files are read losslessly and written back canonical on the next write;
38
+ * there is no disk migration. `escalated` maps to `paused` — the caller is expected to
39
+ * stamp `control.pausedBy = "governor"` to preserve the "stopped by the governor" nuance.
40
+ */
41
+ export function normalizeStoredStatus(raw) {
42
+ switch (raw) {
43
+ case undefined:
44
+ case "":
45
+ case "open":
46
+ case "in-progress":
47
+ return "active";
48
+ case "awaiting-user":
49
+ case "blocked":
50
+ return "waiting";
51
+ case "escalated":
52
+ return "paused";
53
+ default:
54
+ return TASK_STATUSES.includes(raw) ? raw : "active";
55
+ }
56
+ }
57
+ /** True when the stored status was the legacy `escalated` (⇒ paused by the governor). */
58
+ export function wasLegacyEscalated(raw) {
59
+ return raw === "escalated";
60
+ }
61
+ export function isSettableTaskStatus(value) {
62
+ return SETTABLE_TASK_STATUSES.includes(value);
63
+ }
64
+ /**
65
+ * Assert an action is legal from the current status, throwing a uniform error otherwise.
66
+ * Returns the resolved target status: a fixed status, or — for `to: "caller"` actions —
67
+ * `requestedStatus` when supplied (validated as settable) else the unchanged `from`.
68
+ */
69
+ export function resolveTaskTransition(action, id, from, requestedStatus) {
70
+ const rule = TRANSITIONS[action];
71
+ if (!rule.from.includes(from)) {
72
+ throw new RecoverableToolError(`Task ${id} is ${from}; action ${action} allows only from: ${rule.from.join(", ") || "(none)"}.`);
73
+ }
74
+ if (rule.to !== "caller")
75
+ return rule.to;
76
+ if (requestedStatus === undefined)
77
+ return from;
78
+ if (!isSettableTaskStatus(requestedStatus)) {
79
+ throw new RecoverableToolError(`Invalid status "${requestedStatus}". Use one of ${SETTABLE_TASK_STATUSES.join(", ")}.`);
80
+ }
81
+ return requestedStatus;
82
+ }
@@ -15,6 +15,8 @@ declare const bashSchema: Type.TObject<{
15
15
  command: Type.TString;
16
16
  timeout: Type.TOptional<Type.TInteger>;
17
17
  async: Type.TOptional<Type.TBoolean>;
18
+ notify: Type.TOptional<Type.TBoolean>;
19
+ taskId: Type.TOptional<Type.TString>;
18
20
  }>;
19
21
  export interface BashToolOptions {
20
22
  defaultTimeoutSeconds?: number;