@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +148 -1245
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +7 -1
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +10 -10
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
- package/dist/{runtime/app-home.js → app/home.js} +4 -75
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +10 -10
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +3 -3
- package/dist/commands/catalog.js +3 -3
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
- package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
- package/dist/{settings.js → config/settings.js} +7 -10
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +6 -2
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +6 -109
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/main.js +2 -2
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +2 -1
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +37 -755
- package/dist/runtime/durable-dispatch.d.ts +17 -4
- package/dist/runtime/durable-dispatch.js +60 -18
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +2 -2
- package/dist/runtime/task-driver.js +3 -3
- package/dist/runtime/task-migration.js +2 -2
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +1 -1
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.js +4 -0
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/host-process.js +1 -1
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +1 -1
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +2 -2
- package/dist/subagents/external/settlement.d.ts +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +7 -243
- package/dist/subagents/runs.js +8 -291
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/tasks/board.d.ts +2 -2
- package/dist/tasks/board.js +2 -2
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/{log.js → loop-log.js} +1 -1
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +2 -2
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
- package/dist/tools/{tool-details.js → contract/details.js} +4 -4
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +3 -3
- package/dist/tools/index.js +7 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.js +4 -3
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +3 -3
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +1 -1
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/usage/ledger.js +4 -0
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1470
- package/dist/subagents/tool.d.ts +0 -213
- package/dist/subagents/tool.js +0 -1282
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
- /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → app}/proxy.js +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/delivery.js +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/events/{event-validation.js → validation.js} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
package/dist/subagents/tool.js
DELETED
|
@@ -1,1282 +0,0 @@
|
|
|
1
|
-
import { realpathSync, statSync } from "node:fs";
|
|
2
|
-
import { mkdir, readFile } from "node:fs/promises";
|
|
3
|
-
import { join, resolve } from "node:path";
|
|
4
|
-
import { Agent, } from "@earendil-works/pi-agent-core";
|
|
5
|
-
import { clampThinkingLevel, isRetryableAssistantError, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
6
|
-
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
7
|
-
import { Type } from "typebox";
|
|
8
|
-
import { shouldFallback } from "../agent/model-fallback.js";
|
|
9
|
-
import { getChannelDir } from "../channel/channel-paths.js";
|
|
10
|
-
import * as log from "../log.js";
|
|
11
|
-
import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, JOURNAL_TAIL_MAX_UNITS, WORKSPACE_MEMORY_MAX_UNITS, } from "../memory/index-budget.js";
|
|
12
|
-
import { getJournalDir, readJournalDay } from "../memory/journal.js";
|
|
13
|
-
import { renderMemoryBootstrap } from "../memory/render.js";
|
|
14
|
-
import { getChannelMemoryDir, getChannelMemoryIndexPath, listMemoryEntries } from "../memory/store.js";
|
|
15
|
-
import { formatModelReference } from "../models/utils.js";
|
|
16
|
-
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
17
|
-
import { localDayKey } from "../shared/local-time.js";
|
|
18
|
-
import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
|
|
19
|
-
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
20
|
-
import { errorMessage, extractAssistantText } from "../shared/text-utils.js";
|
|
21
|
-
import { addUsage, createEmptyUsageTotals } from "../shared/types.js";
|
|
22
|
-
import { sleepUnref } from "../shared/with-timeout.js";
|
|
23
|
-
import { findTaskItem, parseTaskItems } from "../tasks/ledger.js";
|
|
24
|
-
import { readStoredTask } from "../tasks/store.js";
|
|
25
|
-
import { describeToolCall } from "../tools/presentation.js";
|
|
26
|
-
import { buildToolSet } from "../tools/registry.js";
|
|
27
|
-
import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
|
|
28
|
-
import { launchExternalRun } from "./external/run.js";
|
|
29
|
-
import { resolveSyncGraceMs } from "./runs.js";
|
|
30
|
-
import { resolveVerificationVerdict } from "./verification-outcome.js";
|
|
31
|
-
import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
|
|
32
|
-
import { changedPathsSummary, snapshotWorkspace } from "./workspace-summary.js";
|
|
33
|
-
/** Shared by both invocation surfaces (spec 046, D2.1). */
|
|
34
|
-
const workingDirectoryField = Type.Optional(Type.String({
|
|
35
|
-
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.",
|
|
36
|
-
}));
|
|
37
|
-
const purposeField = Type.Optional(Type.Union([Type.Literal("work"), Type.Literal("verify")], {
|
|
38
|
-
description: 'Use "verify" for an independent check: the sub-agent is given the checker protocol and ends with VERDICT: PASS|FAIL. The verdict is information for you to weigh, not a gate.',
|
|
39
|
-
}));
|
|
40
|
-
const taskIdField = Type.Optional(Type.String({
|
|
41
|
-
description: "Persistent task this work belongs to. Inside a task session it is bound automatically — omit it. In chat, pass it to have the result recorded on that task's board.",
|
|
42
|
-
}));
|
|
43
|
-
const itemField = Type.Optional(Type.String({
|
|
44
|
-
description: 'The task\'s Work Item this delegation is for, e.g. "W2". Requires a task (bound automatically in a task session).',
|
|
45
|
-
}));
|
|
46
|
-
/**
|
|
47
|
-
* Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
|
|
48
|
-
* ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
|
|
49
|
-
* a call naming an external role cannot pass any of them (there is nowhere for it to put them).
|
|
50
|
-
*/
|
|
51
|
-
const subagentSchema = Type.Object({
|
|
52
|
-
agent: Type.String({ description: "Name of a configured sub-agent from workspaceDir/sub-agents/" }),
|
|
53
|
-
task: Type.String({ description: "Complete task description for the sub-agent" }),
|
|
54
|
-
workingDirectory: workingDirectoryField,
|
|
55
|
-
purpose: purposeField,
|
|
56
|
-
taskId: taskIdField,
|
|
57
|
-
item: itemField,
|
|
58
|
-
});
|
|
59
|
-
/**
|
|
60
|
-
* Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
|
|
61
|
-
* Carries every field a role file would otherwise supply.
|
|
62
|
-
*/
|
|
63
|
-
const subagentInlineSchema = Type.Object({
|
|
64
|
-
task: Type.String({ description: "Complete task description for the sub-agent" }),
|
|
65
|
-
systemPrompt: Type.String({ description: "System prompt defining this one-off sub-agent's identity and task." }),
|
|
66
|
-
tools: Type.Optional(Type.Array(Type.String(), { description: "Optional tool whitelist for the sub-agent" })),
|
|
67
|
-
model: Type.Optional(Type.String({ description: "Optional exact model reference. Defaults to the parent's current model." })),
|
|
68
|
-
effort: Type.Optional(Type.Union([Type.Literal("quick"), Type.Literal("standard"), Type.Literal("deep")], {
|
|
69
|
-
description: 'Execution budget preset (turns, tool calls, wall time). "standard" is the default; "quick" for narrow lookups, "deep" for long analyses.',
|
|
70
|
-
})),
|
|
71
|
-
context: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("index")], {
|
|
72
|
-
description: 'What context to inject. "none" (default) runs fully isolated; "index" adds the workspace background, the channel memory index, and today\'s journal tail.',
|
|
73
|
-
})),
|
|
74
|
-
thinkingLevel: Type.Optional(Type.Union([
|
|
75
|
-
Type.Literal("off"),
|
|
76
|
-
Type.Literal("minimal"),
|
|
77
|
-
Type.Literal("low"),
|
|
78
|
-
Type.Literal("medium"),
|
|
79
|
-
Type.Literal("high"),
|
|
80
|
-
Type.Literal("xhigh"),
|
|
81
|
-
Type.Literal("max"),
|
|
82
|
-
], {
|
|
83
|
-
description: "Optional reasoning effort for the sub-agent.",
|
|
84
|
-
})),
|
|
85
|
-
mutates: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("write")], {
|
|
86
|
-
description: 'Whether this delegation will modify the working directory. Declare "write" whenever the sub-agent may write ' +
|
|
87
|
-
"files (including through bash) so it takes the exclusive workspace write lease.",
|
|
88
|
-
})),
|
|
89
|
-
workingDirectory: workingDirectoryField,
|
|
90
|
-
purpose: purposeField,
|
|
91
|
-
taskId: taskIdField,
|
|
92
|
-
item: itemField,
|
|
93
|
-
});
|
|
94
|
-
const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
95
|
-
/**
|
|
96
|
-
* Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
|
|
97
|
-
* same prompt-unit currency as the system prompt budget (shared/prompt-units.ts). The full
|
|
98
|
-
* output always lands on disk under the artifact directory regardless of this budget — this
|
|
99
|
-
* only caps what gets echoed into the parent's context.
|
|
100
|
-
*/
|
|
101
|
-
export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
|
|
102
|
-
/**
|
|
103
|
-
* Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
|
|
104
|
-
* separator-free run of letters/digits counts as a single unit, so a units-only budget can still
|
|
105
|
-
* pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
|
|
106
|
-
*/
|
|
107
|
-
export const MAX_SUBAGENT_RESULT_CHARS = 12_000;
|
|
108
|
-
const RESULT_TRUNCATION_HEAD_RATIO = 1;
|
|
109
|
-
/**
|
|
110
|
-
* Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
|
|
111
|
-
* tool-free turn to summarize what it already found instead of having its work discarded.
|
|
112
|
-
* This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
|
|
113
|
-
*/
|
|
114
|
-
const CONVERGENCE_WALL_CLOCK_MS = 60_000;
|
|
115
|
-
/**
|
|
116
|
-
* A provider error (429, overloaded, 5xx, dropped stream) used to fail an internal run outright —
|
|
117
|
-
* the main session retries those, a bare `Agent` does not. Retried in place with exponential
|
|
118
|
-
* backoff (2s, 4s, 8s) before falling back to the backup model; the wall-time budget still bounds
|
|
119
|
-
* the whole thing.
|
|
120
|
-
*/
|
|
121
|
-
const MAX_TRANSIENT_RETRIES = 3;
|
|
122
|
-
const RETRY_BASE_DELAY_MS = 2_000;
|
|
123
|
-
/**
|
|
124
|
-
* D2's grace window is per turn, not per call. The SDK runs a whole tool batch sequentially as
|
|
125
|
-
* soon as one call in it is sequential (`bash`, `edit`, `write`), so "a worktree, then three
|
|
126
|
-
* delegations" in one message used to block the channel for three back-to-back grace windows.
|
|
127
|
-
* Every call in one agent run shares that run's AbortSignal, which is what keys the deadline:
|
|
128
|
-
* the first delegation of a turn starts the clock, later ones get only what is left of it.
|
|
129
|
-
*/
|
|
130
|
-
const turnGraceDeadlines = new WeakMap();
|
|
131
|
-
function graceDeadlineFor(signal, graceMs, now) {
|
|
132
|
-
if (!signal)
|
|
133
|
-
return now + graceMs;
|
|
134
|
-
let deadline = turnGraceDeadlines.get(signal);
|
|
135
|
-
if (deadline === undefined) {
|
|
136
|
-
deadline = now + graceMs;
|
|
137
|
-
turnGraceDeadlines.set(signal, deadline);
|
|
138
|
-
}
|
|
139
|
-
return deadline;
|
|
140
|
-
}
|
|
141
|
-
/** Resolves once `signal` aborts (never rejects; pending forever without one). `dispose` drops
|
|
142
|
-
* the listener, since a turn's signal outlives every call that raced against it. */
|
|
143
|
-
function watchAbort(signal) {
|
|
144
|
-
let dispose = () => { };
|
|
145
|
-
const aborted = new Promise((resolve) => {
|
|
146
|
-
if (!signal)
|
|
147
|
-
return;
|
|
148
|
-
if (signal.aborted) {
|
|
149
|
-
resolve("aborted");
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
const onAbort = () => resolve("aborted");
|
|
153
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
154
|
-
dispose = () => signal.removeEventListener("abort", onAbort);
|
|
155
|
-
});
|
|
156
|
-
return { aborted, dispose };
|
|
157
|
-
}
|
|
158
|
-
const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
|
|
159
|
-
/**
|
|
160
|
-
* Pins every command a run issues to the run's working directory. It sets the child's real `cwd`
|
|
161
|
-
* rather than prefixing `cd <dir> &&`: the prefix silently produced a *different* command than the
|
|
162
|
-
* guard inspected, and a directory that cannot be entered surfaced as a shell error inside an
|
|
163
|
-
* otherwise successful command line.
|
|
164
|
-
*/
|
|
165
|
-
class DirectoryExecutor {
|
|
166
|
-
constructor(base, directory) {
|
|
167
|
-
this.base = base;
|
|
168
|
-
this.directory = directory;
|
|
169
|
-
}
|
|
170
|
-
exec(command, options) {
|
|
171
|
-
return this.base.exec(command, { ...options, cwd: this.directory });
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
function safeRunSegment(value) {
|
|
175
|
-
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
|
|
176
|
-
}
|
|
177
|
-
function getSubAgentArtifactsRoot(channelDir) {
|
|
178
|
-
return join(channelDir, "subagent-artifacts");
|
|
179
|
-
}
|
|
180
|
-
/** Every run gets its own artifact directory (spec 032 D4), independent of `returns` mode. */
|
|
181
|
-
async function prepareArtifactDir(channelDir, runId) {
|
|
182
|
-
const artifactDir = join(getSubAgentArtifactsRoot(channelDir), safeRunSegment(runId));
|
|
183
|
-
await mkdir(artifactDir, { recursive: true });
|
|
184
|
-
return artifactDir;
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Resolve the checkout a run works in (spec 036, D3).
|
|
188
|
-
*
|
|
189
|
-
* Spec 036 removed task-owned worktrees on the premise that a caller needing a separate checkout
|
|
190
|
-
* would `git worktree add` on the host and "pass it in as an ordinary working directory" — but no
|
|
191
|
-
* parameter for that ever existed, so every run was pinned to the daemon's own cwd. This is that
|
|
192
|
-
* parameter. Path guards are unaffected: they judge the *resolved absolute* target, so a cwd
|
|
193
|
-
* outside the allowed roots makes relative paths fail exactly as an absolute one there would.
|
|
194
|
-
*/
|
|
195
|
-
function realpathOrSelf(path) {
|
|
196
|
-
try {
|
|
197
|
-
return realpathSync(path);
|
|
198
|
-
}
|
|
199
|
-
catch {
|
|
200
|
-
return path;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* D6.2's boundary check, hardened against symlinks (review 2026-08-23 §2.3): a plain
|
|
205
|
-
* `resolve()` + string-prefix comparison only judges the *requested* path, so `<projectRoot
|
|
206
|
-
* >/link -> /somewhere/else` passes the check and then everything downstream — the internal
|
|
207
|
-
* agent's own `securityContext.projectRoot`, an external process's `cwd` (which bypasses the
|
|
208
|
-
* path guard entirely) — trusts that escaped target. Comparing realpaths closes it, matching
|
|
209
|
-
* `project-scope.ts` and `workspaceLeaseKey`, the two other places in the tree that already do
|
|
210
|
-
* this.
|
|
211
|
-
*/
|
|
212
|
-
export function assertWithinProjectBoundary(target, base, requested) {
|
|
213
|
-
const realBase = realpathOrSelf(base);
|
|
214
|
-
const realTarget = realpathOrSelf(target);
|
|
215
|
-
if (realTarget !== realBase && !realTarget.startsWith(`${realBase}/`)) {
|
|
216
|
-
throw new RecoverableToolError(`workingDirectory "${requested}" must be inside the project root (${base}).`);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function resolveRunWorkingDirectory(requested, options) {
|
|
220
|
-
const base = resolve(options.workingDirectory ?? process.cwd());
|
|
221
|
-
const trimmed = requested?.trim();
|
|
222
|
-
// Resolve the project root once as well. Returning an alias here would leave the later lease,
|
|
223
|
-
// executor, subject hash, and external cwd exposed to a symlink swap after admission.
|
|
224
|
-
const canonicalBase = realpathOrSelf(base);
|
|
225
|
-
if (!trimmed)
|
|
226
|
-
return canonicalBase;
|
|
227
|
-
const target = resolve(canonicalBase, trimmed);
|
|
228
|
-
let canonicalTarget;
|
|
229
|
-
try {
|
|
230
|
-
canonicalTarget = realpathSync(target);
|
|
231
|
-
if (!statSync(canonicalTarget).isDirectory())
|
|
232
|
-
throw new Error("not a directory");
|
|
233
|
-
}
|
|
234
|
-
catch {
|
|
235
|
-
throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
|
|
236
|
-
}
|
|
237
|
-
if (options.projectBoundary === "project") {
|
|
238
|
-
assertWithinProjectBoundary(canonicalTarget, canonicalBase, requested ?? trimmed);
|
|
239
|
-
}
|
|
240
|
-
return canonicalTarget;
|
|
241
|
-
}
|
|
242
|
-
async function prepareRunContext(runId, params, options) {
|
|
243
|
-
const purpose = params.purpose ?? "work";
|
|
244
|
-
let taskId = params.taskId?.trim() || undefined;
|
|
245
|
-
// Inside a task session the binding is automatic, like `bash`'s: a delegation from a task step
|
|
246
|
-
// belongs to that task, so the leader never has to remember to pass it (spec 052, D4).
|
|
247
|
-
if (options.boundTaskId) {
|
|
248
|
-
if (taskId && taskId !== options.boundTaskId) {
|
|
249
|
-
throw new RecoverableToolError(`This is task ${options.boundTaskId}'s session — drop taskId (it is bound automatically); "${taskId}" does not belong here.`);
|
|
250
|
-
}
|
|
251
|
-
taskId = options.boundTaskId;
|
|
252
|
-
}
|
|
253
|
-
const item = params.item?.trim() || undefined;
|
|
254
|
-
if (item && !taskId)
|
|
255
|
-
throw new RecoverableToolError("item names a Work Item of a task; pass taskId too.");
|
|
256
|
-
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
257
|
-
throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
|
|
258
|
-
if (taskId) {
|
|
259
|
-
const task = await readStoredTask(options.channelDir, taskId);
|
|
260
|
-
if (!task) {
|
|
261
|
-
throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
|
|
262
|
-
}
|
|
263
|
-
if (item && !findTaskItem(task.body, item)) {
|
|
264
|
-
const known = parseTaskItems(task.body)
|
|
265
|
-
?.items.map((entry) => entry.id)
|
|
266
|
-
.join(", ");
|
|
267
|
-
throw new RecoverableToolError(`Task ${taskId} has no Work Item "${item}"${known ? ` (known: ${known})` : " (it has no Work Items yet — add one with task_update first)"}.`);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
const artifactDir = await prepareArtifactDir(options.channelDir, runId);
|
|
271
|
-
const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
|
|
272
|
-
return { runId, purpose, taskId, item, workingDirectory, artifactDir };
|
|
273
|
-
}
|
|
274
|
-
function isAssistantMessage(message) {
|
|
275
|
-
return typeof message === "object" && message !== null && "role" in message && message.role === "assistant";
|
|
276
|
-
}
|
|
277
|
-
function getLastAssistantMessage(messages) {
|
|
278
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
279
|
-
const message = messages[i];
|
|
280
|
-
if (isAssistantMessage(message)) {
|
|
281
|
-
return message;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return null;
|
|
285
|
-
}
|
|
286
|
-
function formatStatus(agentName, text) {
|
|
287
|
-
return `Subagent ${agentName}: ${text}`;
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* The "still running, don't wait or re-dispatch" reply shared by every dispatch path that hands
|
|
291
|
-
* back a placeholder instead of the run's own result: external always takes this path (D2); an
|
|
292
|
-
* internal run takes it once the sync grace window elapses (D2/D7). Only the runtime label
|
|
293
|
-
* (`external, <harness>` vs `internal, async`) differs between the two.
|
|
294
|
-
*/
|
|
295
|
-
function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
|
|
296
|
-
return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
|
|
297
|
-
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
298
|
-
"Finish independent work and dispatches, then end the turn when only waiting remains; do not re-dispatch or poll to wait. " +
|
|
299
|
-
'Inside a task step, use task_step_end outcome=park with ticket {"kind":"work"}.');
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* `buildContextualBlocks` shared by the external dispatch path and `runToCompletion`'s internal
|
|
303
|
-
* one (spec 040 gap closed post-review): context injection is an enhancement, not a
|
|
304
|
-
* precondition, so a failure here degrades to no context blocks rather than failing a dispatch
|
|
305
|
-
* that would otherwise have run fine.
|
|
306
|
-
*/
|
|
307
|
-
async function resolveContextualBlocks(config, options) {
|
|
308
|
-
return buildContextualBlocks(config, options).catch((error) => {
|
|
309
|
-
log.logWarn("subagent.context.inject_failed", "Sub-agent context injection failed; continuing without it", {
|
|
310
|
-
channelId: options.runtimeContext.channelId,
|
|
311
|
-
reason: errorMessage(error),
|
|
312
|
-
});
|
|
313
|
-
return [];
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
function buildFailureText(config, reason, lastAssistantText) {
|
|
317
|
-
const trimmedLastText = lastAssistantText.trim();
|
|
318
|
-
if (!trimmedLastText) {
|
|
319
|
-
return `Sub-agent ${config.name} failed: ${reason}`;
|
|
320
|
-
}
|
|
321
|
-
return `Sub-agent ${config.name} failed: ${reason}\n\nLast output:\n${trimmedLastText}`;
|
|
322
|
-
}
|
|
323
|
-
function buildStoppedText(config, reason, finalText) {
|
|
324
|
-
const trimmedFinalText = finalText.trim();
|
|
325
|
-
if (!trimmedFinalText) {
|
|
326
|
-
return `Sub-agent ${config.name} stopped: ${reason}`;
|
|
327
|
-
}
|
|
328
|
-
return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Spec 032 D4: the full text always lands on disk, independent of whether it fits the reply
|
|
332
|
-
* budget. What comes back to the parent is capped at MAX_SUBAGENT_RESULT_UNITS; a reply over
|
|
333
|
-
* budget is truncated with a pointer to the file a chatty sub-agent can no longer blow out the
|
|
334
|
-
* parent's context.
|
|
335
|
-
*
|
|
336
|
-
* The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
|
|
337
|
-
* runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
|
|
338
|
-
* This function only needs the path, to point at it.
|
|
339
|
-
*
|
|
340
|
-
* Spec 046 D2.2 removed `returns: "artifact"` and the ARTIFACT marker protocol: a caller that
|
|
341
|
-
* needs a specific output file states the path in the task text instead, the path external roles
|
|
342
|
-
* already had to follow.
|
|
343
|
-
*/
|
|
344
|
-
function finalizeSubAgentOutput(runContext, finalText) {
|
|
345
|
-
const outputPath = join(runContext.artifactDir, "output.md");
|
|
346
|
-
if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS && finalText.length <= MAX_SUBAGENT_RESULT_CHARS) {
|
|
347
|
-
return { replyText: finalText, truncated: false };
|
|
348
|
-
}
|
|
349
|
-
const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
|
|
350
|
-
headRatio: RESULT_TRUNCATION_HEAD_RATIO,
|
|
351
|
-
maxChars: MAX_SUBAGENT_RESULT_CHARS,
|
|
352
|
-
marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
|
|
353
|
-
});
|
|
354
|
-
return { replyText: clipped.text, truncated: true };
|
|
355
|
-
}
|
|
356
|
-
/**
|
|
357
|
-
* Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
|
|
358
|
-
* context (task text), never the "the MEMORY.md index is generated, write memory only through
|
|
359
|
-
* memory_save" rule the main agent gets in its system prompt (the memory tools themselves are
|
|
360
|
-
* withheld from sub-agents). Denying these paths at the path-guard level closes that gap
|
|
361
|
-
* structurally instead of relying on a sub-agent to infer an instruction it never received — a
|
|
362
|
-
* stray write/edit here would race the shared memory serial queue (channel-maintenance-queue)
|
|
363
|
-
* and silently corrupt durable memory.
|
|
364
|
-
*/
|
|
365
|
-
function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
|
|
366
|
-
const protectedPaths = [
|
|
367
|
-
getChannelMemoryDir(channelDir),
|
|
368
|
-
getJournalDir(channelDir),
|
|
369
|
-
getChannelMemoryIndexPath(channelDir),
|
|
370
|
-
];
|
|
371
|
-
// The role directory gets the same structural denial (spec 040, D8.1): a sub-agent's write/edit
|
|
372
|
-
// tools are exactly as capable of writing a self-authorizing `runtime: external` role file as
|
|
373
|
-
// the main agent's are.
|
|
374
|
-
return withSubAgentsDirWriteDeny({
|
|
375
|
-
...securityConfig,
|
|
376
|
-
pathGuard: {
|
|
377
|
-
...securityConfig.pathGuard,
|
|
378
|
-
writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
|
|
379
|
-
},
|
|
380
|
-
}, workspaceDir);
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* Build a sub-agent's tool set from the shared tool registry, filtered by the shared
|
|
384
|
-
* sub-agent whitelist (files + web). Sub-agents run with their own security context
|
|
385
|
-
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
386
|
-
*/
|
|
387
|
-
function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
388
|
-
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
|
|
389
|
-
return buildToolSet({
|
|
390
|
-
executor,
|
|
391
|
-
fileStore: options.fileStore,
|
|
392
|
-
securityConfig,
|
|
393
|
-
securityContext: {
|
|
394
|
-
// No `channelDir`: a sub-agent receives channel state through its injected context
|
|
395
|
-
// blocks, not by reading the channel's own files, so it does not inherit the parent's
|
|
396
|
-
// channel-directory exception (see security/types.ts).
|
|
397
|
-
agentWorkspaceDir: options.workspaceDir,
|
|
398
|
-
projectRoot: runContext.workingDirectory,
|
|
399
|
-
boundary: options.projectBoundary,
|
|
400
|
-
},
|
|
401
|
-
channelId: options.runtimeContext.channelId,
|
|
402
|
-
channelDir: options.channelDir,
|
|
403
|
-
workspaceDir: options.workspaceDir,
|
|
404
|
-
webConfig: options.webConfig,
|
|
405
|
-
rtkEnabled: options.rtkEnabled,
|
|
406
|
-
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
407
|
-
}, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
|
|
408
|
-
}
|
|
409
|
-
/**
|
|
410
|
-
* Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9).
|
|
411
|
-
* A check bound to a Work Item covers that item only: holding it to the whole DoD would fail it
|
|
412
|
-
* for the items still in progress.
|
|
413
|
-
*/
|
|
414
|
-
export function buildVerificationProtocol(taskPath, item) {
|
|
415
|
-
const scope = !taskPath
|
|
416
|
-
? "- Independently inspect the work described in the task above and verify it against concrete evidence."
|
|
417
|
-
: item
|
|
418
|
-
? `- Independently inspect Work Item ${item} in ${taskPath} — its text and the DoD items it references (\`→ dod:N\`) — and verify it against concrete evidence. Other Work Items are out of scope; do not fail this check because they are unfinished.`
|
|
419
|
-
: `- Independently inspect ${taskPath} and verify every DoD item against concrete evidence.`;
|
|
420
|
-
return [
|
|
421
|
-
"Verification protocol:",
|
|
422
|
-
scope,
|
|
423
|
-
"- You are the checker, not the maker. Do not modify the implementation or fix failures to make a check pass; report them.",
|
|
424
|
-
"- You may run npm tests/builds and other deterministic checks; keep any generated output out of tracked files and product directories.",
|
|
425
|
-
"- Run deterministic checks when available and distinguish observed evidence from assumptions.",
|
|
426
|
-
"- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
|
|
427
|
-
].join("\n");
|
|
428
|
-
}
|
|
429
|
-
/**
|
|
430
|
-
* D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
|
|
431
|
-
* target with an active write lease is refused up front. A write-capable verifier is allowed: it
|
|
432
|
-
* takes the same exclusive lease as a work writer.
|
|
433
|
-
* Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
|
|
434
|
-
* dispatch does, including the remaining `exec` restriction.
|
|
435
|
-
*/
|
|
436
|
-
export function assertVerifyAdmissible(config, purpose, workingDirectory) {
|
|
437
|
-
if (purpose !== "verify")
|
|
438
|
-
return;
|
|
439
|
-
if (config.runtime === "external" && config.harness === "exec") {
|
|
440
|
-
throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
|
|
441
|
-
}
|
|
442
|
-
const holder = findWorkspaceLeaseHolder(workingDirectory);
|
|
443
|
-
if (holder) {
|
|
444
|
-
throw new RecoverableToolError(`Cannot verify "${workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* The task envelope both runtimes' first dispatch sends (a follow-up sends `buildFollowUpTask`
|
|
449
|
-
* instead). `config` is narrowed to `{ name }` — the only field this function reads.
|
|
450
|
-
*/
|
|
451
|
-
export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
|
|
452
|
-
const taskText = task.trim();
|
|
453
|
-
const lines = [
|
|
454
|
-
`Runtime context:`,
|
|
455
|
-
`- Workspace root: ${runtimeContext.workspaceDir}`,
|
|
456
|
-
`- Channel id: ${runtimeContext.channelId}`,
|
|
457
|
-
`- Channel directory: ${getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId)}`,
|
|
458
|
-
`- Working directory: ${runContext.workingDirectory}`,
|
|
459
|
-
`- Artifact directory: ${runContext.artifactDir}`,
|
|
460
|
-
`- Your configured role: ${config.name}`,
|
|
461
|
-
];
|
|
462
|
-
for (const block of contextBlocks) {
|
|
463
|
-
if (!block.trim()) {
|
|
464
|
-
continue;
|
|
465
|
-
}
|
|
466
|
-
lines.push("", block.trim());
|
|
467
|
-
}
|
|
468
|
-
lines.push("", `Task:`, taskText);
|
|
469
|
-
if (runContext.purpose === "verify") {
|
|
470
|
-
lines.push("", buildVerificationProtocol(verificationTaskPath(runtimeContext, runContext), runContext.item));
|
|
471
|
-
}
|
|
472
|
-
return lines.join("\n");
|
|
473
|
-
}
|
|
474
|
-
function verificationTaskPath(runtimeContext, runContext) {
|
|
475
|
-
return runContext.taskId
|
|
476
|
-
? join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`)
|
|
477
|
-
: undefined;
|
|
478
|
-
}
|
|
479
|
-
/**
|
|
480
|
-
* The envelope for `subagent_run op=follow_up`. A resumed session already holds the first
|
|
481
|
-
* dispatch's whole envelope — runtime paths, injected memory/context blocks, the role — so sending
|
|
482
|
-
* it again only re-bills that context and buries the new instruction. Only what is new goes: the
|
|
483
|
-
* artifact directory (fresh per run) and the instruction itself, plus the checker protocol again
|
|
484
|
-
* for a verify run, since its final VERDICT line is what settlement reads.
|
|
485
|
-
*/
|
|
486
|
-
export function buildFollowUpTask(task, runtimeContext, runContext) {
|
|
487
|
-
const lines = [
|
|
488
|
-
"Follow-up in the same session. Your earlier instructions and context still apply unless this changes them.",
|
|
489
|
-
`- Working directory: ${runContext.workingDirectory}`,
|
|
490
|
-
`- Artifact directory for this follow-up: ${runContext.artifactDir}`,
|
|
491
|
-
"",
|
|
492
|
-
"Follow-up instruction:",
|
|
493
|
-
task.trim(),
|
|
494
|
-
];
|
|
495
|
-
if (runContext.purpose === "verify") {
|
|
496
|
-
lines.push("", buildVerificationProtocol(verificationTaskPath(runtimeContext, runContext), runContext.item));
|
|
497
|
-
}
|
|
498
|
-
return lines.join("\n");
|
|
499
|
-
}
|
|
500
|
-
/**
|
|
501
|
-
* Spec 050, D12: `memory: index` injects the same three sections the main agent's first-turn
|
|
502
|
-
* bootstrap does — workspace MEMORY.md, the channel index, today's journal tail — at half the
|
|
503
|
-
* main agent's budget. No per-call LLM recall: a sub-agent task is short-lived, so there is no
|
|
504
|
-
* "first turn" to bootstrap once and reuse; it gets the same snapshot every dispatch.
|
|
505
|
-
*/
|
|
506
|
-
async function buildContextualBlocks(config, options) {
|
|
507
|
-
if (config.contextMode !== "contextual") {
|
|
508
|
-
return [];
|
|
509
|
-
}
|
|
510
|
-
const blocks = [];
|
|
511
|
-
if (config.paths.length > 0) {
|
|
512
|
-
blocks.push(`Preferred focus paths:\n${config.paths.map((path) => `- ${path}`).join("\n")}`);
|
|
513
|
-
}
|
|
514
|
-
if (config.memory === "none") {
|
|
515
|
-
return blocks;
|
|
516
|
-
}
|
|
517
|
-
const today = localDayKey();
|
|
518
|
-
const readOptionalFile = async (path) => {
|
|
519
|
-
try {
|
|
520
|
-
return await readFile(path, "utf-8");
|
|
521
|
-
}
|
|
522
|
-
catch {
|
|
523
|
-
return "";
|
|
524
|
-
}
|
|
525
|
-
};
|
|
526
|
-
const [entries, workspaceMemory, journalToday] = await Promise.all([
|
|
527
|
-
listMemoryEntries(options.channelDir).catch(() => []),
|
|
528
|
-
readOptionalFile(join(options.workspaceDir, "MEMORY.md")),
|
|
529
|
-
readJournalDay(options.channelDir, today).catch(() => ""),
|
|
530
|
-
]);
|
|
531
|
-
const index = buildChannelIndexForBootstrap(entries, CHANNEL_INDEX_MAX_UNITS / 2);
|
|
532
|
-
const bootstrap = renderMemoryBootstrap({
|
|
533
|
-
workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory, WORKSPACE_MEMORY_MAX_UNITS / 2),
|
|
534
|
-
channelIndex: entries.length > 0 ? index.text : "",
|
|
535
|
-
journal: (() => {
|
|
536
|
-
const text = clipJournalTailForBootstrap(journalToday, JOURNAL_TAIL_MAX_UNITS / 2);
|
|
537
|
-
return text ? { date: today, text } : undefined;
|
|
538
|
-
})(),
|
|
539
|
-
});
|
|
540
|
-
if (bootstrap) {
|
|
541
|
-
blocks.push(bootstrap);
|
|
542
|
-
}
|
|
543
|
-
return blocks;
|
|
544
|
-
}
|
|
545
|
-
function filterToolsByName(allTools, names) {
|
|
546
|
-
const allowed = new Set(names);
|
|
547
|
-
return allTools.filter((tool) => allowed.has(tool.name));
|
|
548
|
-
}
|
|
549
|
-
function createDetails(input) {
|
|
550
|
-
return {
|
|
551
|
-
agent: input.config.name,
|
|
552
|
-
source: input.config.source,
|
|
553
|
-
model: input.modelOverride ??
|
|
554
|
-
(input.config.runtime === "external"
|
|
555
|
-
? (input.config.externalModelRef ?? "default")
|
|
556
|
-
: formatModelReference(input.config.model)),
|
|
557
|
-
tools: input.toolsOverride ?? [...input.config.tools],
|
|
558
|
-
turns: input.turns,
|
|
559
|
-
toolCalls: input.toolCalls,
|
|
560
|
-
durationMs: input.durationMs,
|
|
561
|
-
failed: input.failed ?? false,
|
|
562
|
-
failureReason: input.failureReason,
|
|
563
|
-
usage: {
|
|
564
|
-
...input.usage,
|
|
565
|
-
cost: { ...input.usage.cost },
|
|
566
|
-
},
|
|
567
|
-
runId: input.runContext.runId,
|
|
568
|
-
purpose: input.runContext.purpose,
|
|
569
|
-
taskId: input.runContext.taskId,
|
|
570
|
-
verificationVerdict: input.verificationVerdict,
|
|
571
|
-
artifactDir: input.runContext.artifactDir,
|
|
572
|
-
resultTruncated: input.resultTruncated ?? false,
|
|
573
|
-
dispatched: input.dispatched,
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
/**
|
|
577
|
-
* A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
|
|
578
|
-
* `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
|
|
579
|
-
* jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
|
|
580
|
-
* effect of stopping something else.
|
|
581
|
-
*/
|
|
582
|
-
/**
|
|
583
|
-
* Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
|
|
584
|
-
* after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
|
|
585
|
-
* the internal/external fork, budget/turn/tool-call enforcement, the verification verdict, and
|
|
586
|
-
* the sync-grace/detached-placeholder split — is identical regardless of which schema the model
|
|
587
|
-
* called through.
|
|
588
|
-
*/
|
|
589
|
-
async function dispatchSubAgentRun(options, currentModel, config, warning, params, signal, onUpdate) {
|
|
590
|
-
// Derived rather than model-supplied (spec 045): `${agent}: ${task's first line}`, the
|
|
591
|
-
// same shape `subagent_run op=follow_up` already builds by hand.
|
|
592
|
-
const runLabel = `${config.name}: ${params.task.split("\n")[0]?.slice(0, 80) ?? ""}`;
|
|
593
|
-
// Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
|
|
594
|
-
// `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
|
|
595
|
-
const mutatesNote = warning ? `Note: ${warning}\n\n` : "";
|
|
596
|
-
const runManager = options.getRunManager(options.runtimeContext.channelId);
|
|
597
|
-
// A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
|
|
598
|
-
// on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
|
|
599
|
-
const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
|
|
600
|
-
// D9: an independent verifier checks against a target that isn't moving under it — shared
|
|
601
|
-
// with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
|
|
602
|
-
// cannot drift between the two dispatch paths.
|
|
603
|
-
assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
|
|
604
|
-
// Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
|
|
605
|
-
// workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
|
|
606
|
-
// never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
|
|
607
|
-
let leaseKey;
|
|
608
|
-
if (config.mutates === "write") {
|
|
609
|
-
const lease = acquireWorkspaceLease({
|
|
610
|
-
runId: runContext.runId,
|
|
611
|
-
channelId: options.runtimeContext.channelId,
|
|
612
|
-
workingDirectory: runContext.workingDirectory,
|
|
613
|
-
});
|
|
614
|
-
if (!lease.ok) {
|
|
615
|
-
throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
|
|
616
|
-
}
|
|
617
|
-
leaseKey = lease.leaseKey;
|
|
618
|
-
}
|
|
619
|
-
// Taken under the lease, before the run can write: what "already dirty" means for this run.
|
|
620
|
-
const workspaceBaseline = config.mutates === "write" ? await snapshotWorkspace(runContext.workingDirectory) : undefined;
|
|
621
|
-
if (config.runtime === "external") {
|
|
622
|
-
return dispatchExternalRun({
|
|
623
|
-
options,
|
|
624
|
-
currentModel,
|
|
625
|
-
config,
|
|
626
|
-
runLabel,
|
|
627
|
-
runContext,
|
|
628
|
-
leaseKey,
|
|
629
|
-
params,
|
|
630
|
-
runManager,
|
|
631
|
-
workspaceBaseline,
|
|
632
|
-
});
|
|
633
|
-
}
|
|
634
|
-
return dispatchInternalRun({
|
|
635
|
-
options,
|
|
636
|
-
currentModel,
|
|
637
|
-
config,
|
|
638
|
-
runLabel,
|
|
639
|
-
mutatesNote,
|
|
640
|
-
runContext,
|
|
641
|
-
leaseKey,
|
|
642
|
-
params,
|
|
643
|
-
signal,
|
|
644
|
-
onUpdate,
|
|
645
|
-
runManager,
|
|
646
|
-
workspaceBaseline,
|
|
647
|
-
});
|
|
648
|
-
}
|
|
649
|
-
/**
|
|
650
|
-
* The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
|
|
651
|
-
* process and always returns the "[Dispatched]" placeholder — external's sync grace window is
|
|
652
|
-
* always 0, so there is no inline-wait branch to share with the internal path.
|
|
653
|
-
*/
|
|
654
|
-
async function dispatchExternalRun(input) {
|
|
655
|
-
const { options, config, runLabel, runContext, leaseKey, params } = input;
|
|
656
|
-
let launchResult;
|
|
657
|
-
try {
|
|
658
|
-
// D9/T5: external roles get the same task envelope internal workers do — runtime
|
|
659
|
-
// paths, injected context blocks, and (for purpose=verify) the verification
|
|
660
|
-
// protocol — rather than the raw task text (spec 040 gap closed post-review).
|
|
661
|
-
const contextualBlocks = await resolveContextualBlocks(config, options);
|
|
662
|
-
const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
|
|
663
|
-
launchResult = await launchExternalRun({
|
|
664
|
-
runManager: input.runManager,
|
|
665
|
-
runId: runContext.runId,
|
|
666
|
-
channelId: options.runtimeContext.channelId,
|
|
667
|
-
channelDir: options.channelDir,
|
|
668
|
-
label: runLabel,
|
|
669
|
-
agent: config.name,
|
|
670
|
-
source: config.source,
|
|
671
|
-
harness: config.harness,
|
|
672
|
-
command: config.command,
|
|
673
|
-
shell: config.shell,
|
|
674
|
-
env: config.env,
|
|
675
|
-
externalModelRef: config.externalModelRef,
|
|
676
|
-
thinkingLevel: config.thinkingLevel,
|
|
677
|
-
maxWallTimeSec: config.maxWallTimeSec,
|
|
678
|
-
systemPrompt: config.systemPrompt,
|
|
679
|
-
task: envelopedTask,
|
|
680
|
-
workingDirectory: runContext.workingDirectory,
|
|
681
|
-
artifactDir: runContext.artifactDir,
|
|
682
|
-
purpose: runContext.purpose,
|
|
683
|
-
taskId: runContext.taskId,
|
|
684
|
-
item: runContext.item,
|
|
685
|
-
leaseKey,
|
|
686
|
-
mutates: config.mutates,
|
|
687
|
-
workspaceBaseline: input.workspaceBaseline,
|
|
688
|
-
roleFingerprint: externalRoleFingerprint(config),
|
|
689
|
-
workspaceDir: options.workspaceDir,
|
|
690
|
-
securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
|
|
691
|
-
});
|
|
692
|
-
}
|
|
693
|
-
catch (error) {
|
|
694
|
-
// Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
|
|
695
|
-
// every failure past that point settles the run itself and already released this
|
|
696
|
-
// lease (spec 042 D2/D5), so this catch must not release it a second time.
|
|
697
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
698
|
-
throw error;
|
|
699
|
-
}
|
|
700
|
-
// Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
|
|
701
|
-
// "[Dispatched]" placeholder the model would wait on forever — two of the three
|
|
702
|
-
// failure kinds never used to announce at all. `settle()` already released the lease.
|
|
703
|
-
if (!launchResult.ok) {
|
|
704
|
-
if (launchResult.kind === "missing-binary") {
|
|
705
|
-
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.`);
|
|
706
|
-
}
|
|
707
|
-
throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
|
|
708
|
-
}
|
|
709
|
-
// D2: external's sync grace window is always 0 — always the dispatched placeholder,
|
|
710
|
-
// never an inline wait. The run keeps going in the background and wakes the channel.
|
|
711
|
-
return {
|
|
712
|
-
content: [
|
|
713
|
-
{
|
|
714
|
-
type: "text",
|
|
715
|
-
text: buildDispatchedText(runContext.runId, config.name, `external, ${config.harness}`, runContext.workingDirectory),
|
|
716
|
-
},
|
|
717
|
-
],
|
|
718
|
-
details: createDetails({
|
|
719
|
-
config,
|
|
720
|
-
runContext,
|
|
721
|
-
usage: createEmptyUsageTotals(),
|
|
722
|
-
turns: 0,
|
|
723
|
-
toolCalls: 0,
|
|
724
|
-
durationMs: 0,
|
|
725
|
-
dispatched: true,
|
|
726
|
-
modelOverride: config.externalModelRef ?? "unknown",
|
|
727
|
-
toolsOverride: [],
|
|
728
|
-
}),
|
|
729
|
-
};
|
|
730
|
-
}
|
|
731
|
-
/**
|
|
732
|
-
* The `runtime: internal` half of `dispatchSubAgentRun` (spec 046, D2.5): registers the durable
|
|
733
|
-
* run record, runs the worker (with budget enforcement and the D6 convergence turn), settles it,
|
|
734
|
-
* and returns either its real result or — once the sync grace window elapses — a "[Dispatched]"
|
|
735
|
-
* placeholder while the run keeps going in the background.
|
|
736
|
-
*/
|
|
737
|
-
async function dispatchInternalRun(input) {
|
|
738
|
-
const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, signal, onUpdate, runManager } = input;
|
|
739
|
-
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
740
|
-
let apiKey;
|
|
741
|
-
try {
|
|
742
|
-
apiKey = await options.resolveApiKey(config.model);
|
|
743
|
-
}
|
|
744
|
-
catch (error) {
|
|
745
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
746
|
-
throw error;
|
|
747
|
-
}
|
|
748
|
-
const startedAt = Date.now();
|
|
749
|
-
const usage = createEmptyUsageTotals();
|
|
750
|
-
let assistantTurns = 0;
|
|
751
|
-
let toolCalls = 0;
|
|
752
|
-
let failureReason;
|
|
753
|
-
/** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
|
|
754
|
-
let budgetExceeded = false;
|
|
755
|
-
/** Set only by the `subagent_run op=cancel` handle registered as soon as the run is durable. */
|
|
756
|
-
let externallyCancelled = false;
|
|
757
|
-
/** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
|
|
758
|
-
let detached = false;
|
|
759
|
-
let lastUpdateText = "";
|
|
760
|
-
/** The model actually answering; differs from `config.model` once a backup-model switch happened. */
|
|
761
|
-
let activeModel = config.model;
|
|
762
|
-
/** Set when the run switched to the backup model, for the reply and the record. */
|
|
763
|
-
let fallbackNote;
|
|
764
|
-
/** Wakes a retry backoff early when the run is cancelled or out of wall time. */
|
|
765
|
-
const retryBackoff = new AbortController();
|
|
766
|
-
let worker;
|
|
767
|
-
try {
|
|
768
|
-
await runManager.register({
|
|
769
|
-
runId: runContext.runId,
|
|
770
|
-
channelId: options.runtimeContext.channelId,
|
|
771
|
-
runtime: "internal",
|
|
772
|
-
agent: config.name,
|
|
773
|
-
label: runLabel,
|
|
774
|
-
source: config.source,
|
|
775
|
-
tools: [...config.tools],
|
|
776
|
-
model: formatModelReference(config.model),
|
|
777
|
-
purpose: runContext.purpose,
|
|
778
|
-
taskId: runContext.taskId,
|
|
779
|
-
item: runContext.item,
|
|
780
|
-
workingDirectory: runContext.workingDirectory,
|
|
781
|
-
artifactDir: runContext.artifactDir,
|
|
782
|
-
channelDir: options.channelDir,
|
|
783
|
-
leaseKey,
|
|
784
|
-
mutates: config.mutates,
|
|
785
|
-
workspaceBaseline: input.workspaceBaseline,
|
|
786
|
-
});
|
|
787
|
-
}
|
|
788
|
-
catch (error) {
|
|
789
|
-
// Until the durable running record exists, setup still owns the lease. A channel/host
|
|
790
|
-
// admission rejection or required persist failure must leave no invisible writer lock.
|
|
791
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
792
|
-
throw error;
|
|
793
|
-
}
|
|
794
|
-
// Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
|
|
795
|
-
// creation) can yield. Without this provisional handle, a cancel in that window was treated as
|
|
796
|
-
// an unreachable run: the manager released the lease and settled it while the worker could still
|
|
797
|
-
// start writing after the supposed cancellation (especially dangerous for a write verifier).
|
|
798
|
-
runManager.registerCancelHandle(runContext.runId, () => {
|
|
799
|
-
externallyCancelled = true;
|
|
800
|
-
retryBackoff.abort();
|
|
801
|
-
worker?.abort();
|
|
802
|
-
});
|
|
803
|
-
const emitUpdate = (text) => {
|
|
804
|
-
// Once detached, execute() has already returned to the SDK; nothing is listening
|
|
805
|
-
// for further progress on this (from its view, finished) tool call.
|
|
806
|
-
if (detached)
|
|
807
|
-
return;
|
|
808
|
-
const nextText = text.trim();
|
|
809
|
-
if (!nextText || nextText === lastUpdateText) {
|
|
810
|
-
return;
|
|
811
|
-
}
|
|
812
|
-
lastUpdateText = nextText;
|
|
813
|
-
onUpdate?.({
|
|
814
|
-
content: [{ type: "text", text: nextText }],
|
|
815
|
-
details: createDetails({
|
|
816
|
-
config,
|
|
817
|
-
runContext,
|
|
818
|
-
usage,
|
|
819
|
-
turns: assistantTurns,
|
|
820
|
-
toolCalls,
|
|
821
|
-
durationMs: Date.now() - startedAt,
|
|
822
|
-
failed: Boolean(failureReason),
|
|
823
|
-
failureReason,
|
|
824
|
-
modelOverride: fallbackNote ? formatModelReference(activeModel) : undefined,
|
|
825
|
-
}),
|
|
826
|
-
});
|
|
827
|
-
};
|
|
828
|
-
let wallClockTimer;
|
|
829
|
-
let unsubscribe;
|
|
830
|
-
try {
|
|
831
|
-
const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
|
|
832
|
-
worker =
|
|
833
|
-
options.createWorker?.({
|
|
834
|
-
subAgent: config,
|
|
835
|
-
apiKey,
|
|
836
|
-
tools: filterToolsByName(availableTools, config.tools),
|
|
837
|
-
}) ??
|
|
838
|
-
new Agent({
|
|
839
|
-
initialState: {
|
|
840
|
-
systemPrompt: config.systemPrompt,
|
|
841
|
-
model: config.model,
|
|
842
|
-
// Same clamp the main agent applies (channel-runner.ts) before setting a model's
|
|
843
|
-
// thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
|
|
844
|
-
// snaps to the nearest one, instead of a raw unsupported value reaching the provider.
|
|
845
|
-
// The internal path's resolved config always fills thinkingLevel; the fallback
|
|
846
|
-
// here only closes the type.
|
|
847
|
-
thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
|
|
848
|
-
tools: filterToolsByName(availableTools, config.tools),
|
|
849
|
-
},
|
|
850
|
-
convertToLlm,
|
|
851
|
-
// Read on every request, so a backup-model switch only has to replace the key.
|
|
852
|
-
getApiKey: async () => apiKey,
|
|
853
|
-
streamFn: streamSimple,
|
|
854
|
-
});
|
|
855
|
-
wallClockTimer = setTimeout(() => {
|
|
856
|
-
failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
|
|
857
|
-
budgetExceeded = true;
|
|
858
|
-
retryBackoff.abort();
|
|
859
|
-
worker?.abort();
|
|
860
|
-
}, config.maxWallTimeSec * 1000);
|
|
861
|
-
unsubscribe = worker.subscribe((event) => {
|
|
862
|
-
if (event.type === "message_end" && isAssistantMessage(event.message)) {
|
|
863
|
-
assistantTurns++;
|
|
864
|
-
addUsage(usage, event.message.usage);
|
|
865
|
-
}
|
|
866
|
-
if (event.type === "tool_execution_start") {
|
|
867
|
-
toolCalls++;
|
|
868
|
-
const label = describeToolCall(event.toolName, event.args);
|
|
869
|
-
emitUpdate(formatStatus(config.name, label));
|
|
870
|
-
// After detaching, the step goes out as a paced run notice instead, like an external
|
|
871
|
-
// run's progress tail — otherwise an async internal run is silent until it settles.
|
|
872
|
-
if (detached)
|
|
873
|
-
runManager.noteProgress(runContext.runId, label);
|
|
874
|
-
if (toolCalls > config.maxToolCalls) {
|
|
875
|
-
failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
|
|
876
|
-
budgetExceeded = true;
|
|
877
|
-
emitUpdate(formatStatus(config.name, "tool budget reached"));
|
|
878
|
-
worker?.abort();
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
if (event.type === "turn_end" &&
|
|
882
|
-
isAssistantMessage(event.message) &&
|
|
883
|
-
event.toolResults.length > 0 &&
|
|
884
|
-
assistantTurns >= config.maxTurns) {
|
|
885
|
-
failureReason = `Turn budget exceeded (${config.maxTurns})`;
|
|
886
|
-
budgetExceeded = true;
|
|
887
|
-
emitUpdate(formatStatus(config.name, "turn budget reached"));
|
|
888
|
-
worker?.abort();
|
|
889
|
-
}
|
|
890
|
-
});
|
|
891
|
-
emitUpdate(formatStatus(config.name, "started"));
|
|
892
|
-
}
|
|
893
|
-
catch (error) {
|
|
894
|
-
unsubscribe?.();
|
|
895
|
-
if (wallClockTimer)
|
|
896
|
-
clearTimeout(wallClockTimer);
|
|
897
|
-
runManager.clearCancelHandle(runContext.runId);
|
|
898
|
-
try {
|
|
899
|
-
worker?.abort();
|
|
900
|
-
}
|
|
901
|
-
catch {
|
|
902
|
-
// Preserve the setup error; settlement below is the lifecycle authority.
|
|
903
|
-
}
|
|
904
|
-
const setupError = error instanceof Error ? error : new Error(String(error));
|
|
905
|
-
await runManager.settle(runContext.runId, {
|
|
906
|
-
status: "failed",
|
|
907
|
-
failureReason: setupError.message,
|
|
908
|
-
usage,
|
|
909
|
-
usageKnown: true,
|
|
910
|
-
costKnown: true,
|
|
911
|
-
turns: assistantTurns,
|
|
912
|
-
toolCalls,
|
|
913
|
-
durationMs: Date.now() - startedAt,
|
|
914
|
-
outputText: "",
|
|
915
|
-
}, { announce: false });
|
|
916
|
-
throw setupError;
|
|
917
|
-
}
|
|
918
|
-
const activeWorker = worker;
|
|
919
|
-
const activeUnsubscribe = unsubscribe;
|
|
920
|
-
const activeWallClockTimer = wallClockTimer;
|
|
921
|
-
/**
|
|
922
|
-
* A transcript ending in a provider error is retried in place (the error message removed, the
|
|
923
|
-
* loop continued from the last user/tool message): transient errors up to
|
|
924
|
-
* MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
|
|
925
|
-
* switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
|
|
926
|
-
* aborts and explicit cancels are never retried.
|
|
927
|
-
*/
|
|
928
|
-
async function recoverFromProviderErrors() {
|
|
929
|
-
const resume = activeWorker.continue?.bind(activeWorker);
|
|
930
|
-
if (!resume)
|
|
931
|
-
return;
|
|
932
|
-
let retries = 0;
|
|
933
|
-
let switched = false;
|
|
934
|
-
for (;;) {
|
|
935
|
-
if (budgetExceeded || externallyCancelled)
|
|
936
|
-
return;
|
|
937
|
-
const last = activeWorker.state.messages.at(-1);
|
|
938
|
-
if (!last || !isAssistantMessage(last) || last.stopReason !== "error")
|
|
939
|
-
return;
|
|
940
|
-
// `shouldFallback` is false only for a context overflow, which no retry or model switch fixes.
|
|
941
|
-
if (!shouldFallback(last.errorMessage))
|
|
942
|
-
return;
|
|
943
|
-
if (retries < MAX_TRANSIENT_RETRIES && isRetryableAssistantError(last)) {
|
|
944
|
-
retries++;
|
|
945
|
-
emitUpdate(formatStatus(config.name, `provider error, retrying (${retries}/${MAX_TRANSIENT_RETRIES})`));
|
|
946
|
-
const delayMs = (options.retryBaseDelayMs ?? RETRY_BASE_DELAY_MS) * 2 ** (retries - 1);
|
|
947
|
-
await sleepUnref(delayMs, retryBackoff.signal);
|
|
948
|
-
if (budgetExceeded || externallyCancelled)
|
|
949
|
-
return;
|
|
950
|
-
}
|
|
951
|
-
else {
|
|
952
|
-
if (switched || !options.resolveFallbackModel)
|
|
953
|
-
return;
|
|
954
|
-
const candidate = await options.resolveFallbackModel().catch(() => null);
|
|
955
|
-
if (!candidate || formatModelReference(candidate) === formatModelReference(activeModel))
|
|
956
|
-
return;
|
|
957
|
-
let candidateKey;
|
|
958
|
-
try {
|
|
959
|
-
candidateKey = await options.resolveApiKey(candidate);
|
|
960
|
-
}
|
|
961
|
-
catch {
|
|
962
|
-
return;
|
|
963
|
-
}
|
|
964
|
-
switched = true;
|
|
965
|
-
retries = 0;
|
|
966
|
-
const fromRef = formatModelReference(activeModel);
|
|
967
|
-
activeModel = candidate;
|
|
968
|
-
apiKey = candidateKey;
|
|
969
|
-
activeWorker.state.model = candidate;
|
|
970
|
-
activeWorker.state.thinkingLevel = clampThinkingLevel(candidate, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL);
|
|
971
|
-
fallbackNote = `switched from ${fromRef} to backup model ${formatModelReference(candidate)} after: ${last.errorMessage?.split("\n")[0]?.slice(0, 200) ?? "unknown error"}`;
|
|
972
|
-
emitUpdate(formatStatus(config.name, `switching to backup model ${formatModelReference(candidate)}`));
|
|
973
|
-
}
|
|
974
|
-
activeWorker.state.messages = activeWorker.state.messages.slice(0, -1);
|
|
975
|
-
await resume();
|
|
976
|
-
await activeWorker.waitForIdle();
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
/**
|
|
980
|
-
* Runs the worker to completion, including the D6 convergence turn, and returns the
|
|
981
|
-
* tool result plus the data `runs.ts` needs to settle. Rejects only for the single
|
|
982
|
-
* fatal case (no assistant message at all) — every other outcome, including a budget
|
|
983
|
-
* abort or explicit cancel, is a normal (if failed) result.
|
|
984
|
-
*/
|
|
985
|
-
async function runToCompletion() {
|
|
986
|
-
try {
|
|
987
|
-
const contextualBlocks = await resolveContextualBlocks(config, options);
|
|
988
|
-
if (externallyCancelled) {
|
|
989
|
-
failureReason = failureReason || "Cancelled by request.";
|
|
990
|
-
}
|
|
991
|
-
else {
|
|
992
|
-
await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
|
|
993
|
-
await activeWorker.waitForIdle();
|
|
994
|
-
await recoverFromProviderErrors();
|
|
995
|
-
}
|
|
996
|
-
// D6: a self-inflicted budget abort gets one tool-free turn to converge on a
|
|
997
|
-
// conclusion instead of discarding the work outright. An explicit cancel skips
|
|
998
|
-
// this — the model asked this run to stop now, not to wrap up.
|
|
999
|
-
if (budgetExceeded && !externallyCancelled) {
|
|
1000
|
-
clearTimeout(activeWallClockTimer);
|
|
1001
|
-
emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
|
|
1002
|
-
const preConvergenceMessageCount = activeWorker.state.messages.length;
|
|
1003
|
-
activeWorker.state.tools = [];
|
|
1004
|
-
let convergenceTimedOut = false;
|
|
1005
|
-
const convergenceTimer = setTimeout(() => {
|
|
1006
|
-
convergenceTimedOut = true;
|
|
1007
|
-
activeWorker.abort();
|
|
1008
|
-
}, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
|
|
1009
|
-
try {
|
|
1010
|
-
await activeWorker.prompt(CONVERGENCE_PROMPT);
|
|
1011
|
-
await activeWorker.waitForIdle();
|
|
1012
|
-
}
|
|
1013
|
-
catch {
|
|
1014
|
-
// Best effort: fall through to whatever worker.state.messages holds.
|
|
1015
|
-
}
|
|
1016
|
-
finally {
|
|
1017
|
-
clearTimeout(convergenceTimer);
|
|
1018
|
-
}
|
|
1019
|
-
if (convergenceTimedOut) {
|
|
1020
|
-
// Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
|
|
1021
|
-
// convergence turn and fall back to whatever came before it.
|
|
1022
|
-
activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
finally {
|
|
1027
|
-
activeUnsubscribe();
|
|
1028
|
-
clearTimeout(activeWallClockTimer);
|
|
1029
|
-
}
|
|
1030
|
-
const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
|
|
1031
|
-
const durationMs = Date.now() - startedAt;
|
|
1032
|
-
const modelRef = fallbackNote ? formatModelReference(activeModel) : undefined;
|
|
1033
|
-
const fallbackLine = fallbackNote ? `Note: this run ${fallbackNote}.\n\n` : "";
|
|
1034
|
-
if (!lastAssistantMessage) {
|
|
1035
|
-
failureReason = failureReason || "Sub-agent returned no assistant message";
|
|
1036
|
-
emitUpdate(formatStatus(config.name, "failed"));
|
|
1037
|
-
throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
|
|
1038
|
-
}
|
|
1039
|
-
const finalText = extractAssistantText(lastAssistantMessage);
|
|
1040
|
-
const effectiveFailureReason = failureReason ||
|
|
1041
|
-
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
1042
|
-
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
1043
|
-
: undefined);
|
|
1044
|
-
// The pass/fail rule is shared with the external verify path (spec 042 D1): one place
|
|
1045
|
-
// deciding what a verify run's own output proves. Spec 052, D6: it is the checker's declared
|
|
1046
|
-
// verdict, recorded for the leader to weigh — not a runtime-enforced gate.
|
|
1047
|
-
const verificationVerdict = runContext.purpose === "verify"
|
|
1048
|
-
? resolveVerificationVerdict({ finalText, runFailed: Boolean(effectiveFailureReason) })
|
|
1049
|
-
: undefined;
|
|
1050
|
-
// Internal runs always report full usage; cost is "unknown" only for the shape a
|
|
1051
|
-
// free/local model produces (tokens spent, nothing billed) — external harnesses
|
|
1052
|
-
// override both explicitly once they land (D4/D9).
|
|
1053
|
-
const costKnown = usage.cost.total > 0 || usage.total === 0;
|
|
1054
|
-
const baseSettleInput = {
|
|
1055
|
-
usage,
|
|
1056
|
-
usageKnown: true,
|
|
1057
|
-
costKnown,
|
|
1058
|
-
turns: assistantTurns,
|
|
1059
|
-
toolCalls,
|
|
1060
|
-
durationMs,
|
|
1061
|
-
verificationVerdict,
|
|
1062
|
-
model: modelRef,
|
|
1063
|
-
};
|
|
1064
|
-
if (effectiveFailureReason) {
|
|
1065
|
-
if (!finalText.trim()) {
|
|
1066
|
-
emitUpdate(formatStatus(config.name, "failed"));
|
|
1067
|
-
// Settlement records the reason itself, not the next-step advice wrapped around it below.
|
|
1068
|
-
failureReason = effectiveFailureReason;
|
|
1069
|
-
// The delegating model can act on this alone — re-dispatch, narrow the task, or do the
|
|
1070
|
-
// work itself — so it is not a user-facing error bubble.
|
|
1071
|
-
throw new RecoverableToolError(`${fallbackLine}${buildFailureText(config, effectiveFailureReason, finalText)}\n` +
|
|
1072
|
-
`Retry the delegation (narrower if it hit a budget), or do the work directly; subagent_run op=show runId=${runContext.runId} has the details.`);
|
|
1073
|
-
}
|
|
1074
|
-
emitUpdate(formatStatus(config.name, "stopped"));
|
|
1075
|
-
const finalized = finalizeSubAgentOutput(runContext, finalText);
|
|
1076
|
-
return {
|
|
1077
|
-
toolResult: {
|
|
1078
|
-
content: [
|
|
1079
|
-
{
|
|
1080
|
-
type: "text",
|
|
1081
|
-
text: mutatesNote +
|
|
1082
|
-
fallbackLine +
|
|
1083
|
-
buildStoppedText(config, effectiveFailureReason, finalized.replyText),
|
|
1084
|
-
},
|
|
1085
|
-
],
|
|
1086
|
-
details: createDetails({
|
|
1087
|
-
config,
|
|
1088
|
-
runContext,
|
|
1089
|
-
usage,
|
|
1090
|
-
turns: assistantTurns,
|
|
1091
|
-
toolCalls,
|
|
1092
|
-
durationMs,
|
|
1093
|
-
failed: true,
|
|
1094
|
-
failureReason: effectiveFailureReason,
|
|
1095
|
-
verificationVerdict,
|
|
1096
|
-
resultTruncated: finalized.truncated,
|
|
1097
|
-
modelOverride: modelRef,
|
|
1098
|
-
}),
|
|
1099
|
-
},
|
|
1100
|
-
settleInput: {
|
|
1101
|
-
...baseSettleInput,
|
|
1102
|
-
// An explicit cancel is not a failure (P1-1) — the model asked this run to
|
|
1103
|
-
// stop, and it did.
|
|
1104
|
-
status: externallyCancelled ? "cancelled" : "failed",
|
|
1105
|
-
failureReason: effectiveFailureReason,
|
|
1106
|
-
outputText: finalText,
|
|
1107
|
-
},
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
// P2-2, same as an external write run: what this run changed, so the reader does not spend
|
|
1111
|
-
// its first tool call finding out. Only a cleanly completed write run pays for it.
|
|
1112
|
-
const workspaceSummary = config.mutates === "write"
|
|
1113
|
-
? await changedPathsSummary(runContext.workingDirectory, input.workspaceBaseline).catch(() => undefined)
|
|
1114
|
-
: undefined;
|
|
1115
|
-
const workspaceLine = workspaceSummary
|
|
1116
|
-
? `\n\nWorkspace after the run (git status --porcelain): ${workspaceSummary}`
|
|
1117
|
-
: "";
|
|
1118
|
-
const finalized = finalizeSubAgentOutput(runContext, finalText);
|
|
1119
|
-
return {
|
|
1120
|
-
toolResult: {
|
|
1121
|
-
content: [
|
|
1122
|
-
{
|
|
1123
|
-
type: "text",
|
|
1124
|
-
text: mutatesNote +
|
|
1125
|
-
fallbackLine +
|
|
1126
|
-
(finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`) +
|
|
1127
|
-
workspaceLine,
|
|
1128
|
-
},
|
|
1129
|
-
],
|
|
1130
|
-
details: createDetails({
|
|
1131
|
-
config,
|
|
1132
|
-
runContext,
|
|
1133
|
-
usage,
|
|
1134
|
-
turns: assistantTurns,
|
|
1135
|
-
toolCalls,
|
|
1136
|
-
durationMs,
|
|
1137
|
-
verificationVerdict,
|
|
1138
|
-
resultTruncated: finalized.truncated,
|
|
1139
|
-
modelOverride: modelRef,
|
|
1140
|
-
}),
|
|
1141
|
-
},
|
|
1142
|
-
settleInput: { ...baseSettleInput, status: "completed", outputText: finalText, workspaceSummary },
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
/** Best-effort settle input for the one fatal path that rejects instead of resolving. */
|
|
1146
|
-
function fatalSettleInput(error) {
|
|
1147
|
-
return {
|
|
1148
|
-
status: externallyCancelled ? "cancelled" : "failed",
|
|
1149
|
-
failureReason: failureReason || error.message,
|
|
1150
|
-
usage,
|
|
1151
|
-
usageKnown: true,
|
|
1152
|
-
costKnown: usage.cost.total > 0 || usage.total === 0,
|
|
1153
|
-
turns: assistantTurns,
|
|
1154
|
-
toolCalls,
|
|
1155
|
-
durationMs: Date.now() - startedAt,
|
|
1156
|
-
outputText: "",
|
|
1157
|
-
model: fallbackNote ? formatModelReference(activeModel) : undefined,
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
// D2: the tool call waits at most until this turn's shared grace deadline (never longer than
|
|
1161
|
-
// the run's own wall clock budget) before degrading to a "still running" placeholder. It also
|
|
1162
|
-
// stops waiting the moment the turn is aborted (`/stop`): the SDK awaits this call, so ignoring
|
|
1163
|
-
// the signal held `/stop` until its force-end fallback — and a result that then arrived inside
|
|
1164
|
-
// the grace window settled `announce: false` into a turn that no longer existed, so nobody
|
|
1165
|
-
// ever saw it. The run itself keeps executing either way — only the *return* differs.
|
|
1166
|
-
const now = Date.now();
|
|
1167
|
-
const deadline = Math.min(graceDeadlineFor(signal, resolveSyncGraceMs(options.syncGraceMs), now), now + config.maxWallTimeSec * 1000);
|
|
1168
|
-
const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
|
|
1169
|
-
ok: false,
|
|
1170
|
-
error: error instanceof Error ? error : new Error(String(error)),
|
|
1171
|
-
}));
|
|
1172
|
-
const abortWatch = watchAbort(signal);
|
|
1173
|
-
const raceResult = await Promise.race([
|
|
1174
|
-
outcomePromise,
|
|
1175
|
-
sleepUnref(Math.max(0, deadline - now)).then(() => "timed-out"),
|
|
1176
|
-
abortWatch.aborted,
|
|
1177
|
-
]);
|
|
1178
|
-
abortWatch.dispose();
|
|
1179
|
-
if (raceResult !== "timed-out" && raceResult !== "aborted") {
|
|
1180
|
-
runManager.clearCancelHandle(runContext.runId);
|
|
1181
|
-
if (!raceResult.ok) {
|
|
1182
|
-
await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
|
|
1183
|
-
throw raceResult.error;
|
|
1184
|
-
}
|
|
1185
|
-
await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
|
|
1186
|
-
return raceResult.value.toolResult;
|
|
1187
|
-
}
|
|
1188
|
-
// Grace window elapsed (or the turn was stopped): hand back a placeholder now and let the run
|
|
1189
|
-
// keep going in the background. It settles and, this time, announces itself with a completion
|
|
1190
|
-
// wake (D2/D7) — the same "runtime guarantees completion" contract background jobs already keep.
|
|
1191
|
-
detached = true;
|
|
1192
|
-
void outcomePromise.then(async (outcome) => {
|
|
1193
|
-
runManager.clearCancelHandle(runContext.runId);
|
|
1194
|
-
const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
|
|
1195
|
-
await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
|
|
1196
|
-
log.logWarn("subagent.settle.failed", "Detached run settlement failed", {
|
|
1197
|
-
reason: errorMessage(error),
|
|
1198
|
-
fields: { runId: runContext.runId },
|
|
1199
|
-
});
|
|
1200
|
-
});
|
|
1201
|
-
});
|
|
1202
|
-
return {
|
|
1203
|
-
content: [
|
|
1204
|
-
{
|
|
1205
|
-
type: "text",
|
|
1206
|
-
text: mutatesNote +
|
|
1207
|
-
buildDispatchedText(runContext.runId, config.name, "internal, async", runContext.workingDirectory),
|
|
1208
|
-
},
|
|
1209
|
-
],
|
|
1210
|
-
details: createDetails({
|
|
1211
|
-
config,
|
|
1212
|
-
runContext,
|
|
1213
|
-
usage,
|
|
1214
|
-
turns: assistantTurns,
|
|
1215
|
-
toolCalls,
|
|
1216
|
-
durationMs: Date.now() - startedAt,
|
|
1217
|
-
dispatched: true,
|
|
1218
|
-
}),
|
|
1219
|
-
};
|
|
1220
|
-
}
|
|
1221
|
-
export function createSubAgentTool(options) {
|
|
1222
|
-
return {
|
|
1223
|
-
name: "subagent",
|
|
1224
|
-
label: "subagent",
|
|
1225
|
-
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.",
|
|
1226
|
-
parameters: subagentSchema,
|
|
1227
|
-
execute: async (_toolCallId, params, signal, onUpdate) => {
|
|
1228
|
-
if (signal?.aborted) {
|
|
1229
|
-
throw new Error("Sub-agent aborted");
|
|
1230
|
-
}
|
|
1231
|
-
const availableModels = options.getAvailableModels();
|
|
1232
|
-
const discovery = options.getSubAgentDiscovery?.() ?? {
|
|
1233
|
-
directory: `${options.workspaceDir}/sub-agents`,
|
|
1234
|
-
agents: [],
|
|
1235
|
-
warnings: [],
|
|
1236
|
-
};
|
|
1237
|
-
const currentModel = options.getCurrentModel();
|
|
1238
|
-
const taskLengthError = validateSubAgentTask(params.task);
|
|
1239
|
-
if (taskLengthError) {
|
|
1240
|
-
throw new RecoverableToolError(taskLengthError);
|
|
1241
|
-
}
|
|
1242
|
-
const invocation = resolveConfiguredRole(availableModels, currentModel, discovery.agents, { agent: params.agent, purpose: params.purpose }, options.getSubAgentModelReference?.() ?? undefined);
|
|
1243
|
-
if (!invocation.config) {
|
|
1244
|
-
throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
|
|
1245
|
-
}
|
|
1246
|
-
return dispatchSubAgentRun(options, currentModel, invocation.config, undefined, params, signal, onUpdate);
|
|
1247
|
-
},
|
|
1248
|
-
};
|
|
1249
|
-
}
|
|
1250
|
-
export function createSubAgentInlineTool(options) {
|
|
1251
|
-
return {
|
|
1252
|
-
name: "subagent_inline",
|
|
1253
|
-
label: "subagent_inline",
|
|
1254
|
-
description: "Advanced fallback only, not the default: use `subagent` first whenever any configured role in the workspace `sub-agents/` can do the work. `subagent` is the normal role-based path: pass its `agent` and complete `task`; the role file supplies the tools, model, budget and context policy. Use `subagent_inline` only when no configured role is suitable. It is a raw one-shot meta-executor, not a shorthand for `subagent`: there is no role file to supply those settings. Build a complete valid inline call yourself — `task` and `systemPrompt` are required; choose valid values for any needed `tools`, `model`, `effort`, `context`, `thinkingLevel`, `mutates`, `workingDirectory`, `purpose` and `taskId` fields. Do not send a partial role-style payload or choose this tool just because it is available. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
|
|
1255
|
-
parameters: subagentInlineSchema,
|
|
1256
|
-
execute: async (_toolCallId, params, signal, onUpdate) => {
|
|
1257
|
-
if (signal?.aborted) {
|
|
1258
|
-
throw new Error("Sub-agent aborted");
|
|
1259
|
-
}
|
|
1260
|
-
const availableModels = options.getAvailableModels();
|
|
1261
|
-
const currentModel = options.getCurrentModel();
|
|
1262
|
-
const taskLengthError = validateSubAgentTask(params.task);
|
|
1263
|
-
if (taskLengthError) {
|
|
1264
|
-
throw new RecoverableToolError(taskLengthError);
|
|
1265
|
-
}
|
|
1266
|
-
const invocation = resolveInlineAgent(availableModels, currentModel, {
|
|
1267
|
-
systemPrompt: params.systemPrompt,
|
|
1268
|
-
tools: params.tools,
|
|
1269
|
-
model: params.model,
|
|
1270
|
-
effort: params.effort,
|
|
1271
|
-
context: params.context,
|
|
1272
|
-
thinkingLevel: params.thinkingLevel,
|
|
1273
|
-
mutates: params.mutates,
|
|
1274
|
-
purpose: params.purpose,
|
|
1275
|
-
}, options.getSubAgentModelReference?.() ?? undefined);
|
|
1276
|
-
if (!invocation.config) {
|
|
1277
|
-
throw new RecoverableToolError(invocation.error ?? "Unable to resolve inline sub-agent.");
|
|
1278
|
-
}
|
|
1279
|
-
return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, signal, onUpdate);
|
|
1280
|
-
},
|
|
1281
|
-
};
|
|
1282
|
-
}
|