pi-subagents 0.34.0 → 0.35.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 +78 -9
- package/README.md +213 -32
- package/index.ts +1 -0
- package/install.mjs +1 -1
- package/package.json +23 -8
- package/prompts/review-loop.md +3 -1
- package/skills/pi-subagents/SKILL.md +87 -25
- package/src/agents/agent-management.ts +82 -15
- package/src/agents/agent-serializer.ts +19 -0
- package/src/agents/agents.ts +91 -49
- package/src/agents/frontmatter.ts +67 -13
- package/src/agents/skills.ts +25 -12
- package/src/api/background-work.ts +197 -0
- package/src/api/delegation.ts +158 -0
- package/src/extension/chain-validation.ts +165 -0
- package/src/extension/doctor.ts +15 -0
- package/src/extension/fanout-child.ts +3 -1
- package/src/extension/index.ts +65 -124
- package/src/extension/rpc.ts +10 -2
- package/src/extension/schemas.ts +18 -14
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +20 -9
- package/src/intercom/intercom-bridge.ts +3 -2
- package/src/intercom/native-supervisor-channel.ts +9 -1
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/async-execution.ts +293 -44
- package/src/runs/background/async-job-tracker.ts +56 -9
- package/src/runs/background/async-resume.ts +159 -52
- package/src/runs/background/async-status.ts +25 -18
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-root-attachment.ts +16 -8
- package/src/runs/background/control-channel.ts +260 -13
- package/src/runs/background/fleet-view.ts +23 -2
- package/src/runs/background/notify.ts +79 -10
- package/src/runs/background/result-watcher.ts +12 -9
- package/src/runs/background/run-id-resolver.ts +14 -2
- package/src/runs/background/run-status.ts +23 -15
- package/src/runs/background/scheduled-runs.ts +3 -0
- package/src/runs/background/stale-run-reconciler.ts +32 -10
- package/src/runs/background/steering.ts +237 -0
- package/src/runs/background/subagent-runner.ts +898 -236
- package/src/runs/background/subagent-wait.ts +484 -0
- package/src/runs/background/top-level-async.ts +2 -1
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-tool.ts +26 -0
- package/src/runs/foreground/async-steering-action.ts +230 -0
- package/src/runs/foreground/chain-clarify.ts +22 -6
- package/src/runs/foreground/chain-execution.ts +50 -32
- package/src/runs/foreground/execution.ts +308 -94
- package/src/runs/foreground/subagent-executor.ts +592 -268
- package/src/runs/shared/acceptance.ts +355 -97
- package/src/runs/shared/child-protocol.ts +121 -0
- package/src/runs/shared/completion-guard.ts +8 -127
- package/src/runs/shared/dynamic-fanout.ts +6 -4
- package/src/runs/shared/model-fallback.ts +36 -0
- package/src/runs/shared/nested-events.ts +9 -4
- package/src/runs/shared/nested-render.ts +4 -1
- package/src/runs/shared/parallel-utils.ts +7 -0
- package/src/runs/shared/pi-args.ts +34 -7
- package/src/runs/shared/pi-spawn.ts +18 -12
- package/src/runs/shared/session-lease.ts +279 -0
- package/src/runs/shared/single-output.ts +61 -6
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/subagent-control.ts +10 -6
- package/src/runs/shared/subagent-prompt-runtime.ts +127 -26
- package/src/runs/shared/task-intent.ts +176 -0
- package/src/runs/shared/tool-availability.ts +65 -0
- package/src/runs/shared/turn-budget.ts +49 -4
- package/src/shared/atomic-json.ts +4 -1
- package/src/shared/fork-context.ts +28 -3
- package/src/shared/model-info.ts +7 -4
- package/src/shared/status-format.ts +7 -1
- package/src/shared/types.ts +203 -25
- package/src/shared/utils.ts +35 -7
- package/src/slash/delegation-adapters.ts +457 -0
- package/src/slash/delegation-request.ts +103 -0
- package/src/slash/prompt-template-bridge.ts +167 -344
- package/src/slash/slash-commands.ts +239 -6
- package/src/slash/subagents-admin.ts +428 -0
- package/src/slash/subagents-editor.ts +86 -0
- package/src/tui/fleet.ts +405 -0
- package/src/tui/render.ts +90 -16
- package/src/watchdog/change-signature.ts +127 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +532 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +433 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +293 -0
- package/src/watchdog/runtime.ts +712 -0
- package/src/watchdog/settings.ts +528 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +188 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/runs/background/wait.ts +0 -394
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `subagent_wait` tool: block the current turn until outstanding async runs
|
|
3
|
+
* or a named remembered detached foreground run finishes.
|
|
4
|
+
*
|
|
5
|
+
* Background subagent runs are detached. In an interactive session the parent
|
|
6
|
+
* can end its turn and Pi will wake it with a completion notification. That
|
|
7
|
+
* does not work when the parent is a skill that must run to completion, and it
|
|
8
|
+
* cannot work at all non-interactively (`pi -p ...`), where the run is a single
|
|
9
|
+
* turn: once the turn ends there is nothing left to receive the notification.
|
|
10
|
+
*
|
|
11
|
+
* `subagent_wait` closes that gap. It keeps the turn alive until a tracked async
|
|
12
|
+
* run for this session reaches a terminal state (complete / failed / paused),
|
|
13
|
+
* the caller-supplied timeout elapses, or the turn is aborted. Because it awaits
|
|
14
|
+
* inside the turn, the completion the model was told to wait for is actually
|
|
15
|
+
* observed before the tool returns.
|
|
16
|
+
*
|
|
17
|
+
* By default `subagent_wait` returns as soon as ONE run finishes, so a fleet
|
|
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 `subagent_wait`
|
|
20
|
+
* again — keeping N in flight instead of draining to zero between batches.
|
|
21
|
+
* Pass `all: true` to block until every tracked async run is terminal, or `id`
|
|
22
|
+
* to block on one specific async or remembered detached foreground run.
|
|
23
|
+
*
|
|
24
|
+
* `subagent_wait` also returns when a run needs attention — not just on
|
|
25
|
+
* completion. A child that goes idle or blocks for a decision surfaces
|
|
26
|
+
* `needs_attention` (the same signal Pi shows as a control notice and,
|
|
27
|
+
* interactively, wakes the parent with). Since `subagent_wait` is used exactly
|
|
28
|
+
* where there is no next turn to receive that notice, it must break on it too,
|
|
29
|
+
* or a stuck child would stall the loop until the timeout. Attention runs are
|
|
30
|
+
* reported so the caller can inspect / nudge / resume / interrupt them.
|
|
31
|
+
*
|
|
32
|
+
* Wake mechanism: when given Pi's event bus (`deps.events`), `subagent_wait`
|
|
33
|
+
* subscribes to the subagent completion/control channels and wakes the instant
|
|
34
|
+
* any fires, rather than waiting out a fixed poll interval. A poll still runs
|
|
35
|
+
* on the interval as a reconciliation fallback (crashed runners, missed
|
|
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, `subagent_wait` degrades to pure
|
|
38
|
+
* polling.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
42
|
+
import {
|
|
43
|
+
listBackgroundWorkWakeChannels,
|
|
44
|
+
snapshotBackgroundWork,
|
|
45
|
+
type BackgroundWorkSnapshot,
|
|
46
|
+
type RegisteredBackgroundWorkItem,
|
|
47
|
+
} from "../../api/background-work.ts";
|
|
48
|
+
import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
|
|
49
|
+
import {
|
|
50
|
+
ASYNC_DIR,
|
|
51
|
+
RESULTS_DIR,
|
|
52
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
53
|
+
SUBAGENT_FOREGROUND_COMPLETE_EVENT,
|
|
54
|
+
SUBAGENT_CONTROL_EVENT,
|
|
55
|
+
SUBAGENT_CONTROL_INTERCOM_EVENT,
|
|
56
|
+
SUBAGENT_RESULT_INTERCOM_EVENT,
|
|
57
|
+
type Details,
|
|
58
|
+
type ForegroundResumeRun,
|
|
59
|
+
type SubagentState,
|
|
60
|
+
} from "../../shared/types.ts";
|
|
61
|
+
import { formatDuration } from "../../shared/formatters.ts";
|
|
62
|
+
export { WAIT_TOOL_ENABLED_ENV, resolveWaitToolConfig, type ResolvedWaitToolConfig } from "./wait-config.ts";
|
|
63
|
+
|
|
64
|
+
/** States that mean a run is still in flight (not yet resolved). */
|
|
65
|
+
const ACTIVE_STATES: ReadonlyArray<AsyncRunSummary["state"]> = ["queued", "running"];
|
|
66
|
+
|
|
67
|
+
const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
|
|
68
|
+
const MIN_POLL_INTERVAL_MS = 250;
|
|
69
|
+
const DEFAULT_POLL_INTERVAL_MS = 1000;
|
|
70
|
+
|
|
71
|
+
export interface SubagentWaitParams {
|
|
72
|
+
/** Optional run id/prefix to wait for. When omitted, waits across every active run in this session. */
|
|
73
|
+
id?: string;
|
|
74
|
+
/**
|
|
75
|
+
* When true, block until EVERY active run in this session (or matching `id`)
|
|
76
|
+
* is terminal. Default false: return as soon as the first run finishes, so a
|
|
77
|
+
* fleet manager can spawn a replacement and wait again. Ignored when `id`
|
|
78
|
+
* targets a single run.
|
|
79
|
+
*/
|
|
80
|
+
all?: boolean;
|
|
81
|
+
/** Give up after this many milliseconds. Defaults to 30 minutes. */
|
|
82
|
+
timeoutMs?: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Minimal event-bus surface wait subscribes to (matches pi.events). */
|
|
86
|
+
export interface WaitEventBus {
|
|
87
|
+
on(channel: string, handler: (data: unknown) => void): () => void;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface SubagentWaitDeps {
|
|
91
|
+
state: SubagentState;
|
|
92
|
+
asyncDirRoot?: string;
|
|
93
|
+
resultsDir?: string;
|
|
94
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
95
|
+
now?: () => number;
|
|
96
|
+
pollIntervalMs?: number;
|
|
97
|
+
/** False makes the tool return immediately without blocking active async runs. */
|
|
98
|
+
enabled?: boolean;
|
|
99
|
+
/** Injectable sleep for tests. */
|
|
100
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
101
|
+
/** Internal auto-drain mode waits through needs-attention states. */
|
|
102
|
+
stopOnAttention?: boolean;
|
|
103
|
+
/** Internal auto-drain mode surfaces failed terminal subagent runs as errors. */
|
|
104
|
+
failOnFailedRuns?: boolean;
|
|
105
|
+
/** Injectable provider protocol surfaces for deterministic tests. */
|
|
106
|
+
backgroundWork?: {
|
|
107
|
+
snapshot(sessionId: string, nowMs: number): BackgroundWorkSnapshot;
|
|
108
|
+
wakeChannels(): readonly string[];
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Optional event bus (pi.events). When provided, wait wakes immediately on a
|
|
112
|
+
* subagent completion/control event instead of waiting out the poll interval;
|
|
113
|
+
* the poll then remains as a reconciliation fallback (crashed runners, missed
|
|
114
|
+
* events). Omit in tests that want pure poll behavior.
|
|
115
|
+
*/
|
|
116
|
+
events?: WaitEventBus;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Bus channels that indicate a run changed state or needs attention. */
|
|
120
|
+
const WAKE_CHANNELS = [
|
|
121
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
122
|
+
SUBAGENT_FOREGROUND_COMPLETE_EVENT,
|
|
123
|
+
SUBAGENT_CONTROL_EVENT,
|
|
124
|
+
SUBAGENT_CONTROL_INTERCOM_EVENT,
|
|
125
|
+
SUBAGENT_RESULT_INTERCOM_EVENT,
|
|
126
|
+
];
|
|
127
|
+
|
|
128
|
+
function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
if (signal?.aborted) {
|
|
131
|
+
resolve();
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const timer = setTimeout(() => {
|
|
135
|
+
signal?.removeEventListener("abort", onAbort);
|
|
136
|
+
resolve();
|
|
137
|
+
}, ms);
|
|
138
|
+
const onAbort = () => {
|
|
139
|
+
clearTimeout(timer);
|
|
140
|
+
resolve();
|
|
141
|
+
};
|
|
142
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Sleep up to `ms`, but wake early if a subagent event fires on the bus (or the
|
|
148
|
+
* turn aborts). Returns when the first of those happens. With no bus this is a
|
|
149
|
+
* plain sleep, so the poll interval alone drives progress.
|
|
150
|
+
*/
|
|
151
|
+
function waitForWake(ms: number, signal: AbortSignal | undefined, deps: SubagentWaitDeps): Promise<void> {
|
|
152
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
153
|
+
const events = deps.events;
|
|
154
|
+
if (!events) return sleep(ms, signal);
|
|
155
|
+
const providerChannels = deps.backgroundWork?.wakeChannels() ?? listBackgroundWorkWakeChannels();
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
let settled = false;
|
|
158
|
+
const unsubs: Array<() => void> = [];
|
|
159
|
+
const wakeController = new AbortController();
|
|
160
|
+
const done = () => {
|
|
161
|
+
if (settled) return;
|
|
162
|
+
settled = true;
|
|
163
|
+
wakeController.abort();
|
|
164
|
+
signal?.removeEventListener("abort", done);
|
|
165
|
+
for (const u of unsubs) {
|
|
166
|
+
try { u(); } catch { /* best effort */ }
|
|
167
|
+
}
|
|
168
|
+
resolve();
|
|
169
|
+
};
|
|
170
|
+
if (signal?.aborted) {
|
|
171
|
+
done();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
175
|
+
try {
|
|
176
|
+
for (const channel of [...new Set([...WAKE_CHANNELS, ...providerChannels])]) {
|
|
177
|
+
unsubs.push(events.on(channel, done));
|
|
178
|
+
}
|
|
179
|
+
} catch (error) {
|
|
180
|
+
signal?.removeEventListener("abort", done);
|
|
181
|
+
for (const unsubscribe of unsubs) {
|
|
182
|
+
try { unsubscribe(); } catch { /* best effort cleanup */ }
|
|
183
|
+
}
|
|
184
|
+
reject(error);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
// Poll-interval fallback so we still reconcile even if no event arrives.
|
|
188
|
+
// The local signal cancels that fallback timer when an event wakes us first.
|
|
189
|
+
void sleep(ms, wakeController.signal).then(done);
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function matchesId(run: AsyncRunSummary, id: string): boolean {
|
|
194
|
+
return run.id === id || run.id.startsWith(id);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function activeDetachedForegroundRuns(params: SubagentWaitParams, deps: SubagentWaitDeps): ForegroundResumeRun[] {
|
|
198
|
+
if (!params.id || !deps.state.foregroundRuns) return [];
|
|
199
|
+
const sessionId = deps.state.currentSessionId;
|
|
200
|
+
if (!sessionId) return [];
|
|
201
|
+
return [...deps.state.foregroundRuns.values()].filter((run) =>
|
|
202
|
+
(run.runId === params.id || run.runId.startsWith(params.id!))
|
|
203
|
+
&& run.sessionId === sessionId
|
|
204
|
+
&& run.children.some((child) => child.status === "detached")
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function summarizeForegroundChildren(run: ForegroundResumeRun, indices: Set<number>): string {
|
|
209
|
+
const counts = new Map<string, number>();
|
|
210
|
+
for (const child of run.children) {
|
|
211
|
+
if (!indices.has(child.index) || child.status === "detached") continue;
|
|
212
|
+
counts.set(child.status, (counts.get(child.status) ?? 0) + 1);
|
|
213
|
+
}
|
|
214
|
+
return [...counts.entries()].map(([status, count]) => `${count} ${status}`).join(", ");
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A running run that has flagged it needs the parent's attention. */
|
|
218
|
+
function needsAttention(run: AsyncRunSummary): boolean {
|
|
219
|
+
return run.activityState === "needs_attention";
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function backgroundWorkIdentity(item: RegisteredBackgroundWorkItem): string {
|
|
223
|
+
return `${item.provider}\0${item.sessionId}\0${item.id}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function backgroundWorkForSession(deps: SubagentWaitDeps, nowMs: number): BackgroundWorkSnapshot {
|
|
227
|
+
const sessionId = deps.state.currentSessionId;
|
|
228
|
+
if (!sessionId) throw new Error("subagent_wait requires an active session identity to scope background work safely.");
|
|
229
|
+
return deps.backgroundWork?.snapshot(sessionId, nowMs) ?? snapshotBackgroundWork(sessionId, nowMs);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Queued/running runs from this session, including runs that need attention. */
|
|
233
|
+
function activeRunsForSession(params: SubagentWaitParams, deps: SubagentWaitDeps): AsyncRunSummary[] {
|
|
234
|
+
const asyncDirRoot = deps.asyncDirRoot ?? ASYNC_DIR;
|
|
235
|
+
const resultsDir = deps.resultsDir ?? RESULTS_DIR;
|
|
236
|
+
const runs = listAsyncRuns(asyncDirRoot, {
|
|
237
|
+
states: [...ACTIVE_STATES],
|
|
238
|
+
sessionId: deps.state.currentSessionId ?? undefined,
|
|
239
|
+
resultsDir,
|
|
240
|
+
kill: deps.kill,
|
|
241
|
+
now: deps.now,
|
|
242
|
+
});
|
|
243
|
+
return params.id ? runs.filter((run) => matchesId(run, params.id!)) : runs;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Runs (from the initial set) currently flagged needs_attention, for reporting. */
|
|
247
|
+
function attentionRunsForSession(params: SubagentWaitParams, deps: SubagentWaitDeps, initialIds: Set<string>): AsyncRunSummary[] {
|
|
248
|
+
return activeRunsForSession(params, deps).filter((run) => needsAttention(run) && initialIds.has(run.id));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** All runs (any state) for this session, for the final summary. */
|
|
252
|
+
function allRunsForSession(params: SubagentWaitParams, deps: SubagentWaitDeps): AsyncRunSummary[] {
|
|
253
|
+
const asyncDirRoot = deps.asyncDirRoot ?? ASYNC_DIR;
|
|
254
|
+
const resultsDir = deps.resultsDir ?? RESULTS_DIR;
|
|
255
|
+
const runs = listAsyncRuns(asyncDirRoot, {
|
|
256
|
+
sessionId: deps.state.currentSessionId ?? undefined,
|
|
257
|
+
resultsDir,
|
|
258
|
+
kill: deps.kill,
|
|
259
|
+
now: deps.now,
|
|
260
|
+
});
|
|
261
|
+
return params.id ? runs.filter((run) => matchesId(run, params.id!)) : runs;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function summarizeTerminalRuns(runs: AsyncRunSummary[], providerFinishedCount = 0): string {
|
|
265
|
+
if (runs.length === 0 && providerFinishedCount === 0) return "";
|
|
266
|
+
const counts = { complete: 0, failed: 0, paused: 0 } as Record<string, number>;
|
|
267
|
+
for (const run of runs) {
|
|
268
|
+
if (run.state in counts) counts[run.state] += 1;
|
|
269
|
+
}
|
|
270
|
+
const parts: string[] = [];
|
|
271
|
+
if (counts.complete) parts.push(`${counts.complete} complete`);
|
|
272
|
+
if (counts.failed) parts.push(`${counts.failed} failed`);
|
|
273
|
+
if (counts.paused) parts.push(`${counts.paused} paused`);
|
|
274
|
+
if (providerFinishedCount > 0) parts.push(`${providerFinishedCount} provider item(s) finished`);
|
|
275
|
+
return parts.join(", ");
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function result(text: string, isError = false): AgentToolResult<Details> {
|
|
279
|
+
return {
|
|
280
|
+
content: [{ type: "text", text }],
|
|
281
|
+
...(isError ? { isError: true } : {}),
|
|
282
|
+
details: { mode: "management", results: [] },
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function waitForDetachedForegroundRun(
|
|
287
|
+
run: ForegroundResumeRun,
|
|
288
|
+
signal: AbortSignal | undefined,
|
|
289
|
+
deps: SubagentWaitDeps,
|
|
290
|
+
startedAt: number,
|
|
291
|
+
now: () => number,
|
|
292
|
+
pollIntervalMs: number,
|
|
293
|
+
timeoutMs: number,
|
|
294
|
+
): Promise<AgentToolResult<Details>> {
|
|
295
|
+
const initialDetachedIndices = new Set(run.children.filter((child) => child.status === "detached").map((child) => child.index));
|
|
296
|
+
while (true) {
|
|
297
|
+
if (deps.state.currentSessionId !== run.sessionId) {
|
|
298
|
+
return result(`Wait stopped because the active session changed while remembered foreground run "${run.runId}" was still detached. Return to the originating session to inspect or wait for it.`, true);
|
|
299
|
+
}
|
|
300
|
+
const current = deps.state.foregroundRuns?.get(run.runId);
|
|
301
|
+
if (!current || current.sessionId !== run.sessionId) {
|
|
302
|
+
return result(`Remembered foreground run "${run.runId}" disappeared before a terminal child result was recorded. Completion cannot be confirmed; do not launch a replacement without checking the originating child session.`, true);
|
|
303
|
+
}
|
|
304
|
+
const pending = current.children.filter((child) => initialDetachedIndices.has(child.index) && child.status === "detached");
|
|
305
|
+
if (pending.length === 0) {
|
|
306
|
+
const outcome = summarizeForegroundChildren(current, initialDetachedIndices);
|
|
307
|
+
return result(
|
|
308
|
+
`Waited ${formatDuration(now() - startedAt)} for remembered detached foreground run "${run.runId}"; done. Outcome: ${outcome || "no recovered child status"}. Completion event observed; inspect with subagent({ action: "status", id: "${run.runId}" }) for recovered output.`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
if (signal?.aborted) {
|
|
312
|
+
return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Remembered foreground run "${run.runId}" remains detached.`, true);
|
|
313
|
+
}
|
|
314
|
+
if (now() - startedAt >= timeoutMs) {
|
|
315
|
+
return result(
|
|
316
|
+
`Wait timed out after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call subagent_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`,
|
|
317
|
+
true,
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
await waitForWake(pollIntervalMs, signal, deps);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Block until the targeted async or remembered detached foreground run finishes,
|
|
326
|
+
* the timeout elapses, or the turn is aborted. Resolves with a short
|
|
327
|
+
* human-readable summary either way.
|
|
328
|
+
*/
|
|
329
|
+
export async function waitForSubagents(
|
|
330
|
+
params: SubagentWaitParams,
|
|
331
|
+
signal: AbortSignal | undefined,
|
|
332
|
+
deps: SubagentWaitDeps,
|
|
333
|
+
): Promise<AgentToolResult<Details>> {
|
|
334
|
+
if (deps.enabled === false) {
|
|
335
|
+
return result("subagent_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.");
|
|
336
|
+
}
|
|
337
|
+
if (!deps.state.currentSessionId) {
|
|
338
|
+
return result("subagent_wait requires an active session identity to scope background work safely.", true);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const now = deps.now ?? Date.now;
|
|
342
|
+
const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
|
|
343
|
+
const timeoutMs = params.timeoutMs !== undefined && params.timeoutMs > 0 ? params.timeoutMs : DEFAULT_TIMEOUT_MS;
|
|
344
|
+
const startedAt = now();
|
|
345
|
+
const waitForAll = params.id ? true : params.all === true;
|
|
346
|
+
|
|
347
|
+
let active: AsyncRunSummary[];
|
|
348
|
+
let foreground: ForegroundResumeRun[];
|
|
349
|
+
let providerSnapshot: BackgroundWorkSnapshot;
|
|
350
|
+
try {
|
|
351
|
+
active = activeRunsForSession(params, deps);
|
|
352
|
+
foreground = activeDetachedForegroundRuns(params, deps);
|
|
353
|
+
providerSnapshot = params.id ? { providers: [], items: [] } : backgroundWorkForSession(deps, startedAt);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
return result(error instanceof Error ? error.message : String(error), true);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (params.id) {
|
|
359
|
+
const candidates = [
|
|
360
|
+
...active.map((run) => ({ kind: "async" as const, id: run.id, run })),
|
|
361
|
+
...foreground.map((run) => ({ kind: "foreground" as const, id: run.runId, run })),
|
|
362
|
+
];
|
|
363
|
+
const exact = candidates.filter((candidate) => candidate.id === params.id);
|
|
364
|
+
const matches = exact.length > 0 ? exact : candidates;
|
|
365
|
+
if (matches.length > 1) {
|
|
366
|
+
return result(`Ambiguous subagent run id prefix "${params.id}" matched ${matches.length} active runs: ${matches.map((candidate) => candidate.id).join(", ")}. Pass a longer id.`, true);
|
|
367
|
+
}
|
|
368
|
+
const selected = matches[0];
|
|
369
|
+
if (selected?.kind === "foreground") {
|
|
370
|
+
return waitForDetachedForegroundRun(selected.run, signal, deps, startedAt, now, pollIntervalMs, timeoutMs);
|
|
371
|
+
}
|
|
372
|
+
active = selected?.kind === "async" ? [selected.run] : [];
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
let providerActive = providerSnapshot.items;
|
|
376
|
+
if (active.length === 0 && providerActive.length === 0) {
|
|
377
|
+
return result(params.id
|
|
378
|
+
? `No active run matched "${params.id}". Nothing to wait for.`
|
|
379
|
+
: "No active async runs or registered provider work in this session. Nothing to wait for.");
|
|
380
|
+
}
|
|
381
|
+
const waitParams = params.id ? { ...params, id: active[0]!.id } : params;
|
|
382
|
+
const initialAsyncIds = new Set(active.map((run) => run.id));
|
|
383
|
+
const initialProviderIds = new Set(providerActive.map(backgroundWorkIdentity));
|
|
384
|
+
const initialProviderNames = new Set(providerActive.map((item) => item.provider));
|
|
385
|
+
const initialCount = initialAsyncIds.size + initialProviderIds.size;
|
|
386
|
+
const stopOnAttention = deps.stopOnAttention !== false;
|
|
387
|
+
let attention = active.filter((run) => needsAttention(run));
|
|
388
|
+
|
|
389
|
+
const isDone = (): boolean => {
|
|
390
|
+
if (stopOnAttention && attention.some((run) => initialAsyncIds.has(run.id))) return true;
|
|
391
|
+
const activeAsyncIds = new Set(active.map((run) => run.id));
|
|
392
|
+
const activeProviderIds = new Set(providerActive.map(backgroundWorkIdentity));
|
|
393
|
+
if (waitForAll) {
|
|
394
|
+
return [...initialAsyncIds].every((id) => !activeAsyncIds.has(id))
|
|
395
|
+
&& [...initialProviderIds].every((id) => !activeProviderIds.has(id));
|
|
396
|
+
}
|
|
397
|
+
return [...initialAsyncIds].some((id) => !activeAsyncIds.has(id))
|
|
398
|
+
|| [...initialProviderIds].some((id) => !activeProviderIds.has(id));
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
while (!isDone()) {
|
|
402
|
+
const activeInitialRuns = active.filter((run) => initialAsyncIds.has(run.id));
|
|
403
|
+
const activeInitialProviderItems = providerActive.filter((item) => initialProviderIds.has(backgroundWorkIdentity(item)));
|
|
404
|
+
const stillActive = [
|
|
405
|
+
...activeInitialRuns.map((run) => `${run.id} (${run.state})`),
|
|
406
|
+
...activeInitialProviderItems.map((item) => `${item.provider}/${item.id}`),
|
|
407
|
+
].join(", ");
|
|
408
|
+
if (signal?.aborted) {
|
|
409
|
+
return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Still active: ${stillActive}.`, true);
|
|
410
|
+
}
|
|
411
|
+
if (now() - startedAt >= timeoutMs) {
|
|
412
|
+
return result(
|
|
413
|
+
`Wait timed out after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call subagent_wait again or inspect subagent status.`,
|
|
414
|
+
true,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
await waitForWake(pollIntervalMs, signal, deps);
|
|
419
|
+
active = activeRunsForSession(waitParams, deps);
|
|
420
|
+
attention = attentionRunsForSession(waitParams, deps, initialAsyncIds);
|
|
421
|
+
providerSnapshot = params.id ? providerSnapshot : backgroundWorkForSession(deps, now());
|
|
422
|
+
for (const provider of initialProviderNames) {
|
|
423
|
+
if (!providerSnapshot.providers.includes(provider)) {
|
|
424
|
+
return result(`Background-work provider '${provider}' disappeared while subagent_wait was tracking its active work; completion cannot be confirmed.`, true);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
providerActive = providerSnapshot.items;
|
|
428
|
+
} catch (error) {
|
|
429
|
+
return result(error instanceof Error ? error.message : String(error), true);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
let terminalSummary: string;
|
|
434
|
+
let finishedAsyncCount: number;
|
|
435
|
+
let failedAsyncCount: number;
|
|
436
|
+
const activeProviderIds = new Set(providerActive.map(backgroundWorkIdentity));
|
|
437
|
+
const providerFinishedCount = [...initialProviderIds].filter((id) => !activeProviderIds.has(id)).length;
|
|
438
|
+
try {
|
|
439
|
+
const allNow = allRunsForSession(waitParams, deps);
|
|
440
|
+
const terminal = allNow.filter((run) => !ACTIVE_STATES.includes(run.state) && initialAsyncIds.has(run.id));
|
|
441
|
+
finishedAsyncCount = terminal.length;
|
|
442
|
+
failedAsyncCount = terminal.filter((run) => run.state === "failed").length;
|
|
443
|
+
terminalSummary = summarizeTerminalRuns(terminal, providerFinishedCount);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
return result(error instanceof Error ? error.message : String(error), true);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const relevantAttention = attention.filter((run) => initialAsyncIds.has(run.id));
|
|
449
|
+
const attentionNote = relevantAttention.length > 0
|
|
450
|
+
? ` ${relevantAttention.length} run(s) need attention: ${relevantAttention.map((run) => run.id).join(", ")} — inspect with subagent({ action: "status" }) then steer a top-level live async child, resume a paused/completed/failed child, or interrupt explicitly.`
|
|
451
|
+
: "";
|
|
452
|
+
const stillRunning = active.filter((run) => initialAsyncIds.has(run.id)).length
|
|
453
|
+
+ providerActive.filter((item) => initialProviderIds.has(backgroundWorkIdentity(item))).length;
|
|
454
|
+
const elapsed = formatDuration(now() - startedAt);
|
|
455
|
+
const outcome = terminalSummary ? ` Outcome: ${terminalSummary}.` : "";
|
|
456
|
+
|
|
457
|
+
if (waitForAll) {
|
|
458
|
+
const scope = params.id
|
|
459
|
+
? `run "${params.id}"`
|
|
460
|
+
: initialProviderIds.size === 0
|
|
461
|
+
? `${initialAsyncIds.size} async run(s)`
|
|
462
|
+
: `${initialAsyncIds.size} async run(s) and ${initialProviderIds.size} provider item(s)`;
|
|
463
|
+
const status = relevantAttention.length > 0 ? "attention required" : "done";
|
|
464
|
+
return result(
|
|
465
|
+
`Waited ${elapsed} for ${scope}; ${status}.${outcome}${attentionNote} Completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
466
|
+
deps.failOnFailedRuns === true && failedAsyncCount > 0,
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const finishedCount = finishedAsyncCount + providerFinishedCount;
|
|
471
|
+
const subject = initialProviderIds.size === 0 ? "run(s)" : "item(s)";
|
|
472
|
+
const remainder = stillRunning > 0
|
|
473
|
+
? ` ${stillRunning} ${subject} still in flight — call subagent_wait again to catch the next one.`
|
|
474
|
+
: relevantAttention.length > 0
|
|
475
|
+
? " No other work is waitable until attention is handled."
|
|
476
|
+
: initialProviderIds.size === 0 ? " No runs remain in flight." : " No work remains in flight.";
|
|
477
|
+
const progress = relevantAttention.length > 0 && finishedCount === 0
|
|
478
|
+
? `${relevantAttention.length} of ${initialCount} ${subject} need attention`
|
|
479
|
+
: `${finishedCount} of ${initialCount} ${subject} finished`;
|
|
480
|
+
return result(
|
|
481
|
+
`Waited ${elapsed}; ${progress}.${outcome}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
|
|
482
|
+
deps.failOnFailedRuns === true && failedAsyncCount > 0,
|
|
483
|
+
);
|
|
484
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
interface AsyncOverrideParams {
|
|
2
2
|
async?: boolean;
|
|
3
3
|
clarify?: boolean;
|
|
4
|
+
foregroundOnly?: boolean;
|
|
4
5
|
}
|
|
5
6
|
|
|
6
7
|
export function applyForceTopLevelAsyncOverride<T extends AsyncOverrideParams>(
|
|
@@ -8,6 +9,6 @@ export function applyForceTopLevelAsyncOverride<T extends AsyncOverrideParams>(
|
|
|
8
9
|
depth: number,
|
|
9
10
|
forceTopLevelAsync: boolean,
|
|
10
11
|
): T {
|
|
11
|
-
if (!(depth === 0 && forceTopLevelAsync)) return params;
|
|
12
|
+
if (params.foregroundOnly || !(depth === 0 && forceTopLevelAsync)) return params;
|
|
12
13
|
return { ...params, async: true, clarify: false };
|
|
13
14
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { WaitToolConfig } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
export const WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
|
|
4
|
+
|
|
5
|
+
export interface ResolvedWaitToolConfig {
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const TRUE_VALUES = new Set(["1", "true", "yes", "on", "enabled"]);
|
|
10
|
+
const FALSE_VALUES = new Set(["0", "false", "no", "off", "disabled"]);
|
|
11
|
+
|
|
12
|
+
function environmentValue(value: string | undefined): boolean | undefined {
|
|
13
|
+
if (value === undefined) return undefined;
|
|
14
|
+
const normalized = value.trim().toLowerCase();
|
|
15
|
+
if (TRUE_VALUES.has(normalized)) return true;
|
|
16
|
+
if (FALSE_VALUES.has(normalized)) return false;
|
|
17
|
+
throw new Error(`${WAIT_TOOL_ENABLED_ENV} must be one of true/false, 1/0, yes/no, on/off, or enabled/disabled.`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function configuredValue(config: unknown): boolean | undefined {
|
|
21
|
+
if (config === undefined) return undefined;
|
|
22
|
+
if (typeof config === "boolean") return config;
|
|
23
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
24
|
+
throw new Error("config.waitTool must be a boolean or an object with optional enabled boolean.");
|
|
25
|
+
}
|
|
26
|
+
const enabled = (config as { enabled?: unknown }).enabled;
|
|
27
|
+
if (enabled === undefined) return undefined;
|
|
28
|
+
if (typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
|
|
29
|
+
return enabled;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function resolveWaitToolConfig(config?: WaitToolConfig, env: Record<string, string | undefined> = process.env): ResolvedWaitToolConfig {
|
|
33
|
+
return {
|
|
34
|
+
enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configuredValue(config) ?? true,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { SubagentWaitParams } from "../../extension/schemas.ts";
|
|
3
|
+
import type { Details, SubagentState } from "../../shared/types.ts";
|
|
4
|
+
import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
|
|
5
|
+
|
|
6
|
+
export function registerWaitTool(pi: ExtensionAPI, state: SubagentState, enabled = resolveWaitToolConfig().enabled): void {
|
|
7
|
+
const tool: ToolDefinition<typeof SubagentWaitParams, Details> = {
|
|
8
|
+
name: "subagent_wait",
|
|
9
|
+
label: "Subagent Wait",
|
|
10
|
+
description: `Block until background work owned by this session changes, then return.
|
|
11
|
+
|
|
12
|
+
In an interactive chat, do not call this merely to wait: return control to the user and let Pi wake the session on completion. Override that default and call it when the current request is run-to-completion — for example, the user asked you to report results back before continuing or a skill cannot return before its work finishes. Headless runs auto-drain current-session work at agent_end; call this when the current turn must receive results before it ends.
|
|
13
|
+
|
|
14
|
+
• { } — return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
|
|
15
|
+
• { all: true } — wait for every async run and provider item that was active when the call began.
|
|
16
|
+
• { id: "..." } — wait for one async or remembered detached foreground subagent run (id or prefix).
|
|
17
|
+
• { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running.
|
|
18
|
+
|
|
19
|
+
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 \`subagent_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: subagent_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`,
|
|
20
|
+
parameters: SubagentWaitParams,
|
|
21
|
+
execute(_id, params, signal) {
|
|
22
|
+
return waitForSubagents(params, signal, { state, events: pi.events, enabled });
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
pi.registerTool(tool);
|
|
26
|
+
}
|