@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.1

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 (149) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -1
  2. package/dist/agent/channel-runner.js +9 -5
  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 +6 -4
  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 +5 -5
  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 +10 -10
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/security/block-message.d.ts +11 -0
  50. package/dist/security/block-message.js +12 -0
  51. package/dist/security/path-guard-check.d.ts +13 -0
  52. package/dist/security/path-guard-check.js +39 -0
  53. package/dist/security/path-guard.js +32 -14
  54. package/dist/settings.js +3 -2
  55. package/dist/shared/atomic-file.d.ts +17 -1
  56. package/dist/shared/atomic-file.js +50 -3
  57. package/dist/shared/duration.d.ts +2 -0
  58. package/dist/shared/duration.js +7 -0
  59. package/dist/shared/safe-id.d.ts +19 -0
  60. package/dist/shared/safe-id.js +24 -0
  61. package/dist/shared/text-utils.d.ts +1 -1
  62. package/dist/shared/text-utils.js +3 -8
  63. package/dist/shared/type-guards.d.ts +2 -0
  64. package/dist/shared/type-guards.js +4 -0
  65. package/dist/subagents/discovery.d.ts +44 -17
  66. package/dist/subagents/discovery.js +82 -111
  67. package/dist/subagents/external/claude-code.js +1 -3
  68. package/dist/subagents/external/harness.d.ts +1 -1
  69. package/dist/subagents/format.d.ts +3 -2
  70. package/dist/subagents/format.js +3 -7
  71. package/dist/subagents/runs.d.ts +1 -1
  72. package/dist/subagents/runs.js +4 -9
  73. package/dist/subagents/tool.d.ts +31 -19
  74. package/dist/subagents/tool.js +582 -561
  75. package/dist/subagents/workspace-lease.js +1 -1
  76. package/dist/tasks/control.js +7 -9
  77. package/dist/tasks/ledger.d.ts +2 -2
  78. package/dist/tasks/ledger.js +3 -7
  79. package/dist/tasks/transitions.d.ts +5 -1
  80. package/dist/tasks/transitions.js +2 -2
  81. package/dist/tools/bash.d.ts +0 -1
  82. package/dist/tools/bash.js +45 -40
  83. package/dist/tools/config.d.ts +6 -1
  84. package/dist/tools/config.js +9 -0
  85. package/dist/tools/edit.d.ts +2 -3
  86. package/dist/tools/edit.js +274 -86
  87. package/dist/tools/event-manage.d.ts +13 -7
  88. package/dist/tools/event-manage.js +52 -14
  89. package/dist/tools/glob-match.d.ts +11 -0
  90. package/dist/tools/glob-match.js +75 -0
  91. package/dist/tools/glob.d.ts +15 -0
  92. package/dist/tools/glob.js +113 -0
  93. package/dist/tools/grep.d.ts +0 -1
  94. package/dist/tools/grep.js +57 -42
  95. package/dist/tools/ignore-dirs.d.ts +6 -0
  96. package/dist/tools/ignore-dirs.js +15 -0
  97. package/dist/tools/index.d.ts +3 -0
  98. package/dist/tools/index.js +50 -40
  99. package/dist/tools/job.d.ts +0 -1
  100. package/dist/tools/job.js +1 -8
  101. package/dist/tools/line-index.d.ts +16 -0
  102. package/dist/tools/line-index.js +76 -0
  103. package/dist/tools/memory-manage.d.ts +20 -8
  104. package/dist/tools/memory-manage.js +65 -92
  105. package/dist/tools/presentation.d.ts +2 -0
  106. package/dist/tools/presentation.js +109 -0
  107. package/dist/tools/read.d.ts +2 -2
  108. package/dist/tools/read.js +97 -133
  109. package/dist/tools/registry.d.ts +4 -1
  110. package/dist/tools/registry.js +89 -22
  111. package/dist/tools/send-media.d.ts +6 -6
  112. package/dist/tools/send-media.js +16 -49
  113. package/dist/tools/session-search.d.ts +0 -1
  114. package/dist/tools/session-search.js +0 -1
  115. package/dist/tools/skill-security.d.ts +0 -2
  116. package/dist/tools/skill-security.js +0 -24
  117. package/dist/tools/skill.d.ts +31 -0
  118. package/dist/tools/skill.js +153 -0
  119. package/dist/tools/subagent-manage.d.ts +6 -5
  120. package/dist/tools/subagent-manage.js +47 -47
  121. package/dist/tools/task-manage/create.d.ts +2 -2
  122. package/dist/tools/task-manage/create.js +1 -3
  123. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  124. package/dist/tools/task-manage/lifecycle.js +49 -56
  125. package/dist/tools/task-manage/schema.d.ts +27 -15
  126. package/dist/tools/task-manage/schema.js +58 -74
  127. package/dist/tools/task-manage/shared.d.ts +11 -6
  128. package/dist/tools/task-manage/shared.js +30 -21
  129. package/dist/tools/task-manage/types.d.ts +14 -15
  130. package/dist/tools/task-manage/verification.d.ts +4 -4
  131. package/dist/tools/task-manage/verification.js +6 -8
  132. package/dist/tools/task-manage.d.ts +8 -11
  133. package/dist/tools/task-manage.js +63 -50
  134. package/dist/tools/tool-details.d.ts +17 -1
  135. package/dist/tools/tool-details.js +24 -0
  136. package/dist/tools/truncate.d.ts +5 -5
  137. package/dist/tools/truncate.js +5 -5
  138. package/dist/tools/web-fetch.d.ts +0 -1
  139. package/dist/tools/web-fetch.js +0 -1
  140. package/dist/tools/web-search.d.ts +0 -1
  141. package/dist/tools/web-search.js +0 -1
  142. package/dist/tools/write-content.d.ts +3 -3
  143. package/dist/tools/write-content.js +12 -51
  144. package/dist/tools/write.d.ts +2 -3
  145. package/dist/tools/write.js +3 -4
  146. package/dist/usage/ledger.js +7 -4
  147. package/package.json +1 -1
  148. package/dist/tools/skill-manage.d.ts +0 -41
  149. package/dist/tools/skill-manage.js +0 -232
