@oyasmi/pipiclaw 0.9.1-beta.2 → 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.
- package/dist/agent/channel-runner.d.ts +9 -1
- package/dist/agent/channel-runner.js +51 -18
- package/dist/agent/command-extension.js +24 -27
- package/dist/agent/commands.d.ts +51 -7
- package/dist/agent/commands.js +199 -59
- package/dist/agent/effect-ledger.js +9 -2
- package/dist/agent/job-manager.d.ts +4 -0
- package/dist/agent/job-manager.js +17 -2
- package/dist/agent/prompt/manifest.d.ts +1 -1
- package/dist/agent/prompt/manifest.js +6 -7
- package/dist/agent/prompt/sections.js +9 -5
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +29 -14
- package/dist/agent/status-render.js +12 -12
- package/dist/agent/turn-recovery.js +2 -2
- package/dist/agent/type-guards.js +5 -1
- package/dist/agent/workspace-resources.d.ts +2 -2
- package/dist/agent/workspace-resources.js +41 -3
- package/dist/executor.d.ts +28 -0
- package/dist/executor.js +120 -18
- package/dist/file-store.d.ts +96 -0
- package/dist/file-store.js +189 -0
- package/dist/main.js +3 -4
- package/dist/memory/commands.js +79 -38
- package/dist/memory/consolidation.d.ts +5 -1
- package/dist/memory/consolidation.js +35 -38
- package/dist/memory/extraction.d.ts +8 -1
- package/dist/memory/extraction.js +47 -4
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +31 -12
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +16 -38
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +19 -0
- package/dist/memory/recall.js +116 -24
- package/dist/memory/review-log.d.ts +0 -2
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/session-corpus.js +5 -0
- package/dist/memory/session-search.js +15 -22
- package/dist/memory/sidecar-worker.js +4 -0
- package/dist/memory/source-window.d.ts +0 -1
- package/dist/memory/source-window.js +0 -5
- package/dist/memory/transcript.d.ts +10 -0
- package/dist/memory/transcript.js +39 -0
- package/dist/playbooks/agent-delegation.md +34 -25
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/catalog.d.ts +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/event-scheduling.md +15 -15
- package/dist/playbooks/memory-and-learning.md +30 -23
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +36 -38
- package/dist/playbooks/task-planning.md +21 -21
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +16 -7
- package/dist/runtime/bootstrap.js +54 -13
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/delivery.js +3 -3
- package/dist/runtime/dingtalk.d.ts +9 -1
- package/dist/runtime/dingtalk.js +30 -15
- package/dist/runtime/durable-dispatch.d.ts +26 -1
- package/dist/runtime/durable-dispatch.js +51 -5
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +55 -56
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +15 -20
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +13 -17
- package/dist/runtime/subagent-commands.d.ts +20 -0
- package/dist/runtime/subagent-commands.js +61 -58
- package/dist/runtime/task-commands.d.ts +37 -0
- package/dist/runtime/task-commands.js +108 -66
- package/dist/runtime/task-driver.js +2 -2
- package/dist/security/block-message.d.ts +11 -0
- package/dist/security/block-message.js +12 -0
- package/dist/security/path-guard-check.d.ts +13 -0
- package/dist/security/path-guard-check.js +39 -0
- package/dist/security/path-guard.js +61 -12
- package/dist/security/types.d.ts +9 -0
- package/dist/settings.js +3 -2
- package/dist/shared/atomic-file.d.ts +17 -1
- package/dist/shared/atomic-file.js +50 -3
- package/dist/shared/duration.d.ts +2 -0
- package/dist/shared/duration.js +7 -0
- package/dist/shared/safe-id.d.ts +19 -0
- package/dist/shared/safe-id.js +24 -0
- package/dist/shared/text-utils.d.ts +1 -1
- package/dist/shared/text-utils.js +3 -8
- package/dist/shared/type-guards.d.ts +2 -0
- package/dist/shared/type-guards.js +4 -0
- package/dist/subagents/discovery.d.ts +51 -19
- package/dist/subagents/discovery.js +93 -98
- package/dist/subagents/external/claude-code.js +40 -2
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/run.js +61 -8
- package/dist/subagents/format.d.ts +3 -2
- package/dist/subagents/format.js +3 -7
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/runs.js +10 -9
- package/dist/subagents/tool.d.ts +31 -18
- package/dist/subagents/tool.js +592 -562
- package/dist/subagents/workspace-lease.js +1 -1
- package/dist/tasks/control.js +7 -9
- package/dist/tasks/ledger.d.ts +2 -2
- package/dist/tasks/ledger.js +3 -7
- package/dist/tasks/transitions.d.ts +5 -1
- package/dist/tasks/transitions.js +2 -2
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -2
- package/dist/tools/bash.js +99 -76
- package/dist/tools/config.d.ts +6 -1
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +2 -3
- package/dist/tools/edit.js +276 -75
- package/dist/tools/event-manage.d.ts +13 -7
- package/dist/tools/event-manage.js +52 -14
- package/dist/tools/glob-match.d.ts +11 -0
- package/dist/tools/glob-match.js +75 -0
- package/dist/tools/glob.d.ts +15 -0
- package/dist/tools/glob.js +113 -0
- package/dist/tools/grep.d.ts +0 -1
- package/dist/tools/grep.js +60 -44
- package/dist/tools/ignore-dirs.d.ts +6 -0
- package/dist/tools/ignore-dirs.js +15 -0
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +54 -40
- package/dist/tools/job.d.ts +0 -1
- package/dist/tools/job.js +3 -9
- package/dist/tools/line-index.d.ts +16 -0
- package/dist/tools/line-index.js +76 -0
- package/dist/tools/memory-manage.d.ts +21 -8
- package/dist/tools/memory-manage.js +114 -103
- package/dist/tools/presentation.d.ts +2 -0
- package/dist/tools/presentation.js +109 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +100 -120
- package/dist/tools/registry.d.ts +4 -1
- package/dist/tools/registry.js +89 -22
- package/dist/tools/send-media.d.ts +6 -6
- package/dist/tools/send-media.js +21 -43
- package/dist/tools/session-search.d.ts +0 -1
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-security.d.ts +0 -2
- package/dist/tools/skill-security.js +1 -25
- package/dist/tools/skill.d.ts +31 -0
- package/dist/tools/skill.js +153 -0
- package/dist/tools/subagent-manage.d.ts +6 -5
- package/dist/tools/subagent-manage.js +47 -47
- package/dist/tools/task-manage/create.d.ts +2 -2
- package/dist/tools/task-manage/create.js +1 -3
- package/dist/tools/task-manage/lifecycle.d.ts +9 -6
- package/dist/tools/task-manage/lifecycle.js +49 -56
- package/dist/tools/task-manage/schema.d.ts +27 -15
- package/dist/tools/task-manage/schema.js +58 -74
- package/dist/tools/task-manage/shared.d.ts +11 -6
- package/dist/tools/task-manage/shared.js +30 -21
- package/dist/tools/task-manage/types.d.ts +14 -15
- package/dist/tools/task-manage/verification.d.ts +4 -4
- package/dist/tools/task-manage/verification.js +6 -8
- package/dist/tools/task-manage.d.ts +8 -11
- package/dist/tools/task-manage.js +63 -50
- package/dist/tools/tool-details.d.ts +17 -1
- package/dist/tools/tool-details.js +24 -0
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.d.ts +0 -1
- package/dist/tools/web-fetch.js +9 -2
- package/dist/tools/web-search.d.ts +0 -1
- package/dist/tools/web-search.js +0 -1
- package/dist/tools/write-content.d.ts +3 -3
- package/dist/tools/write-content.js +12 -41
- package/dist/tools/write.d.ts +2 -3
- package/dist/tools/write.js +3 -4
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/tui/turn-controller.js +14 -4
- package/dist/usage/ledger.js +7 -4
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
- package/dist/tools/skill-manage.d.ts +0 -41
- package/dist/tools/skill-manage.js +0 -231
package/dist/subagents/tool.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
2
2
|
import { mkdir } from "node:fs/promises";
|
|
3
|
-
import {
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
4
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
5
|
-
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
5
|
+
import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
6
6
|
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { Type } from "typebox";
|
|
8
8
|
import * as log from "../log.js";
|
|
@@ -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
|
|
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 { externalRoleFingerprint, formatSubAgentList,
|
|
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
|
-
|
|
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
|
-
|
|
34
|
-
|
|
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,8 +70,15 @@ const subagentSchema = Type.Object({
|
|
|
63
70
|
Type.Literal("xhigh"),
|
|
64
71
|
Type.Literal("max"),
|
|
65
72
|
], {
|
|
66
|
-
description:
|
|
73
|
+
description: "Optional reasoning effort for the sub-agent.",
|
|
67
74
|
})),
|
|
75
|
+
mutates: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("write")], {
|
|
76
|
+
description: 'Whether this delegation will modify the working directory. Declare "write" whenever the sub-agent may write ' +
|
|
77
|
+
"files (including through bash) so it takes the exclusive workspace write lease.",
|
|
78
|
+
})),
|
|
79
|
+
workingDirectory: workingDirectoryField,
|
|
80
|
+
purpose: purposeField,
|
|
81
|
+
taskId: taskIdField,
|
|
68
82
|
});
|
|
69
83
|
const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
|
|
70
84
|
enabled: true,
|
|
@@ -85,7 +99,7 @@ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
|
85
99
|
* only caps what gets echoed into the parent's context.
|
|
86
100
|
*/
|
|
87
101
|
export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
|
|
88
|
-
const
|
|
102
|
+
const RESULT_TRUNCATION_HEAD_RATIO = 1;
|
|
89
103
|
/**
|
|
90
104
|
* Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
|
|
91
105
|
* tool-free turn to summarize what it already found instead of having its work discarded.
|
|
@@ -175,7 +189,7 @@ async function prepareRunContext(runId, params, options) {
|
|
|
175
189
|
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
176
190
|
throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
|
|
177
191
|
if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
|
|
178
|
-
throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with
|
|
192
|
+
throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
|
|
179
193
|
}
|
|
180
194
|
const artifactDir = await prepareArtifactDir(options.channelDir, runId);
|
|
181
195
|
const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
|
|
@@ -214,47 +228,35 @@ function buildStoppedText(config, reason, finalText) {
|
|
|
214
228
|
}
|
|
215
229
|
return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
|
|
216
230
|
}
|
|
217
|
-
const ARTIFACT_MARKER_PATTERN = /(?:^|\n)ARTIFACT:\s*(\S+)\s*$/i;
|
|
218
|
-
function parseArtifactMarker(output) {
|
|
219
|
-
return ARTIFACT_MARKER_PATTERN.exec(output.trim())?.[1];
|
|
220
|
-
}
|
|
221
231
|
/**
|
|
222
|
-
* Spec 032 D4: the full text always lands on disk, independent of
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
*
|
|
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.
|
|
226
236
|
*
|
|
227
237
|
* The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
|
|
228
238
|
* runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
|
|
229
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.
|
|
230
244
|
*/
|
|
231
|
-
function finalizeSubAgentOutput(runContext, finalText
|
|
232
|
-
const trimmed = finalText.trim();
|
|
245
|
+
function finalizeSubAgentOutput(runContext, finalText) {
|
|
233
246
|
const outputPath = join(runContext.artifactDir, "output.md");
|
|
234
|
-
let artifactPath;
|
|
235
|
-
if (returns === "artifact" && trimmed) {
|
|
236
|
-
const filename = parseArtifactMarker(trimmed);
|
|
237
|
-
if (filename) {
|
|
238
|
-
const candidate = resolve(runContext.artifactDir, filename);
|
|
239
|
-
const rel = relative(runContext.artifactDir, candidate);
|
|
240
|
-
if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
|
|
241
|
-
artifactPath = candidate;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
247
|
if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
|
|
246
|
-
return {
|
|
248
|
+
return { replyText: finalText, truncated: false };
|
|
247
249
|
}
|
|
248
250
|
const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
|
|
249
|
-
headRatio:
|
|
251
|
+
headRatio: RESULT_TRUNCATION_HEAD_RATIO,
|
|
250
252
|
marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
|
|
251
253
|
});
|
|
252
|
-
return {
|
|
254
|
+
return { replyText: clipped.text, truncated: true };
|
|
253
255
|
}
|
|
254
256
|
/**
|
|
255
257
|
* Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
|
|
256
258
|
* context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
|
|
257
|
-
*
|
|
259
|
+
* memory_save instead" rule the main agent gets in its system prompt (the memory tools
|
|
258
260
|
* itself is withheld from sub-agents). Denying these paths at the path-guard level closes
|
|
259
261
|
* that gap structurally instead of relying on a sub-agent to infer an instruction it never
|
|
260
262
|
* received — a stray write/edit here would race the shared memory serial queue
|
|
@@ -286,8 +288,12 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
|
286
288
|
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
|
|
287
289
|
return buildToolSet({
|
|
288
290
|
executor,
|
|
291
|
+
fileStore: options.fileStore,
|
|
289
292
|
securityConfig,
|
|
290
293
|
securityContext: {
|
|
294
|
+
// No `channelDir`: a sub-agent receives channel state through its injected context
|
|
295
|
+
// blocks, not by reading the channel's own files, so it does not inherit the parent's
|
|
296
|
+
// channel-directory exception (see security/types.ts).
|
|
291
297
|
agentWorkspaceDir: options.workspaceDir,
|
|
292
298
|
projectRoot: runContext.workingDirectory,
|
|
293
299
|
boundary: options.projectBoundary,
|
|
@@ -300,7 +306,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
|
300
306
|
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
301
307
|
}, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
|
|
302
308
|
}
|
|
303
|
-
/** Shared by both runtimes' task envelopes and `
|
|
309
|
+
/** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
|
|
304
310
|
export function buildVerificationProtocol(taskPath) {
|
|
305
311
|
return [
|
|
306
312
|
"Verification protocol:",
|
|
@@ -314,7 +320,7 @@ export function buildVerificationProtocol(taskPath) {
|
|
|
314
320
|
* D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
|
|
315
321
|
* protocol terminal to prove it even ran to completion, and a target with an active write lease
|
|
316
322
|
* is refused up front (cheaper than explaining afterward why the attestation would be worthless).
|
|
317
|
-
* Spec 042 D7: exported so `
|
|
323
|
+
* Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
|
|
318
324
|
* dispatch does — before this function existed, follow_up on a role that had since been hot-edited
|
|
319
325
|
* to `mutates: write` would silently take the write lease and dispatch instead of refusing.
|
|
320
326
|
*/
|
|
@@ -333,13 +339,13 @@ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
|
|
|
333
339
|
}
|
|
334
340
|
}
|
|
335
341
|
/**
|
|
336
|
-
* Exported for `
|
|
342
|
+
* Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
|
|
337
343
|
* envelope the same way the initial dispatch does rather than a hand-rolled approximation.
|
|
338
344
|
* `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
|
|
339
345
|
* caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
|
|
340
346
|
* `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
|
|
341
347
|
*/
|
|
342
|
-
export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext
|
|
348
|
+
export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
|
|
343
349
|
const taskText = task.trim();
|
|
344
350
|
const lines = [
|
|
345
351
|
`Runtime context:`,
|
|
@@ -361,9 +367,6 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
|
|
|
361
367
|
const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
|
|
362
368
|
lines.push("", buildVerificationProtocol(taskPath));
|
|
363
369
|
}
|
|
364
|
-
else if (returns === "artifact") {
|
|
365
|
-
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>");
|
|
366
|
-
}
|
|
367
370
|
return lines.join("\n");
|
|
368
371
|
}
|
|
369
372
|
function buildSessionContextBlock(sessionMarkdown) {
|
|
@@ -449,8 +452,8 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
|
|
|
449
452
|
return {
|
|
450
453
|
agent: config.name,
|
|
451
454
|
source: config.source,
|
|
452
|
-
model: formatModelReference(config.model),
|
|
453
|
-
tools: [...config.tools],
|
|
455
|
+
model: extras?.modelOverride ?? formatModelReference(config.model),
|
|
456
|
+
tools: extras?.toolsOverride ?? [...config.tools],
|
|
454
457
|
turns,
|
|
455
458
|
toolCalls,
|
|
456
459
|
durationMs,
|
|
@@ -465,14 +468,14 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
|
|
|
465
468
|
taskId: runContext.taskId,
|
|
466
469
|
verificationVerdict,
|
|
467
470
|
artifactDir: runContext.artifactDir,
|
|
468
|
-
artifactPath: extras?.artifactPath,
|
|
469
471
|
resultTruncated: extras?.resultTruncated ?? false,
|
|
472
|
+
dispatched: extras?.dispatched,
|
|
470
473
|
};
|
|
471
474
|
}
|
|
472
475
|
/**
|
|
473
476
|
* A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
|
|
474
477
|
* `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
|
|
475
|
-
* jobs. Stopping a run is now an explicit decision (`
|
|
478
|
+
* jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
|
|
476
479
|
* effect of stopping something else.
|
|
477
480
|
*/
|
|
478
481
|
function sleep(ms) {
|
|
@@ -481,11 +484,505 @@ function sleep(ms) {
|
|
|
481
484
|
timer.unref?.();
|
|
482
485
|
});
|
|
483
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
|
+
}
|
|
484
981
|
export function createSubAgentTool(options) {
|
|
485
982
|
return {
|
|
486
983
|
name: "subagent",
|
|
487
984
|
label: "subagent",
|
|
488
|
-
description: "Delegate a task to a sub-agent
|
|
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.",
|
|
489
986
|
parameters: subagentSchema,
|
|
490
987
|
execute: async (_toolCallId, params, signal, onUpdate) => {
|
|
491
988
|
if (signal?.aborted) {
|
|
@@ -502,511 +999,44 @@ export function createSubAgentTool(options) {
|
|
|
502
999
|
if (taskLengthError) {
|
|
503
1000
|
throw new RecoverableToolError(taskLengthError);
|
|
504
1001
|
}
|
|
505
|
-
const invocation =
|
|
1002
|
+
const invocation = resolveConfiguredRole(availableModels, currentModel, discovery.agents, { agent: params.agent, purpose: params.purpose }, options.getSubAgentModelReference?.() ?? undefined);
|
|
506
1003
|
if (!invocation.config) {
|
|
507
1004
|
throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
|
|
508
1005
|
}
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
// A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
|
|
523
|
-
// on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
|
|
524
|
-
const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
|
|
525
|
-
// D9: an independent verifier checks against a target that isn't moving under it — shared
|
|
526
|
-
// with `subagent_manage op=follow_up` (spec 042 D7) so a verify run's admission rules
|
|
527
|
-
// cannot drift between the two dispatch paths.
|
|
528
|
-
assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
|
|
529
|
-
// Admission: a write-mutating run takes an exclusive workspace lease before it is even
|
|
530
|
-
// registered (spec 040, D10.1) — a rejected delegation should never count as "started".
|
|
531
|
-
// Read runs and purpose=verify never take one. Shared by both runtimes.
|
|
532
|
-
let leaseKey;
|
|
533
|
-
if (config.mutates === "write" && runContext.purpose !== "verify") {
|
|
534
|
-
const lease = acquireWorkspaceLease({
|
|
535
|
-
runId: runContext.runId,
|
|
536
|
-
channelId: options.runtimeContext.channelId,
|
|
537
|
-
workingDirectory: runContext.workingDirectory,
|
|
538
|
-
});
|
|
539
|
-
if (!lease.ok) {
|
|
540
|
-
throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
|
|
541
|
-
}
|
|
542
|
-
leaseKey = lease.leaseKey;
|
|
543
|
-
}
|
|
544
|
-
if (config.runtime === "external") {
|
|
545
|
-
if (!config.harness) {
|
|
546
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
547
|
-
throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
|
|
548
|
-
}
|
|
549
|
-
let launchResult;
|
|
550
|
-
try {
|
|
551
|
-
// D9/T5: external roles get the same task envelope internal workers do — runtime
|
|
552
|
-
// paths, injected context blocks, and (for purpose=verify) the verification
|
|
553
|
-
// protocol — rather than the raw task text (spec 040 gap closed post-review).
|
|
554
|
-
// Spec 042 D3: `returns: "artifact"` is rejected for external above, so this is
|
|
555
|
-
// always "text" here — passed literally rather than the `returns` variable so the
|
|
556
|
-
// ARTIFACT marker protocol is never injected into an external envelope, which no
|
|
557
|
-
// external result parser has ever read.
|
|
558
|
-
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
559
|
-
const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, "text");
|
|
560
|
-
launchResult = await launchExternalRun({
|
|
561
|
-
runId: runContext.runId,
|
|
562
|
-
channelId: options.runtimeContext.channelId,
|
|
563
|
-
channelDir: options.channelDir,
|
|
564
|
-
label: params.label,
|
|
565
|
-
agent: config.name,
|
|
566
|
-
source: config.source,
|
|
567
|
-
harness: config.harness,
|
|
568
|
-
command: config.command ?? "",
|
|
569
|
-
shell: config.shell,
|
|
570
|
-
env: config.env,
|
|
571
|
-
externalModelRef: config.externalModelRef,
|
|
572
|
-
thinkingLevel: config.thinkingLevel,
|
|
573
|
-
maxWallTimeSec: config.maxWallTimeSec,
|
|
574
|
-
systemPrompt: config.systemPrompt,
|
|
575
|
-
task: envelopedTask,
|
|
576
|
-
workingDirectory: runContext.workingDirectory,
|
|
577
|
-
artifactDir: runContext.artifactDir,
|
|
578
|
-
purpose: runContext.purpose,
|
|
579
|
-
taskId: runContext.taskId,
|
|
580
|
-
leaseKey,
|
|
581
|
-
mutates: config.mutates,
|
|
582
|
-
roleFingerprint: externalRoleFingerprint(config),
|
|
583
|
-
workspaceDir: options.workspaceDir,
|
|
584
|
-
securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
|
|
585
|
-
});
|
|
586
|
-
}
|
|
587
|
-
catch (error) {
|
|
588
|
-
// Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
|
|
589
|
-
// every failure past that point settles the run itself and already released this
|
|
590
|
-
// lease (spec 042 D2/D5), so this catch must not release it a second time.
|
|
591
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
592
|
-
throw error;
|
|
593
|
-
}
|
|
594
|
-
// Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
|
|
595
|
-
// "[Dispatched]" placeholder the model would wait on forever — two of the three
|
|
596
|
-
// failure kinds never used to announce at all. `settle()` already released the lease.
|
|
597
|
-
if (!launchResult.ok) {
|
|
598
|
-
if (launchResult.kind === "missing-binary") {
|
|
599
|
-
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.`);
|
|
600
|
-
}
|
|
601
|
-
throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
|
|
602
|
-
}
|
|
603
|
-
// D2: external's sync grace window is always 0 — always the dispatched placeholder,
|
|
604
|
-
// never an inline wait. The run keeps going in the background and wakes the channel.
|
|
605
|
-
return {
|
|
606
|
-
content: [
|
|
607
|
-
{
|
|
608
|
-
type: "text",
|
|
609
|
-
text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
|
|
610
|
-
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
611
|
-
"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.",
|
|
612
|
-
},
|
|
613
|
-
],
|
|
614
|
-
details: {
|
|
615
|
-
agent: config.name,
|
|
616
|
-
source: config.source,
|
|
617
|
-
model: config.externalModelRef ?? "unknown",
|
|
618
|
-
tools: [],
|
|
619
|
-
turns: 0,
|
|
620
|
-
toolCalls: 0,
|
|
621
|
-
durationMs: 0,
|
|
622
|
-
failed: false,
|
|
623
|
-
usage: createEmptyUsageTotals(),
|
|
624
|
-
runId: runContext.runId,
|
|
625
|
-
purpose: runContext.purpose,
|
|
626
|
-
taskId: runContext.taskId,
|
|
627
|
-
artifactDir: runContext.artifactDir,
|
|
628
|
-
resultTruncated: false,
|
|
629
|
-
dispatched: true,
|
|
630
|
-
},
|
|
631
|
-
};
|
|
632
|
-
}
|
|
633
|
-
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
634
|
-
let apiKey;
|
|
635
|
-
try {
|
|
636
|
-
apiKey = await options.resolveApiKey(config.model);
|
|
637
|
-
}
|
|
638
|
-
catch (error) {
|
|
639
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
640
|
-
throw error;
|
|
641
|
-
}
|
|
642
|
-
const startedAt = Date.now();
|
|
643
|
-
const usage = createEmptyUsageTotals();
|
|
644
|
-
let assistantTurns = 0;
|
|
645
|
-
let toolCalls = 0;
|
|
646
|
-
let failureReason;
|
|
647
|
-
/** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
|
|
648
|
-
let budgetExceeded = false;
|
|
649
|
-
/** Set only by the `subagent_manage op=cancel` handle registered below — a real stop, unlike a budget abort. */
|
|
650
|
-
let externallyCancelled = false;
|
|
651
|
-
/** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
|
|
652
|
-
let detached = false;
|
|
653
|
-
let lastUpdateText = "";
|
|
654
|
-
try {
|
|
655
|
-
await runManager.register({
|
|
656
|
-
runId: runContext.runId,
|
|
657
|
-
channelId: options.runtimeContext.channelId,
|
|
658
|
-
runtime: "internal",
|
|
659
|
-
agent: config.name,
|
|
660
|
-
label: params.label,
|
|
661
|
-
source: config.source,
|
|
662
|
-
tools: [...config.tools],
|
|
663
|
-
model: formatModelReference(config.model),
|
|
664
|
-
purpose: runContext.purpose,
|
|
665
|
-
taskId: runContext.taskId,
|
|
666
|
-
workingDirectory: runContext.workingDirectory,
|
|
667
|
-
artifactDir: runContext.artifactDir,
|
|
668
|
-
leaseKey,
|
|
669
|
-
});
|
|
670
|
-
}
|
|
671
|
-
catch (error) {
|
|
672
|
-
// Until the durable running record exists, setup still owns the lease. A channel/host
|
|
673
|
-
// admission rejection or required persist failure must leave no invisible writer lock.
|
|
674
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
675
|
-
throw error;
|
|
676
|
-
}
|
|
677
|
-
const emitUpdate = (text) => {
|
|
678
|
-
// Once detached, execute() has already returned to the SDK; nothing is listening
|
|
679
|
-
// for further progress on this (from its view, finished) tool call.
|
|
680
|
-
if (detached)
|
|
681
|
-
return;
|
|
682
|
-
const nextText = text.trim();
|
|
683
|
-
if (!nextText || nextText === lastUpdateText) {
|
|
684
|
-
return;
|
|
685
|
-
}
|
|
686
|
-
lastUpdateText = nextText;
|
|
687
|
-
onUpdate?.({
|
|
688
|
-
content: [{ type: "text", text: nextText }],
|
|
689
|
-
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
690
|
-
});
|
|
691
|
-
};
|
|
692
|
-
let worker;
|
|
693
|
-
let wallClockTimer;
|
|
694
|
-
let unsubscribe;
|
|
695
|
-
let verifierGitStateBefore;
|
|
696
|
-
let verifierSubjectBefore;
|
|
697
|
-
try {
|
|
698
|
-
const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
|
|
699
|
-
verifierGitStateBefore =
|
|
700
|
-
runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
701
|
-
verifierSubjectBefore =
|
|
702
|
-
runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
703
|
-
worker =
|
|
704
|
-
options.createWorker?.({
|
|
705
|
-
subAgent: config,
|
|
706
|
-
apiKey,
|
|
707
|
-
tools: filterToolsByName(availableTools, config.tools),
|
|
708
|
-
}) ??
|
|
709
|
-
new Agent({
|
|
710
|
-
initialState: {
|
|
711
|
-
systemPrompt: config.systemPrompt,
|
|
712
|
-
model: config.model,
|
|
713
|
-
thinkingLevel: config.thinkingLevel,
|
|
714
|
-
tools: filterToolsByName(availableTools, config.tools),
|
|
715
|
-
},
|
|
716
|
-
convertToLlm,
|
|
717
|
-
getApiKey: async () => apiKey,
|
|
718
|
-
streamFn: streamSimple,
|
|
719
|
-
});
|
|
720
|
-
runManager.registerCancelHandle(runContext.runId, () => {
|
|
721
|
-
externallyCancelled = true;
|
|
722
|
-
worker?.abort();
|
|
723
|
-
});
|
|
724
|
-
wallClockTimer = setTimeout(() => {
|
|
725
|
-
failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
|
|
726
|
-
budgetExceeded = true;
|
|
727
|
-
worker?.abort();
|
|
728
|
-
}, config.maxWallTimeSec * 1000);
|
|
729
|
-
unsubscribe = worker.subscribe((event) => {
|
|
730
|
-
if (event.type === "message_end" && isAssistantMessage(event.message)) {
|
|
731
|
-
assistantTurns++;
|
|
732
|
-
const messageUsage = event.message.usage;
|
|
733
|
-
usage.input += messageUsage.input;
|
|
734
|
-
usage.output += messageUsage.output;
|
|
735
|
-
usage.cacheRead += messageUsage.cacheRead;
|
|
736
|
-
usage.cacheWrite += messageUsage.cacheWrite;
|
|
737
|
-
usage.total += messageUsage.totalTokens;
|
|
738
|
-
usage.cost.input += messageUsage.cost.input;
|
|
739
|
-
usage.cost.output += messageUsage.cost.output;
|
|
740
|
-
usage.cost.cacheRead += messageUsage.cost.cacheRead;
|
|
741
|
-
usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
|
|
742
|
-
usage.cost.total += messageUsage.cost.total;
|
|
743
|
-
}
|
|
744
|
-
if (event.type === "tool_execution_start") {
|
|
745
|
-
toolCalls++;
|
|
746
|
-
const label = extractLabelFromArgs(event.args) || event.toolName;
|
|
747
|
-
emitUpdate(formatStatus(config.name, label));
|
|
748
|
-
if (toolCalls > config.maxToolCalls) {
|
|
749
|
-
failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
|
|
750
|
-
budgetExceeded = true;
|
|
751
|
-
emitUpdate(formatStatus(config.name, "tool budget reached"));
|
|
752
|
-
worker?.abort();
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
if (event.type === "turn_end" &&
|
|
756
|
-
isAssistantMessage(event.message) &&
|
|
757
|
-
event.toolResults.length > 0 &&
|
|
758
|
-
assistantTurns >= config.maxTurns) {
|
|
759
|
-
failureReason = `Turn budget exceeded (${config.maxTurns})`;
|
|
760
|
-
budgetExceeded = true;
|
|
761
|
-
emitUpdate(formatStatus(config.name, "turn budget reached"));
|
|
762
|
-
worker?.abort();
|
|
763
|
-
}
|
|
764
|
-
});
|
|
765
|
-
emitUpdate(formatStatus(config.name, "started"));
|
|
766
|
-
}
|
|
767
|
-
catch (error) {
|
|
768
|
-
unsubscribe?.();
|
|
769
|
-
if (wallClockTimer)
|
|
770
|
-
clearTimeout(wallClockTimer);
|
|
771
|
-
runManager.clearCancelHandle(runContext.runId);
|
|
772
|
-
try {
|
|
773
|
-
worker?.abort();
|
|
774
|
-
}
|
|
775
|
-
catch {
|
|
776
|
-
// Preserve the setup error; settlement below is the lifecycle authority.
|
|
777
|
-
}
|
|
778
|
-
const setupError = error instanceof Error ? error : new Error(String(error));
|
|
779
|
-
await runManager.settle(runContext.runId, {
|
|
780
|
-
status: "failed",
|
|
781
|
-
failureReason: setupError.message,
|
|
782
|
-
usage,
|
|
783
|
-
usageKnown: true,
|
|
784
|
-
costKnown: true,
|
|
785
|
-
turns: assistantTurns,
|
|
786
|
-
toolCalls,
|
|
787
|
-
durationMs: Date.now() - startedAt,
|
|
788
|
-
outputText: "",
|
|
789
|
-
}, { announce: false });
|
|
790
|
-
throw setupError;
|
|
791
|
-
}
|
|
792
|
-
const activeWorker = worker;
|
|
793
|
-
const activeUnsubscribe = unsubscribe;
|
|
794
|
-
const activeWallClockTimer = wallClockTimer;
|
|
795
|
-
/**
|
|
796
|
-
* Runs the worker to completion, including the D6 convergence turn, and returns the
|
|
797
|
-
* tool result plus the data `runs.ts` needs to settle. Rejects only for the single
|
|
798
|
-
* fatal case (no assistant message at all) — every other outcome, including a budget
|
|
799
|
-
* abort or explicit cancel, is a normal (if failed) result.
|
|
800
|
-
*/
|
|
801
|
-
async function runToCompletion() {
|
|
802
|
-
try {
|
|
803
|
-
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
804
|
-
await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
|
|
805
|
-
await activeWorker.waitForIdle();
|
|
806
|
-
// D6: a self-inflicted budget abort gets one tool-free turn to converge on a
|
|
807
|
-
// conclusion instead of discarding the work outright. An explicit cancel skips
|
|
808
|
-
// this — the model asked this run to stop now, not to wrap up.
|
|
809
|
-
if (budgetExceeded && !externallyCancelled) {
|
|
810
|
-
clearTimeout(activeWallClockTimer);
|
|
811
|
-
emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
|
|
812
|
-
const preConvergenceMessageCount = activeWorker.state.messages.length;
|
|
813
|
-
activeWorker.state.tools = [];
|
|
814
|
-
let convergenceTimedOut = false;
|
|
815
|
-
const convergenceTimer = setTimeout(() => {
|
|
816
|
-
convergenceTimedOut = true;
|
|
817
|
-
activeWorker.abort();
|
|
818
|
-
}, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
|
|
819
|
-
try {
|
|
820
|
-
await activeWorker.prompt(CONVERGENCE_PROMPT);
|
|
821
|
-
await activeWorker.waitForIdle();
|
|
822
|
-
}
|
|
823
|
-
catch {
|
|
824
|
-
// Best effort: fall through to whatever worker.state.messages holds.
|
|
825
|
-
}
|
|
826
|
-
finally {
|
|
827
|
-
clearTimeout(convergenceTimer);
|
|
828
|
-
}
|
|
829
|
-
if (convergenceTimedOut) {
|
|
830
|
-
// Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
|
|
831
|
-
// convergence turn and fall back to whatever came before it.
|
|
832
|
-
activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
finally {
|
|
837
|
-
activeUnsubscribe();
|
|
838
|
-
clearTimeout(activeWallClockTimer);
|
|
839
|
-
}
|
|
840
|
-
const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
|
|
841
|
-
const durationMs = Date.now() - startedAt;
|
|
842
|
-
if (!lastAssistantMessage) {
|
|
843
|
-
failureReason = failureReason || "Sub-agent returned no assistant message";
|
|
844
|
-
emitUpdate(formatStatus(config.name, "failed"));
|
|
845
|
-
throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
|
|
846
|
-
}
|
|
847
|
-
const finalText = extractAssistantText(lastAssistantMessage);
|
|
848
|
-
const effectiveFailureReason = failureReason ||
|
|
849
|
-
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
850
|
-
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
851
|
-
: undefined);
|
|
852
|
-
const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
853
|
-
const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
854
|
-
// Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
|
|
855
|
-
// (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
|
|
856
|
-
// run's own output does and does not prove. Only the attestation write (and its
|
|
857
|
-
// "enforced" strength) stays here, since only the internal path structurally removes
|
|
858
|
-
// write/edit from the verifier's tool set.
|
|
859
|
-
const verification = runContext.purpose === "verify"
|
|
860
|
-
? resolveVerificationOutcome({
|
|
861
|
-
subjectBefore: verifierSubjectBefore,
|
|
862
|
-
subjectAfter: verifierSubjectAfter,
|
|
863
|
-
gitStateBefore: verifierGitStateBefore,
|
|
864
|
-
gitStateAfter: verifierGitStateAfter,
|
|
865
|
-
finalText,
|
|
866
|
-
runFailed: Boolean(effectiveFailureReason),
|
|
867
|
-
})
|
|
868
|
-
: undefined;
|
|
869
|
-
const verificationVerdict = verification?.verdict;
|
|
870
|
-
if (runContext.purpose === "verify" && runContext.taskId && verification) {
|
|
871
|
-
await writeVerificationAttestation(options.channelDir, {
|
|
872
|
-
runId: runContext.runId,
|
|
873
|
-
taskId: runContext.taskId,
|
|
874
|
-
verdict: verification.verdict,
|
|
875
|
-
checkedAt: formatLocalTime(),
|
|
876
|
-
evidence: verification.evidence,
|
|
877
|
-
workspaceChanged: verification.workspaceChanged,
|
|
878
|
-
subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
|
|
879
|
-
subjectDir: runContext.workingDirectory,
|
|
880
|
-
// Internal verify always keeps write/edit structurally removed from the
|
|
881
|
-
// verifier's tool set (buildSubagentTools above), but `bash` stays available by
|
|
882
|
-
// default and can write files just as well — labeling that "enforced" would be
|
|
883
|
-
// dishonest (review 2026-08-23 §2.2). Only a role that dropped `bash` from its
|
|
884
|
-
// declared tool list earns the stronger label.
|
|
885
|
-
verificationStrength: config.tools.includes("bash") ? "advisory" : "enforced",
|
|
886
|
-
});
|
|
887
|
-
}
|
|
888
|
-
// Internal runs always report full usage; cost is "unknown" only for the shape a
|
|
889
|
-
// free/local model produces (tokens spent, nothing billed) — external harnesses
|
|
890
|
-
// override both explicitly once they land (D4/D9).
|
|
891
|
-
const costKnown = usage.cost.total > 0 || usage.total === 0;
|
|
892
|
-
const baseSettleInput = {
|
|
893
|
-
usage,
|
|
894
|
-
usageKnown: true,
|
|
895
|
-
costKnown,
|
|
896
|
-
turns: assistantTurns,
|
|
897
|
-
toolCalls,
|
|
898
|
-
durationMs,
|
|
899
|
-
verificationVerdict,
|
|
900
|
-
verificationStrength: runContext.purpose === "verify" ? "enforced" : undefined,
|
|
901
|
-
};
|
|
902
|
-
if (effectiveFailureReason) {
|
|
903
|
-
if (!finalText.trim()) {
|
|
904
|
-
emitUpdate(formatStatus(config.name, "failed"));
|
|
905
|
-
throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
|
|
906
|
-
}
|
|
907
|
-
emitUpdate(formatStatus(config.name, "stopped"));
|
|
908
|
-
const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
|
|
909
|
-
return {
|
|
910
|
-
toolResult: {
|
|
911
|
-
content: [
|
|
912
|
-
{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) },
|
|
913
|
-
],
|
|
914
|
-
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
|
|
915
|
-
},
|
|
916
|
-
settleInput: {
|
|
917
|
-
...baseSettleInput,
|
|
918
|
-
// An explicit cancel is not a failure (P1-1) — the model asked this run to
|
|
919
|
-
// stop, and it did.
|
|
920
|
-
status: externallyCancelled ? "cancelled" : "failed",
|
|
921
|
-
failureReason: effectiveFailureReason,
|
|
922
|
-
outputText: finalText,
|
|
923
|
-
},
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
|
|
927
|
-
return {
|
|
928
|
-
toolResult: {
|
|
929
|
-
content: [
|
|
930
|
-
{
|
|
931
|
-
type: "text",
|
|
932
|
-
text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
|
|
933
|
-
},
|
|
934
|
-
],
|
|
935
|
-
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
|
|
936
|
-
},
|
|
937
|
-
settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
|
|
938
|
-
};
|
|
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");
|
|
939
1019
|
}
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
usage,
|
|
946
|
-
usageKnown: true,
|
|
947
|
-
costKnown: usage.cost.total > 0 || usage.total === 0,
|
|
948
|
-
turns: assistantTurns,
|
|
949
|
-
toolCalls,
|
|
950
|
-
durationMs: Date.now() - startedAt,
|
|
951
|
-
outputText: "",
|
|
952
|
-
};
|
|
1020
|
+
const availableModels = options.getAvailableModels();
|
|
1021
|
+
const currentModel = options.getCurrentModel();
|
|
1022
|
+
const taskLengthError = validateSubAgentTask(params.task);
|
|
1023
|
+
if (taskLengthError) {
|
|
1024
|
+
throw new RecoverableToolError(taskLengthError);
|
|
953
1025
|
}
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
|
|
967
|
-
throw raceResult.error;
|
|
968
|
-
}
|
|
969
|
-
await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
|
|
970
|
-
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.");
|
|
971
1038
|
}
|
|
972
|
-
|
|
973
|
-
// background. It settles and, this time, announces itself with a completion wake (D2/D7)
|
|
974
|
-
// — the same "runtime guarantees completion" contract background jobs already keep.
|
|
975
|
-
detached = true;
|
|
976
|
-
void outcomePromise.then(async (outcome) => {
|
|
977
|
-
runManager.clearCancelHandle(runContext.runId);
|
|
978
|
-
const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
|
|
979
|
-
await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
|
|
980
|
-
log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
|
|
981
|
-
});
|
|
982
|
-
});
|
|
983
|
-
return {
|
|
984
|
-
content: [
|
|
985
|
-
{
|
|
986
|
-
type: "text",
|
|
987
|
-
text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
|
|
988
|
-
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
989
|
-
"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.",
|
|
990
|
-
},
|
|
991
|
-
],
|
|
992
|
-
details: {
|
|
993
|
-
agent: config.name,
|
|
994
|
-
source: config.source,
|
|
995
|
-
model: formatModelReference(config.model),
|
|
996
|
-
tools: [...config.tools],
|
|
997
|
-
turns: assistantTurns,
|
|
998
|
-
toolCalls,
|
|
999
|
-
durationMs: Date.now() - startedAt,
|
|
1000
|
-
failed: false,
|
|
1001
|
-
usage: { ...usage, cost: { ...usage.cost } },
|
|
1002
|
-
runId: runContext.runId,
|
|
1003
|
-
purpose: runContext.purpose,
|
|
1004
|
-
taskId: runContext.taskId,
|
|
1005
|
-
artifactDir: runContext.artifactDir,
|
|
1006
|
-
resultTruncated: false,
|
|
1007
|
-
dispatched: true,
|
|
1008
|
-
},
|
|
1009
|
-
};
|
|
1039
|
+
return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, onUpdate);
|
|
1010
1040
|
},
|
|
1011
1041
|
};
|
|
1012
1042
|
}
|