@xzzpig/pi-subagents 0.8.0 → 0.10.0
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/CHANGELOG.md +477 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +195 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +384 -115
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +14 -2
- package/src/agents/agents.ts +935 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +42 -21
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +77 -21
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +65 -29
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +7 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +417 -133
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +60 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +204 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +718 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +489 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1223 -402
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +364 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +366 -0
- package/src/runs/shared/child-tool-plan.ts +632 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +146 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +99 -77
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +20 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/sandbox-profile-guard.ts +85 -0
- package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +11 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/sandbox-profile.ts +23 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +545 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `
|
|
2
|
+
* `bg_wait` tool: block the current turn until outstanding async runs
|
|
3
3
|
* or a named remembered detached foreground run finishes.
|
|
4
4
|
*
|
|
5
5
|
* Background subagent runs are detached. In an interactive session the parent
|
|
@@ -8,33 +8,33 @@
|
|
|
8
8
|
* cannot work at all non-interactively (`pi -p ...`), where the run is a single
|
|
9
9
|
* turn: once the turn ends there is nothing left to receive the notification.
|
|
10
10
|
*
|
|
11
|
-
* `
|
|
11
|
+
* `bg_wait` closes that gap. It keeps the turn alive until a tracked async
|
|
12
12
|
* run for this session reaches a terminal state (complete / failed / paused),
|
|
13
13
|
* the caller-supplied timeout elapses, or the turn is aborted. Because it awaits
|
|
14
14
|
* inside the turn, the completion the model was told to wait for is actually
|
|
15
15
|
* observed before the tool returns.
|
|
16
16
|
*
|
|
17
|
-
* By default `
|
|
17
|
+
* By default `bg_wait` returns as soon as ONE run finishes, so a fleet
|
|
18
18
|
* manager can use it in a rolling-replacement loop: launch N workers, wait for
|
|
19
|
-
* the next one to finish, spawn its replacement, then call `
|
|
19
|
+
* the next one to finish, spawn its replacement, then call `bg_wait`
|
|
20
20
|
* again — keeping N in flight instead of draining to zero between batches.
|
|
21
21
|
* Pass `all: true` to block until every tracked async run is terminal, or `id`
|
|
22
22
|
* to block on one specific async or remembered detached foreground run.
|
|
23
23
|
*
|
|
24
|
-
* `
|
|
24
|
+
* `bg_wait` also returns when a run needs attention — not just on
|
|
25
25
|
* completion. A child that goes idle or blocks for a decision surfaces
|
|
26
26
|
* `needs_attention` (the same signal Pi shows as a control notice and,
|
|
27
|
-
* interactively, wakes the parent with). Since `
|
|
27
|
+
* interactively, wakes the parent with). Since `bg_wait` is used exactly
|
|
28
28
|
* where there is no next turn to receive that notice, it must break on it too,
|
|
29
29
|
* or a stuck child would stall the loop until the timeout. Attention runs are
|
|
30
30
|
* reported so the caller can inspect / nudge / resume / interrupt them.
|
|
31
31
|
*
|
|
32
|
-
* Wake mechanism: when given Pi's event bus (`deps.events`), `
|
|
32
|
+
* Wake mechanism: when given Pi's event bus (`deps.events`), `bg_wait`
|
|
33
33
|
* subscribes to the subagent completion/control channels and wakes the instant
|
|
34
34
|
* any fires, rather than waiting out a fixed poll interval. A poll still runs
|
|
35
35
|
* on the interval as a reconciliation fallback (crashed runners, missed
|
|
36
36
|
* events), and the poll is the source of truth for what actually changed — the
|
|
37
|
-
* event only ends the sleep early. With no bus, `
|
|
37
|
+
* event only ends the sleep early. With no bus, `bg_wait` degrades to pure
|
|
38
38
|
* polling.
|
|
39
39
|
*/
|
|
40
40
|
|
|
@@ -58,12 +58,15 @@ import {
|
|
|
58
58
|
type Details,
|
|
59
59
|
type ForegroundResumeRun,
|
|
60
60
|
type SubagentState,
|
|
61
|
+
type Usage,
|
|
61
62
|
type WaitCompletion,
|
|
62
63
|
} from "../../shared/types.ts";
|
|
63
64
|
import { formatDuration, shortenPath } from "../../shared/formatters.ts";
|
|
65
|
+
import { toAgentToolUsage } from "../../shared/utils.ts";
|
|
64
66
|
import { collectWaitCompletions } from "./wait-completions.ts";
|
|
65
67
|
import { formatResumeFirstFailedRunsNote } from "./resume-guidance.ts";
|
|
66
|
-
|
|
68
|
+
import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
|
|
69
|
+
export { WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV, WAIT_TOOL_ENABLED_ENV, resolveWaitToolConfig, type ResolvedWaitToolConfig } from "./wait-config.ts";
|
|
67
70
|
|
|
68
71
|
/** States that mean a run is still in flight (not yet resolved). */
|
|
69
72
|
const ACTIVE_STATES: ReadonlyArray<AsyncRunSummary["state"]> = ["queued", "running"];
|
|
@@ -79,12 +82,11 @@ export interface SubagentWaitParams {
|
|
|
79
82
|
nonBlocking?: boolean;
|
|
80
83
|
/**
|
|
81
84
|
* When true, block until EVERY active run in this session (or matching `id`)
|
|
82
|
-
* is terminal. Default false: return
|
|
83
|
-
*
|
|
84
|
-
* targets a single run.
|
|
85
|
+
* is terminal. Default false: return when the first tracked run or provider
|
|
86
|
+
* item finishes or needs attention. Ignored when `id` targets a single run.
|
|
85
87
|
*/
|
|
86
88
|
all?: boolean;
|
|
87
|
-
/** Give up after this many milliseconds. Defaults to 30 minutes. */
|
|
89
|
+
/** Give up after this many milliseconds. Defaults to waitTool.defaultTimeoutMs, then 30 minutes. */
|
|
88
90
|
timeoutMs?: number;
|
|
89
91
|
/** False keeps a blocking wait open through idle attention; supervisor/contact requests still stop the wait. */
|
|
90
92
|
stopOnAttention?: boolean;
|
|
@@ -106,6 +108,8 @@ export interface SubagentWaitDeps {
|
|
|
106
108
|
pollIntervalMs?: number;
|
|
107
109
|
/** False makes the tool return immediately without blocking active async runs. */
|
|
108
110
|
enabled?: boolean;
|
|
111
|
+
/** Configured blocking window used when the call omits timeoutMs. */
|
|
112
|
+
defaultTimeoutMs?: number;
|
|
109
113
|
/** Injectable sleep for tests. */
|
|
110
114
|
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
111
115
|
/** Internal auto-drain mode waits through needs-attention states. */
|
|
@@ -236,7 +240,7 @@ function foregroundChildrenNeedingAttention(run: ForegroundResumeRun, indices: S
|
|
|
236
240
|
function formatForegroundAttention(run: ForegroundResumeRun, children: ReturnType<typeof foregroundChildrenNeedingAttention>, elapsedMs: number): AgentToolResult<Details> {
|
|
237
241
|
const childList = children.map((child) => `${child.agent}${child.index !== undefined ? `#${child.index}` : ""}`).join(", ");
|
|
238
242
|
return result(
|
|
239
|
-
`Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call
|
|
243
|
+
`Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`,
|
|
240
244
|
);
|
|
241
245
|
}
|
|
242
246
|
|
|
@@ -257,7 +261,7 @@ function backgroundWorkIdentity(item: RegisteredBackgroundWorkItem): string {
|
|
|
257
261
|
|
|
258
262
|
function backgroundWorkForSession(deps: SubagentWaitDeps, nowMs: number): BackgroundWorkSnapshot {
|
|
259
263
|
const sessionId = deps.state.currentSessionId;
|
|
260
|
-
if (!sessionId) throw new Error("
|
|
264
|
+
if (!sessionId) throw new Error("bg_wait requires an active session identity to scope background work safely.");
|
|
261
265
|
return deps.backgroundWork?.snapshot(sessionId, nowMs) ?? snapshotBackgroundWork(sessionId, nowMs);
|
|
262
266
|
}
|
|
263
267
|
|
|
@@ -312,10 +316,31 @@ function summarizeTerminalRuns(runs: AsyncRunSummary[], providerFinishedCount =
|
|
|
312
316
|
return parts.join(", ");
|
|
313
317
|
}
|
|
314
318
|
|
|
319
|
+
function completionUsage(completions: WaitCompletion[] | undefined): Usage | undefined {
|
|
320
|
+
if (!completions?.length) return undefined;
|
|
321
|
+
const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
322
|
+
let projected = false;
|
|
323
|
+
for (const completion of completions) {
|
|
324
|
+
for (const child of completion.results ?? []) {
|
|
325
|
+
if (!child.usage || (child.usage.input === 0 && child.usage.output === 0 && child.usage.cacheRead === 0 && child.usage.cacheWrite === 0 && child.usage.cost === 0 && child.usage.turns === 0)) continue;
|
|
326
|
+
projected = true;
|
|
327
|
+
usage.input += child.usage.input;
|
|
328
|
+
usage.output += child.usage.output;
|
|
329
|
+
usage.cacheRead += child.usage.cacheRead;
|
|
330
|
+
usage.cacheWrite += child.usage.cacheWrite;
|
|
331
|
+
usage.cost += child.usage.cost;
|
|
332
|
+
usage.turns += child.usage.turns;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return projected ? usage : undefined;
|
|
336
|
+
}
|
|
337
|
+
|
|
315
338
|
function result(text: string, isError = false, completions?: WaitCompletion[]): AgentToolResult<Details> {
|
|
339
|
+
const usage = completionUsage(completions);
|
|
316
340
|
return {
|
|
317
341
|
content: [{ type: "text", text }],
|
|
318
342
|
...(isError ? { isError: true } : {}),
|
|
343
|
+
...(usage ? { usage: toAgentToolUsage(usage) } : {}),
|
|
319
344
|
details: {
|
|
320
345
|
mode: "management",
|
|
321
346
|
results: [],
|
|
@@ -324,7 +349,33 @@ function result(text: string, isError = false, completions?: WaitCompletion[]):
|
|
|
324
349
|
};
|
|
325
350
|
}
|
|
326
351
|
|
|
327
|
-
|
|
352
|
+
function formatCompletionRecovery(completions: WaitCompletion[] | undefined): string {
|
|
353
|
+
const lines = (completions ?? []).flatMap((completion) =>
|
|
354
|
+
(completion.results ?? []).flatMap((child) => formatTimeoutRecoveryLines(child.timeoutRecovery)));
|
|
355
|
+
return lines.length > 0 ? `\n${lines.join("\n")}` : "";
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function windowElapsedResult(
|
|
359
|
+
text: string,
|
|
360
|
+
activeRunIds: string[],
|
|
361
|
+
activeProviderItems: readonly RegisteredBackgroundWorkItem[] = [],
|
|
362
|
+
): AgentToolResult<Details> {
|
|
363
|
+
return {
|
|
364
|
+
content: [{ type: "text", text }],
|
|
365
|
+
details: {
|
|
366
|
+
mode: "management",
|
|
367
|
+
results: [],
|
|
368
|
+
wait: {
|
|
369
|
+
reason: "window_elapsed",
|
|
370
|
+
timedOut: true,
|
|
371
|
+
activeRunIds,
|
|
372
|
+
activeProviderItems: activeProviderItems.map(({ provider, id }) => ({ provider, id })),
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Build the live status shown while async work keeps bg_wait blocked. */
|
|
328
379
|
function asyncWaitUpdate(runs: AsyncRunSummary[], providerCount: number, elapsedMs: number): AgentToolResult<Details> {
|
|
329
380
|
const activity = runs.flatMap((run) => {
|
|
330
381
|
const activeSteps = run.steps.filter((step) => step.status === "pending" || step.status === "running");
|
|
@@ -471,9 +522,9 @@ async function waitForDetachedForegroundRun(
|
|
|
471
522
|
return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Remembered foreground run "${run.runId}" remains detached. Reply to any pending supervisor request before resuming or launching a replacement.`, true);
|
|
472
523
|
}
|
|
473
524
|
if (now() - startedAt >= timeoutMs) {
|
|
474
|
-
return
|
|
475
|
-
`Wait
|
|
476
|
-
|
|
525
|
+
return windowElapsedResult(
|
|
526
|
+
`Wait window elapsed after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`,
|
|
527
|
+
[run.runId],
|
|
477
528
|
);
|
|
478
529
|
}
|
|
479
530
|
await waitForWake(pollIntervalMs, signal, deps);
|
|
@@ -491,15 +542,17 @@ export async function waitForSubagents(
|
|
|
491
542
|
deps: SubagentWaitDeps,
|
|
492
543
|
): Promise<AgentToolResult<Details>> {
|
|
493
544
|
if (deps.enabled === false) {
|
|
494
|
-
return result("
|
|
545
|
+
return result("bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: \"status\" }) or rely on completion notifications.");
|
|
495
546
|
}
|
|
496
547
|
if (!deps.state.currentSessionId) {
|
|
497
|
-
return result("
|
|
548
|
+
return result("bg_wait requires an active session identity to scope background work safely.", true);
|
|
498
549
|
}
|
|
499
550
|
|
|
500
551
|
const now = deps.now ?? Date.now;
|
|
501
552
|
const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
|
|
502
|
-
const timeoutMs = params.timeoutMs !== undefined && params.timeoutMs > 0
|
|
553
|
+
const timeoutMs = params.timeoutMs !== undefined && params.timeoutMs > 0
|
|
554
|
+
? params.timeoutMs
|
|
555
|
+
: deps.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
503
556
|
const startedAt = now();
|
|
504
557
|
const waitForAll = params.id ? true : params.all === true;
|
|
505
558
|
if (params.nonBlocking && !params.id) {
|
|
@@ -533,7 +586,7 @@ export async function waitForSubagents(
|
|
|
533
586
|
const selected = matches[0];
|
|
534
587
|
if (selected && params.nonBlocking) {
|
|
535
588
|
if (!deps.subscribe) {
|
|
536
|
-
return result("Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking
|
|
589
|
+
return result("Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking bg_wait calls.", true);
|
|
537
590
|
}
|
|
538
591
|
try {
|
|
539
592
|
const registration = deps.subscribe({ targetKind: selected.kind, runId: selected.id, requestedId: params.id, timeoutMs });
|
|
@@ -586,9 +639,10 @@ export async function waitForSubagents(
|
|
|
586
639
|
return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Still active: ${stillActive}.`, true);
|
|
587
640
|
}
|
|
588
641
|
if (now() - startedAt >= timeoutMs) {
|
|
589
|
-
return
|
|
590
|
-
`Wait
|
|
591
|
-
|
|
642
|
+
return windowElapsedResult(
|
|
643
|
+
`Wait window elapsed after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call bg_wait again or inspect subagent status.`,
|
|
644
|
+
activeInitialRuns.map((run) => run.id),
|
|
645
|
+
activeInitialProviderItems,
|
|
592
646
|
);
|
|
593
647
|
}
|
|
594
648
|
try {
|
|
@@ -598,7 +652,7 @@ export async function waitForSubagents(
|
|
|
598
652
|
providerSnapshot = params.id ? providerSnapshot : backgroundWorkForSession(deps, now());
|
|
599
653
|
for (const provider of initialProviderNames) {
|
|
600
654
|
if (!providerSnapshot.providers.includes(provider)) {
|
|
601
|
-
return result(`Background-work provider '${provider}' disappeared while
|
|
655
|
+
return result(`Background-work provider '${provider}' disappeared while bg_wait was tracking its active work; completion cannot be confirmed.`, true);
|
|
602
656
|
}
|
|
603
657
|
}
|
|
604
658
|
providerActive = providerSnapshot.items;
|
|
@@ -618,7 +672,7 @@ export async function waitForSubagents(
|
|
|
618
672
|
const allNow = runsForIds(initialAsyncIds, deps);
|
|
619
673
|
const terminal = allNow.filter((run) => !ACTIVE_STATES.includes(run.state) && initialAsyncIds.has(run.id));
|
|
620
674
|
finishedAsyncCount = terminal.length;
|
|
621
|
-
failedAsyncCount = terminal.filter((run) => run.state === "failed").length;
|
|
675
|
+
failedAsyncCount = terminal.filter((run) => run.state === "failed" || run.state === "partial").length;
|
|
622
676
|
terminalSummary = summarizeTerminalRuns(terminal, providerFinishedCount);
|
|
623
677
|
resumeGuidance = formatResumeFirstFailedRunsNote(terminal);
|
|
624
678
|
completions = collectWaitCompletions(terminal, deps.state, deps.resultsDir ?? DIRS.results);
|
|
@@ -637,6 +691,7 @@ export async function waitForSubagents(
|
|
|
637
691
|
+ providerActive.filter((item) => initialProviderIds.has(backgroundWorkIdentity(item))).length;
|
|
638
692
|
const elapsed = formatDuration(now() - startedAt);
|
|
639
693
|
const outcome = terminalSummary ? ` Outcome: ${terminalSummary}.` : "";
|
|
694
|
+
const recoveryNote = formatCompletionRecovery(completions);
|
|
640
695
|
|
|
641
696
|
if (waitForAll) {
|
|
642
697
|
const scope = params.id
|
|
@@ -646,7 +701,7 @@ export async function waitForSubagents(
|
|
|
646
701
|
: `${initialAsyncIds.size} async run(s) and ${initialProviderIds.size} provider item(s)`;
|
|
647
702
|
const status = relevantAttention.length > 0 ? "attention required" : "done";
|
|
648
703
|
return result(
|
|
649
|
-
`Waited ${elapsed} for ${scope}; ${status}.${outcome}${resumeGuidance}${attentionNote} Completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
704
|
+
`Waited ${elapsed} for ${scope}; ${status}.${outcome}${recoveryNote}${resumeGuidance}${attentionNote} Completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
650
705
|
(deps.failOnFailedRuns === true && failedAsyncCount > 0) || (deps.failOnAttention === true && relevantAttention.length > 0),
|
|
651
706
|
completions,
|
|
652
707
|
);
|
|
@@ -655,7 +710,7 @@ export async function waitForSubagents(
|
|
|
655
710
|
const finishedCount = finishedAsyncCount + providerFinishedCount;
|
|
656
711
|
const subject = initialProviderIds.size === 0 ? "run(s)" : "item(s)";
|
|
657
712
|
const remainder = stillRunning > 0
|
|
658
|
-
? ` ${stillRunning} ${subject} still in flight — call
|
|
713
|
+
? ` ${stillRunning} ${subject} still in flight — call bg_wait again to catch the next one.`
|
|
659
714
|
: relevantAttention.length > 0
|
|
660
715
|
? " No other work is waitable until attention is handled."
|
|
661
716
|
: initialProviderIds.size === 0 ? " No runs remain in flight." : " No work remains in flight.";
|
|
@@ -663,7 +718,7 @@ export async function waitForSubagents(
|
|
|
663
718
|
? `${relevantAttention.length} of ${initialCount} ${subject} need attention`
|
|
664
719
|
: `${finishedCount} of ${initialCount} ${subject} finished`;
|
|
665
720
|
return result(
|
|
666
|
-
`Waited ${elapsed}; ${progress}.${outcome}${resumeGuidance}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
721
|
+
`Waited ${elapsed}; ${progress}.${outcome}${recoveryNote}${resumeGuidance}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
667
722
|
(deps.failOnFailedRuns === true && failedAsyncCount > 0) || (deps.failOnAttention === true && relevantAttention.length > 0),
|
|
668
723
|
completions,
|
|
669
724
|
);
|
|
@@ -18,7 +18,7 @@ interface TerminalRunIndexEntry {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
function isTerminalState(state: AsyncStatus["state"]): boolean {
|
|
21
|
-
return state === "complete" || state === "failed" || state === "paused" || state === "stopped" || state === "rejected";
|
|
21
|
+
return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped" || state === "rejected";
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
function indexRoot(asyncDirRoot: string): string {
|
|
@@ -1,13 +1,32 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
-
import type { ArtifactPaths, SubagentState, WaitCompletion, WaitCompletionChild } from "../../shared/types.ts";
|
|
2
|
+
import type { ArtifactPaths, SubagentState, Usage, WaitCompletion, WaitCompletionChild } from "../../shared/types.ts";
|
|
3
3
|
import type { AsyncRunSummary } from "./async-status.ts";
|
|
4
4
|
import { readCompletionReplay, writeCompletionReplay } from "./completion-replay.ts";
|
|
5
5
|
import { fallbackResultPayloadPathForSessionRun, resultFilePath, resultPayloadPathForSessionRun } from "./result-files.ts";
|
|
6
|
+
import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
|
|
7
|
+
import { projectTimeoutRecovery } from "../shared/mutation-evidence.ts";
|
|
6
8
|
|
|
7
9
|
function asNonEmptyString(value: unknown): string | undefined {
|
|
8
10
|
return typeof value === "string" && value ? value : undefined;
|
|
9
11
|
}
|
|
10
12
|
|
|
13
|
+
function nonNegativeNumber(value: unknown): number | undefined {
|
|
14
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function projectedUsage(value: unknown): Usage | undefined {
|
|
18
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
19
|
+
const record = value as Record<string, unknown>;
|
|
20
|
+
const input = nonNegativeNumber(record.input);
|
|
21
|
+
const output = nonNegativeNumber(record.output);
|
|
22
|
+
const cacheRead = nonNegativeNumber(record.cacheRead);
|
|
23
|
+
const cacheWrite = nonNegativeNumber(record.cacheWrite);
|
|
24
|
+
const cost = nonNegativeNumber(record.cost);
|
|
25
|
+
const turns = nonNegativeNumber(record.turns);
|
|
26
|
+
if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined || cost === undefined || turns === undefined || !Number.isSafeInteger(turns)) return undefined;
|
|
27
|
+
return { input, output, cacheRead, cacheWrite, cost, turns };
|
|
28
|
+
}
|
|
29
|
+
|
|
11
30
|
function errorCode(error: unknown): string | undefined {
|
|
12
31
|
return typeof error === "object" && error !== null && "code" in error
|
|
13
32
|
? (error as NodeJS.ErrnoException).code
|
|
@@ -23,6 +42,15 @@ function errorMessage(error: unknown): string {
|
|
|
23
42
|
return error instanceof Error ? error.message : String(error);
|
|
24
43
|
}
|
|
25
44
|
|
|
45
|
+
const STRUCTURED_OUTPUT_INLINE_LIMIT_BYTES = 4 * 1024;
|
|
46
|
+
|
|
47
|
+
export function projectStructuredOutput(value: unknown): unknown {
|
|
48
|
+
if (value === undefined) return undefined;
|
|
49
|
+
const serialized = JSON.stringify(value);
|
|
50
|
+
if (typeof serialized !== "string") throw new Error("Structured output must be JSON-serializable");
|
|
51
|
+
return Buffer.byteLength(serialized, "utf8") <= STRUCTURED_OUTPUT_INLINE_LIMIT_BYTES ? JSON.parse(serialized) : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
26
54
|
/**
|
|
27
55
|
* Project a terminal result payload into the slim shape that is safe to surface in
|
|
28
56
|
* tool_result details: run identity, per-child outcome, and the artifact trail.
|
|
@@ -42,24 +70,36 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
|
|
|
42
70
|
: undefined;
|
|
43
71
|
const agent = asNonEmptyString(child.agent);
|
|
44
72
|
const childRunId = asNonEmptyString(child.runId);
|
|
73
|
+
const usage = projectedUsage(child.usage);
|
|
74
|
+
const sessionFile = asNonEmptyString(child.sessionFile);
|
|
45
75
|
const error = asNonEmptyString(child.error);
|
|
46
76
|
const model = asNonEmptyString(child.model);
|
|
77
|
+
const structuredOutput = projectStructuredOutput(child.structuredOutput);
|
|
78
|
+
const structuredOutputPath = asNonEmptyString(child.structuredOutputPath);
|
|
47
79
|
const contextOverflow = child.contextOverflow === true;
|
|
80
|
+
const timeoutRecovery = projectTimeoutRecovery(child.timeoutRecovery);
|
|
48
81
|
return [{
|
|
49
82
|
...(agent ? { agent } : {}),
|
|
50
83
|
...(childRunId ? { runId: childRunId } : {}),
|
|
84
|
+
...(usage ? { usage } : {}),
|
|
85
|
+
...(sessionFile ? { sessionFile } : {}),
|
|
51
86
|
...(typeof child.success === "boolean" ? { success: child.success } : {}),
|
|
52
87
|
...(outputState ? { outputState } : {}),
|
|
88
|
+
...(structuredOutput !== undefined ? { structuredOutput } : {}),
|
|
89
|
+
...(structuredOutputPath ? { structuredOutputPath } : {}),
|
|
53
90
|
...(error ? { error } : {}),
|
|
54
91
|
...(model ? { model } : {}),
|
|
55
92
|
...(contextOverflow ? { contextOverflow: true } : {}),
|
|
56
93
|
...(artifactPaths ? { artifactPaths } : {}),
|
|
94
|
+
...(timeoutRecovery ? { timeoutRecovery } : {}),
|
|
57
95
|
}];
|
|
58
96
|
})
|
|
59
97
|
: undefined;
|
|
60
98
|
const agent = asNonEmptyString(data.agent);
|
|
61
99
|
const mode = asNonEmptyString(data.mode);
|
|
62
100
|
const state = asNonEmptyString(data.state);
|
|
101
|
+
const workflowChildren = parseWorkflowChildSummary(data.workflowChildren);
|
|
102
|
+
if (workflowChildren && workflowChildren.workflowRunId !== runId) throw new Error("workflowChildren.workflowRunId does not match its completion run id.");
|
|
63
103
|
return {
|
|
64
104
|
runId,
|
|
65
105
|
...(agent ? { agent } : {}),
|
|
@@ -67,11 +107,12 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
|
|
|
67
107
|
...(state ? { state } : {}),
|
|
68
108
|
...(typeof data.success === "boolean" ? { success: data.success } : {}),
|
|
69
109
|
...(results && results.length > 0 ? { results } : {}),
|
|
110
|
+
...(workflowChildren ? { workflowChildren } : {}),
|
|
70
111
|
};
|
|
71
112
|
}
|
|
72
113
|
|
|
73
114
|
/**
|
|
74
|
-
* Record a consumed terminal payload for later surfacing by
|
|
115
|
+
* Record a consumed terminal payload for later surfacing by bg_wait, pruning
|
|
75
116
|
* stale entries with the same TTL that dedupes completion notifications. The result
|
|
76
117
|
* file is deleted after delivery, so this record is the only in-process source once
|
|
77
118
|
* the watcher has consumed it.
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { WaitToolConfig } from "../../shared/types.ts";
|
|
2
2
|
|
|
3
3
|
export const WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
|
|
4
|
+
export const WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV = "PI_SUBAGENT_WAIT_TOOL_DEFAULT_TIMEOUT_MS";
|
|
4
5
|
|
|
5
6
|
export interface ResolvedWaitToolConfig {
|
|
6
7
|
enabled: boolean;
|
|
8
|
+
defaultTimeoutMs?: number;
|
|
7
9
|
}
|
|
8
10
|
|
|
9
11
|
const TRUE_VALUES = new Set(["1", "true", "yes", "on", "enabled"]);
|
|
@@ -17,20 +19,32 @@ function environmentValue(value: string | undefined): boolean | undefined {
|
|
|
17
19
|
throw new Error(`${WAIT_TOOL_ENABLED_ENV} must be one of true/false, 1/0, yes/no, on/off, or enabled/disabled.`);
|
|
18
20
|
}
|
|
19
21
|
|
|
20
|
-
function
|
|
21
|
-
if (
|
|
22
|
-
|
|
22
|
+
function environmentDefaultTimeoutMs(value: string | undefined): number | undefined {
|
|
23
|
+
if (value === undefined) return undefined;
|
|
24
|
+
const parsed = Number(value);
|
|
25
|
+
if (!Number.isInteger(parsed) || parsed < 1) throw new Error(`${WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV} must be a positive integer.`);
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function configuredValue(config: unknown): { enabled?: boolean; defaultTimeoutMs?: number } {
|
|
30
|
+
if (config === undefined) return {};
|
|
31
|
+
if (typeof config === "boolean") return { enabled: config };
|
|
23
32
|
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
24
|
-
throw new Error("config.waitTool must be a boolean or an object with optional enabled
|
|
33
|
+
throw new Error("config.waitTool must be a boolean or an object with optional enabled and defaultTimeoutMs values.");
|
|
34
|
+
}
|
|
35
|
+
const { enabled, defaultTimeoutMs } = config as { enabled?: unknown; defaultTimeoutMs?: unknown };
|
|
36
|
+
if (enabled !== undefined && typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
|
|
37
|
+
if (defaultTimeoutMs !== undefined && (!Number.isInteger(defaultTimeoutMs) || (defaultTimeoutMs as number) < 1)) {
|
|
38
|
+
throw new Error("config.waitTool.defaultTimeoutMs must be a positive integer.");
|
|
25
39
|
}
|
|
26
|
-
|
|
27
|
-
if (enabled === undefined) return undefined;
|
|
28
|
-
if (typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
|
|
29
|
-
return enabled;
|
|
40
|
+
return { enabled, ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs: defaultTimeoutMs as number } : {}) };
|
|
30
41
|
}
|
|
31
42
|
|
|
32
43
|
export function resolveWaitToolConfig(config?: WaitToolConfig, env: Record<string, string | undefined> = process.env): ResolvedWaitToolConfig {
|
|
44
|
+
const configured = configuredValue(config);
|
|
45
|
+
const envDefaultTimeoutMs = environmentDefaultTimeoutMs(env[WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV]);
|
|
33
46
|
return {
|
|
34
|
-
enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ??
|
|
47
|
+
enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configured.enabled ?? true,
|
|
48
|
+
...(envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {}),
|
|
35
49
|
};
|
|
36
50
|
}
|
|
@@ -5,32 +5,39 @@ import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
|
|
|
5
5
|
import type { WaitSubscriptionManager } from "./wait-subscriptions.ts";
|
|
6
6
|
import { finalizeToolResult } from "../../extension/tool-result.ts";
|
|
7
7
|
|
|
8
|
-
export function registerWaitTool(
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
export function registerWaitTool(
|
|
9
|
+
pi: ExtensionAPI,
|
|
10
|
+
state: SubagentState,
|
|
11
|
+
enabled = resolveWaitToolConfig().enabled,
|
|
12
|
+
subscriptions?: Pick<WaitSubscriptionManager, "arm">,
|
|
13
|
+
defaultTimeoutMs?: number,
|
|
14
|
+
): void {
|
|
15
|
+
const description = `Wait for background, provider, or detached work that has no native completion notification, then return.
|
|
13
16
|
|
|
14
|
-
|
|
17
|
+
Ordinary async subagent runs already notify this session natively when they complete or need attention. In an interactive chat, return control instead of calling this merely to wait. Use this tool for provider jobs, remembered detached foreground runs, or other background work without a native notification path. Headless runs auto-drain current-session subagent work at agent_end; use this tool only when the current turn must receive non-notifying background work results.
|
|
15
18
|
|
|
16
19
|
• { } — return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
|
|
17
20
|
• { all: true } — wait for every async run and provider item that was active when the call began.
|
|
18
21
|
• { id: "..." } — wait for one async or remembered detached foreground subagent run (id or prefix).
|
|
19
|
-
• { id: "...", nonBlocking: true } — resolve the prefix once, persist an exact-run wake subscription, and return immediately.
|
|
22
|
+
• { id: "...", nonBlocking: true } — resolve the prefix once, persist an exact-run wake subscription, and return immediately. Use this for detached work without native completion delivery; the originating interactive session wakes on completion, failure, attention, reconciliation failure, or timeout.
|
|
20
23
|
• { stopOnAttention: false } — for blocking waits only, keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.
|
|
21
|
-
• { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running.
|
|
24
|
+
• { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running. Omitted values use waitTool.defaultTimeoutMs, then 30 minutes. Window expiry returns a non-error window_elapsed result with active work identities.
|
|
22
25
|
|
|
23
|
-
Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`
|
|
26
|
+
Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`bg_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : "\n\nConfigured behavior: bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`;
|
|
27
|
+
const execute: ToolDefinition<typeof SubagentWaitParams, Details>["execute"] = async (_id, params, signal, onUpdate, ctx) => finalizeToolResult(await waitForSubagents(params, signal, {
|
|
28
|
+
state,
|
|
29
|
+
events: pi.events,
|
|
30
|
+
enabled,
|
|
31
|
+
...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
|
|
32
|
+
onUpdate,
|
|
33
|
+
...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
|
|
34
|
+
}));
|
|
35
|
+
const primaryTool: ToolDefinition<typeof SubagentWaitParams, Details> = {
|
|
36
|
+
name: "bg_wait",
|
|
37
|
+
label: "Background Wait",
|
|
38
|
+
description,
|
|
24
39
|
parameters: SubagentWaitParams,
|
|
25
|
-
|
|
26
|
-
return finalizeToolResult(await waitForSubagents(params, signal, {
|
|
27
|
-
state,
|
|
28
|
-
events: pi.events,
|
|
29
|
-
enabled,
|
|
30
|
-
onUpdate,
|
|
31
|
-
...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
|
|
32
|
-
}));
|
|
33
|
-
},
|
|
40
|
+
execute,
|
|
34
41
|
};
|
|
35
|
-
pi.registerTool(
|
|
42
|
+
pi.registerTool(primaryTool);
|
|
36
43
|
}
|
|
@@ -3,9 +3,9 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
5
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
6
|
-
import type { AsyncStatus, Details, SubagentState, ToolBudgetConfig
|
|
6
|
+
import type { AsyncStatus, Details, SubagentState, ToolBudgetConfig } from "../../shared/types.ts";
|
|
7
7
|
import { readStatus } from "../../shared/utils.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { deliverInterruptRequest, queueRevivalBrief, requestAsyncSteer, type SteerDeliveryMode, type SteerRequest } from "../background/control-channel.ts";
|
|
9
9
|
import { resolveAsyncResumeTarget } from "../background/async-resume.ts";
|
|
10
10
|
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
11
11
|
import { actionResultFromSteeringStatus, claimSteeringRecovery, createSteeringStatus, recordSteeringRequest, remainingSteeringRecoveryLimits, steeringReceipt, updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
|
|
@@ -34,7 +34,7 @@ export async function steerAsyncRun(input: {
|
|
|
34
34
|
onRequestQueued?: (requestPath: string) => void;
|
|
35
35
|
onBeforeRecoveryClaim?: (requestId: string, committedAt: number) => void;
|
|
36
36
|
onRecoveryCommitted?: (requestId: string, committedAt: number) => void;
|
|
37
|
-
recover?: (limits: { timeoutMs?: number; absoluteDeadlineAt?: number;
|
|
37
|
+
recover?: (limits: { timeoutMs?: number; absoluteDeadlineAt?: number; toolBudget?: ToolBudgetConfig }) => Promise<AgentToolResult<Details>>;
|
|
38
38
|
}): Promise<AgentToolResult<Details>> {
|
|
39
39
|
if (!input.location.asyncDir) {
|
|
40
40
|
return {
|
|
@@ -195,22 +195,6 @@ export async function steerAsyncRun(input: {
|
|
|
195
195
|
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
|
196
196
|
}
|
|
197
197
|
if (!paused) throw new Error("Source run did not reach confirmed paused state within 15 seconds; no replacement was launched and the recovery claim remains committed to prevent a delayed duplicate.");
|
|
198
|
-
let lateAckRecorded = false;
|
|
199
|
-
for (const ack of consumeSteerAcks(asyncDir)) {
|
|
200
|
-
if (!paused.steering?.recent.some((request) => request.id === ack.requestId && request.targets.some((target) => target.index === ack.index))) continue;
|
|
201
|
-
const state = ack.state === "delivered" ? "late" : "failed";
|
|
202
|
-
const reason = ack.state === "delivered" ? "acknowledged after recovery commit" : ack.message;
|
|
203
|
-
updateSteeringTarget(paused.steering, ack.requestId, ack.index, state, ack.ts, { reason });
|
|
204
|
-
const stepSteering = paused.steps?.[ack.index]?.steering;
|
|
205
|
-
if (stepSteering) updateSteeringTarget(stepSteering, ack.requestId, ack.index, state, ack.ts, { reason });
|
|
206
|
-
lateAckRecorded = true;
|
|
207
|
-
try {
|
|
208
|
-
fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: ack.state === "delivered" ? "subagent.steer.delivered" : "subagent.steer.failed", ts: ack.ts, runId: status.runId, requestId: ack.requestId, index: ack.index, late: true, message: ack.message })}\n`);
|
|
209
|
-
} catch {
|
|
210
|
-
// Status remains authoritative when diagnostic event persistence fails.
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
if (lateAckRecorded) writeAtomicJson(path.join(asyncDir, "status.json"), paused);
|
|
214
198
|
let recoveryTarget;
|
|
215
199
|
try {
|
|
216
200
|
recoveryTarget = resolveAsyncResumeTarget(
|