@oyasmi/pipiclaw 0.9.1 → 0.9.2-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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -1,6 +1,6 @@
1
- import { existsSync, realpathSync, statSync } from "node:fs";
1
+ import { realpathSync, statSync } from "node:fs";
2
2
  import { mkdir } from "node:fs/promises";
3
- import { isAbsolute, join, relative, resolve } from "node:path";
3
+ import { join, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
5
5
  import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
6
6
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
@@ -14,25 +14,45 @@ import { formatLocalTime } from "../shared/local-time.js";
14
14
  import { splitH1Sections } from "../shared/markdown-sections.js";
15
15
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
16
16
  import { RecoverableToolError } from "../shared/recoverable-error.js";
17
- import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
17
+ import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
18
18
  import { createEmptyUsageTotals } from "../shared/types.js";
19
- import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
19
+ import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
20
20
  import { readStoredTask } from "../tasks/store.js";
21
21
  import { writeVerificationAttestation } from "../tasks/verification.js";
22
+ import { describeToolCall } from "../tools/presentation.js";
22
23
  import { buildToolSet } from "../tools/registry.js";
23
- import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
24
+ import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
24
25
  import { launchExternalRun } from "./external/run.js";
25
26
  import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
26
27
  import { resolveVerificationOutcome } from "./verification-outcome.js";
27
28
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
29
+ /** Shared by both invocation surfaces (spec 046, D2.1). */
30
+ const workingDirectoryField = Type.Optional(Type.String({
31
+ description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
32
+ }));
33
+ const purposeField = Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
34
+ description: 'Use "verify" for an independent task acceptance check. A write-capable verifier may run tests/builds; its attestation is advisory.',
35
+ }));
36
+ const taskIdField = Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." }));
37
+ /**
38
+ * Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
39
+ * ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
40
+ * a call naming an external role cannot pass any of them (there is nowhere for it to put them).
41
+ */
28
42
  const subagentSchema = Type.Object({
29
- label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
30
- agent: Type.Optional(Type.String({ description: "Name of a configured sub-agent from workspaceDir/sub-agents/" })),
31
- name: Type.Optional(Type.String({ description: "Optional display name for an inline sub-agent" })),
43
+ agent: Type.String({ description: "Name of a configured sub-agent from workspaceDir/sub-agents/" }),
32
44
  task: Type.String({ description: "Complete task description for the sub-agent" }),
33
- systemPrompt: Type.Optional(Type.String({
34
- description: "Optional inline system prompt for a temporary sub-agent. Use when no configured agent fits.",
35
- })),
45
+ workingDirectory: workingDirectoryField,
46
+ purpose: purposeField,
47
+ taskId: taskIdField,
48
+ });
49
+ /**
50
+ * Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
51
+ * Carries every field a role file would otherwise supply.
52
+ */
53
+ const subagentInlineSchema = Type.Object({
54
+ task: Type.String({ description: "Complete task description for the sub-agent" }),
55
+ systemPrompt: Type.String({ description: "System prompt defining this one-off sub-agent's identity and task." }),
36
56
  tools: Type.Optional(Type.Array(Type.String(), { description: "Optional tool whitelist for the sub-agent" })),
37
57
  model: Type.Optional(Type.String({ description: "Optional exact model reference. Defaults to the parent's current model." })),
38
58
  effort: Type.Optional(Type.Union([Type.Literal("quick"), Type.Literal("standard"), Type.Literal("deep")], {
@@ -41,19 +61,6 @@ const subagentSchema = Type.Object({
41
61
  context: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
42
62
  description: 'What context to inject. "none" (default) runs fully isolated; "session" adds current session state; "relevant" adds session state plus recalled memory.',
43
63
  })),
44
- paths: Type.Optional(Type.Array(Type.String(), {
45
- description: "Optional preferred file or directory paths for the sub-agent to focus on.",
46
- })),
47
- workingDirectory: Type.Optional(Type.String({
48
- description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
49
- })),
50
- purpose: Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
51
- description: 'Use "verify" for an independent, read-only task acceptance check.',
52
- })),
53
- taskId: Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." })),
54
- returns: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("artifact")], {
55
- description: '"text" (default) returns the response directly; "artifact" makes the sub-agent write its primary output to a file and end with an ARTIFACT: <filename> marker. The full output is saved to disk either way.',
56
- })),
57
64
  thinkingLevel: Type.Optional(Type.Union([
58
65
  Type.Literal("off"),
59
66
  Type.Literal("minimal"),
@@ -63,14 +70,15 @@ const subagentSchema = Type.Object({
63
70
  Type.Literal("xhigh"),
64
71
  Type.Literal("max"),
65
72
  ], {
66
- description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for internal delegations and for external purpose=verify; ' +
67
- "an external purpose=work delegation with no explicit value leaves this unset, so the target CLI's own configuration decides.",
73
+ description: "Optional reasoning effort for the sub-agent.",
68
74
  })),
69
75
  mutates: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("write")], {
70
76
  description: 'Whether this delegation will modify the working directory. Declare "write" whenever the sub-agent may write ' +
71
- "files (including through bash) so it takes the exclusive workspace write lease. Defaults to inference from " +
72
- "`tools` (write/edit only), which does not see bash.",
77
+ "files (including through bash) so it takes the exclusive workspace write lease.",
73
78
  })),
79
+ workingDirectory: workingDirectoryField,
80
+ purpose: purposeField,
81
+ taskId: taskIdField,
74
82
  });
75
83
  const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
76
84
  enabled: true,
@@ -91,7 +99,7 @@ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
91
99
  * only caps what gets echoed into the parent's context.
92
100
  */
93
101
  export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