@@ -1,6 +1,6 @@
1
1
  import { existsSync, 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
19
  import { workspaceSubjectHash } 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, read-only task acceptance check.',
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.
@@ -181,7 +189,7 @@ async function prepareRunContext(runId, params, options) {
181
189
  if (taskId && !TASK_ID_PATTERN.test(taskId))
182
190
  throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
183
191
  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.`);
192
+ throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
185
193
  }
186
194
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
187
195
  const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
@@ -220,47 +228,35 @@ function buildStoppedText(config, reason, finalText) {
220
228
  }
221
229
  return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
222
230
  }
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
231
  /**
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.
232
+ * Spec 032 D4: the full text always lands on disk, independent of whether it fits the reply
233
+ * budget. What comes back to the parent is capped at MAX_SUBAGENT_RESULT_UNITS; a reply over
234
+ * budget is truncated with a pointer to the file a chatty sub-agent can no longer blow out the
235
+ * parent's context.
232
236
  *
233
237
  * The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
234
238
  * runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
235
239
  * This function only needs the path, to point at it.
240
+ *
241
+ * Spec 046 D2.2 removed `returns: "artifact"` and the ARTIFACT marker protocol: a caller that
242
+ * needs a specific output file states the path in the task text instead, the path external roles
243
+ * already had to follow.
236
244
  */
237
- function finalizeSubAgentOutput(runContext, finalText, returns) {
238
- const trimmed = finalText.trim();
245
+ function finalizeSubAgentOutput(runContext, finalText) {
239
246
  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
247
  if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
252
- return { artifactPath, replyText: finalText, truncated: false };
248
+ return { replyText: finalText, truncated: false };
253
249
  }
254
250
  const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
255
- headRatio: ARTIFACT_TRUNCATION_HEAD_RATIO,
251
+ headRatio: RESULT_TRUNCATION_HEAD_RATIO,
256
252
  marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
257
253
  });
258
- return { artifactPath, replyText: clipped.text, truncated: true };
254
+ return { replyText: clipped.text, truncated: true };
259
255
  }
260
256
  /**
261
257
  * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
262
258
  * 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
259
+ * memory_save instead" rule the main agent gets in its system prompt (the memory tools
264
260
  * itself is withheld from sub-agents). Denying these paths at the path-guard level closes
265
261
  * that gap structurally instead of relying on a sub-agent to infer an instruction it never
266
262
  * received — a stray write/edit here would race the shared memory serial queue
@@ -292,6 +288,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
292
288
  const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
293
289
  return buildToolSet({
294
290
  executor,
291
+ fileStore: options.fileStore,
295
292
  securityConfig,
296
293
  securityContext: {
297
294
  // No `channelDir`: a sub-agent receives channel state through its injected context
@@ -309,7 +306,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
309
306
  bashDefaultTimeoutSeconds: bashTimeoutSec,
310
307
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
311
308
  }
312
- /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
309
+ /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
313
310
  export function buildVerificationProtocol(taskPath) {
314
311
  return [
315
312
  "Verification protocol:",
@@ -323,7 +320,7 @@ export function buildVerificationProtocol(taskPath) {
323
320
  * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
324
321
  * protocol terminal to prove it even ran to completion, and a target with an active write lease
325
322
  * 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
323
+ * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
327
324
  * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
328
325
  * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
329
326
  */
@@ -342,13 +339,13 @@ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
342
339
  }
343
340
  }
344
341
  /**
345
- * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
342
+ * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
346
343
  * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
347
344
  * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
348
345
  * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
349
346
  * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
350
347
  */
351
- export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
348
+ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
352
349
  const taskText = task.trim();
353
350
  const lines = [
354
351
  `Runtime context:`,
@@ -370,9 +367,6 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
370
367
  const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
371
368
  lines.push("", buildVerificationProtocol(taskPath));
372
369
  }
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
370
  return lines.join("\n");
377
371
  }
378
372
  function buildSessionContextBlock(sessionMarkdown) {
@@ -474,7 +468,6 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
474
468
  taskId: runContext.taskId,
475
469
  verificationVerdict,
476
470
  artifactDir: runContext.artifactDir,
477
- artifactPath: extras?.artifactPath,
478
471
  resultTruncated: extras?.resultTruncated ?? false,
479
472
  dispatched: extras?.dispatched,
480
473
  };
@@ -482,7 +475,7 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
482
475
  /**
483
476
  * A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
484
477
  * `/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
478
+ * jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
486
479
  * effect of stopping something else.
487
480
  */
488
481
  function sleep(ms) {
@@ -491,11 +484,505 @@ function sleep(ms) {
491
484
  timer.unref?.();
492
485
  });
493
486
  }
487
+ /**
488
+ * Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
489
+ * after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
490
+ * the internal/external fork, budget/turn/tool-call enforcement, verification attestation, and
491
+ * the sync-grace/detached-placeholder split — is identical regardless of which schema the model
492
+ * called through.
493
+ */
494
+ async function dispatchSubAgentRun(options, currentModel, config, warning, params, onUpdate) {
495
+ // Derived rather than model-supplied (spec 045): `${agent}: ${task's first line}`, the
496
+ // same shape `subagent_run op=follow_up` already builds by hand.
497
+ const runLabel = `${config.name}: ${params.task.split("\n")[0]?.slice(0, 80) ?? ""}`;
498
+ // Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
499
+ // `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
500
+ const mutatesNote = warning ? `Note: ${warning}\n\n` : "";
501
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
502
+ // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
503
+ // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
504
+ const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
505
+ // D9: an independent verifier checks against a target that isn't moving under it — shared
506
+ // with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
507
+ // cannot drift between the two dispatch paths.
508
+ assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
509
+ // Admission: a write-mutating run takes an exclusive workspace lease before it is even
510
+ // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
511
+ // Read runs and purpose=verify never take one. Shared by both runtimes.
512
+ let leaseKey;
513
+ if (config.mutates === "write" && runContext.purpose !== "verify") {
514
+ const lease = acquireWorkspaceLease({
515
+ runId: runContext.runId,
516
+ channelId: options.runtimeContext.channelId,
517
+ workingDirectory: runContext.workingDirectory,
518
+ });
519
+ if (!lease.ok) {
520
+ throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
521
+ }
522
+ leaseKey = lease.leaseKey;
523
+ }
524
+ if (config.runtime === "external") {
525
+ if (!config.harness) {
526
+ releaseWorkspaceLease(leaseKey, runContext.runId);
527
+ throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
528
+ }
529
+ let launchResult;
530
+ try {
531
+ // D9/T5: external roles get the same task envelope internal workers do — runtime
532
+ // paths, injected context blocks, and (for purpose=verify) the verification
533
+ // protocol — rather than the raw task text (spec 040 gap closed post-review).
534
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
535
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
536
+ // beats failing a dispatch that would otherwise have run fine.
537
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
538
+ return [];
539
+ });
540
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
541
+ launchResult = await launchExternalRun({
542
+ runId: runContext.runId,
543
+ channelId: options.runtimeContext.channelId,
544
+ channelDir: options.channelDir,
545
+ label: runLabel,
546
+ agent: config.name,
547
+ source: config.source,
548
+ harness: config.harness,
549
+ command: config.command ?? "",
550
+ shell: config.shell,
551
+ env: config.env,
552
+ externalModelRef: config.externalModelRef,
553
+ thinkingLevel: config.thinkingLevel,
554
+ maxWallTimeSec: config.maxWallTimeSec,
555
+ systemPrompt: config.systemPrompt,
556
+ task: envelopedTask,
557
+ workingDirectory: runContext.workingDirectory,
558
+ artifactDir: runContext.artifactDir,
559
+ purpose: runContext.purpose,
560
+ taskId: runContext.taskId,
561
+ leaseKey,
562
+ mutates: config.mutates,
563
+ roleFingerprint: externalRoleFingerprint(config),
564
+ workspaceDir: options.workspaceDir,
565
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
566
+ });
567
+ }
568
+ catch (error) {
569
+ // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
570
+ // every failure past that point settles the run itself and already released this
571
+ // lease (spec 042 D2/D5), so this catch must not release it a second time.
572
+ releaseWorkspaceLease(leaseKey, runContext.runId);
573
+ throw error;
574
+ }
575
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
576
+ // "[Dispatched]" placeholder the model would wait on forever — two of the three
577
+ // failure kinds never used to announce at all. `settle()` already released the lease.
578
+ if (!launchResult.ok) {
579
+ if (launchResult.kind === "missing-binary") {
580
+ 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.`);
581
+ }
582
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
583
+ }
584
+ // D2: external's sync grace window is always 0 — always the dispatched placeholder,
585
+ // never an inline wait. The run keeps going in the background and wakes the channel.
586
+ return {
587
+ content: [
588
+ {
589
+ type: "text",
590
+ text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
591
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
592
+ "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.",
593
+ },
594
+ ],
595
+ details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
596
+ dispatched: true,
597
+ modelOverride: config.externalModelRef ?? "unknown",
598
+ toolsOverride: [],
599
+ }),
600
+ };
601
+ }
602
+ const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
603
+ let apiKey;
604
+ try {
605
+ apiKey = await options.resolveApiKey(config.model);
606
+ }
607
+ catch (error) {
608
+ releaseWorkspaceLease(leaseKey, runContext.runId);
609
+ throw error;
610
+ }
611
+ const startedAt = Date.now();
612
+ const usage = createEmptyUsageTotals();
613
+ let assistantTurns = 0;
614
+ let toolCalls = 0;
615
+ let failureReason;
616
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
617
+ let budgetExceeded = false;
618
+ /** Set only by the `subagent_run op=cancel` handle registered below — a real stop, unlike a budget abort. */
619
+ let externallyCancelled = false;
620
+ /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
621
+ let detached = false;
622
+ let lastUpdateText = "";
623
+ try {
624
+ await runManager.register({
625
+ runId: runContext.runId,
626
+ channelId: options.runtimeContext.channelId,
627
+ runtime: "internal",
628
+ agent: config.name,
629
+ label: runLabel,
630
+ source: config.source,
631
+ tools: [...config.tools],
632
+ model: formatModelReference(config.model),
633
+ purpose: runContext.purpose,
634
+ taskId: runContext.taskId,
635
+ workingDirectory: runContext.workingDirectory,
636
+ artifactDir: runContext.artifactDir,
637
+ leaseKey,
638
+ });
639
+ }
640
+ catch (error) {
641
+ // Until the durable running record exists, setup still owns the lease. A channel/host
642
+ // admission rejection or required persist failure must leave no invisible writer lock.
643
+ releaseWorkspaceLease(leaseKey, runContext.runId);
644
+ throw error;
645
+ }
646
+ const emitUpdate = (text) => {
647
+ // Once detached, execute() has already returned to the SDK; nothing is listening
648
+ // for further progress on this (from its view, finished) tool call.
649
+ if (detached)
650
+ return;
651
+ const nextText = text.trim();
652
+ if (!nextText || nextText === lastUpdateText) {
653
+ return;
654
+ }
655
+ lastUpdateText = nextText;
656
+ onUpdate?.({
657
+ content: [{ type: "text", text: nextText }],
658
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
659
+ });
660
+ };
661
+ let worker;
662
+ let wallClockTimer;
663
+ let unsubscribe;
664
+ let verifierGitStateBefore;
665
+ let verifierSubjectBefore;
666
+ try {
667
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
668
+ verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
669
+ verifierSubjectBefore =
670
+ runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
671
+ worker =
672
+ options.createWorker?.({
673
+ subAgent: config,
674
+ apiKey,
675
+ tools: filterToolsByName(availableTools, config.tools),
676
+ }) ??
677
+ new Agent({
678
+ initialState: {
679
+ systemPrompt: config.systemPrompt,
680
+ model: config.model,
681
+ // Same clamp the main agent applies (channel-runner.ts) before setting a model's
682
+ // thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
683
+ // snaps to the nearest one, instead of a raw unsupported value reaching the provider.
684
+ // The internal path's resolved config always fills thinkingLevel; the fallback
685
+ // here only closes the type.
686
+ thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
687
+ tools: filterToolsByName(availableTools, config.tools),
688
+ },
689
+ convertToLlm,
690
+ getApiKey: async () => apiKey,
691
+ streamFn: streamSimple,
692
+ });
693
+ runManager.registerCancelHandle(runContext.runId, () => {
694
+ externallyCancelled = true;
695
+ worker?.abort();
696
+ });
697
+ wallClockTimer = setTimeout(() => {
698
+ failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
699
+ budgetExceeded = true;
700
+ worker?.abort();
701
+ }, config.maxWallTimeSec * 1000);
702
+ unsubscribe = worker.subscribe((event) => {
703
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
704
+ assistantTurns++;
705
+ const messageUsage = event.message.usage;
706
+ usage.input += messageUsage.input;
707
+ usage.output += messageUsage.output;
708
+ usage.cacheRead += messageUsage.cacheRead;
709
+ usage.cacheWrite += messageUsage.cacheWrite;
710
+ usage.total += messageUsage.totalTokens;
711
+ usage.cost.input += messageUsage.cost.input;
712
+ usage.cost.output += messageUsage.cost.output;
713
+ usage.cost.cacheRead += messageUsage.cost.cacheRead;
714
+ usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
715
+ usage.cost.total += messageUsage.cost.total;
716
+ }
717
+ if (event.type === "tool_execution_start") {
718
+ toolCalls++;
719
+ const label = describeToolCall(event.toolName, event.args);
720
+ emitUpdate(formatStatus(config.name, label));
721
+ if (toolCalls > config.maxToolCalls) {
722
+ failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
723
+ budgetExceeded = true;
724
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
725
+ worker?.abort();
726
+ }
727
+ }
728
+ if (event.type === "turn_end" &&
729
+ isAssistantMessage(event.message) &&
730
+ event.toolResults.length > 0 &&
731
+ assistantTurns >= config.maxTurns) {
732
+ failureReason = `Turn budget exceeded (${config.maxTurns})`;
733
+ budgetExceeded = true;
734
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
735
+ worker?.abort();
736
+ }
737
+ });
738
+ emitUpdate(formatStatus(config.name, "started"));
739
+ }
740
+ catch (error) {
741
+ unsubscribe?.();
742
+ if (wallClockTimer)
743
+ clearTimeout(wallClockTimer);
744
+ runManager.clearCancelHandle(runContext.runId);
745
+ try {
746
+ worker?.abort();
747
+ }
748
+ catch {
749
+ // Preserve the setup error; settlement below is the lifecycle authority.
750
+ }
751
+ const setupError = error instanceof Error ? error : new Error(String(error));
752
+ await runManager.settle(runContext.runId, {
753
+ status: "failed",
754
+ failureReason: setupError.message,
755
+ usage,
756
+ usageKnown: true,
757
+ costKnown: true,
758
+ turns: assistantTurns,
759
+ toolCalls,
760
+ durationMs: Date.now() - startedAt,
761
+ outputText: "",
762
+ }, { announce: false });
763
+ throw setupError;
764
+ }
765
+ const activeWorker = worker;
766
+ const activeUnsubscribe = unsubscribe;
767
+ const activeWallClockTimer = wallClockTimer;
768
+ /**
769
+ * Runs the worker to completion, including the D6 convergence turn, and returns the
770
+ * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
771
+ * fatal case (no assistant message at all) — every other outcome, including a budget
772
+ * abort or explicit cancel, is a normal (if failed) result.
773
+ */
774
+ async function runToCompletion() {
775
+ try {
776
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
777
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
778
+ // beats failing a dispatch that would otherwise have run fine.
779
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
780
+ return [];
781
+ });
782
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
783
+ await activeWorker.waitForIdle();
784
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
785
+ // conclusion instead of discarding the work outright. An explicit cancel skips
786
+ // this — the model asked this run to stop now, not to wrap up.
787
+ if (budgetExceeded && !externallyCancelled) {
788
+ clearTimeout(activeWallClockTimer);
789
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
790
+ const preConvergenceMessageCount = activeWorker.state.messages.length;
791
+ activeWorker.state.tools = [];
792
+ let convergenceTimedOut = false;
793
+ const convergenceTimer = setTimeout(() => {
794
+ convergenceTimedOut = true;
795
+ activeWorker.abort();
796
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
797
+ try {
798
+ await activeWorker.prompt(CONVERGENCE_PROMPT);
799
+ await activeWorker.waitForIdle();
800
+ }
801
+ catch {
802
+ // Best effort: fall through to whatever worker.state.messages holds.
803
+ }
804
+ finally {
805
+ clearTimeout(convergenceTimer);
806
+ }
807
+ if (convergenceTimedOut) {
808
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
809
+ // convergence turn and fall back to whatever came before it.
810
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
811
+ }
812
+ }
813
+ }
814
+ finally {
815
+ activeUnsubscribe();
816
+ clearTimeout(activeWallClockTimer);
817
+ }
818
+ const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
819
+ const durationMs = Date.now() - startedAt;
820
+ if (!lastAssistantMessage) {
821
+ failureReason = failureReason || "Sub-agent returned no assistant message";
822
+ emitUpdate(formatStatus(config.name, "failed"));
823
+ throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
824
+ }
825
+ const finalText = extractAssistantText(lastAssistantMessage);
826
+ const effectiveFailureReason = failureReason ||
827
+ (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
828
+ ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
829
+ : undefined);
830
+ const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
831
+ const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
832
+ // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
833
+ // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
834
+ // run's own output does and does not prove. Only the attestation write and the
835
+ // strength label stay here, since only the internal path can structurally remove
836
+ // write/edit from the verifier's tool set.
837
+ const verification = runContext.purpose === "verify"
838
+ ? resolveVerificationOutcome({
839
+ subjectBefore: verifierSubjectBefore,
840
+ subjectAfter: verifierSubjectAfter,
841
+ gitStateBefore: verifierGitStateBefore,
842
+ gitStateAfter: verifierGitStateAfter,
843
+ finalText,
844
+ runFailed: Boolean(effectiveFailureReason),
845
+ })
846
+ : undefined;
847
+ const verificationVerdict = verification?.verdict;
848
+ // Internal verify always keeps write/edit structurally removed from the verifier's
849
+ // tool set (buildSubagentTools above), but `bash` stays available by default and can
850
+ // write files just as well — labeling that "enforced" would be dishonest (review
851
+ // 2026-08-23 §2.2). Only a role that dropped `bash` from its declared tool list earns
852
+ // the stronger label. Computed once so the attestation and the run record — the
853
+ // latter is what the completion wake and `subagent_list` display — cannot disagree.
854
+ const internalVerificationStrength = config.tools.includes("bash")
855
+ ? "advisory"
856
+ : "enforced";
857
+ if (runContext.purpose === "verify" && runContext.taskId && verification) {
858
+ await writeVerificationAttestation(options.channelDir, {
859
+ runId: runContext.runId,
860
+ taskId: runContext.taskId,
861
+ verdict: verification.verdict,
862
+ checkedAt: formatLocalTime(),
863
+ evidence: verification.evidence,
864
+ workspaceChanged: verification.workspaceChanged,
865
+ subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
866
+ subjectDir: runContext.workingDirectory,
867
+ verificationStrength: internalVerificationStrength,
868
+ });
869
+ }
870
+ // Internal runs always report full usage; cost is "unknown" only for the shape a
871
+ // free/local model produces (tokens spent, nothing billed) — external harnesses
872
+ // override both explicitly once they land (D4/D9).
873
+ const costKnown = usage.cost.total > 0 || usage.total === 0;
874
+ const baseSettleInput = {
875
+ usage,
876
+ usageKnown: true,
877
+ costKnown,
878
+ turns: assistantTurns,
879
+ toolCalls,
880
+ durationMs,
881
+ verificationVerdict,
882
+ verificationStrength: runContext.purpose === "verify" ? internalVerificationStrength : undefined,
883
+ };
884
+ if (effectiveFailureReason) {
885
+ if (!finalText.trim()) {
886
+ emitUpdate(formatStatus(config.name, "failed"));
887
+ throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
888
+ }
889
+ emitUpdate(formatStatus(config.name, "stopped"));
890
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
891
+ return {
892
+ toolResult: {
893
+ content: [
894
+ {
895
+ type: "text",
896
+ text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
897
+ },
898
+ ],
899
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { resultTruncated: finalized.truncated }),
900
+ },
901
+ settleInput: {
902
+ ...baseSettleInput,
903
+ // An explicit cancel is not a failure (P1-1) — the model asked this run to
904
+ // stop, and it did.
905
+ status: externallyCancelled ? "cancelled" : "failed",
906
+ failureReason: effectiveFailureReason,
907
+ outputText: finalText,
908
+ },
909
+ };
910
+ }
911
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
912
+ return {
913
+ toolResult: {
914
+ content: [
915
+ {
916
+ type: "text",
917
+ text: mutatesNote + (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
918
+ },
919
+ ],
920
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { resultTruncated: finalized.truncated }),
921
+ },
922
+ settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
923
+ };
924
+ }
925
+ /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
926
+ function fatalSettleInput(error) {
927
+ return {
928
+ status: externallyCancelled ? "cancelled" : "failed",
929
+ failureReason: failureReason || error.message,
930
+ usage,
931
+ usageKnown: true,
932
+ costKnown: usage.cost.total > 0 || usage.total === 0,
933
+ turns: assistantTurns,
934
+ toolCalls,
935
+ durationMs: Date.now() - startedAt,
936
+ outputText: "",
937
+ };
938
+ }
939
+ // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
940
+ // clock budget) before degrading to a "still running" placeholder. The run itself keeps
941
+ // executing either way — only the *return* differs.
942
+ const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
943
+ const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
944
+ ok: false,
945
+ error: error instanceof Error ? error : new Error(String(error)),
946
+ }));
947
+ const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
948
+ if (raceResult !== "timed-out") {
949
+ runManager.clearCancelHandle(runContext.runId);
950
+ if (!raceResult.ok) {
951
+ await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
952
+ throw raceResult.error;
953
+ }
954
+ await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
955
+ return raceResult.value.toolResult;
956
+ }
957
+ // Grace window elapsed: hand back a placeholder now and let the run keep going in the
958
+ // background. It settles and, this time, announces itself with a completion wake (D2/D7)
959
+ // — the same "runtime guarantees completion" contract background jobs already keep.
960
+ detached = true;
961
+ void outcomePromise.then(async (outcome) => {
962
+ runManager.clearCancelHandle(runContext.runId);
963
+ const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
964
+ await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
965
+ log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
966
+ });
967
+ });
968
+ return {
969
+ content: [
970
+ {
971
+ type: "text",
972
+ text: mutatesNote +
973
+ `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
974
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
975
+ "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.",
976
+ },
977
+ ],
978
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, false, undefined, undefined, { dispatched: true }),
979
+ };
980
+ }
494
981
  export function createSubAgentTool(options) {
495
982
  return {
496
983
  name: "subagent",
497
984
  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.",
985
+ 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
986
  parameters: subagentSchema,
500
987
  execute: async (_toolCallId, params, signal, onUpdate) => {
501
988
  if (signal?.aborted) {
@@ -512,510 +999,44 @@ export function createSubAgentTool(options) {
512
999
  if (taskLengthError) {
513
1000
  throw new RecoverableToolError(taskLengthError);
514
1001
  }
515
- const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
1002
+ const invocation = resolveConfiguredRole(availableModels, currentModel, discovery.agents, { agent: params.agent, purpose: params.purpose }, options.getSubAgentModelReference?.() ?? undefined);
516
1003
  if (!invocation.config) {
517
1004
  throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
518
1005
  }
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
- };
1006
+ return dispatchSubAgentRun(options, currentModel, invocation.config, undefined, params, onUpdate);
1007
+ },
1008
+ };
1009
+ }
1010
+ export function createSubAgentInlineTool(options) {
1011
+ return {
1012
+ name: "subagent_inline",
1013
+ label: "subagent_inline",
1014
+ 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.",
1015
+ parameters: subagentInlineSchema,
1016
+ execute: async (_toolCallId, params, signal, onUpdate) => {
1017
+ if (signal?.aborted) {
1018
+ throw new Error("Sub-agent aborted");
963
1019
  }
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
- };
1020
+ const availableModels = options.getAvailableModels();
1021
+ const currentModel = options.getCurrentModel();
1022
+ const taskLengthError = validateSubAgentTask(params.task);
1023
+ if (taskLengthError) {
1024
+ throw new RecoverableToolError(taskLengthError);
977
1025
  }
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;
1026
+ const invocation = resolveInlineAgent(availableModels, currentModel, {
1027
+ systemPrompt: params.systemPrompt,
1028
+ tools: params.tools,
1029
+ model: params.model,
1030
+ effort: params.effort,
1031
+ context: params.context,
1032
+ thinkingLevel: params.thinkingLevel,
1033
+ mutates: params.mutates,
1034
+ purpose: params.purpose,
1035
+ }, options.getSubAgentModelReference?.() ?? undefined);
1036
+ if (!invocation.config) {
1037
+ throw new RecoverableToolError(invocation.error ?? "Unable to resolve inline sub-agent.");
995
1038
  }
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
- };
1039
+ return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, onUpdate);
1019
1040
  },
1020
1041
  };
1021
1042
  }