@ferris1225/pi-subagents 6.0.2 → 6.0.4
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 +23 -0
- package/README.md +71 -191
- package/index.ts +2 -12
- package/package.json +7 -7
- package/src/configuration/config.ts +2 -6
- package/src/configuration/role-migration.ts +3 -14
- package/src/configuration/schema.ts +10 -0
- package/src/configuration/setup.ts +75 -36
- package/src/configuration/ui.ts +355 -53
- package/src/delegation/agents.ts +0 -1
- package/src/delegation/builtin-agents.ts +6 -27
- package/src/delegation/dispatch.ts +29 -120
- package/src/delegation/prompt.ts +16 -48
- package/src/execution/spawn.ts +2 -2
- package/src/lifecycle/cancellation.ts +4 -8
- package/src/lifecycle/durable.ts +0 -18
- package/src/lifecycle/runtime.ts +7 -56
- package/src/lifecycle/thread-lifecycle.ts +5 -33
- package/src/lifecycle/thread-restore.ts +0 -3
- package/src/lifecycle/thread-shared.ts +1 -11
- package/src/lifecycle/tools.ts +12 -97
- package/src/presentation/monitor.ts +727 -758
- package/src/presentation/widget.ts +36 -134
- package/src/delegation/ownership.ts +0 -98
- package/src/delegation/phase-scope.ts +0 -186
- package/src/workflow/acceptance.ts +0 -67
- package/src/workflow/durable.ts +0 -228
- package/src/workflow/engine.ts +0 -816
- package/src/workflow/plan.ts +0 -409
- package/src/workflow/state.ts +0 -55
- package/src/workflow/templates.ts +0 -156
- package/src/workflow/tool.ts +0 -254
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -9,9 +9,6 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
|
|
12
|
-
import { findDuplicateDispatch } from "../delegation/prompt.ts";
|
|
13
|
-
import { pendingWorkflowLeases } from "../delegation/ownership.ts";
|
|
14
|
-
import type { PhaseScope } from "../delegation/phase-scope.ts";
|
|
15
12
|
import { rmSync } from "node:fs";
|
|
16
13
|
import { BackgroundTaskQueue } from "../execution/background.ts";
|
|
17
14
|
import {
|
|
@@ -23,11 +20,10 @@ import {
|
|
|
23
20
|
} from "./completion.ts";
|
|
24
21
|
import { type ThinkingLevel } from "../configuration/config.ts";
|
|
25
22
|
import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
|
|
26
|
-
import { isRunActiveStatus, monitor
|
|
23
|
+
import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
|
|
27
24
|
import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
|
|
28
25
|
import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
|
|
29
26
|
import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
|
|
30
|
-
import type { WorkflowRun } from "../workflow/state.ts";
|
|
31
27
|
|
|
32
28
|
export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
|
|
33
29
|
|
|
@@ -40,12 +36,6 @@ export interface SubagentThread {
|
|
|
40
36
|
generation: number;
|
|
41
37
|
agentName: string;
|
|
42
38
|
task: string;
|
|
43
|
-
phaseId?: string;
|
|
44
|
-
scope?: PhaseScope;
|
|
45
|
-
/** Capability snapshot used by declared-scope admission, including after restore. */
|
|
46
|
-
writeCapable?: boolean;
|
|
47
|
-
/** Live graph membership; graph summaries own delivery for these runs. */
|
|
48
|
-
workflow?: RunWorkflowTag;
|
|
49
39
|
/** Caller-facing cwd in the original worktree. */
|
|
50
40
|
cwd: string;
|
|
51
41
|
/** Actual child cwd (the equivalent path inside an isolated worktree). */
|
|
@@ -95,7 +85,7 @@ export interface SubagentRuntime {
|
|
|
95
85
|
suppressCompletions: boolean;
|
|
96
86
|
discardCompletions: () => void;
|
|
97
87
|
/** Record cancellation for the next user turn without waking the parent. */
|
|
98
|
-
recordCancellation: (runIds: number[]
|
|
88
|
+
recordCancellation: (runIds: number[]) => void;
|
|
99
89
|
/** Resolves when the load-time durable restore pass has finished. Everything
|
|
100
90
|
* that answers "which threads exist" awaits it — the lookup tools, a fresh
|
|
101
91
|
* dispatch before it allocates a run id, and the restored-thread notice — so
|
|
@@ -127,18 +117,7 @@ export interface SubagentRuntime {
|
|
|
127
117
|
registerRunResult: (runId: number, result: SingleResult) => void;
|
|
128
118
|
/** Logical threads outlive process attempts and completed generations. */
|
|
129
119
|
threads: Map<number, SubagentThread>;
|
|
130
|
-
/**
|
|
131
|
-
mainWrites: Map<string, { toolName: string; scope: PhaseScope }>;
|
|
132
|
-
/** Workflow graphs started in this parent session, live and settled. */
|
|
133
|
-
workflows: Map<number, WorkflowRun>;
|
|
134
|
-
/** Stable mapping from persisted identities to this window's display ids. */
|
|
135
|
-
workflowRecordIds: Map<string, number>;
|
|
136
|
-
/** Allocate a graph id that no retained or live workflow record owns. */
|
|
137
|
-
reserveWorkflowId: () => number;
|
|
138
|
-
/** Raise the graph-id allocator above an id restored from a durable record. */
|
|
139
|
-
ensureWorkflowIdAbove: (id: number) => void;
|
|
140
|
-
/** Session-teardown tasks that must run before runtime state is released
|
|
141
|
-
* (persisting a graph's shape, for example). */
|
|
120
|
+
/** Session-teardown tasks that must run before runtime state is released. */
|
|
142
121
|
shutdownHooks: Array<() => Promise<void> | void>;
|
|
143
122
|
/** Every session directory retained for this parent session. */
|
|
144
123
|
sessionDirs: Set<string>;
|
|
@@ -148,22 +127,8 @@ export interface SubagentRuntime {
|
|
|
148
127
|
shutdown: () => Promise<void>;
|
|
149
128
|
}
|
|
150
129
|
|
|
151
|
-
/** Pending nodes reserve their phases before they allocate ordinary run ids. */
|
|
152
|
-
export function findPendingWorkflowPhase(
|
|
153
|
-
runtime: Pick<SubagentRuntime, "workflows">,
|
|
154
|
-
task: string,
|
|
155
|
-
cwd: string,
|
|
156
|
-
phaseId?: string,
|
|
157
|
-
excludeWorkflowId?: number,
|
|
158
|
-
): { workflowId: number; nodeId: string; agent: string } | undefined {
|
|
159
|
-
const duplicate = findDuplicateDispatch(pendingWorkflowLeases(runtime, excludeWorkflowId), task, cwd, phaseId);
|
|
160
|
-
const owner = duplicate?.source;
|
|
161
|
-
return owner?.workflow ? { workflowId: owner.workflow.workflowId, nodeId: owner.workflow.nodeId, agent: owner.agentName } : undefined;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
130
|
export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
|
|
165
131
|
const backgroundQueue = new BackgroundTaskQueue();
|
|
166
|
-
let nextWorkflowId = 1;
|
|
167
132
|
// Compaction reads the whole history, summarizes it, and replaces it. A
|
|
168
133
|
// completion injected into that window can be swallowed by the summary,
|
|
169
134
|
// silently losing a result a child spent minutes producing — so delivery is
|
|
@@ -179,16 +144,14 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
179
144
|
getToolInfos: () => pi.getAllTools(),
|
|
180
145
|
sessionActive: true,
|
|
181
146
|
suppressCompletions: false,
|
|
182
|
-
recordCancellation: (runIds
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
...(workflowIds.length ? ["workflows " + workflowIds.map((id) => `#${id}`).join(", ")] : []),
|
|
186
|
-
].join("; ");
|
|
147
|
+
recordCancellation: (runIds) => {
|
|
148
|
+
if (!runIds.length) return;
|
|
149
|
+
const targets = "runs " + runIds.map((id) => `#${id}`).join(", ");
|
|
187
150
|
pi.sendMessage({
|
|
188
151
|
customType: "subagent-cancelled",
|
|
189
152
|
content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
|
|
190
153
|
display: true,
|
|
191
|
-
details: { runIds
|
|
154
|
+
details: { runIds },
|
|
192
155
|
}, { deliverAs: "nextTurn", triggerTurn: false });
|
|
193
156
|
},
|
|
194
157
|
discardCompletions: () => {
|
|
@@ -255,13 +218,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
255
218
|
settledRuns: new Map<number, SingleResult>(),
|
|
256
219
|
settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
|
|
257
220
|
threads: new Map<number, SubagentThread>(),
|
|
258
|
-
mainWrites: new Map(),
|
|
259
|
-
workflows: new Map<number, WorkflowRun>(),
|
|
260
|
-
workflowRecordIds: new Map(),
|
|
261
|
-
reserveWorkflowId: () => nextWorkflowId++,
|
|
262
|
-
ensureWorkflowIdAbove: (id) => {
|
|
263
|
-
if (id >= nextWorkflowId) nextWorkflowId = id + 1;
|
|
264
|
-
},
|
|
265
221
|
shutdownHooks: [],
|
|
266
222
|
sessionDirs: new Set<string>(),
|
|
267
223
|
retainSession: (result) => {
|
|
@@ -382,8 +338,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
382
338
|
/* best-effort; the state-root sweep catches leftovers later */
|
|
383
339
|
}
|
|
384
340
|
}
|
|
385
|
-
// Let owners persist their own last state (a workflow's shape) while the
|
|
386
|
-
// threads it refers to still exist.
|
|
387
341
|
for (const hook of runtime.shutdownHooks) {
|
|
388
342
|
try {
|
|
389
343
|
await hook();
|
|
@@ -399,9 +353,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
399
353
|
// manifest; the next process re-registers them at restore.
|
|
400
354
|
runtime.sessionDirs.clear();
|
|
401
355
|
runtime.threads.clear();
|
|
402
|
-
runtime.mainWrites.clear();
|
|
403
|
-
runtime.workflows.clear();
|
|
404
|
-
runtime.workflowRecordIds.clear();
|
|
405
356
|
runtime.shutdownHooks = [];
|
|
406
357
|
monitor.clear();
|
|
407
358
|
},
|
|
@@ -9,16 +9,14 @@
|
|
|
9
9
|
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
11
|
import { join, resolve } from "node:path";
|
|
12
|
-
import {
|
|
12
|
+
import { resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
|
|
13
13
|
import type { CompletionMessageItem } from "./completion.ts";
|
|
14
14
|
import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
15
15
|
import { dispatchFailedResult, failedStartResult, formatCompletionBlock, modelLevelTakeoverNote, queuedResult } from "../presentation/format.ts";
|
|
16
16
|
import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
|
|
17
17
|
import { findDuplicateDispatch } from "../delegation/prompt.ts";
|
|
18
|
-
import { normalizePhaseId, normalizePhaseScope } from "../delegation/phase-scope.ts";
|
|
19
|
-
import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
|
|
20
18
|
import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
|
|
21
|
-
import {
|
|
19
|
+
import { type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
|
|
22
20
|
import {
|
|
23
21
|
getProjectRoot,
|
|
24
22
|
RunControl,
|
|
@@ -101,18 +99,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
101
99
|
resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
|
|
102
100
|
const agent = resolveLiveAgentTools(discoveredAgent);
|
|
103
101
|
const originalCwd = resolve(cwd ?? runCtx.cwd);
|
|
104
|
-
let phaseId: string | undefined;
|
|
105
|
-
let scope: ReturnType<typeof normalizePhaseScope>;
|
|
106
|
-
try {
|
|
107
|
-
phaseId = normalizePhaseId(startOptions.phaseId);
|
|
108
|
-
scope = normalizePhaseScope(startOptions.scope, originalCwd);
|
|
109
|
-
} catch (error) {
|
|
110
|
-
return failedStartResult(agentName, task, error instanceof Error ? error.message : String(error));
|
|
111
|
-
}
|
|
112
|
-
const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
|
|
113
|
-
// A workflow node is an ordinary managed run whose reporting belongs to
|
|
114
|
-
// the graph: it settles into the graph's single summary instead of
|
|
115
|
-
// waking the parent once per node.
|
|
116
102
|
const quiet = startOptions.quiet === true;
|
|
117
103
|
if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
|
|
118
104
|
return {
|
|
@@ -120,31 +106,22 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
120
106
|
isolation,
|
|
121
107
|
};
|
|
122
108
|
}
|
|
123
|
-
const
|
|
124
|
-
if (pendingOwner) return failedStartResult(agentName, task, `Workflow #${pendingOwner.workflowId} node "${pendingOwner.nodeId}" already owns this pending phase. Inspect the graph with subagent_status; main handles follow-up work.`);
|
|
125
|
-
const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd, phaseId);
|
|
109
|
+
const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd);
|
|
126
110
|
if (duplicate) {
|
|
127
111
|
// A phase stays owned across reloads: an interrupted run keeps its claim
|
|
128
112
|
// until it is retired, so "let it finish" is wrong advice for a parked
|
|
129
113
|
// owner and leaves the caller with no way forward.
|
|
130
114
|
const owner = duplicate.source;
|
|
131
115
|
const remedy = owner.state === "parked" || owner.retired
|
|
132
|
-
? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused
|
|
116
|
+
? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused.`
|
|
133
117
|
: owner.state === "completed"
|
|
134
|
-
? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief
|
|
118
|
+
? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief.`
|
|
135
119
|
: owner.state === "failed"
|
|
136
120
|
? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
|
|
137
121
|
: "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
|
|
138
122
|
return failedStartResult(agentName, task,
|
|
139
123
|
`Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
|
|
140
124
|
}
|
|
141
|
-
if (writeCapable && scope) {
|
|
142
|
-
const conflict = findRuntimeWriterConflict(runtime, scope, { excludeWorkflowId: startOptions.workflow?.workflowId });
|
|
143
|
-
if (conflict) {
|
|
144
|
-
return failedStartResult(agentName, task,
|
|
145
|
-
`Declared writer scope ${conflict.overlap.left} overlaps ${conflict.owner} scope ${conflict.overlap.right}; no run was started.`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
125
|
const projectRoot = getProjectRoot(runtime.configPath, originalCwd);
|
|
149
126
|
const sessionsRoot = join(projectRoot, "sessions");
|
|
150
127
|
const worktreesRoot = join(projectRoot, "worktrees");
|
|
@@ -159,7 +136,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
159
136
|
const thinkingLevel = route.thinkingLevel;
|
|
160
137
|
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
161
138
|
isolation,
|
|
162
|
-
...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
|
|
163
139
|
});
|
|
164
140
|
if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
|
|
165
141
|
const generation = 1;
|
|
@@ -194,10 +170,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
194
170
|
generation,
|
|
195
171
|
agentName: agent.name,
|
|
196
172
|
task,
|
|
197
|
-
phaseId,
|
|
198
|
-
scope,
|
|
199
|
-
writeCapable,
|
|
200
|
-
...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
|
|
201
173
|
cwd: originalCwd,
|
|
202
174
|
executionCwd,
|
|
203
175
|
thinkingLevel,
|
|
@@ -53,9 +53,6 @@ function createRestoredThread(
|
|
|
53
53
|
generation: record.generation,
|
|
54
54
|
agentName: record.agentName,
|
|
55
55
|
task: record.task,
|
|
56
|
-
phaseId: record.phaseId,
|
|
57
|
-
scope: record.scope,
|
|
58
|
-
writeCapable: record.writeCapable ?? record.agentName !== "scout",
|
|
59
56
|
cwd: record.cwd,
|
|
60
57
|
executionCwd: record.executionCwd,
|
|
61
58
|
...(record.thinkingLevel ? { thinkingLevel: record.thinkingLevel as ThinkingLevel } : {}),
|
|
@@ -5,7 +5,6 @@ import { realpath } from "node:fs/promises";
|
|
|
5
5
|
import { join, resolve } from "node:path";
|
|
6
6
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
|
|
8
|
-
import type { PhaseScope } from "../delegation/phase-scope.ts";
|
|
9
8
|
import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
|
|
10
9
|
import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
|
|
11
10
|
import {
|
|
@@ -16,7 +15,6 @@ import {
|
|
|
16
15
|
resolveAgentModelRoute,
|
|
17
16
|
resolveThinkingLevel,
|
|
18
17
|
} from "../configuration/models.ts";
|
|
19
|
-
import type { RunWorkflowTag } from "../presentation/monitor.ts";
|
|
20
18
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
21
19
|
import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
|
|
22
20
|
import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
|
|
@@ -129,20 +127,12 @@ export interface DispatchEnvironment {
|
|
|
129
127
|
export interface StartBackgroundOptions {
|
|
130
128
|
/** A private copy of a settled session used for a follow-up run. */
|
|
131
129
|
resumeSession?: { sessionId: string; sessionDir: string };
|
|
132
|
-
phaseId?: string;
|
|
133
|
-
scope?: PhaseScope;
|
|
134
|
-
/** A false hint cannot downgrade a live write-capable role. */
|
|
135
|
-
writeCapable?: boolean;
|
|
136
130
|
/** Omitted public isolation may fall back only when no Git baseline exists. */
|
|
137
131
|
automaticIsolation?: boolean;
|
|
138
132
|
/** Chosen by the tool call before the queue can start a fast child. */
|
|
139
133
|
deliveryRoute?: "background" | "await";
|
|
140
|
-
/**
|
|
141
|
-
* completion message and no per-run toast, so a wide graph cannot flood the
|
|
142
|
-
* parent with one wake-up per node. */
|
|
134
|
+
/** Suppress per-run completion messages and toasts when needed. */
|
|
143
135
|
quiet?: boolean;
|
|
144
|
-
/** Graph membership rendered by the widget and node status rows. */
|
|
145
|
-
workflow?: RunWorkflowTag;
|
|
146
136
|
}
|
|
147
137
|
|
|
148
138
|
export type StartBackgroundInternal = (
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -21,13 +21,6 @@ import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../pre
|
|
|
21
21
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
22
22
|
import { projectResultsRoot } from "./thread-shared.ts";
|
|
23
23
|
import { getResultError } from "../execution/spawn.ts";
|
|
24
|
-
import {
|
|
25
|
-
formatRetainedWorkflow,
|
|
26
|
-
formatWorkflowStatus,
|
|
27
|
-
readRetainedWorkflows,
|
|
28
|
-
stopWorkflow,
|
|
29
|
-
workflowStatus,
|
|
30
|
-
} from "../workflow/engine.ts";
|
|
31
24
|
|
|
32
25
|
function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
|
|
33
26
|
const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
|
|
@@ -89,7 +82,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
89
82
|
pi.registerTool({
|
|
90
83
|
name: "subagent_status",
|
|
91
84
|
label: "Subagent Status",
|
|
92
|
-
description: "Inspect run
|
|
85
|
+
description: "Inspect run ownership, progress, and failures. An exact run id also returns its retained result so completed work can be reused. Omit id to list runs. Results arrive automatically; do not poll.",
|
|
93
86
|
exposure: "model-only",
|
|
94
87
|
executionMode: "parallel",
|
|
95
88
|
annotations: {
|
|
@@ -100,9 +93,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
100
93
|
},
|
|
101
94
|
parameters: Type.Object({
|
|
102
95
|
id: Type.Optional(Type.Integer({ minimum: 1, description: "Exact run id; omit to list all runs in this parent session." })),
|
|
103
|
-
workflow: Type.Optional(Type.Integer({ minimum: 1, description: "Workflow graph id; omit to list every graph in this parent session." })),
|
|
104
96
|
}),
|
|
105
|
-
async execute(_toolCallId, params
|
|
97
|
+
async execute(_toolCallId, params) {
|
|
106
98
|
await runtime.durableRestore;
|
|
107
99
|
const threads = [...runtime.threads.values()]
|
|
108
100
|
.filter((thread) => params.id === undefined || thread.id === params.id)
|
|
@@ -117,10 +109,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
117
109
|
return {
|
|
118
110
|
id: thread.id,
|
|
119
111
|
agent: thread.agentName,
|
|
120
|
-
phaseId: thread.phaseId,
|
|
121
112
|
cwd: thread.cwd,
|
|
122
113
|
executionCwd: thread.executionCwd,
|
|
123
|
-
scope: thread.scope,
|
|
124
114
|
taskSummary: formatTaskSummary(thread.task, 80, false),
|
|
125
115
|
state,
|
|
126
116
|
waitReason: state === "queued" ? live?.waitReason : undefined,
|
|
@@ -152,8 +142,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
152
142
|
: runs.map((run) => {
|
|
153
143
|
const wait = run.waitReason ? ` — ${runWaitLabel({ status: "queued", waitReason: run.waitReason })}` : "";
|
|
154
144
|
const lines = [`#${run.id} ${run.agent} · ${run.state} · ${formatDuration(run.elapsedMs)}${wait}`, ` task: ${run.taskSummary}`];
|
|
155
|
-
if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
|
|
156
|
-
if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
|
|
157
145
|
if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
|
|
158
146
|
if (run.lastSteering) lines.push(` last steering: ${run.lastSteering.disposition} · acknowledged ${formatDuration(Math.max(0, Date.now() - run.lastSteering.acknowledgedAt))} ago${run.lastSteering.requestId ? ` · request ${run.lastSteering.requestId}` : ""} · ${run.lastSteering.message}`);
|
|
159
147
|
if (run.followUpContext) lines.push(` follow-up: ${run.followUpContext}${run.followUpContext === "summary" ? " (retained session unavailable)" : " available"}`);
|
|
@@ -174,20 +162,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
174
162
|
if (paths.length > 0) lines.push(` ${paths.join("\n ")}`);
|
|
175
163
|
return lines.join("\n");
|
|
176
164
|
}).join("\n");
|
|
177
|
-
// Workflow graphs are reported beside individual runs: which nodes have
|
|
178
|
-
// started, which one is waiting on a dependency, and what a graph that
|
|
179
|
-
// outlived its session left behind.
|
|
180
|
-
const workflowId = params.id === undefined ? params.workflow : undefined;
|
|
181
|
-
const workflowRuns = [...runtime.workflows.values()]
|
|
182
|
-
.filter((run) => workflowId === undefined || run.id === workflowId)
|
|
183
|
-
.sort((left, right) => left.id - right.id);
|
|
184
|
-
const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
|
|
185
|
-
.filter((record) => workflowId === undefined || record.id === workflowId)
|
|
186
|
-
.filter((record) => !workflowRuns.some((run) => run.id === record.id));
|
|
187
|
-
const workflowSections = params.id === undefined ? [
|
|
188
|
-
...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
|
|
189
|
-
...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
|
|
190
|
-
] : [];
|
|
191
165
|
const selected = params.id === undefined ? undefined : runtime.threads.get(params.id);
|
|
192
166
|
const retainedResult = selected ? runtime.settledRuns.get(selected.id) ?? selected.lastResult : undefined;
|
|
193
167
|
const evidence = retainedResult && retainedResult.exitCode !== -1
|
|
@@ -195,21 +169,14 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
195
169
|
? `Read the retained result: ${retainedResult.resultFile}`
|
|
196
170
|
: formatCompletionBlock(retainedResult, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, selected!.cwd) })
|
|
197
171
|
: "";
|
|
198
|
-
const sections = [text,
|
|
199
|
-
const unknownWorkflow = workflowId !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
|
|
172
|
+
const sections = [text, evidence].filter((section) => section.trim().length > 0);
|
|
200
173
|
return {
|
|
201
174
|
content: [{
|
|
202
175
|
type: "text",
|
|
203
|
-
text:
|
|
204
|
-
? `No workflow graph matches #${params.workflow} in this parent session.`
|
|
205
|
-
: sections.join("\n\n"),
|
|
176
|
+
text: sections.join("\n\n"),
|
|
206
177
|
}],
|
|
207
|
-
details: {
|
|
208
|
-
|
|
209
|
-
workflows: workflowRuns.map(workflowStatus),
|
|
210
|
-
retainedWorkflows,
|
|
211
|
-
},
|
|
212
|
-
...((params.id !== undefined && runs.length === 0) || unknownWorkflow ? { isError: true } : {}),
|
|
178
|
+
details: { runs },
|
|
179
|
+
...(params.id !== undefined && runs.length === 0 ? { isError: true } : {}),
|
|
213
180
|
};
|
|
214
181
|
},
|
|
215
182
|
renderCall(args, theme) {
|
|
@@ -296,7 +263,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
296
263
|
: buildSummaryFollowUp(thread, params.message);
|
|
297
264
|
const wait = params.wait ?? (ctx.hasUI === false);
|
|
298
265
|
const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
|
|
299
|
-
phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
|
|
300
266
|
deliveryRoute: wait ? "await" : "background",
|
|
301
267
|
...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
|
|
302
268
|
});
|
|
@@ -343,17 +309,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
343
309
|
description: "Run id or prefix to stop (see subagent dispatch output).",
|
|
344
310
|
}),
|
|
345
311
|
),
|
|
346
|
-
all: Type.Optional(Type.Boolean({ description: "Stop every active run
|
|
347
|
-
workflow: Type.Optional(Type.Integer({
|
|
348
|
-
minimum: 1,
|
|
349
|
-
description: "Stop this workflow graph: no dependent node starts and running nodes are cancelled.",
|
|
350
|
-
})),
|
|
312
|
+
all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
|
|
351
313
|
});
|
|
352
314
|
|
|
353
315
|
pi.registerTool({
|
|
354
316
|
name: "subagent_stop",
|
|
355
317
|
label: "Subagent Stop",
|
|
356
|
-
description: "Destructively stop and retire one run by id/prefix,
|
|
318
|
+
description: "Destructively stop and retire one run by id/prefix, or this session’s active runs with all: true. all takes precedence over id. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
|
|
357
319
|
exposure: "model-only",
|
|
358
320
|
executionMode: "sequential",
|
|
359
321
|
annotations: {
|
|
@@ -366,43 +328,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
366
328
|
|
|
367
329
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
368
330
|
await runtime.durableRestore;
|
|
369
|
-
// A graph stop owns its own lifecycle: dependents must not start, and the
|
|
370
|
-
// graph's own summary reports what had already completed. Stopping the
|
|
371
|
-
// nodes one by one first would let the runner dispatch the next layer.
|
|
372
|
-
if (params.all !== true && !params.id?.trim() && params.workflow !== undefined) {
|
|
373
|
-
const graph = runtime.workflows.get(params.workflow);
|
|
374
|
-
if (!graph) {
|
|
375
|
-
const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
|
|
376
|
-
return {
|
|
377
|
-
content: [{
|
|
378
|
-
type: "text",
|
|
379
|
-
text: `No workflow graph matches #${params.workflow}.${known ? ` Known graphs: ${known}.` : ""}`,
|
|
380
|
-
}],
|
|
381
|
-
details: {},
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
|
|
385
|
-
return {
|
|
386
|
-
content: [{
|
|
387
|
-
type: "text",
|
|
388
|
-
text: `Stopped workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? `; cancelled ${cancelled.map((id) => `#${id}`).join(", ")}` : "; no node had started"}. Its summary reports the completed work, and each node keeps its own run evidence.`,
|
|
389
|
-
}],
|
|
390
|
-
details: {},
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
const graphStops: string[] = [];
|
|
394
|
-
const graphStopPromises: Array<Promise<void>> = [];
|
|
395
|
-
const graphRunIds = new Set<number>();
|
|
396
|
-
if (params.all === true) {
|
|
397
|
-
const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
|
|
398
|
-
for (const graph of graphs) for (const node of graph.nodes) { if (node.runId !== undefined) graphRunIds.add(node.runId); }
|
|
399
|
-
graphStopPromises.push(...graphs.map(async (graph) => {
|
|
400
|
-
const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
|
|
401
|
-
graphStops.push(
|
|
402
|
-
`workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
|
|
403
|
-
);
|
|
404
|
-
}));
|
|
405
|
-
}
|
|
406
331
|
const candidateIds = params.all === true
|
|
407
332
|
? [...new Set([
|
|
408
333
|
...runtime.runControllers.keys(),
|
|
@@ -414,17 +339,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
414
339
|
const targets = params.all === true
|
|
415
340
|
? candidateIds
|
|
416
341
|
: params.id?.trim() ? matchRunIds(candidateIds, params.id.trim()) : [];
|
|
417
|
-
const threadTargets = targets.filter((id) => !graphRunIds.has(id));
|
|
418
342
|
|
|
419
|
-
if (
|
|
420
|
-
await Promise.all(graphStopPromises);
|
|
343
|
+
if (targets.length === 0) {
|
|
421
344
|
const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
|
|
422
|
-
if (graphStops.length > 0) {
|
|
423
|
-
return {
|
|
424
|
-
content: [{ type: "text", text: `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}.` }],
|
|
425
|
-
details: {},
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
345
|
return {
|
|
429
346
|
content: [{ type: "text", text: params.all === true
|
|
430
347
|
? "No active subagent runs to stop."
|
|
@@ -433,11 +350,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
433
350
|
};
|
|
434
351
|
}
|
|
435
352
|
|
|
436
|
-
const
|
|
437
|
-
await Promise.all(graphStopPromises);
|
|
438
|
-
const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopping;
|
|
353
|
+
const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopThreads(runtime, targets);
|
|
439
354
|
if (completionResults.length > 0) {
|
|
440
|
-
runtime.sendCompletionGroup(completionResults.
|
|
355
|
+
runtime.sendCompletionGroup(completionResults.map((result) => ({
|
|
441
356
|
agent: result.agent,
|
|
442
357
|
block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
|
|
443
358
|
triggerTurn: true,
|
|
@@ -448,7 +363,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
448
363
|
return {
|
|
449
364
|
content: [{
|
|
450
365
|
type: "text",
|
|
451
|
-
text:
|
|
366
|
+
text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
|
|
452
367
|
}],
|
|
453
368
|
details: {},
|
|
454
369
|
};
|