94
- const ARTIFACT_TRUNCATION_HEAD_RATIO = 1;
102
+ const RESULT_TRUNCATION_HEAD_RATIO = 1;
95
103
  /**
96
104
  * Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
97
105
  * tool-free turn to summarize what it already found instead of having its work discarded.
@@ -162,16 +170,25 @@ export function assertWithinProjectBoundary(target, base, requested) {
162
170
  function resolveRunWorkingDirectory(requested, options) {
163
171
  const base = resolve(options.workingDirectory ?? process.cwd());
164
172
  const trimmed = requested?.trim();
173
+ // Resolve the project root once as well. Returning an alias here would leave the later lease,
174
+ // executor, subject hash, and external cwd exposed to a symlink swap after admission.
175
+ const canonicalBase = realpathOrSelf(base);
165
176
  if (!trimmed)
166
- return base;
167
- const target = resolve(base, trimmed);
168
- if (!existsSync(target) || !statSync(target).isDirectory()) {
177
+ return canonicalBase;
178
+ const target = resolve(canonicalBase, trimmed);
179
+ let canonicalTarget;
180
+ try {
181
+ canonicalTarget = realpathSync(target);
182
+ if (!statSync(canonicalTarget).isDirectory())
183
+ throw new Error("not a directory");
184
+ }
185
+ catch {
169
186
  throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
170
187
  }
171
188
  if (options.projectBoundary === "project") {
172
- assertWithinProjectBoundary(target, base, requested ?? trimmed);
189
+ assertWithinProjectBoundary(canonicalTarget, canonicalBase, requested ?? trimmed);
173
190
  }
174
- return target;
191
+ return canonicalTarget;
175
192
  }
176
193
  async function prepareRunContext(runId, params, options) {
177
194
  const purpose = params.purpose ?? "work";
@@ -181,7 +198,7 @@ async function prepareRunContext(runId, params, options) {
181
198
  if (taskId && !TASK_ID_PATTERN.test(taskId))
182
199
  throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
183
200
  if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
184
- throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
201
+ throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
185
202
  }
186
203
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
187
204
  const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
@@ -220,47 +237,35 @@ function buildStoppedText(config, reason, finalText) {
220
237
  }
221
238
  return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
222
239
  }
223
- const ARTIFACT_MARKER_PATTERN = /(?:^|\n)ARTIFACT:\s*(\S+)\s*$/i;
224
- function parseArtifactMarker(output) {
225
- return ARTIFACT_MARKER_PATTERN.exec(output.trim())?.[1];
226
- }
227
240
  /**
228
- * Spec 032 D4: the full text always lands on disk, independent of `returns` mode and of
229
- * whether it fits the reply budget. What comes back to the parent is capped at
230
- * MAX_SUBAGENT_RESULT_UNITS; a reply over budget is truncated with a pointer to the file
231
- * a chatty sub-agent can no longer blow out the parent's context.
241
+ * Spec 032 D4: the full text always lands on disk, independent of whether it fits the reply
242
+ * budget. What comes back to the parent is capped at MAX_SUBAGENT_RESULT_UNITS; a reply over
243
+ * budget is truncated with a pointer to the file a chatty sub-agent can no longer blow out the
244
+ * parent's context.
232
245
  *
233
246
  * The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
234
247
  * runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
235
248
  * This function only needs the path, to point at it.
249
+ *
250
+ * Spec 046 D2.2 removed `returns: "artifact"` and the ARTIFACT marker protocol: a caller that
251
+ * needs a specific output file states the path in the task text instead, the path external roles
252
+ * already had to follow.
236
253
  */
237
- function finalizeSubAgentOutput(runContext, finalText, returns) {
238
- const trimmed = finalText.trim();
254
+ function finalizeSubAgentOutput(runContext, finalText) {
239
255
  const outputPath = join(runContext.artifactDir, "output.md");
240
- let artifactPath;
241
- if (returns === "artifact" && trimmed) {
242
- const filename = parseArtifactMarker(trimmed);
243
- if (filename) {
244
- const candidate = resolve(runContext.artifactDir, filename);
245
- const rel = relative(runContext.artifactDir, candidate);
246
- if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
247
- artifactPath = candidate;
248
- }
249
- }
250
- }
251
256
  if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
252
- return { artifactPath, replyText: finalText, truncated: false };
257
+ return { replyText: finalText, truncated: false };
253
258
  }
254
259
  const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
255
- headRatio: ARTIFACT_TRUNCATION_HEAD_RATIO,
260
+ headRatio: RESULT_TRUNCATION_HEAD_RATIO,
256
261
  marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
257
262
  });
258
- return { artifactPath, replyText: clipped.text, truncated: true };
263
+ return { replyText: clipped.text, truncated: true };
259
264
  }
260
265
  /**
261
266
  * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
262
267
  * context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
263
- * memory_manage instead" rule the main agent gets in its system prompt (memory_manage
268
+ * memory_save instead" rule the main agent gets in its system prompt (the memory tools
264
269
  * itself is withheld from sub-agents). Denying these paths at the path-guard level closes
265
270
  * that gap structurally instead of relying on a sub-agent to infer an instruction it never
266
271
  * received — a stray write/edit here would race the shared memory serial queue
@@ -292,6 +297,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
292
297
  const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
293
298
  return buildToolSet({
294
299
  executor,
300
+ fileStore: options.fileStore,
295
301
  securityConfig,
296
302
  securityContext: {
297
303
  // No `channelDir`: a sub-agent receives channel state through its injected context
@@ -309,30 +315,28 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
309
315
  bashDefaultTimeoutSeconds: bashTimeoutSec,
310
316
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
311
317
  }
312
- /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
318
+ /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
313
319
  export function buildVerificationProtocol(taskPath) {
314
320
  return [
315
321
  "Verification protocol:",
316
322
  `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
317
- "- You are the checker, not the maker. Do not edit files or fix failures; report them.",
323
+ "- You are the checker, not the maker. Do not modify the implementation or fix failures to make a check pass; report them.",
324
+ "- You may run npm tests/builds and other deterministic checks. Newly created outputs under recognized transient artifact paths (for example .run/, coverage/, build/, dist/ or caches) are allowed, but do not change tracked files or pre-existing untracked product files.",
325
+ "- This verification is advisory when the verifier can write or use bash: runtime cannot structurally prove that every write was harmless. Review the diff and evidence before trusting PASS.",
318
326
  "- Run deterministic checks when available and distinguish observed evidence from assumptions.",
319
327
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
320
328
  ].join("\n");
321
329
  }
322
330
  /**
323
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
324
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
325
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
326
- * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
327
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
328
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
331
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
332
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
333
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
334
+ * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
335
+ * dispatch does, including the remaining `exec` restriction.
329
336
  */
330
337
  export function assertVerifyAdmissible(config, purpose, workingDirectory) {
331
338
  if (purpose !== "verify")
332
339
  return;
333
- if (config.mutates === "write") {
334
- throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
335
- }
336
340
  if (config.runtime === "external" && config.harness === "exec") {
337
341
  throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
338
342
  }
@@ -342,13 +346,13 @@ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
342
346
  }
343
347
  }
344
348
  /**
345
- * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
349
+ * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
346
350
  * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
347
351
  * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
348
352
  * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
349
353
  * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
350
354
  */
351
- export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
355
+ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
352
356
  const taskText = task.trim();
353
357
  const lines = [
354
358
  `Runtime context:`,
@@ -370,9 +374,6 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
370
374
  const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
371
375
  lines.push("", buildVerificationProtocol(taskPath));
372
376
  }
373
- else if (returns === "artifact") {
374
- 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>");
375
- }
376
377
  return lines.join("\n");
377
378
  }
378
379
  function buildSessionContextBlock(sessionMarkdown) {
@@ -474,7 +475,6 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
474
475
  taskId: runContext.taskId,
475
476
  verificationVerdict,
476
477
  artifactDir: runContext.artifactDir,
477
- artifactPath: extras?.artifactPath,
478
478
  resultTruncated: extras?.resultTruncated ?? false,
479
479
  dispatched: extras?.dispatched,
480
480
  };
@@ -482,7 +482,7 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
482
482
  /**
483
483
  * A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
484
484
  * `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
485
- * jobs. Stopping a run is now an explicit decision (`subagent_manage op=cancel`), not a side
485
+ * jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
486
486
  * effect of stopping something else.
487
487
  */
