@oyasmi/pipiclaw 0.9.3 → 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 +167 -1188
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +45 -64
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +11 -2
- 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} +48 -35
- 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/session-adapter.js +159 -0
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +24 -13
- 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} +5 -3
- package/dist/agent/status-render.d.ts +0 -1
- package/dist/agent/status-render.js +4 -16
- 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} +10 -5
- 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-error.d.ts +31 -0
- package/dist/agent/turn/turn-error.js +68 -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} +14 -10
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
- package/dist/{runtime/app-home.js → app/home.js} +22 -75
- package/dist/{runtime → app}/proxy.js +4 -2
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +17 -14
- 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/channel/channel-index.js +4 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
- package/dist/channel/project-scope-store.js +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +24 -7
- package/dist/commands/catalog.js +91 -44
- package/dist/commands/reply-limits.d.ts +6 -0
- package/dist/commands/reply-limits.js +24 -0
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
- package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
- package/dist/{settings.js → config/settings.js} +11 -11
- 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 +4 -1
- 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/{runtime → dingtalk}/delivery.js +29 -15
- 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} +99 -45
- 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} +14 -3
- package/dist/events/{event-validation.js → validation.js} +17 -9
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +63 -121
- package/dist/executor.js +2 -2
- 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} +34 -157
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/log.d.ts +12 -2
- package/dist/log.js +26 -34
- package/dist/main.js +3 -3
- package/dist/memory/commands.js +29 -23
- package/dist/memory/lifecycle.js +26 -5
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-state.js +4 -1
- 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 +5 -2
- 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/paths.d.ts +2 -0
- package/dist/paths.js +9 -0
- package/dist/playbooks/agent-delegation.md +2 -2
- 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 +70 -659
- package/dist/runtime/durable-dispatch.d.ts +43 -4
- package/dist/runtime/durable-dispatch.js +153 -3
- 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 +6 -4
- package/dist/runtime/task-driver.js +58 -23
- package/dist/runtime/task-migration.js +25 -8
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +13 -6
- 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/runtime/wake-coalescing.d.ts +18 -0
- package/dist/runtime/wake-coalescing.js +29 -0
- package/dist/security/block-message.d.ts +22 -1
- package/dist/security/block-message.js +66 -1
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.d.ts +2 -1
- package/dist/security/network.js +7 -2
- package/dist/security/path-guard-check.js +2 -2
- 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/format.d.ts +12 -0
- package/dist/shared/format.js +37 -0
- package/dist/shared/host-process.js +16 -4
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/shared/with-timeout.d.ts +3 -2
- package/dist/shared/with-timeout.js +14 -3
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
- 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} +9 -7
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
- 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/claude-code.js +23 -1
- 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 +18 -1
- package/dist/subagents/external/progress-tail.js +64 -17
- package/dist/subagents/external/run.d.ts +5 -1
- package/dist/subagents/external/run.js +23 -9
- package/dist/subagents/external/settlement.d.ts +4 -1
- package/dist/subagents/external/settlement.js +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 +16 -232
- package/dist/subagents/runs.js +132 -310
- 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/subagents/workspace-summary.d.ts +16 -4
- package/dist/subagents/workspace-summary.js +74 -18
- package/dist/tasks/board.d.ts +10 -3
- package/dist/tasks/board.js +38 -3
- 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} +117 -67
- 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/frontmatter.d.ts +5 -0
- package/dist/tasks/frontmatter.js +8 -0
- package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
- package/dist/tasks/{log.js → loop-log.js} +59 -3
- 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 +6 -4
- package/dist/tasks/ticket.d.ts +3 -1
- package/dist/tasks/ticket.js +19 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +2 -2
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
- package/dist/tools/{tool-details.js → contract/details.js} +42 -5
- 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 +5 -3
- package/dist/tools/index.js +8 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/memory-manage.js +4 -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.d.ts +1 -1
- package/dist/tools/subagent-manage.js +19 -13
- 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 +7 -4
- 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 +3 -3
- package/dist/tui/commands.js +4 -4
- 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/pitui-frontend.js +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/renderer.js +3 -2
- 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 +3 -1
- package/dist/tui/turn-controller.js +36 -21
- package/dist/usage/ledger.js +7 -1
- package/dist/usage/render.js +3 -1
- 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/agent/session-adapter.js +0 -77
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1416
- package/dist/subagents/tool.d.ts +0 -206
- package/dist/subagents/tool.js +0 -1088
- /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-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 → dingtalk}/channel-queue.d.ts +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/{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/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
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The synchronous wait window of a delegation call (spec 040 D2): one shared per-turn deadline, and
|
|
3
|
+
* a watcher for the turn's abort signal. Used by the internal run; kept apart because the window is
|
|
4
|
+
* a property of the dispatching turn, not of one run.
|
|
5
|
+
*/
|
|
6
|
+
export declare function graceDeadlineFor(signal: AbortSignal | undefined, graceMs: number, now: number): number;
|
|
7
|
+
/** Resolves once `signal` aborts (never rejects; pending forever without one). `dispose` drops
|
|
8
|
+
* the listener, since a turn's signal outlives every call that raced against it. */
|
|
9
|
+
export declare function watchAbort(signal: AbortSignal | undefined): {
|
|
10
|
+
aborted: Promise<"aborted">;
|
|
11
|
+
dispose(): void;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Longest a dispatching tool call waits for its run to settle before returning a "still running"
|
|
15
|
+
* placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
|
|
16
|
+
* rule for numeric thresholds.
|
|
17
|
+
*/
|
|
18
|
+
export declare const SYNC_GRACE_MS = 120000;
|
|
19
|
+
/**
|
|
20
|
+
* Effective sync grace window. A test-only env override (`PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS`)
|
|
21
|
+
* lets the deterministic e2e layer exercise the detached-settlement + completion-wake path
|
|
22
|
+
* (spec 048 A14/A15/A16) without a multi-minute wait; production always uses `SYNC_GRACE_MS`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function resolveSyncGraceMs(override?: number): number;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The synchronous wait window of a delegation call (spec 040 D2): one shared per-turn deadline, and
|
|
3
|
+
* a watcher for the turn's abort signal. Used by the internal run; kept apart because the window is
|
|
4
|
+
* a property of the dispatching turn, not of one run.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* D2's grace window is per turn, not per call. The SDK runs a whole tool batch sequentially as
|
|
8
|
+
* soon as one call in it is sequential (`bash`, `edit`, `write`), so "a worktree, then three
|
|
9
|
+
* delegations" in one message used to block the channel for three back-to-back grace windows.
|
|
10
|
+
* Every call in one agent run shares that run's AbortSignal, which is what keys the deadline:
|
|
11
|
+
* the first delegation of a turn starts the clock, later ones get only what is left of it.
|
|
12
|
+
*/
|
|
13
|
+
const turnGraceDeadlines = new WeakMap();
|
|
14
|
+
export function graceDeadlineFor(signal, graceMs, now) {
|
|
15
|
+
if (!signal)
|
|
16
|
+
return now + graceMs;
|
|
17
|
+
let deadline = turnGraceDeadlines.get(signal);
|
|
18
|
+
if (deadline === undefined) {
|
|
19
|
+
deadline = now + graceMs;
|
|
20
|
+
turnGraceDeadlines.set(signal, deadline);
|
|
21
|
+
}
|
|
22
|
+
return deadline;
|
|
23
|
+
}
|
|
24
|
+
/** Resolves once `signal` aborts (never rejects; pending forever without one). `dispose` drops
|
|
25
|
+
* the listener, since a turn's signal outlives every call that raced against it. */
|
|
26
|
+
export function watchAbort(signal) {
|
|
27
|
+
let dispose = () => { };
|
|
28
|
+
const aborted = new Promise((resolve) => {
|
|
29
|
+
if (!signal)
|
|
30
|
+
return;
|
|
31
|
+
if (signal.aborted) {
|
|
32
|
+
resolve("aborted");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const onAbort = () => resolve("aborted");
|
|
36
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
37
|
+
dispose = () => signal.removeEventListener("abort", onAbort);
|
|
38
|
+
});
|
|
39
|
+
return { aborted, dispose };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Longest a dispatching tool call waits for its run to settle before returning a "still running"
|
|
43
|
+
* placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
|
|
44
|
+
* rule for numeric thresholds.
|
|
45
|
+
*/
|
|
46
|
+
export const SYNC_GRACE_MS = 120_000;
|
|
47
|
+
/**
|
|
48
|
+
* Effective sync grace window. A test-only env override (`PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS`)
|
|
49
|
+
* lets the deterministic e2e layer exercise the detached-settlement + completion-wake path
|
|
50
|
+
* (spec 048 A14/A15/A16) without a multi-minute wait; production always uses `SYNC_GRACE_MS`.
|
|
51
|
+
*/
|
|
52
|
+
export function resolveSyncGraceMs(override) {
|
|
53
|
+
if (override !== undefined)
|
|
54
|
+
return override;
|
|
55
|
+
const env = Number(process.env.PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS);
|
|
56
|
+
return Number.isFinite(env) && env > 0 ? env : SYNC_GRACE_MS;
|
|
57
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ResolvedInternalSubAgentConfig } from "../discovery.js";
|
|
2
|
+
import type { SettleInput } from "../run-record.js";
|
|
3
|
+
import type { DelegationResult, SubAgentRunContext, SubAgentWorker } from "../types.js";
|
|
4
|
+
import { type WorkspaceBaseline } from "../workspace-summary.js";
|
|
5
|
+
import type { InternalRunState } from "./state.js";
|
|
6
|
+
/**
|
|
7
|
+
* Assemble the result of a finished worker. Rejects only for the single fatal case (no assistant
|
|
8
|
+
* message at all) — every other outcome, including a budget abort or explicit cancel, is a normal
|
|
9
|
+
* (if failed) result.
|
|
10
|
+
*/
|
|
11
|
+
export declare function buildInternalOutcome(input: {
|
|
12
|
+
worker: SubAgentWorker;
|
|
13
|
+
config: ResolvedInternalSubAgentConfig;
|
|
14
|
+
runContext: SubAgentRunContext;
|
|
15
|
+
state: InternalRunState;
|
|
16
|
+
mutatesNote: string;
|
|
17
|
+
workspaceBaseline: WorkspaceBaseline | undefined;
|
|
18
|
+
emitUpdate: (text: string) => void;
|
|
19
|
+
}): Promise<{
|
|
20
|
+
toolResult: DelegationResult;
|
|
21
|
+
settleInput: SettleInput;
|
|
22
|
+
}>;
|
|
23
|
+
/** Best-effort settle input for the one fatal path that rejects instead of resolving. */
|
|
24
|
+
export declare function fatalSettleInput(state: InternalRunState, error: Error): SettleInput;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning a finished internal worker into what the run hands back: the tool result for the model
|
|
3
|
+
* and the `SettleInput` for the run manager — covering success, a failure with output, a failure
|
|
4
|
+
* without any (which rejects), and the best-effort settle input for that rejecting path.
|
|
5
|
+
*/
|
|
6
|
+
import { formatModelReference } from "../../models/reference.js";
|
|
7
|
+
import { RecoverableToolError } from "../../shared/recoverable-error.js";
|
|
8
|
+
import { extractAssistantText } from "../../shared/text-utils.js";
|
|
9
|
+
import { buildFailureText, buildStoppedText, createDetails, finalizeSubAgentOutput, formatStatus } from "../result.js";
|
|
10
|
+
import { resolveVerificationVerdict } from "../verification-outcome.js";
|
|
11
|
+
import { changedPathsSummary } from "../workspace-summary.js";
|
|
12
|
+
import { getLastAssistantMessage } from "./worker.js";
|
|
13
|
+
/**
|
|
14
|
+
* Assemble the result of a finished worker. Rejects only for the single fatal case (no assistant
|
|
15
|
+
* message at all) — every other outcome, including a budget abort or explicit cancel, is a normal
|
|
16
|
+
* (if failed) result.
|
|
17
|
+
*/
|
|
18
|
+
export async function buildInternalOutcome(input) {
|
|
19
|
+
const { worker, config, runContext, state, mutatesNote, emitUpdate } = input;
|
|
20
|
+
const { usage } = state;
|
|
21
|
+
const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
|
|
22
|
+
const durationMs = Date.now() - state.startedAt;
|
|
23
|
+
const modelRef = state.fallbackNote ? formatModelReference(state.activeModel) : undefined;
|
|
24
|
+
const fallbackLine = state.fallbackNote ? `Note: this run ${state.fallbackNote}.\n\n` : "";
|
|
25
|
+
if (!lastAssistantMessage) {
|
|
26
|
+
state.failureReason = state.failureReason || "Sub-agent returned no assistant message";
|
|
27
|
+
emitUpdate(formatStatus(config.name, "failed"));
|
|
28
|
+
throw new Error(`Sub-agent ${config.name} failed: ${state.failureReason}`);
|
|
29
|
+
}
|
|
30
|
+
const finalText = extractAssistantText(lastAssistantMessage);
|
|
31
|
+
const effectiveFailureReason = state.failureReason ||
|
|
32
|
+
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
33
|
+
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
34
|
+
: undefined);
|
|
35
|
+
// The pass/fail rule is shared with the external verify path (spec 042 D1): one place
|
|
36
|
+
// deciding what a verify run's own output proves. Spec 052, D6: it is the checker's declared
|
|
37
|
+
// verdict, recorded for the leader to weigh — not a runtime-enforced gate.
|
|
38
|
+
const verificationVerdict = runContext.purpose === "verify"
|
|
39
|
+
? resolveVerificationVerdict({ finalText, runFailed: Boolean(effectiveFailureReason) })
|
|
40
|
+
: undefined;
|
|
41
|
+
// Internal runs always report full usage; cost is "unknown" only for the shape a
|
|
42
|
+
// free/local model produces (tokens spent, nothing billed) — external harnesses
|
|
43
|
+
// override both explicitly once they land (D4/D9).
|
|
44
|
+
const costKnown = usage.cost.total > 0 || usage.total === 0;
|
|
45
|
+
const baseSettleInput = {
|
|
46
|
+
usage,
|
|
47
|
+
usageKnown: true,
|
|
48
|
+
costKnown,
|
|
49
|
+
turns: state.assistantTurns,
|
|
50
|
+
toolCalls: state.toolCalls,
|
|
51
|
+
durationMs,
|
|
52
|
+
verificationVerdict,
|
|
53
|
+
model: modelRef,
|
|
54
|
+
};
|
|
55
|
+
if (effectiveFailureReason) {
|
|
56
|
+
if (!finalText.trim()) {
|
|
57
|
+
emitUpdate(formatStatus(config.name, "failed"));
|
|
58
|
+
// Settlement records the reason itself, not the next-step advice wrapped around it below.
|
|
59
|
+
state.failureReason = effectiveFailureReason;
|
|
60
|
+
// The delegating model can act on this alone — re-dispatch, narrow the task, or do the
|
|
61
|
+
// work itself — so it is not a user-facing error bubble.
|
|
62
|
+
throw new RecoverableToolError(`${fallbackLine}${buildFailureText(config, effectiveFailureReason, finalText)}\n` +
|
|
63
|
+
`Retry the delegation (narrower if it hit a budget), or do the work directly; subagent_run op=show runId=${runContext.runId} has the details.`);
|
|
64
|
+
}
|
|
65
|
+
emitUpdate(formatStatus(config.name, "stopped"));
|
|
66
|
+
const finalized = finalizeSubAgentOutput(runContext, finalText);
|
|
67
|
+
return {
|
|
68
|
+
toolResult: {
|
|
69
|
+
content: [
|
|
70
|
+
{
|
|
71
|
+
type: "text",
|
|
72
|
+
text: mutatesNote + fallbackLine + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
|
|
73
|
+
},
|
|
74
|
+
],
|
|
75
|
+
details: createDetails({
|
|
76
|
+
config,
|
|
77
|
+
runContext,
|
|
78
|
+
usage,
|
|
79
|
+
turns: state.assistantTurns,
|
|
80
|
+
toolCalls: state.toolCalls,
|
|
81
|
+
durationMs,
|
|
82
|
+
failed: true,
|
|
83
|
+
failureReason: effectiveFailureReason,
|
|
84
|
+
verificationVerdict,
|
|
85
|
+
resultTruncated: finalized.truncated,
|
|
86
|
+
modelOverride: modelRef,
|
|
87
|
+
}),
|
|
88
|
+
},
|
|
89
|
+
settleInput: {
|
|
90
|
+
...baseSettleInput,
|
|
91
|
+
// An explicit cancel is not a failure (P1-1) — the model asked this run to
|
|
92
|
+
// stop, and it did.
|
|
93
|
+
status: state.externallyCancelled ? "cancelled" : "failed",
|
|
94
|
+
failureReason: effectiveFailureReason,
|
|
95
|
+
outputText: finalText,
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// P2-2, same as an external write run: what this run changed, so the reader does not spend
|
|
100
|
+
// its first tool call finding out. Only a cleanly completed write run pays for it.
|
|
101
|
+
const workspaceSummary = config.mutates === "write"
|
|
102
|
+
? await changedPathsSummary(runContext.workingDirectory, input.workspaceBaseline).catch(() => undefined)
|
|
103
|
+
: undefined;
|
|
104
|
+
const workspaceLine = workspaceSummary
|
|
105
|
+
? `\n\nWorkspace after the run (git status --porcelain): ${workspaceSummary}`
|
|
106
|
+
: "";
|
|
107
|
+
const finalized = finalizeSubAgentOutput(runContext, finalText);
|
|
108
|
+
return {
|
|
109
|
+
toolResult: {
|
|
110
|
+
content: [
|
|
111
|
+
{
|
|
112
|
+
type: "text",
|
|
113
|
+
text: mutatesNote +
|
|
114
|
+
fallbackLine +
|
|
115
|
+
(finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`) +
|
|
116
|
+
workspaceLine,
|
|
117
|
+
},
|
|
118
|
+
],
|
|
119
|
+
details: createDetails({
|
|
120
|
+
config,
|
|
121
|
+
runContext,
|
|
122
|
+
usage,
|
|
123
|
+
turns: state.assistantTurns,
|
|
124
|
+
toolCalls: state.toolCalls,
|
|
125
|
+
durationMs,
|
|
126
|
+
verificationVerdict,
|
|
127
|
+
resultTruncated: finalized.truncated,
|
|
128
|
+
modelOverride: modelRef,
|
|
129
|
+
}),
|
|
130
|
+
},
|
|
131
|
+
settleInput: { ...baseSettleInput, status: "completed", outputText: finalText, workspaceSummary },
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** Best-effort settle input for the one fatal path that rejects instead of resolving. */
|
|
135
|
+
export function fatalSettleInput(state, error) {
|
|
136
|
+
const { usage } = state;
|
|
137
|
+
return {
|
|
138
|
+
status: state.externallyCancelled ? "cancelled" : "failed",
|
|
139
|
+
failureReason: state.failureReason || error.message,
|
|
140
|
+
usage,
|
|
141
|
+
usageKnown: true,
|
|
142
|
+
costKnown: usage.cost.total > 0 || usage.total === 0,
|
|
143
|
+
turns: state.assistantTurns,
|
|
144
|
+
toolCalls: state.toolCalls,
|
|
145
|
+
durationMs: Date.now() - state.startedAt,
|
|
146
|
+
outputText: "",
|
|
147
|
+
model: state.fallbackNote ? formatModelReference(state.activeModel) : undefined,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ResolvedInternalSubAgentConfig } from "../discovery.js";
|
|
2
|
+
import type { SubAgentToolOptions, SubAgentWorker } from "../types.js";
|
|
3
|
+
import type { InternalRunState } from "./state.js";
|
|
4
|
+
/**
|
|
5
|
+
* A transcript ending in a provider error is retried in place (the error message removed, the
|
|
6
|
+
* loop continued from the last user/tool message): transient errors up to
|
|
7
|
+
* MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
|
|
8
|
+
* switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
|
|
9
|
+
* aborts and explicit cancels are never retried.
|
|
10
|
+
*/
|
|
11
|
+
export declare function recoverFromProviderErrors(input: {
|
|
12
|
+
worker: SubAgentWorker;
|
|
13
|
+
options: SubAgentToolOptions;
|
|
14
|
+
config: ResolvedInternalSubAgentConfig;
|
|
15
|
+
state: InternalRunState;
|
|
16
|
+
/** Wakes a retry backoff early when the run is cancelled or out of wall time. */
|
|
17
|
+
retryBackoff: AbortController;
|
|
18
|
+
emitUpdate: (text: string) => void;
|
|
19
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider-error recovery for an internal run: a transcript ending in a provider error is retried in
|
|
3
|
+
* place (transient errors, with backoff) and then, once, on the backup model — the same rule the
|
|
4
|
+
* main turn follows.
|
|
5
|
+
*/
|
|
6
|
+
import { clampThinkingLevel, isRetryableAssistantError } from "@earendil-works/pi-ai/compat";
|
|
7
|
+
import { shouldFallback } from "../../models/fallback.js";
|
|
8
|
+
import { formatModelReference } from "../../models/reference.js";
|
|
9
|
+
import { sleepUnref } from "../../shared/with-timeout.js";
|
|
10
|
+
import { DEFAULT_THINKING_LEVEL } from "../discovery.js";
|
|
11
|
+
import { formatStatus } from "../result.js";
|
|
12
|
+
import { isAssistantMessage } from "./worker.js";
|
|
13
|
+
/**
|
|
14
|
+
* A provider error (429, overloaded, 5xx, dropped stream) used to fail an internal run outright —
|
|
15
|
+
* the main session retries those, a bare `Agent` does not. Retried in place with exponential
|
|
16
|
+
* backoff (2s, 4s, 8s) before falling back to the backup model; the wall-time budget still bounds
|
|
17
|
+
* the whole thing.
|
|
18
|
+
*/
|
|
19
|
+
const MAX_TRANSIENT_RETRIES = 3;
|
|
20
|
+
const RETRY_BASE_DELAY_MS = 2_000;
|
|
21
|
+
/**
|
|
22
|
+
* A transcript ending in a provider error is retried in place (the error message removed, the
|
|
23
|
+
* loop continued from the last user/tool message): transient errors up to
|
|
24
|
+
* MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
|
|
25
|
+
* switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
|
|
26
|
+
* aborts and explicit cancels are never retried.
|
|
27
|
+
*/
|
|
28
|
+
export async function recoverFromProviderErrors(input) {
|
|
29
|
+
const { worker, options, config, state, retryBackoff, emitUpdate } = input;
|
|
30
|
+
const resume = worker.continue?.bind(worker);
|
|
31
|
+
if (!resume)
|
|
32
|
+
return;
|
|
33
|
+
let retries = 0;
|
|
34
|
+
let switched = false;
|
|
35
|
+
for (;;) {
|
|
36
|
+
if (state.budgetExceeded || state.externallyCancelled)
|
|
37
|
+
return;
|
|
38
|
+
const last = worker.state.messages.at(-1);
|
|
39
|
+
if (!last || !isAssistantMessage(last) || last.stopReason !== "error")
|
|
40
|
+
return;
|
|
41
|
+
// `shouldFallback` is false only for a context overflow, which no retry or model switch fixes.
|
|
42
|
+
if (!shouldFallback(last.errorMessage))
|
|
43
|
+
return;
|
|
44
|
+
if (retries < MAX_TRANSIENT_RETRIES && isRetryableAssistantError(last)) {
|
|
45
|
+
retries++;
|
|
46
|
+
emitUpdate(formatStatus(config.name, `provider error, retrying (${retries}/${MAX_TRANSIENT_RETRIES})`));
|
|
47
|
+
const delayMs = (options.retryBaseDelayMs ?? RETRY_BASE_DELAY_MS) * 2 ** (retries - 1);
|
|
48
|
+
await sleepUnref(delayMs, retryBackoff.signal);
|
|
49
|
+
if (state.budgetExceeded || state.externallyCancelled)
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
if (switched || !options.resolveFallbackModel)
|
|
54
|
+
return;
|
|
55
|
+
const candidate = await options.resolveFallbackModel().catch(() => null);
|
|
56
|
+
if (state.budgetExceeded || state.externallyCancelled)
|
|
57
|
+
return;
|
|
58
|
+
if (!candidate || formatModelReference(candidate) === formatModelReference(state.activeModel))
|
|
59
|
+
return;
|
|
60
|
+
let candidateKey;
|
|
61
|
+
try {
|
|
62
|
+
candidateKey = await options.resolveApiKey(candidate);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (state.budgetExceeded || state.externallyCancelled)
|
|
68
|
+
return;
|
|
69
|
+
switched = true;
|
|
70
|
+
retries = 0;
|
|
71
|
+
const fromRef = formatModelReference(state.activeModel);
|
|
72
|
+
state.activeModel = candidate;
|
|
73
|
+
state.apiKey = candidateKey;
|
|
74
|
+
worker.state.model = candidate;
|
|
75
|
+
worker.state.thinkingLevel = clampThinkingLevel(candidate, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL);
|
|
76
|
+
state.fallbackNote = `switched from ${fromRef} to backup model ${formatModelReference(candidate)} after: ${last.errorMessage?.split("\n")[0]?.slice(0, 200) ?? "unknown error"}`;
|
|
77
|
+
emitUpdate(formatStatus(config.name, `switching to backup model ${formatModelReference(candidate)}`));
|
|
78
|
+
}
|
|
79
|
+
worker.state.messages = worker.state.messages.slice(0, -1);
|
|
80
|
+
await resume();
|
|
81
|
+
await worker.waitForIdle();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `runtime: internal` half of delegation dispatch (spec 046 D2.5): register the durable run
|
|
3
|
+
* record, start the worker, drive it to completion (with the D6 convergence turn), settle it, and
|
|
4
|
+
* return either its real result or — once the sync grace window elapses — a "[Dispatched]"
|
|
5
|
+
* placeholder while the run keeps going in the background.
|
|
6
|
+
*
|
|
7
|
+
* Orchestration only: the worker, provider retry and outcome assembly live in their own files. The
|
|
8
|
+
* lease release on every pre-registration failure, the cancel handle installed before any setup I/O,
|
|
9
|
+
* and the grace/detach split all stay here, in this order.
|
|
10
|
+
*/
|
|
11
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
12
|
+
import type { ResolvedInternalSubAgentConfig } from "../discovery.js";
|
|
13
|
+
import type { SubAgentRunManager } from "../runs.js";
|
|
14
|
+
import type { DelegationParams, DelegationResult, SubAgentRunContext, SubAgentToolOptions } from "../types.js";
|
|
15
|
+
import type { WorkspaceBaseline } from "../workspace-summary.js";
|
|
16
|
+
interface InternalRunInput {
|
|
17
|
+
options: SubAgentToolOptions;
|
|
18
|
+
currentModel: Model<Api>;
|
|
19
|
+
config: ResolvedInternalSubAgentConfig;
|
|
20
|
+
runLabel: string;
|
|
21
|
+
mutatesNote: string;
|
|
22
|
+
runContext: SubAgentRunContext;
|
|
23
|
+
leaseKey: string | undefined;
|
|
24
|
+
params: DelegationParams;
|
|
25
|
+
signal: AbortSignal | undefined;
|
|
26
|
+
onUpdate?: (update: DelegationResult) => void;
|
|
27
|
+
runManager: SubAgentRunManager;
|
|
28
|
+
workspaceBaseline: WorkspaceBaseline | undefined;
|
|
29
|
+
}
|
|
30
|
+
export declare function dispatchInternalRun(input: InternalRunInput): Promise<DelegationResult>;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import * as log from "../../log.js";
|
|
2
|
+
import { formatModelReference } from "../../models/reference.js";
|
|
3
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
4
|
+
import { sleepUnref } from "../../shared/with-timeout.js";
|
|
5
|
+
import { graceDeadlineFor, resolveSyncGraceMs, watchAbort } from "../grace.js";
|
|
6
|
+
import { buildDispatchedText, createDetails, formatStatus } from "../result.js";
|
|
7
|
+
import { buildSubAgentTask, resolveContextualBlocks } from "../task-envelope.js";
|
|
8
|
+
import { releaseWorkspaceLease } from "../workspace-lease.js";
|
|
9
|
+
import { buildInternalOutcome, fatalSettleInput } from "./outcome.js";
|
|
10
|
+
import { recoverFromProviderErrors } from "./provider-retry.js";
|
|
11
|
+
import { createInternalRunState, createUpdateEmitter } from "./state.js";
|
|
12
|
+
import { DirectoryExecutor, startWorker } from "./worker.js";
|
|
13
|
+
/**
|
|
14
|
+
* Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
|
|
15
|
+
* tool-free turn to summarize what it already found instead of having its work discarded.
|
|
16
|
+
* This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
|
|
17
|
+
*/
|
|
18
|
+
const CONVERGENCE_WALL_CLOCK_MS = 60_000;
|
|
19
|
+
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.";
|
|
20
|
+
export async function dispatchInternalRun(input) {
|
|
21
|
+
const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, signal, onUpdate, runManager } = input;
|
|
22
|
+
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
23
|
+
let apiKey;
|
|
24
|
+
try {
|
|
25
|
+
apiKey = await options.resolveApiKey(config.model);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
const state = createInternalRunState(config.model, apiKey);
|
|
32
|
+
/** Wakes a retry backoff early when the run is cancelled or out of wall time. */
|
|
33
|
+
const retryBackoff = new AbortController();
|
|
34
|
+
const handle = {};
|
|
35
|
+
try {
|
|
36
|
+
await runManager.register({
|
|
37
|
+
runId: runContext.runId,
|
|
38
|
+
channelId: options.runtimeContext.channelId,
|
|
39
|
+
runtime: "internal",
|
|
40
|
+
agent: config.name,
|
|
41
|
+
label: runLabel,
|
|
42
|
+
source: config.source,
|
|
43
|
+
tools: [...config.tools],
|
|
44
|
+
model: formatModelReference(config.model),
|
|
45
|
+
purpose: runContext.purpose,
|
|
46
|
+
taskId: runContext.taskId,
|
|
47
|
+
item: runContext.item,
|
|
48
|
+
workingDirectory: runContext.workingDirectory,
|
|
49
|
+
artifactDir: runContext.artifactDir,
|
|
50
|
+
channelDir: options.channelDir,
|
|
51
|
+
leaseKey,
|
|
52
|
+
mutates: config.mutates,
|
|
53
|
+
workspaceBaseline: input.workspaceBaseline,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
// Until the durable running record exists, setup still owns the lease. A channel/host
|
|
58
|
+
// admission rejection or required persist failure must leave no invisible writer lock.
|
|
59
|
+
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
// Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
|
|
63
|
+
// creation) can yield. Without this provisional handle, a cancel in that window was treated as
|
|
64
|
+
// an unreachable run: the manager released the lease and settled it while the worker could still
|
|
65
|
+
// start writing after the supposed cancellation (especially dangerous for a write verifier).
|
|
66
|
+
runManager.registerCancelHandle(runContext.runId, () => {
|
|
67
|
+
state.externallyCancelled = true;
|
|
68
|
+
retryBackoff.abort();
|
|
69
|
+
handle.worker?.abort();
|
|
70
|
+
});
|
|
71
|
+
const emitUpdate = createUpdateEmitter({ config, runContext, state, onUpdate });
|
|
72
|
+
try {
|
|
73
|
+
startWorker({ handle, options, config, runContext, scopedExecutor, state, retryBackoff, runManager, emitUpdate });
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
await failSetup(error, handle, state, runManager, runContext);
|
|
77
|
+
}
|
|
78
|
+
const worker = handle.worker;
|
|
79
|
+
const unsubscribe = handle.unsubscribe;
|
|
80
|
+
const wallClockTimer = handle.wallClockTimer;
|
|
81
|
+
// D2: the tool call waits at most until this turn's shared grace deadline (never longer than
|
|
82
|
+
// the run's own wall clock budget) before degrading to a "still running" placeholder. It also
|
|
83
|
+
// stops waiting the moment the turn is aborted (`/stop`): the SDK awaits this call, so ignoring
|
|
84
|
+
// the signal held `/stop` until its force-end fallback — and a result that then arrived inside
|
|
85
|
+
// the grace window settled `announce: false` into a turn that no longer existed, so nobody
|
|
86
|
+
// ever saw it. The run itself keeps executing either way — only the *return* differs.
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const deadline = Math.min(graceDeadlineFor(signal, resolveSyncGraceMs(options.syncGraceMs), now), now + config.maxWallTimeSec * 1000);
|
|
89
|
+
const outcomePromise = runToCompletion({
|
|
90
|
+
options,
|
|
91
|
+
config,
|
|
92
|
+
runContext,
|
|
93
|
+
params,
|
|
94
|
+
state,
|
|
95
|
+
retryBackoff,
|
|
96
|
+
emitUpdate,
|
|
97
|
+
worker,
|
|
98
|
+
unsubscribe,
|
|
99
|
+
wallClockTimer,
|
|
100
|
+
mutatesNote,
|
|
101
|
+
workspaceBaseline: input.workspaceBaseline,
|
|
102
|
+
}).then((value) => ({ ok: true, value }), (error) => ({
|
|
103
|
+
ok: false,
|
|
104
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
105
|
+
}));
|
|
106
|
+
const abortWatch = watchAbort(signal);
|
|
107
|
+
const raceResult = await Promise.race([
|
|
108
|
+
outcomePromise,
|
|
109
|
+
sleepUnref(Math.max(0, deadline - now)).then(() => "timed-out"),
|
|
110
|
+
abortWatch.aborted,
|
|
111
|
+
]);
|
|
112
|
+
abortWatch.dispose();
|
|
113
|
+
if (raceResult !== "timed-out" && raceResult !== "aborted") {
|
|
114
|
+
runManager.clearCancelHandle(runContext.runId);
|
|
115
|
+
if (!raceResult.ok) {
|
|
116
|
+
await runManager.settle(runContext.runId, fatalSettleInput(state, raceResult.error), { announce: false });
|
|
117
|
+
throw raceResult.error;
|
|
118
|
+
}
|
|
119
|
+
await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
|
|
120
|
+
return raceResult.value.toolResult;
|
|
121
|
+
}
|
|
122
|
+
// Grace window elapsed (or the turn was stopped): hand back a placeholder now and let the run
|
|
123
|
+
// keep going in the background. It settles and, this time, announces itself with a completion
|
|
124
|
+
// wake (D2/D7) — the same "runtime guarantees completion" contract background jobs already keep.
|
|
125
|
+
state.detached = true;
|
|
126
|
+
void outcomePromise.then(async (outcome) => {
|
|
127
|
+
runManager.clearCancelHandle(runContext.runId);
|
|
128
|
+
const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(state, outcome.error);
|
|
129
|
+
await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
|
|
130
|
+
log.logWarn("subagent.settle.failed", "Detached run settlement failed", {
|
|
131
|
+
reason: errorMessage(error),
|
|
132
|
+
fields: { runId: runContext.runId },
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
content: [
|
|
138
|
+
{
|
|
139
|
+
type: "text",
|
|
140
|
+
text: mutatesNote +
|
|
141
|
+
buildDispatchedText(runContext.runId, config.name, "internal, async", runContext.workingDirectory),
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
details: createDetails({
|
|
145
|
+
config,
|
|
146
|
+
runContext,
|
|
147
|
+
usage: state.usage,
|
|
148
|
+
turns: state.assistantTurns,
|
|
149
|
+
toolCalls: state.toolCalls,
|
|
150
|
+
durationMs: Date.now() - state.startedAt,
|
|
151
|
+
dispatched: true,
|
|
152
|
+
}),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Runs the worker to completion, including the D6 convergence turn, and returns the
|
|
157
|
+
* tool result plus the data `runs.ts` needs to settle.
|
|
158
|
+
*/
|
|
159
|
+
async function runToCompletion(ctx) {
|
|
160
|
+
const { options, config, runContext, params, state, retryBackoff, emitUpdate, worker } = ctx;
|
|
161
|
+
try {
|
|
162
|
+
const contextualBlocks = await resolveContextualBlocks(config, options);
|
|
163
|
+
if (state.externallyCancelled) {
|
|
164
|
+
state.failureReason = state.failureReason || "Cancelled by request.";
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
|
|
168
|
+
await worker.waitForIdle();
|
|
169
|
+
await recoverFromProviderErrors({ worker, options, config, state, retryBackoff, emitUpdate });
|
|
170
|
+
}
|
|
171
|
+
// D6: a self-inflicted budget abort gets one tool-free turn to converge on a
|
|
172
|
+
// conclusion instead of discarding the work outright. An explicit cancel skips
|
|
173
|
+
// this — the model asked this run to stop now, not to wrap up.
|
|
174
|
+
if (state.budgetExceeded && !state.externallyCancelled) {
|
|
175
|
+
clearTimeout(ctx.wallClockTimer);
|
|
176
|
+
emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
|
|
177
|
+
const preConvergenceMessageCount = worker.state.messages.length;
|
|
178
|
+
worker.state.tools = [];
|
|
179
|
+
let convergenceTimedOut = false;
|
|
180
|
+
const convergenceTimer = setTimeout(() => {
|
|
181
|
+
convergenceTimedOut = true;
|
|
182
|
+
worker.abort();
|
|
183
|
+
}, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
|
|
184
|
+
try {
|
|
185
|
+
await worker.prompt(CONVERGENCE_PROMPT);
|
|
186
|
+
await worker.waitForIdle();
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// Best effort: fall through to whatever worker.state.messages holds.
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
clearTimeout(convergenceTimer);
|
|
193
|
+
}
|
|
194
|
+
if (convergenceTimedOut) {
|
|
195
|
+
// Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
|
|
196
|
+
// convergence turn and fall back to whatever came before it.
|
|
197
|
+
worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
ctx.unsubscribe();
|
|
203
|
+
clearTimeout(ctx.wallClockTimer);
|
|
204
|
+
}
|
|
205
|
+
return buildInternalOutcome({
|
|
206
|
+
worker,
|
|
207
|
+
config,
|
|
208
|
+
runContext,
|
|
209
|
+
state,
|
|
210
|
+
mutatesNote: ctx.mutatesNote,
|
|
211
|
+
workspaceBaseline: ctx.workspaceBaseline,
|
|
212
|
+
emitUpdate,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/** Setup threw after the run was registered: undo what was armed, settle it failed, rethrow. */
|
|
216
|
+
async function failSetup(error, handle, state, runManager, runContext) {
|
|
217
|
+
handle.unsubscribe?.();
|
|
218
|
+
if (handle.wallClockTimer)
|
|
219
|
+
clearTimeout(handle.wallClockTimer);
|
|
220
|
+
runManager.clearCancelHandle(runContext.runId);
|
|
221
|
+
try {
|
|
222
|
+
handle.worker?.abort();
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// Preserve the setup error; settlement below is the lifecycle authority.
|
|
226
|
+
}
|
|
227
|
+
const setupError = error instanceof Error ? error : new Error(String(error));
|
|
228
|
+
await runManager.settle(runContext.runId, {
|
|
229
|
+
status: "failed",
|
|
230
|
+
failureReason: setupError.message,
|
|
231
|
+
usage: state.usage,
|
|
232
|
+
usageKnown: true,
|
|
233
|
+
costKnown: true,
|
|
234
|
+
turns: state.assistantTurns,
|
|
235
|
+
toolCalls: state.toolCalls,
|
|
236
|
+
durationMs: Date.now() - state.startedAt,
|
|
237
|
+
outputText: "",
|
|
238
|
+
}, { announce: false });
|
|
239
|
+
throw setupError;
|
|
240
|
+
}
|