488
488
  function sleep(ms) {
@@ -491,11 +491,531 @@ function sleep(ms) {
491
491
  timer.unref?.();
492
492
  });
493
493
  }
494
+ /**
495
+ * Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
496
+ * after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
497
+ * the internal/external fork, budget/turn/tool-call enforcement, verification attestation, and
498
+ * the sync-grace/detached-placeholder split — is identical regardless of which schema the model
499
+ * called through.
500
+ */
501
+ async function dispatchSubAgentRun(options, currentModel, config, warning, params, onUpdate) {
502
+ // Derived rather than model-supplied (spec 045): `${agent}: ${task's first line}`, the
503
+ // same shape `subagent_run op=follow_up` already builds by hand.
504
+ const runLabel = `${config.name}: ${params.task.split("\n")[0]?.slice(0, 80) ?? ""}`;
505
+ // Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
506
+ // `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
507
+ const mutatesNote = warning ? `Note: ${warning}\n\n` : "";
508
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
509
+ // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
510
+ // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
511
+ const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
512
+ // D9: an independent verifier checks against a target that isn't moving under it — shared
513
+ // with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
514
+ // cannot drift between the two dispatch paths.
515
+ assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
516
+ // Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
517
+ // workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
518
+ // never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
519
+ let leaseKey;
520
+ if (config.mutates === "write") {
521
+ const lease = acquireWorkspaceLease({
522
+ runId: runContext.runId,
523
+ channelId: options.runtimeContext.channelId,
524
+ workingDirectory: runContext.workingDirectory,
525
+ });
526
+ if (!lease.ok) {
527
+ throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
528
+ }
529
+ leaseKey = lease.leaseKey;
530
+ }
531
+ if (config.runtime === "external") {
532
+ if (!config.harness) {
533
+ releaseWorkspaceLease(leaseKey, runContext.runId);
534
+ throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
535
+ }
536
+ let launchResult;
537
+ try {
538
+ // D9/T5: external roles get the same task envelope internal workers do — runtime
539
+ // paths, injected context blocks, and (for purpose=verify) the verification
540
+ // protocol — rather than the raw task text (spec 040 gap closed post-review).
541
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
542
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
543
+ // beats failing a dispatch that would otherwise have run fine.
544
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
545
+ return [];
546
+ });
547
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
548
+ launchResult = await launchExternalRun({
549
+ runId: runContext.runId,
550
+ channelId: options.runtimeContext.channelId,
551
+ channelDir: options.channelDir,
552
+ label: runLabel,
553
+ agent: config.name,
554
+ source: config.source,
555
+ harness: config.harness,
556
+ command: config.command ?? "",
557
+ shell: config.shell,
558
+ env: config.env,
559
+ externalModelRef: config.externalModelRef,
560
+ thinkingLevel: config.thinkingLevel,
561
+ maxWallTimeSec: config.maxWallTimeSec,
562
+ systemPrompt: config.systemPrompt,
563
+ task: envelopedTask,
564
+ workingDirectory: runContext.workingDirectory,
565
+ artifactDir: runContext.artifactDir,
566
+ purpose: runContext.purpose,
567
+ taskId: runContext.taskId,
568
+ leaseKey,
569
+ mutates: config.mutates,
570
+ roleFingerprint: externalRoleFingerprint(config),
571
+ workspaceDir: options.workspaceDir,
572
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
573
+ });
574
+ }
575
+ catch (error) {
576
+ // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
577
+ // every failure past that point settles the run itself and already released this
578
+ // lease (spec 042 D2/D5), so this catch must not release it a second time.
579
+ releaseWorkspaceLease(leaseKey, runContext.runId);
580
+ throw error;
581
+ }
582
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
583
+ // "[Dispatched]" placeholder the model would wait on forever — two of the three
584
+ // failure kinds never used to announce at all. `settle()` already released the lease.
585
+ if (!launchResult.ok) {
586
+ if (launchResult.kind === "missing-binary") {
587
+ throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
588
+ }
589
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
590
+ }
591
+ // D2: external's sync grace window is always 0 — always the dispatched placeholder,
592
+ // never an inline wait. The run keeps going in the background and wakes the channel.
593
+ return {
594
+ content: [
595
+ {
596
+ type: "text",
597
+ text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
598
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
599
+ "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.",
600
+ },
601
+ ],
602
+ details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
603
+ dispatched: true,
604
+ modelOverride: config.externalModelRef ?? "unknown",
605
+ toolsOverride: [],
606
+ }),
607
+ };
608
+ }
609
+ const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
610
+ let apiKey;
611
+ try {
612
+ apiKey = await options.resolveApiKey(config.model);
613
+ }
614
+ catch (error) {
615
+ releaseWorkspaceLease(leaseKey, runContext.runId);
616
+ throw error;
617
+ }
618
+ const startedAt = Date.now();
619
+ const usage = createEmptyUsageTotals();
620
+ let assistantTurns = 0;
621
+ let toolCalls = 0;
622
+ let failureReason;
623
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
624
+ let budgetExceeded = false;
625
+ /** Set only by the `subagent_run op=cancel` handle registered as soon as the run is durable. */
626
+ let externallyCancelled = false;
627
+ /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
628
+ let detached = false;
629
+ let lastUpdateText = "";
630
+ let worker;
631
+ try {
632
+ await runManager.register({
633
+ runId: runContext.runId,
634
+ channelId: options.runtimeContext.channelId,
635
+ runtime: "internal",
636
+ agent: config.name,
637
+ label: runLabel,
638
+ source: config.source,
639
+ tools: [...config.tools],
640
+ model: formatModelReference(config.model),
641
+ purpose: runContext.purpose,
642
+ taskId: runContext.taskId,
643
+ workingDirectory: runContext.workingDirectory,
644
+ artifactDir: runContext.artifactDir,
645
+ leaseKey,
646
+ mutates: config.mutates,
647
+ });
648
+ }
649
+ catch (error) {
650
+ // Until the durable running record exists, setup still owns the lease. A channel/host
651
+ // admission rejection or required persist failure must leave no invisible writer lock.
652
+ releaseWorkspaceLease(leaseKey, runContext.runId);
653
+ throw error;
654
+ }
655
+ // Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
656
+ // creation) can yield. Without this provisional handle, a cancel in that window was treated as
657
+ // an unreachable run: the manager released the lease and settled it while the worker could still
658
+ // start writing after the supposed cancellation (especially dangerous for a write verifier).
659
+ runManager.registerCancelHandle(runContext.runId, () => {
660
+ externallyCancelled = true;
661
+ worker?.abort();
662
+ });
663
+ const emitUpdate = (text) => {
664
+ // Once detached, execute() has already returned to the SDK; nothing is listening
665
+ // for further progress on this (from its view, finished) tool call.
666
+ if (detached)
667
+ return;
668
+ const nextText = text.trim();
669
+ if (!nextText || nextText === lastUpdateText) {
670
+ return;
671
+ }
672
+ lastUpdateText = nextText;
673
+ onUpdate?.({
674
+ content: [{ type: "text", text: nextText }],
675
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
676
+ });
677
+ };
678
+ let wallClockTimer;
679
+ let unsubscribe;
680
+ let verifierGitStateBefore;
681
+ let verifierSubjectBefore;
682
+ let verifierSubjectBaseCommit;
683
+ let verifierSubjectBaselineUntrackedPaths;
684
+ try {
685
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
686
+ verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
687
+ if (runContext.purpose === "verify") {
688
+ const subjectSnapshot = await workspaceSubjectSnapshot(runContext.workingDirectory);
689
+ verifierSubjectBefore = subjectSnapshot?.hash;
690
+ verifierSubjectBaseCommit = subjectSnapshot?.baseCommit;
691
+ verifierSubjectBaselineUntrackedPaths = subjectSnapshot?.baselineUntrackedPaths;
692
+ }
693
+ worker =
694
+ options.createWorker?.({
695
+ subAgent: config,
696
+ apiKey,
697
+ tools: filterToolsByName(availableTools, config.tools),
698
+ }) ??
699
+ new Agent({
700
+ initialState: {
701
+ systemPrompt: config.systemPrompt,
702
+ model: config.model,
703
+ // Same clamp the main agent applies (channel-runner.ts) before setting a model's
704
+ // thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
705
+ // snaps to the nearest one, instead of a raw unsupported value reaching the provider.
706
+ // The internal path's resolved config always fills thinkingLevel; the fallback
707
+ // here only closes the type.
708
+ thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
709
+ tools: filterToolsByName(availableTools, config.tools),
710
+ },
711
+ convertToLlm,
712
+ getApiKey: async () => apiKey,
713
+ streamFn: streamSimple,
714
+ });
715
+ wallClockTimer = setTimeout(() => {
716
+ failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
717
+ budgetExceeded = true;
718
+ worker?.abort();
719
+ }, config.maxWallTimeSec * 1000);
720
+ unsubscribe = worker.subscribe((event) => {
721
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
722
+ assistantTurns++;
723
+ const messageUsage = event.message.usage;
724
+ usage.input += messageUsage.input;
725
+ usage.output += messageUsage.output;
726
+ usage.cacheRead += messageUsage.cacheRead;
727
+ usage.cacheWrite += messageUsage.cacheWrite;
728
+ usage.total += messageUsage.totalTokens;
729
+ usage.cost.input += messageUsage.cost.input;
730
+ usage.cost.output += messageUsage.cost.output;
731
+ usage.cost.cacheRead += messageUsage.cost.cacheRead;
732
+ usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
733
+ usage.cost.total += messageUsage.cost.total;
734
+ }
735
+ if (event.type === "tool_execution_start") {
736
+ toolCalls++;
737
+ const label = describeToolCall(event.toolName, event.args);
738
+ emitUpdate(formatStatus(config.name, label));
739
+ if (toolCalls > config.maxToolCalls) {
740
+ failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
741
+ budgetExceeded = true;
742
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
743
+ worker?.abort();
744
+ }
745
+ }
746
+ if (event.type === "turn_end" &&
747
+ isAssistantMessage(event.message) &&
748
+ event.toolResults.length > 0 &&
749
+ assistantTurns >= config.maxTurns) {
750
+ failureReason = `Turn budget exceeded (${config.maxTurns})`;
751
+ budgetExceeded = true;
752
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
753
+ worker?.abort();
754
+ }
755
+ });
756
+ emitUpdate(formatStatus(config.name, "started"));
757
+ }
758
+ catch (error) {
759
+ unsubscribe?.();
760
+ if (wallClockTimer)
761
+ clearTimeout(wallClockTimer);
762
+ runManager.clearCancelHandle(runContext.runId);
763
+ try {
764
+ worker?.abort();
765
+ }
766
+ catch {
767
+ // Preserve the setup error; settlement below is the lifecycle authority.
768
+ }
769
+ const setupError = error instanceof Error ? error : new Error(String(error));
770
+ await runManager.settle(runContext.runId, {
771
+ status: "failed",
772
+ failureReason: setupError.message,
773
+ usage,
774
+ usageKnown: true,
775
+ costKnown: true,
776
+ turns: assistantTurns,
777
+ toolCalls,
778
+ durationMs: Date.now() - startedAt,
779
+ outputText: "",
780
+ }, { announce: false });
781
+ throw setupError;
782
+ }
783
+ const activeWorker = worker;
784
+ const activeUnsubscribe = unsubscribe;
785
+ const activeWallClockTimer = wallClockTimer;
786
+ /**
787
+ * Runs the worker to completion, including the D6 convergence turn, and returns the
788
+ * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
789
+ * fatal case (no assistant message at all) — every other outcome, including a budget
790
+ * abort or explicit cancel, is a normal (if failed) result.
791
+ */
792
+ async function runToCompletion() {
793
+ try {
794
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
795
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
796
+ // beats failing a dispatch that would otherwise have run fine.
797
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
798
+ return [];
799
+ });
800
+ if (externallyCancelled) {
801
+ failureReason = failureReason || "Cancelled by request.";
802
+ }
803
+ else {
804
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
805
+ await activeWorker.waitForIdle();
806
+ }
807
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
808
+ // conclusion instead of discarding the work outright. An explicit cancel skips
809
+ // this — the model asked this run to stop now, not to wrap up.
810
+ if (budgetExceeded && !externallyCancelled) {
811
+ clearTimeout(activeWallClockTimer);
812
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
813
+ const preConvergenceMessageCount = activeWorker.state.messages.length;
814
+ activeWorker.state.tools = [];
815
+ let convergenceTimedOut = false;
816
+ const convergenceTimer = setTimeout(() => {
817
+ convergenceTimedOut = true;
818
+ activeWorker.abort();
819
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
820
+ try {
821
+ await activeWorker.prompt(CONVERGENCE_PROMPT);
822
+ await activeWorker.waitForIdle();
823
+ }
824
+ catch {
825
+ // Best effort: fall through to whatever worker.state.messages holds.
826
+ }
827
+ finally {
828
+ clearTimeout(convergenceTimer);
829
+ }
830
+ if (convergenceTimedOut) {
831
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
832
+ // convergence turn and fall back to whatever came before it.
833
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
834
+ }
835
+ }
836
+ }
837
+ finally {
838
+ activeUnsubscribe();
839
+ clearTimeout(activeWallClockTimer);
840
+ }
841
+ const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
842
+ const durationMs = Date.now() - startedAt;
843
+ if (!lastAssistantMessage) {
844
+ failureReason = failureReason || "Sub-agent returned no assistant message";
845
+ emitUpdate(formatStatus(config.name, "failed"));
846
+ throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
847
+ }
848
+ const finalText = extractAssistantText(lastAssistantMessage);
849
+ const effectiveFailureReason = failureReason ||
850
+ (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
851
+ ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
852
+ : undefined);
853
+ const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
854
+ const verifierSubjectAfter = runContext.purpose === "verify"
855
+ ? await workspaceSubjectHash(runContext.workingDirectory, verifierSubjectBaseCommit
856
+ ? {
857
+ baseCommit: verifierSubjectBaseCommit,
858
+ baselineUntrackedPaths: verifierSubjectBaselineUntrackedPaths,
859
+ }
860
+ : {})
861
+ : undefined;
862
+ // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
863
+ // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
864
+ // run's own output does and does not prove. Only the attestation write and the
865
+ // strength label stay here, since only the internal path can structurally remove
866
+ // write/edit from the verifier's tool set.
867
+ const verification = runContext.purpose === "verify"
868
+ ? resolveVerificationOutcome({
869
+ subjectBefore: verifierSubjectBefore,
870
+ subjectAfter: verifierSubjectAfter,
871
+ gitStateBefore: verifierGitStateBefore,
872
+ gitStateAfter: verifierGitStateAfter,
873
+ finalText,
874
+ runFailed: Boolean(effectiveFailureReason),
875
+ })
876
+ : undefined;
877
+ const verificationVerdict = verification?.verdict;
878
+ // Internal verify always keeps write/edit structurally removed from the verifier's
879
+ // tool set (buildSubagentTools above), but `bash` stays available by default and can
880
+ // write files just as well. A role that declares mutates: write is advisory even when
881
+ // its effective tool list happens not to contain bash: the declaration says this run is
882
+ // not structurally read-only. Computed once so the attestation and run record — the
883
+ // latter is what the completion wake and `subagent_list` display — cannot disagree.
884
+ const internalVerificationStrength = config.mutates === "write" || config.tools.includes("bash") ? "advisory" : "enforced";
885
+ if (runContext.purpose === "verify" && runContext.taskId && verification) {
886
+ const baseSubjectAvailable = verifierSubjectBaseCommit !== undefined && verifierSubjectBaselineUntrackedPaths !== undefined;
887
+ const subjectAvailable = !verification.workspaceChanged && verifierSubjectAfter !== undefined && baseSubjectAvailable;
888
+ await writeVerificationAttestation(options.channelDir, {
889
+ runId: runContext.runId,
890
+ taskId: runContext.taskId,
891
+ verdict: verification.verdict,
892
+ checkedAt: formatLocalTime(),
893
+ evidence: verification.evidence,
894
+ workspaceChanged: verification.workspaceChanged,
895
+ subjectHash: subjectAvailable ? verifierSubjectAfter : undefined,
896
+ subjectDir: subjectAvailable ? runContext.workingDirectory : undefined,
897
+ subjectMode: subjectAvailable ? "base-relative" : undefined,
898
+ subjectBaseCommit: subjectAvailable ? verifierSubjectBaseCommit : undefined,
899
+ subjectBaselineUntrackedPaths: subjectAvailable ? verifierSubjectBaselineUntrackedPaths : undefined,
900
+ verificationStrength: internalVerificationStrength,
901
+ });
902
+ }
903
+ // Internal runs always report full usage; cost is "unknown" only for the shape a
904
+ // free/local model produces (tokens spent, nothing billed) — external harnesses
905
+ // override both explicitly once they land (D4/D9).
906
+ const costKnown = usage.cost.total > 0 || usage.total === 0;
907
+ const baseSettleInput = {
908
+ usage,
909
+ usageKnown: true,
910
+ costKnown,
911
+ turns: assistantTurns,
912
+ toolCalls,
913
+ durationMs,
914
+ verificationVerdict,
915
+ verificationStrength: runContext.purpose === "verify" ? internalVerificationStrength : undefined,
916
+ };
917
+ if (effectiveFailureReason) {
918
+ if (!finalText.trim()) {
919
+ emitUpdate(formatStatus(config.name, "failed"));
920
+ throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
921
+ }
922
+ emitUpdate(formatStatus(config.name, "stopped"));
923
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
924
+ return {
925
+ toolResult: {
926
+ content: [
927
+ {
928
+ type: "text",
929
+ text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
930
+ },
931
+ ],
932
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { resultTruncated: finalized.truncated }),
933
+ },
934
+ settleInput: {
935
+ ...baseSettleInput,
936
+ // An explicit cancel is not a failure (P1-1) — the model asked this run to
937
+ // stop, and it did.
938
+ status: externallyCancelled ? "cancelled" : "failed",
939
+ failureReason: effectiveFailureReason,
940
+ outputText: finalText,
941
+ },
942
+ };
943
+ }
944
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
945
+ return {
946
+ toolResult: {
947
+ content: [
948
+ {
949
+ type: "text",
950
+ text: mutatesNote + (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
951
+ },
952
+ ],
953
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { resultTruncated: finalized.truncated }),
954
+ },
955
+ settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
956
+ };
957
+ }
958
+ /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
959
+ function fatalSettleInput(error) {
960
+ return {
961
+ status: externallyCancelled ? "cancelled" : "failed",
962
+ failureReason: failureReason || error.message,
963
+ usage,
964
+ usageKnown: true,
965
+ costKnown: usage.cost.total > 0 || usage.total === 0,
966
+ turns: assistantTurns,
967
+ toolCalls,
968
+ durationMs: Date.now() - startedAt,
969
+ outputText: "",
970
+ };
971
+ }
972
+ // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
973
+ // clock budget) before degrading to a "still running" placeholder. The run itself keeps
974
+ // executing either way — only the *return* differs.
975
+ const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
976
+ const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
977
+ ok: false,
978
+ error: error instanceof Error ? error : new Error(String(error)),
979
+ }));
980
+ const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
981
+ if (raceResult !== "timed-out") {
982
+ runManager.clearCancelHandle(runContext.runId);
983
+ if (!raceResult.ok) {
984
+ await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
985
+ throw raceResult.error;
986
+ }
987
+ await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
988
+ return raceResult.value.toolResult;
989
+ }
990
+ // Grace window elapsed: hand back a placeholder now and let the run keep going in the
991
+ // background. It settles and, this time, announces itself with a completion wake (D2/D7)
992
+ // — the same "runtime guarantees completion" contract background jobs already keep.
993
+ detached = true;
994
+ void outcomePromise.then(async (outcome) => {
995
+ runManager.clearCancelHandle(runContext.runId);
996
+ const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
997
+ await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
998
+ log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
999
+ });
1000
+ });
1001
+ return {
1002
+ content: [
1003
+ {
1004
+ type: "text",
1005
+ text: mutatesNote +
1006
+ `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
1007
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
1008
+ "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.",
1009
+ },
1010
+ ],
1011
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, false, undefined, undefined, { dispatched: true }),
1012
+ };
1013
+ }
494
1014
  export function createSubAgentTool(options) {
495
1015
  return {
496
1016
  name: "subagent",
497
1017
  label: "subagent",
498
- 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 configured agent is required. You may instead name a configured sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Execution budgets come from `effort` presets and context injection from `context`; both have safe defaults, so state the task well and leave them alone unless you have a reason. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
1018
+ description: "Delegate a task to a configured sub-agent (see the Sub-Agents directory in the system prompt). Prefer this over `subagent_inline` whenever a role fits — its tools, model, budget and context policy all come from the role file. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
499
1019
  parameters: subagentSchema,
500
1020
  execute: async (_toolCallId, params, signal, onUpdate) => {
501
1021
  if (signal?.aborted) {
@@ -512,510 +1032,44 @@ export function createSubAgentTool(options) {
512
1032
  if (taskLengthError) {
513
1033
  throw new RecoverableToolError(taskLengthError);
514
1034
  }
515
- const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
1035
+ const invocation = resolveConfiguredRole(availableModels, currentModel, discovery.agents, { agent: params.agent, purpose: params.purpose }, options.getSubAgentModelReference?.() ?? undefined);
516
1036
  if (!invocation.config) {
517
1037
  throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
518
1038
  }
519
- const config = invocation.config;
520
- // Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
521
- // `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
522
- const mutatesNote = invocation.warning ? `Note: ${invocation.warning}\n\n` : "";
523
- const returns = params.returns ?? "text";
524
- // Spec 042 D3: `returns: "artifact"` has no external equivalent — the marker protocol
525
- // scopes a produced file to `artifactDir`, but an external agent's real output lives in
526
- // its working directory. Implementing it would build a same-named, different-meaning
527
- // protocol; rejecting it is honest about the mismatch. An external run's full output
528
- // always lands in `output.md` regardless (spec 032 D4), so this loses nothing — a caller
529
- // that needs a specific artifact location says so in the task text.
530
- if (config.runtime === "external" && returns === "artifact") {
531
- throw new RecoverableToolError(`Sub-agent "${config.name}" is external; returns: "artifact" has no effect on external roles ` +
532
- "(their full output always lands in output.md). State the desired output file in the task text instead.");
533
- }
534
- const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
535
- // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
536
- // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
537
- const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
538
- // D9: an independent verifier checks against a target that isn't moving under it — shared
539
- // with `subagent_manage op=follow_up` (spec 042 D7) so a verify run's admission rules
540
- // cannot drift between the two dispatch paths.
541
- assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
542
- // Admission: a write-mutating run takes an exclusive workspace lease before it is even
543
- // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
544
- // Read runs and purpose=verify never take one. Shared by both runtimes.
545
- let leaseKey;
546
- if (config.mutates === "write" && runContext.purpose !== "verify") {
547
- const lease = acquireWorkspaceLease({
548
- runId: runContext.runId,
549
- channelId: options.runtimeContext.channelId,
550
- workingDirectory: runContext.workingDirectory,
551
- });
552
- if (!lease.ok) {
553
- throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
554
- }
555
- leaseKey = lease.leaseKey;
556
- }
557
- if (config.runtime === "external") {
558
- if (!config.harness) {
559
- releaseWorkspaceLease(leaseKey, runContext.runId);
560
- throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
561
- }
562
- let launchResult;
563
- try {
564
- // D9/T5: external roles get the same task envelope internal workers do — runtime
565
- // paths, injected context blocks, and (for purpose=verify) the verification
566
- // protocol — rather than the raw task text (spec 040 gap closed post-review).
567
- // Spec 042 D3: `returns: "artifact"` is rejected for external above, so this is
568
- // always "text" here — passed literally rather than the `returns` variable so the
569
- // ARTIFACT marker protocol is never injected into an external envelope, which no
570
- // external result parser has ever read.
571
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
572
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
573
- // beats failing a dispatch that would otherwise have run fine.
574
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
575
- return [];
576
- });
577
- const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, "text");
578
- launchResult = await launchExternalRun({
579
- runId: runContext.runId,
580
- channelId: options.runtimeContext.channelId,
581
- channelDir: options.channelDir,
582
- label: params.label,
583
- agent: config.name,
584
- source: config.source,
585
- harness: config.harness,
586
- command: config.command ?? "",
587
- shell: config.shell,
588
- env: config.env,
589
- externalModelRef: config.externalModelRef,
590
- thinkingLevel: config.thinkingLevel,
591
- maxWallTimeSec: config.maxWallTimeSec,
592
- systemPrompt: config.systemPrompt,
593
- task: envelopedTask,
594
- workingDirectory: runContext.workingDirectory,
595
- artifactDir: runContext.artifactDir,
596
- purpose: runContext.purpose,
597
- taskId: runContext.taskId,
598
- leaseKey,
599
- mutates: config.mutates,
600
- roleFingerprint: externalRoleFingerprint(config),
601
- workspaceDir: options.workspaceDir,
602
- securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
603
- });
604
- }
605
- catch (error) {
606
- // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
607
- // every failure past that point settles the run itself and already released this
608
- // lease (spec 042 D2/D5), so this catch must not release it a second time.
609
- releaseWorkspaceLease(leaseKey, runContext.runId);
610
- throw error;
611
- }
612
- // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
613
- // "[Dispatched]" placeholder the model would wait on forever — two of the three
614
- // failure kinds never used to announce at all. `settle()` already released the lease.
615
- if (!launchResult.ok) {
616
- if (launchResult.kind === "missing-binary") {
617
- throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
618
- }
619
- throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
620
- }
621
- // D2: external's sync grace window is always 0 — always the dispatched placeholder,
622
- // never an inline wait. The run keeps going in the background and wakes the channel.
623
- return {
624
- content: [
625
- {
626
- type: "text",
627
- text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
628
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
629
- "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
630
- },
631
- ],
632
- details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
633
- dispatched: true,
634
- modelOverride: config.externalModelRef ?? "unknown",
635
- toolsOverride: [],
636
- }),
637
- };
638
- }
639
- const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
640
- let apiKey;
641
- try {
642
- apiKey = await options.resolveApiKey(config.model);
643
- }
644
- catch (error) {
645
- releaseWorkspaceLease(leaseKey, runContext.runId);
646
- throw error;
647
- }
648
- const startedAt = Date.now();
649
- const usage = createEmptyUsageTotals();
650
- let assistantTurns = 0;
651
- let toolCalls = 0;
652
- let failureReason;
653
- /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
654
- let budgetExceeded = false;
655
- /** Set only by the `subagent_manage op=cancel` handle registered below — a real stop, unlike a budget abort. */
656
- let externallyCancelled = false;
657
- /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
658
- let detached = false;
659
- let lastUpdateText = "";
660
- try {
661
- await runManager.register({
662
- runId: runContext.runId,
663
- channelId: options.runtimeContext.channelId,
664
- runtime: "internal",
665
- agent: config.name,
666
- label: params.label,
667
- source: config.source,
668
- tools: [...config.tools],
669
- model: formatModelReference(config.model),
670
- purpose: runContext.purpose,
671
- taskId: runContext.taskId,
672
- workingDirectory: runContext.workingDirectory,
673
- artifactDir: runContext.artifactDir,
674
- leaseKey,
675
- });
676
- }
677
- catch (error) {
678
- // Until the durable running record exists, setup still owns the lease. A channel/host
679
- // admission rejection or required persist failure must leave no invisible writer lock.
680
- releaseWorkspaceLease(leaseKey, runContext.runId);
681
- throw error;
682
- }
683
- const emitUpdate = (text) => {
684
- // Once detached, execute() has already returned to the SDK; nothing is listening
685
- // for further progress on this (from its view, finished) tool call.
686
- if (detached)
687
- return;
688
- const nextText = text.trim();
689
- if (!nextText || nextText === lastUpdateText) {
690
- return;
691
- }
692
- lastUpdateText = nextText;
693
- onUpdate?.({
694
- content: [{ type: "text", text: nextText }],
695
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
696
- });
697
- };
698
- let worker;
699
- let wallClockTimer;
700
- let unsubscribe;
701
- let verifierGitStateBefore;
702
- let verifierSubjectBefore;
703
- try {
704
- const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
705
- verifierGitStateBefore =
706
- runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
707
- verifierSubjectBefore =
708
- runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
709
- worker =
710
- options.createWorker?.({
711
- subAgent: config,
712
- apiKey,
713
- tools: filterToolsByName(availableTools, config.tools),
714
- }) ??
715
- new Agent({
716
- initialState: {
717
- systemPrompt: config.systemPrompt,
718
- model: config.model,
719
- // Same clamp the main agent applies (channel-runner.ts) before setting a model's
720
- // thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
721
- // snaps to the nearest one, instead of a raw unsupported value reaching the provider.
722
- // The internal path's resolved config always fills thinkingLevel; the fallback
723
- // here only closes the type.
724
- thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
725
- tools: filterToolsByName(availableTools, config.tools),
726
- },
727
- convertToLlm,
728
- getApiKey: async () => apiKey,
729
- streamFn: streamSimple,
730
- });
731
- runManager.registerCancelHandle(runContext.runId, () => {
732
- externallyCancelled = true;
733
- worker?.abort();
734
- });
735
- wallClockTimer = setTimeout(() => {
736
- failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
737
- budgetExceeded = true;
738
- worker?.abort();
739
- }, config.maxWallTimeSec * 1000);
740
- unsubscribe = worker.subscribe((event) => {
741
- if (event.type === "message_end" && isAssistantMessage(event.message)) {
742
- assistantTurns++;
743
- const messageUsage = event.message.usage;
744
- usage.input += messageUsage.input;
745
- usage.output += messageUsage.output;
746
- usage.cacheRead += messageUsage.cacheRead;
747
- usage.cacheWrite += messageUsage.cacheWrite;
748
- usage.total += messageUsage.totalTokens;
749
- usage.cost.input += messageUsage.cost.input;
750
- usage.cost.output += messageUsage.cost.output;
751
- usage.cost.cacheRead += messageUsage.cost.cacheRead;
752
- usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
753
- usage.cost.total += messageUsage.cost.total;
754
- }
755
- if (event.type === "tool_execution_start") {
756
- toolCalls++;
757
- const label = extractLabelFromArgs(event.args) || event.toolName;
758
- emitUpdate(formatStatus(config.name, label));
759
- if (toolCalls > config.maxToolCalls) {
760
- failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
761
- budgetExceeded = true;
762
- emitUpdate(formatStatus(config.name, "tool budget reached"));
763
- worker?.abort();
764
- }
765
- }
766
- if (event.type === "turn_end" &&
767
- isAssistantMessage(event.message) &&
768
- event.toolResults.length > 0 &&
769
- assistantTurns >= config.maxTurns) {
770
- failureReason = `Turn budget exceeded (${config.maxTurns})`;
771
- budgetExceeded = true;
772
- emitUpdate(formatStatus(config.name, "turn budget reached"));
773
- worker?.abort();
774
- }
775
- });
776
- emitUpdate(formatStatus(config.name, "started"));
777
- }
778
- catch (error) {
779
- unsubscribe?.();
780
- if (wallClockTimer)
781
- clearTimeout(wallClockTimer);
782
- runManager.clearCancelHandle(runContext.runId);
783
- try {
784
- worker?.abort();
785
- }
786
- catch {
787
- // Preserve the setup error; settlement below is the lifecycle authority.
788
- }
789
- const setupError = error instanceof Error ? error : new Error(String(error));
790
- await runManager.settle(runContext.runId, {
791
- status: "failed",
792
- failureReason: setupError.message,
793
- usage,
794
- usageKnown: true,
795
- costKnown: true,
796
- turns: assistantTurns,
797
- toolCalls,
798
- durationMs: Date.now() - startedAt,
799
- outputText: "",
800
- }, { announce: false });
801
- throw setupError;
802
- }
803
- const activeWorker = worker;
804
- const activeUnsubscribe = unsubscribe;
805
- const activeWallClockTimer = wallClockTimer;
806
- /**
807
- * Runs the worker to completion, including the D6 convergence turn, and returns the
808
- * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
809
- * fatal case (no assistant message at all) — every other outcome, including a budget
810
- * abort or explicit cancel, is a normal (if failed) result.
811
- */
812
- async function runToCompletion() {
813
- try {
814
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
815
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
816
- // beats failing a dispatch that would otherwise have run fine.
817
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
818
- return [];
819
- });
820
- await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
821
- await activeWorker.waitForIdle();
822
- // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
823
- // conclusion instead of discarding the work outright. An explicit cancel skips
824
- // this — the model asked this run to stop now, not to wrap up.
825
- if (budgetExceeded && !externallyCancelled) {
826
- clearTimeout(activeWallClockTimer);
827
- emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
828
- const preConvergenceMessageCount = activeWorker.state.messages.length;
829
- activeWorker.state.tools = [];
830
- let convergenceTimedOut = false;
831
- const convergenceTimer = setTimeout(() => {
832
- convergenceTimedOut = true;
833
- activeWorker.abort();
834
- }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
835
- try {
836
- await activeWorker.prompt(CONVERGENCE_PROMPT);
837
- await activeWorker.waitForIdle();
838
- }
839
- catch {
840
- // Best effort: fall through to whatever worker.state.messages holds.
841
- }
842
- finally {
843
- clearTimeout(convergenceTimer);
844
- }
845
- if (convergenceTimedOut) {
846
- // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
847
- // convergence turn and fall back to whatever came before it.
848
- activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
849
- }
850
- }
851
- }
852
- finally {
853
- activeUnsubscribe();
854
- clearTimeout(activeWallClockTimer);
855
- }
856
- const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
857
- const durationMs = Date.now() - startedAt;
858
- if (!lastAssistantMessage) {
859
- failureReason = failureReason || "Sub-agent returned no assistant message";
860
- emitUpdate(formatStatus(config.name, "failed"));
861
- throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
862
- }
863
- const finalText = extractAssistantText(lastAssistantMessage);
864
- const effectiveFailureReason = failureReason ||
865
- (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
866
- ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
867
- : undefined);
868
- const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
869
- const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
870
- // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
871
- // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
872
- // run's own output does and does not prove. Only the attestation write and the
873
- // strength label stay here, since only the internal path can structurally remove
874
- // write/edit from the verifier's tool set.
875
- const verification = runContext.purpose === "verify"
876
- ? resolveVerificationOutcome({
877
- subjectBefore: verifierSubjectBefore,
878
- subjectAfter: verifierSubjectAfter,
879
- gitStateBefore: verifierGitStateBefore,
880
- gitStateAfter: verifierGitStateAfter,
881
- finalText,
882
- runFailed: Boolean(effectiveFailureReason),
883
- })
884
- : undefined;
885
- const verificationVerdict = verification?.verdict;
886
- // Internal verify always keeps write/edit structurally removed from the verifier's
887
- // tool set (buildSubagentTools above), but `bash` stays available by default and can
888
- // write files just as well — labeling that "enforced" would be dishonest (review
889
- // 2026-08-23 §2.2). Only a role that dropped `bash` from its declared tool list earns
890
- // the stronger label. Computed once so the attestation and the run record — the
891
- // latter is what the completion wake and `subagent_manage` display — cannot disagree.
892
- const internalVerificationStrength = config.tools.includes("bash")
893
- ? "advisory"
894
- : "enforced";
895
- if (runContext.purpose === "verify" && runContext.taskId && verification) {
896
- await writeVerificationAttestation(options.channelDir, {
897
- runId: runContext.runId,
898
- taskId: runContext.taskId,
899
- verdict: verification.verdict,
900
- checkedAt: formatLocalTime(),
901
- evidence: verification.evidence,
902
- workspaceChanged: verification.workspaceChanged,
903
- subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
904
- subjectDir: runContext.workingDirectory,
905
- verificationStrength: internalVerificationStrength,
906
- });
907
- }
908
- // Internal runs always report full usage; cost is "unknown" only for the shape a
909
- // free/local model produces (tokens spent, nothing billed) — external harnesses
910
- // override both explicitly once they land (D4/D9).
911
- const costKnown = usage.cost.total > 0 || usage.total === 0;
912
- const baseSettleInput = {
913
- usage,
914
- usageKnown: true,
915
- costKnown,
916
- turns: assistantTurns,
917
- toolCalls,
918
- durationMs,
919
- verificationVerdict,
920
- verificationStrength: runContext.purpose === "verify" ? internalVerificationStrength : undefined,
921
- };
922
- if (effectiveFailureReason) {
923
- if (!finalText.trim()) {
924
- emitUpdate(formatStatus(config.name, "failed"));
925
- throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
926
- }
927
- emitUpdate(formatStatus(config.name, "stopped"));
928
- const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
929
- return {
930
- toolResult: {
931
- content: [
932
- {
933
- type: "text",
934
- text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
935
- },
936
- ],
937
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
938
- },
939
- settleInput: {
940
- ...baseSettleInput,
941
- // An explicit cancel is not a failure (P1-1) — the model asked this run to
942
- // stop, and it did.
943
- status: externallyCancelled ? "cancelled" : "failed",
944
- failureReason: effectiveFailureReason,
945
- outputText: finalText,
946
- },
947
- };
948
- }
949
- const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
950
- return {
951
- toolResult: {
952
- content: [
953
- {
954
- type: "text",
955
- text: mutatesNote +
956
- (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
957
- },
958
- ],
959
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
960
- },
961
- settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
962
- };
1039
+ return dispatchSubAgentRun(options, currentModel, invocation.config, undefined, params, onUpdate);
1040
+ },
1041
+ };
1042
+ }
1043
+ export function createSubAgentInlineTool(options) {
1044
+ return {
1045
+ name: "subagent_inline",
1046
+ label: "subagent_inline",
1047
+ description: "Delegate a task to a one-off inline sub-agent when no configured role fits — define its systemPrompt (plus optional tools/model) here instead of a role file. Prefer `subagent` with a configured `agent` when one already covers this work. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
1048
+ parameters: subagentInlineSchema,
1049
+ execute: async (_toolCallId, params, signal, onUpdate) => {
1050
+ if (signal?.aborted) {
1051
+ throw new Error("Sub-agent aborted");
963
1052
  }
964
- /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
965
- function fatalSettleInput(error) {
966
- return {
967
- status: externallyCancelled ? "cancelled" : "failed",
968
- failureReason: failureReason || error.message,
969
- usage,
970
- usageKnown: true,
971
- costKnown: usage.cost.total > 0 || usage.total === 0,
972
- turns: assistantTurns,
973
- toolCalls,
974
- durationMs: Date.now() - startedAt,
975
- outputText: "",
976
- };
1053
+ const availableModels = options.getAvailableModels();
1054
+ const currentModel = options.getCurrentModel();
1055
+ const taskLengthError = validateSubAgentTask(params.task);
1056
+ if (taskLengthError) {
1057
+ throw new RecoverableToolError(taskLengthError);
977
1058
  }
978
- // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
979
- // clock budget) before degrading to a "still running" placeholder. The run itself keeps
980
- // executing either way — only the *return* differs.
981
- const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
982
- const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
983
- ok: false,
984
- error: error instanceof Error ? error : new Error(String(error)),
985
- }));
986
- const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
987
- if (raceResult !== "timed-out") {
988
- runManager.clearCancelHandle(runContext.runId);
989
- if (!raceResult.ok) {
990
- await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
991
- throw raceResult.error;
992
- }
993
- await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
994
- return raceResult.value.toolResult;
1059
+ const invocation = resolveInlineAgent(availableModels, currentModel, {
1060
+ systemPrompt: params.systemPrompt,
1061
+ tools: params.tools,
1062
+ model: params.model,
1063
+ effort: params.effort,
1064
+ context: params.context,
1065
+ thinkingLevel: params.thinkingLevel,
1066
+ mutates: params.mutates,
1067
+ purpose: params.purpose,
1068
+ }, options.getSubAgentModelReference?.() ?? undefined);
1069
+ if (!invocation.config) {
1070
+ throw new RecoverableToolError(invocation.error ?? "Unable to resolve inline sub-agent.");
995
1071
  }
996
- // Grace window elapsed: hand back a placeholder now and let the run keep going in the
997
- // background. It settles and, this time, announces itself with a completion wake (D2/D7)
998
- // — the same "runtime guarantees completion" contract background jobs already keep.
999
- detached = true;
1000
- void outcomePromise.then(async (outcome) => {
1001
- runManager.clearCancelHandle(runContext.runId);
1002
- const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
1003
- await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
1004
- log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
1005
- });
1006
- });
1007
- return {
1008
- content: [
1009
- {
1010
- type: "text",
1011
- text: mutatesNote +
1012
- `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
1013
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
1014
- "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
1015
- },
1016
- ],
1017
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, false, undefined, undefined, { dispatched: true }),
1018
- };
1072
+ return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, onUpdate);
1019
1073
  },
1020
1074
  };
1021
1075
  }