@narumitw/pi-subagents 2.0.1 → 2.0.3
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/README.md +20 -7
- package/dist/chunks/auto-transport-SY2VHUFH.ts +109 -0
- package/dist/chunks/auto-transport-SY2VHUFH.ts.map +7 -0
- package/dist/chunks/capability-grant-CGEWOEKE.ts +19 -0
- package/dist/chunks/capability-grant-CGEWOEKE.ts.map +7 -0
- package/dist/chunks/chunk-434NII74.ts +282 -0
- package/dist/chunks/chunk-434NII74.ts.map +7 -0
- package/dist/chunks/chunk-47SK2QYC.ts +56 -0
- package/dist/chunks/chunk-47SK2QYC.ts.map +7 -0
- package/dist/chunks/chunk-6KJ34M6S.ts +159 -0
- package/dist/chunks/chunk-6KJ34M6S.ts.map +7 -0
- package/dist/chunks/chunk-7OBINKFM.ts +80 -0
- package/dist/chunks/chunk-7OBINKFM.ts.map +7 -0
- package/dist/chunks/chunk-7QPPBBXZ.ts +335 -0
- package/dist/chunks/chunk-7QPPBBXZ.ts.map +7 -0
- package/dist/chunks/chunk-AEUYS7JC.ts +73 -0
- package/dist/chunks/chunk-AEUYS7JC.ts.map +7 -0
- package/dist/chunks/chunk-BFK2Z4ZF.ts +189 -0
- package/dist/chunks/chunk-BFK2Z4ZF.ts.map +7 -0
- package/dist/chunks/chunk-BOAXY55Y.ts +153 -0
- package/dist/chunks/chunk-BOAXY55Y.ts.map +7 -0
- package/dist/chunks/chunk-C4L6P266.ts +22 -0
- package/dist/chunks/chunk-C4L6P266.ts.map +7 -0
- package/dist/chunks/chunk-DPPVEQAM.ts +29 -0
- package/dist/chunks/chunk-DPPVEQAM.ts.map +7 -0
- package/dist/chunks/chunk-DQMN4OYM.ts +913 -0
- package/dist/chunks/chunk-DQMN4OYM.ts.map +7 -0
- package/dist/chunks/chunk-DSOOH73Y.ts +238 -0
- package/dist/chunks/chunk-DSOOH73Y.ts.map +7 -0
- package/dist/chunks/chunk-EFBPISNT.ts +421 -0
- package/dist/chunks/chunk-EFBPISNT.ts.map +7 -0
- package/dist/chunks/chunk-EWWXFU7N.ts +150 -0
- package/dist/chunks/chunk-EWWXFU7N.ts.map +7 -0
- package/dist/chunks/chunk-F4L2UVSK.ts +380 -0
- package/dist/chunks/chunk-F4L2UVSK.ts.map +7 -0
- package/dist/chunks/chunk-F5YWVHQX.ts +1543 -0
- package/dist/chunks/chunk-F5YWVHQX.ts.map +7 -0
- package/dist/chunks/chunk-G3RSMSXJ.ts +63 -0
- package/dist/chunks/chunk-G3RSMSXJ.ts.map +7 -0
- package/dist/chunks/chunk-G6VZTCFH.ts +70 -0
- package/dist/chunks/chunk-G6VZTCFH.ts.map +7 -0
- package/dist/chunks/chunk-H3FP6DLR.ts +160 -0
- package/dist/chunks/chunk-H3FP6DLR.ts.map +7 -0
- package/dist/chunks/chunk-HA36LPCO.ts +130 -0
- package/dist/chunks/chunk-HA36LPCO.ts.map +7 -0
- package/dist/chunks/chunk-HKC4ES4B.ts +65 -0
- package/dist/chunks/chunk-HKC4ES4B.ts.map +7 -0
- package/dist/chunks/chunk-HOP5FXDT.ts +27 -0
- package/dist/chunks/chunk-HOP5FXDT.ts.map +7 -0
- package/dist/chunks/chunk-I2FAK44T.ts +324 -0
- package/dist/chunks/chunk-I2FAK44T.ts.map +7 -0
- package/dist/chunks/chunk-IGAMVWFN.ts +139 -0
- package/dist/chunks/chunk-IGAMVWFN.ts.map +7 -0
- package/dist/chunks/chunk-KMGKCEO4.ts +38 -0
- package/dist/chunks/chunk-KMGKCEO4.ts.map +7 -0
- package/dist/chunks/chunk-N7BLVXKK.ts +73 -0
- package/dist/chunks/chunk-N7BLVXKK.ts.map +7 -0
- package/dist/chunks/chunk-NIF42QMF.ts +297 -0
- package/dist/chunks/chunk-NIF42QMF.ts.map +7 -0
- package/dist/chunks/chunk-O4VO6JUJ.ts +52 -0
- package/dist/chunks/chunk-O4VO6JUJ.ts.map +7 -0
- package/dist/chunks/chunk-ONDTY4EL.ts +91 -0
- package/dist/chunks/chunk-ONDTY4EL.ts.map +7 -0
- package/dist/chunks/chunk-OVPHFGKO.ts +1769 -0
- package/dist/chunks/chunk-OVPHFGKO.ts.map +7 -0
- package/dist/chunks/chunk-P7OH4XMF.ts +60 -0
- package/dist/chunks/chunk-P7OH4XMF.ts.map +7 -0
- package/dist/chunks/chunk-PSK43Y6A.ts +339 -0
- package/dist/chunks/chunk-PSK43Y6A.ts.map +7 -0
- package/dist/chunks/chunk-QBORTI4W.ts +468 -0
- package/dist/chunks/chunk-QBORTI4W.ts.map +7 -0
- package/dist/chunks/chunk-QDVGH2X7.ts +171 -0
- package/dist/chunks/chunk-QDVGH2X7.ts.map +7 -0
- package/dist/chunks/chunk-RHRQMT7Q.ts +490 -0
- package/dist/chunks/chunk-RHRQMT7Q.ts.map +7 -0
- package/dist/chunks/chunk-RRR66UWR.ts +28 -0
- package/dist/chunks/chunk-RRR66UWR.ts.map +7 -0
- package/dist/chunks/chunk-RSUXZD6S.ts +275 -0
- package/dist/chunks/chunk-RSUXZD6S.ts.map +7 -0
- package/dist/chunks/chunk-RTCVYIZA.ts +221 -0
- package/dist/chunks/chunk-RTCVYIZA.ts.map +7 -0
- package/dist/chunks/chunk-S2IWVK3J.ts +44 -0
- package/dist/chunks/chunk-S2IWVK3J.ts.map +7 -0
- package/dist/chunks/chunk-SCZ33MYW.ts +52 -0
- package/dist/chunks/chunk-SCZ33MYW.ts.map +7 -0
- package/dist/chunks/chunk-SWGQLFSD.ts +60 -0
- package/dist/chunks/chunk-SWGQLFSD.ts.map +7 -0
- package/dist/chunks/chunk-UMBPMVJW.ts +22 -0
- package/dist/chunks/chunk-UMBPMVJW.ts.map +7 -0
- package/dist/chunks/chunk-UVFVHIOP.ts +735 -0
- package/dist/chunks/chunk-UVFVHIOP.ts.map +7 -0
- package/dist/chunks/completion-delivery-YPOWSSV3.ts +16 -0
- package/dist/chunks/completion-delivery-YPOWSSV3.ts.map +7 -0
- package/dist/chunks/config-status-J4GPWP46.ts +34 -0
- package/dist/chunks/config-status-J4GPWP46.ts.map +7 -0
- package/dist/chunks/config-ui-3IBMHTQB.ts +1146 -0
- package/dist/chunks/config-ui-3IBMHTQB.ts.map +7 -0
- package/dist/chunks/consult-NYXVDN5G.ts +518 -0
- package/dist/chunks/consult-NYXVDN5G.ts.map +7 -0
- package/dist/chunks/context-QDKLVQXE.ts +11 -0
- package/dist/chunks/context-QDKLVQXE.ts.map +7 -0
- package/dist/chunks/create-stateful-transport-4WKZHRSI.ts +130 -0
- package/dist/chunks/create-stateful-transport-4WKZHRSI.ts.map +7 -0
- package/dist/chunks/cwd-policy-NB6XZ5GF.ts +17 -0
- package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +7 -0
- package/dist/chunks/delegation-contract-WJPT4FVS.ts +24 -0
- package/dist/chunks/delegation-contract-WJPT4FVS.ts.map +7 -0
- package/dist/chunks/discovery-K25T3SH4.ts +12 -0
- package/dist/chunks/discovery-K25T3SH4.ts.map +7 -0
- package/dist/chunks/execution-DS2DEIQZ.ts +4034 -0
- package/dist/chunks/execution-DS2DEIQZ.ts.map +7 -0
- package/dist/chunks/in-process-transport-TEYAWSEC.ts +38 -0
- package/dist/chunks/in-process-transport-TEYAWSEC.ts.map +7 -0
- package/dist/chunks/inspect-UOQQ3KNL.ts +619 -0
- package/dist/chunks/inspect-UOQQ3KNL.ts.map +7 -0
- package/dist/chunks/peer-communication-KL36Z6CO.ts +294 -0
- package/dist/chunks/peer-communication-KL36Z6CO.ts.map +7 -0
- package/dist/chunks/persistence-VSGXAW4P.ts +344 -0
- package/dist/chunks/persistence-VSGXAW4P.ts.map +7 -0
- package/dist/chunks/registry-E6XPJB7L.ts +1324 -0
- package/dist/chunks/registry-E6XPJB7L.ts.map +7 -0
- package/dist/chunks/retained-semantic-state-7WXSGRJU.ts +81 -0
- package/dist/chunks/retained-semantic-state-7WXSGRJU.ts.map +7 -0
- package/dist/chunks/rpc-transport-Y6LA5BOP.ts +1154 -0
- package/dist/chunks/rpc-transport-Y6LA5BOP.ts.map +7 -0
- package/dist/chunks/runtime-policy-5YELCOVC.ts +15 -0
- package/dist/chunks/runtime-policy-5YELCOVC.ts.map +7 -0
- package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +19 -0
- package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +7 -0
- package/dist/chunks/spawn-idempotency-QGHO2WKC.ts +13 -0
- package/dist/chunks/spawn-idempotency-QGHO2WKC.ts.map +7 -0
- package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +15 -0
- package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +7 -0
- package/dist/chunks/subprocess-transport-C2XVR25R.ts +158 -0
- package/dist/chunks/subprocess-transport-C2XVR25R.ts.map +7 -0
- package/dist/chunks/workspace-WDKLN72J.ts +11 -0
- package/dist/chunks/workspace-WDKLN72J.ts.map +7 -0
- package/dist/index.ts +1057 -0
- package/dist/index.ts.map +7 -0
- package/package.json +9 -5
- package/src/index.ts +1 -1
- package/src/settings-reader.ts +208 -0
- package/src/settings.ts +22 -187
- package/src/stateful-registration.ts +1230 -0
- package/src/stateful-safety.ts +1 -1
- package/src/stateful.ts +2 -1234
- package/src/subagents-extension.ts +307 -0
- package/src/subagents.ts +1 -308
package/src/stateful.ts
CHANGED
|
@@ -1,1237 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Stateful registration remains one lifecycle owner so session replacement, persistence,
|
|
3
|
-
* capability revocation, workspace cleanup, and completion delivery cannot reorder.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
8
|
-
import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
9
|
-
import { Type } from "typebox";
|
|
10
|
-
import {
|
|
11
|
-
type AgentScope,
|
|
12
|
-
type CompletionDelivery,
|
|
13
|
-
isThinkingLevel,
|
|
14
|
-
type SubagentRuntimeSettings,
|
|
15
|
-
type SubagentSettings,
|
|
16
|
-
type SubagentTransportKind,
|
|
17
|
-
THINKING_LEVELS,
|
|
18
|
-
} from "./agents/types.js";
|
|
19
|
-
import type { CompletionDeliveryBroker } from "./completion-delivery.js";
|
|
20
|
-
import type { ContextMode } from "./context.js";
|
|
21
|
-
import type { CreateStatefulTransportOptions } from "./create-stateful-transport.js";
|
|
22
|
-
import { DelegationContractSchema } from "./delegation-contract.js";
|
|
23
|
-
import type { ChildSessionFactory, ParentRuntimeSnapshot } from "./in-process-transport.js";
|
|
24
|
-
import {
|
|
25
|
-
DEFAULT_MAX_CONTEXT_BYTES,
|
|
26
|
-
MAX_SUBAGENT_TIMEOUT_MS,
|
|
27
|
-
MAX_TOOL_MESSAGE_BYTES,
|
|
28
|
-
truncateUtf8,
|
|
29
|
-
} from "./limits.js";
|
|
30
|
-
import type { AgentPersistence } from "./persistence.js";
|
|
31
|
-
import type {
|
|
32
|
-
AgentRegistry,
|
|
33
|
-
AgentRunInspectionDetail,
|
|
34
|
-
AgentRunInspectionSummary,
|
|
35
|
-
ManagedAgent,
|
|
36
|
-
} from "./registry.js";
|
|
37
|
-
import { SUBAGENT_RESULT_FORMATS, type SubagentResultFormat } from "./result-contract.js";
|
|
38
|
-
import { DEFAULT_DELEGATION_CWD_POLICY } from "./settings/inspection.js";
|
|
39
|
-
import { readSubagentSettings } from "./settings.js";
|
|
40
|
-
import {
|
|
41
|
-
assertSpawnIdempotencyKey,
|
|
42
|
-
MAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,
|
|
43
|
-
} from "./spawn-idempotency.js";
|
|
44
|
-
import { summarizeStatefulAgent } from "./stateful-agent-view.js";
|
|
45
|
-
import { resolveCompletionDelivery, resolveStatefulTransportKind } from "./stateful-config.js";
|
|
46
|
-
import { createSpawnPromptGuidelines } from "./stateful-guidance.js";
|
|
47
|
-
import { assertCurrentSpawn, waitForOwnedSpawn } from "./stateful-lifecycle.js";
|
|
48
|
-
import { resolveStatefulLimits, type StatefulLimits } from "./stateful-limits.js";
|
|
49
|
-
import { createStatefulToolRenderer } from "./stateful-render.js";
|
|
50
|
-
import { confirmProjectAgent } from "./stateful-safety.js";
|
|
51
|
-
import { MAX_TASK_NAME_LENGTH } from "./task-path.js";
|
|
52
|
-
import { MAX_SUBAGENT_TOOL_CALLS, MAX_SUBAGENT_TURNS } from "./turn-budget.js";
|
|
53
|
-
|
|
54
|
-
export { isWriteCapable } from "./stateful-safety.js";
|
|
55
|
-
|
|
56
|
-
import {
|
|
57
|
-
MailboxParamsSchema,
|
|
58
|
-
ManageParamsSchema,
|
|
59
|
-
validateMailboxParams,
|
|
60
|
-
validateManageParams,
|
|
61
|
-
} from "./stateful-tool-params.js";
|
|
62
|
-
import type { WorkspaceManager } from "./workspace.js";
|
|
63
|
-
|
|
64
|
-
type CwdPolicyModule = typeof import("./cwd-policy.js");
|
|
65
|
-
type StateLifecycleModule = typeof import("./stateful-lifecycle.js");
|
|
66
|
-
|
|
67
|
-
type StatefulSessionModules = {
|
|
68
|
-
broker: typeof import("./completion-delivery.js");
|
|
69
|
-
peerCommunication: typeof import("./peer-communication.js");
|
|
70
|
-
context: typeof import("./context.js");
|
|
71
|
-
transport: typeof import("./create-stateful-transport.js");
|
|
72
|
-
cwdPolicy: CwdPolicyModule;
|
|
73
|
-
persistence: typeof import("./persistence.js");
|
|
74
|
-
registry: typeof import("./registry.js");
|
|
75
|
-
lifecycle: StateLifecycleModule;
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
type StatefulSpawnModules = {
|
|
79
|
-
agents: typeof import("./agents/discovery.js");
|
|
80
|
-
capabilityGrant: typeof import("./capability-grant.js");
|
|
81
|
-
context: typeof import("./context.js");
|
|
82
|
-
cwdPolicy: CwdPolicyModule;
|
|
83
|
-
delegationContract: typeof import("./delegation-contract.js");
|
|
84
|
-
runtimePolicy: typeof import("./execution/runtime-policy.js");
|
|
85
|
-
retainedSemanticState: typeof import("./retained-semantic-state.js");
|
|
86
|
-
semanticSnapshot: typeof import("./semantic-snapshot.js");
|
|
87
|
-
spawnIdempotency: typeof import("./spawn-idempotency.js");
|
|
88
|
-
};
|
|
89
|
-
|
|
90
|
-
let statefulSessionModules: Promise<StatefulSessionModules> | undefined;
|
|
91
|
-
let statefulSpawnModules: Promise<StatefulSpawnModules> | undefined;
|
|
92
|
-
let workspaceModule: Promise<typeof import("./workspace.js")> | undefined;
|
|
93
|
-
|
|
94
|
-
function loadStatefulSessionModules(): Promise<StatefulSessionModules> {
|
|
95
|
-
statefulSessionModules ??= Promise.all([
|
|
96
|
-
import("./completion-delivery.js"),
|
|
97
|
-
import("./peer-communication.js"),
|
|
98
|
-
import("./context.js"),
|
|
99
|
-
import("./create-stateful-transport.js"),
|
|
100
|
-
import("./cwd-policy.js"),
|
|
101
|
-
import("./persistence.js"),
|
|
102
|
-
import("./registry.js"),
|
|
103
|
-
import("./stateful-lifecycle.js"),
|
|
104
|
-
])
|
|
105
|
-
.then(
|
|
106
|
-
([
|
|
107
|
-
broker,
|
|
108
|
-
peerCommunication,
|
|
109
|
-
context,
|
|
110
|
-
transport,
|
|
111
|
-
cwdPolicy,
|
|
112
|
-
persistence,
|
|
113
|
-
registry,
|
|
114
|
-
lifecycle,
|
|
115
|
-
]) => ({
|
|
116
|
-
broker,
|
|
117
|
-
peerCommunication,
|
|
118
|
-
context,
|
|
119
|
-
transport,
|
|
120
|
-
cwdPolicy,
|
|
121
|
-
persistence,
|
|
122
|
-
registry,
|
|
123
|
-
lifecycle,
|
|
124
|
-
}),
|
|
125
|
-
)
|
|
126
|
-
.catch((error: unknown) => {
|
|
127
|
-
statefulSessionModules = undefined;
|
|
128
|
-
throw error;
|
|
129
|
-
});
|
|
130
|
-
return statefulSessionModules;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
function loadStatefulSpawnModules(): Promise<StatefulSpawnModules> {
|
|
134
|
-
statefulSpawnModules ??= Promise.all([
|
|
135
|
-
import("./agents/discovery.js"),
|
|
136
|
-
import("./capability-grant.js"),
|
|
137
|
-
import("./context.js"),
|
|
138
|
-
import("./cwd-policy.js"),
|
|
139
|
-
import("./delegation-contract.js"),
|
|
140
|
-
import("./execution/runtime-policy.js"),
|
|
141
|
-
import("./retained-semantic-state.js"),
|
|
142
|
-
import("./semantic-snapshot.js"),
|
|
143
|
-
import("./spawn-idempotency.js"),
|
|
144
|
-
])
|
|
145
|
-
.then(
|
|
146
|
-
([
|
|
147
|
-
agents,
|
|
148
|
-
capabilityGrant,
|
|
149
|
-
context,
|
|
150
|
-
cwdPolicy,
|
|
151
|
-
delegationContract,
|
|
152
|
-
runtimePolicy,
|
|
153
|
-
retainedSemanticState,
|
|
154
|
-
semanticSnapshot,
|
|
155
|
-
spawnIdempotency,
|
|
156
|
-
]) => ({
|
|
157
|
-
agents,
|
|
158
|
-
capabilityGrant,
|
|
159
|
-
context,
|
|
160
|
-
cwdPolicy,
|
|
161
|
-
delegationContract,
|
|
162
|
-
runtimePolicy,
|
|
163
|
-
retainedSemanticState,
|
|
164
|
-
semanticSnapshot,
|
|
165
|
-
spawnIdempotency,
|
|
166
|
-
}),
|
|
167
|
-
)
|
|
168
|
-
.catch((error: unknown) => {
|
|
169
|
-
statefulSpawnModules = undefined;
|
|
170
|
-
throw error;
|
|
171
|
-
});
|
|
172
|
-
return statefulSpawnModules;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
async function loadWorkspaceModule(): Promise<typeof import("./workspace.js")> {
|
|
176
|
-
workspaceModule ??= import("./workspace.js").catch((error: unknown) => {
|
|
177
|
-
workspaceModule = undefined;
|
|
178
|
-
throw error;
|
|
179
|
-
});
|
|
180
|
-
return workspaceModule;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const ContextModeSchema = Type.Union([
|
|
184
|
-
StringEnum(["none", "all", "summary"] as const),
|
|
185
|
-
Type.Number({ minimum: 1, description: "Include the most recent N user turns." }),
|
|
186
|
-
]);
|
|
187
|
-
const ScopeSchema = StringEnum(["user", "project", "both"] as const, {
|
|
188
|
-
description:
|
|
189
|
-
'Per-invocation custom agent scope for this spawn. Default: "user". Use "project" for project-local agents or "both" for user and project agents; the selected scope is retained for follow-ups.',
|
|
190
|
-
default: "user",
|
|
191
|
-
});
|
|
192
|
-
const StatefulThinkingLevelSchema = StringEnum(THINKING_LEVELS, {
|
|
193
|
-
description:
|
|
194
|
-
"Optional requested Pi thinking level selected for this task difficulty; retained for every turn of the spawned agent.",
|
|
195
|
-
});
|
|
196
|
-
const StatefulTimeoutSchema = Type.Integer({
|
|
197
|
-
minimum: 1,
|
|
198
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
199
|
-
description:
|
|
200
|
-
"Work deadline in milliseconds selected for the task difficulty. On expiry, Pi aborts the work and makes one separately bounded summary attempt. Retained as the agent default.",
|
|
201
|
-
});
|
|
202
|
-
const StatefulTurnLimitFields = {
|
|
203
|
-
idleTimeoutMs: Type.Optional(
|
|
204
|
-
Type.Integer({
|
|
205
|
-
minimum: 1,
|
|
206
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
207
|
-
description:
|
|
208
|
-
"Maximum milliseconds without a completed assistant turn or tool result; retained as the agent default.",
|
|
209
|
-
}),
|
|
210
|
-
),
|
|
211
|
-
maxTurns: Type.Optional(
|
|
212
|
-
Type.Integer({
|
|
213
|
-
minimum: 1,
|
|
214
|
-
maximum: MAX_SUBAGENT_TURNS,
|
|
215
|
-
description: "Maximum unfinished assistant turns; retained as the agent default.",
|
|
216
|
-
}),
|
|
217
|
-
),
|
|
218
|
-
maxToolCalls: Type.Optional(
|
|
219
|
-
Type.Integer({
|
|
220
|
-
minimum: 1,
|
|
221
|
-
maximum: MAX_SUBAGENT_TOOL_CALLS,
|
|
222
|
-
description: "Maximum tool calls; retained as the agent default.",
|
|
223
|
-
}),
|
|
224
|
-
),
|
|
225
|
-
};
|
|
226
|
-
export interface StatefulSubagentDependencies {
|
|
227
|
-
blockingEnabled?: boolean;
|
|
228
|
-
createInProcessSession?: ChildSessionFactory;
|
|
229
|
-
workspaceManager?: WorkspaceManager;
|
|
230
|
-
settings?: SubagentRuntimeSettings;
|
|
231
|
-
getSettings?: () => SubagentSettings | undefined;
|
|
232
|
-
loadTransport?: CreateStatefulTransportOptions["loadTransport"];
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export interface StatefulSubagentRuntimeStatus {
|
|
236
|
-
enabled: boolean;
|
|
237
|
-
initialized: boolean;
|
|
238
|
-
transport: SubagentTransportKind;
|
|
239
|
-
completionDelivery: CompletionDelivery;
|
|
240
|
-
limits: StatefulLimits;
|
|
241
|
-
activeAgents: number;
|
|
242
|
-
retainedAgents: number;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
export interface StatefulSubagentController {
|
|
246
|
-
getCompletionDelivery(): CompletionDelivery;
|
|
247
|
-
setCompletionDelivery(value: CompletionDelivery): void;
|
|
248
|
-
setAgentCatalog(value: string): void;
|
|
249
|
-
refreshSettingsGuidance(): void;
|
|
250
|
-
getRuntimeStatus(): StatefulSubagentRuntimeStatus;
|
|
251
|
-
listAgents(includeClosed?: boolean): ManagedAgent[];
|
|
252
|
-
listRunInspection(includeClosed?: boolean): AgentRunInspectionSummary[];
|
|
253
|
-
getRunInspection(agentId: string): AgentRunInspectionDetail | undefined;
|
|
254
|
-
clearAgents(): Promise<number>;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
interface StatefulActionToolResult {
|
|
258
|
-
content: Array<{ type: "text"; text: string }>;
|
|
259
|
-
details: Record<string, unknown>;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
export function registerStatefulSubagents(
|
|
263
|
-
pi: ExtensionAPI,
|
|
264
|
-
dependencies: StatefulSubagentDependencies = {},
|
|
265
|
-
): StatefulSubagentController {
|
|
266
|
-
const settings = Object.hasOwn(dependencies, "settings")
|
|
267
|
-
? (dependencies.settings ?? {})
|
|
268
|
-
: (readSubagentSettings()?.stateful ?? {});
|
|
269
|
-
const blockingEnabled = dependencies.blockingEnabled !== false;
|
|
270
|
-
const enabled = settings.enabled !== false;
|
|
271
|
-
const transportKind = resolveStatefulTransportKind(settings.transport);
|
|
272
|
-
let completionDelivery = resolveCompletionDelivery(settings.completionDelivery);
|
|
273
|
-
let runtimeLimits = resolveStatefulLimits(settings);
|
|
274
|
-
let agentCatalog = "";
|
|
275
|
-
let completionBroker: CompletionDeliveryBroker | undefined;
|
|
276
|
-
let peerBroker: import("./peer-communication.js").PeerCommunicationBroker | undefined;
|
|
277
|
-
let refreshSpawnToolRegistration: (() => void) | undefined;
|
|
278
|
-
let registry: AgentRegistry | undefined;
|
|
279
|
-
let persistence: AgentPersistence | undefined;
|
|
280
|
-
let sweepTimer: NodeJS.Timeout | undefined;
|
|
281
|
-
let runtimeGeneration = 0;
|
|
282
|
-
let runtimeTransition: Promise<void> = Promise.resolve();
|
|
283
|
-
let workspaceManager = dependencies.workspaceManager;
|
|
284
|
-
const getWorkspaceManager = async () => {
|
|
285
|
-
if (workspaceManager) return workspaceManager;
|
|
286
|
-
const { WorkspaceManager } = await loadWorkspaceModule();
|
|
287
|
-
workspaceManager = new WorkspaceManager();
|
|
288
|
-
return workspaceManager;
|
|
289
|
-
};
|
|
290
|
-
const isolatedAgents = new Map<string, string>();
|
|
291
|
-
const seenMessageIds = new Set<string>();
|
|
292
|
-
type PendingIdempotentSpawn = {
|
|
293
|
-
generation: number;
|
|
294
|
-
requestHash: string;
|
|
295
|
-
promise: Promise<ManagedAgent>;
|
|
296
|
-
};
|
|
297
|
-
const pendingIdempotentSpawns = new Map<string, PendingIdempotentSpawn>();
|
|
298
|
-
const parentRuntime: ParentRuntimeSnapshot = { model: undefined, thinkingLevel: "off" };
|
|
299
|
-
const getCurrentSettings = () =>
|
|
300
|
-
dependencies.getSettings ? dependencies.getSettings() : readSubagentSettings();
|
|
301
|
-
const getCurrentStatefulSettings = () =>
|
|
302
|
-
dependencies.getSettings ? (dependencies.getSettings()?.stateful ?? {}) : settings;
|
|
303
|
-
|
|
304
|
-
const clearAgents = async (): Promise<number> => {
|
|
305
|
-
const generation = runtimeGeneration;
|
|
306
|
-
const currentRegistry = registry;
|
|
307
|
-
const currentPersistence = persistence;
|
|
308
|
-
if (!currentRegistry) return 0;
|
|
309
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
310
|
-
const count = currentRegistry.list().length;
|
|
311
|
-
const clear = async () => {
|
|
312
|
-
await currentRegistry.closeAll();
|
|
313
|
-
if (generation !== runtimeGeneration) return;
|
|
314
|
-
await currentWorkspaceManager.cleanupAll();
|
|
315
|
-
isolatedAgents.clear();
|
|
316
|
-
seenMessageIds.clear();
|
|
317
|
-
await currentPersistence?.delete();
|
|
318
|
-
};
|
|
319
|
-
const transition = runtimeTransition.then(clear, clear);
|
|
320
|
-
runtimeTransition = transition.catch(() => undefined);
|
|
321
|
-
await transition;
|
|
322
|
-
return count;
|
|
323
|
-
};
|
|
324
|
-
const controller: StatefulSubagentController = {
|
|
325
|
-
getCompletionDelivery() {
|
|
326
|
-
return completionDelivery;
|
|
327
|
-
},
|
|
328
|
-
setCompletionDelivery(value) {
|
|
329
|
-
completionDelivery = value;
|
|
330
|
-
completionBroker?.setDelivery(value);
|
|
331
|
-
refreshSpawnToolRegistration?.();
|
|
332
|
-
},
|
|
333
|
-
setAgentCatalog(value) {
|
|
334
|
-
agentCatalog = value;
|
|
335
|
-
refreshSpawnToolRegistration?.();
|
|
336
|
-
},
|
|
337
|
-
refreshSettingsGuidance() {
|
|
338
|
-
refreshSpawnToolRegistration?.();
|
|
339
|
-
},
|
|
340
|
-
getRuntimeStatus() {
|
|
341
|
-
const counts = registry?.inspectionCounts() ?? { activeAgents: 0, retainedAgents: 0 };
|
|
342
|
-
return {
|
|
343
|
-
enabled,
|
|
344
|
-
initialized: registry !== undefined,
|
|
345
|
-
transport: transportKind,
|
|
346
|
-
completionDelivery,
|
|
347
|
-
limits: { ...runtimeLimits },
|
|
348
|
-
...counts,
|
|
349
|
-
};
|
|
350
|
-
},
|
|
351
|
-
listAgents(includeClosed = false) {
|
|
352
|
-
return registry?.list(includeClosed) ?? [];
|
|
353
|
-
},
|
|
354
|
-
listRunInspection(includeClosed = false) {
|
|
355
|
-
return registry?.listInspection(includeClosed) ?? [];
|
|
356
|
-
},
|
|
357
|
-
getRunInspection(agentId) {
|
|
358
|
-
return registry?.getInspection(agentId);
|
|
359
|
-
},
|
|
360
|
-
clearAgents,
|
|
361
|
-
};
|
|
362
|
-
if (!enabled) return controller;
|
|
363
|
-
|
|
364
|
-
const requireRegistry = () => {
|
|
365
|
-
if (!registry) throw new Error("Stateful subagents are not initialized for this session");
|
|
366
|
-
return registry;
|
|
367
|
-
};
|
|
368
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
369
|
-
const generation = ++runtimeGeneration;
|
|
370
|
-
completionBroker?.close();
|
|
371
|
-
completionBroker = undefined;
|
|
372
|
-
const previousPeerBroker = peerBroker;
|
|
373
|
-
peerBroker = undefined;
|
|
374
|
-
if (sweepTimer) clearInterval(sweepTimer);
|
|
375
|
-
sweepTimer = undefined;
|
|
376
|
-
const previousRegistry = registry;
|
|
377
|
-
registry = undefined;
|
|
378
|
-
persistence = undefined;
|
|
379
|
-
isolatedAgents.clear();
|
|
380
|
-
seenMessageIds.clear();
|
|
381
|
-
pendingIdempotentSpawns.clear();
|
|
382
|
-
const initialize = async () => {
|
|
383
|
-
await previousPeerBroker?.close();
|
|
384
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
385
|
-
const modules = await loadStatefulSessionModules();
|
|
386
|
-
const cleanupErrors = await modules.lifecycle.disposeStatefulRuntime(
|
|
387
|
-
previousRegistry,
|
|
388
|
-
currentWorkspaceManager,
|
|
389
|
-
);
|
|
390
|
-
if (generation !== runtimeGeneration) return;
|
|
391
|
-
if (cleanupErrors.length > 0 && ctx.hasUI) {
|
|
392
|
-
ctx.ui.notify(
|
|
393
|
-
`Previous subagent runtime cleanup reported ${cleanupErrors.length} error(s).`,
|
|
394
|
-
"warning",
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
parentRuntime.model = ctx.model;
|
|
398
|
-
parentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(pi.getThinkingLevel());
|
|
399
|
-
const sessionSettings = getCurrentStatefulSettings();
|
|
400
|
-
const nextLimits = resolveStatefulLimits(sessionSettings);
|
|
401
|
-
const owner =
|
|
402
|
-
ctx.sessionManager.getSessionId?.() ??
|
|
403
|
-
ctx.sessionManager.getSessionFile?.() ??
|
|
404
|
-
`ephemeral:${ctx.cwd}`;
|
|
405
|
-
const sessionPersistence = new modules.persistence.AgentPersistence(owner, {
|
|
406
|
-
retentionDays: sessionSettings.retentionDays,
|
|
407
|
-
maxStoredAgents: nextLimits.maxStoredAgents,
|
|
408
|
-
});
|
|
409
|
-
let nextRegistry: AgentRegistry;
|
|
410
|
-
let transport: import("./transport.js").SubagentTransport;
|
|
411
|
-
const sessionBroker = new modules.broker.CompletionDeliveryBroker(
|
|
412
|
-
pi,
|
|
413
|
-
ctx,
|
|
414
|
-
completionDelivery,
|
|
415
|
-
{
|
|
416
|
-
onDeliveryError: (error) => {
|
|
417
|
-
if (!ctx.hasUI) return;
|
|
418
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
419
|
-
ctx.ui.notify(`Subagent completion delivery failed: ${reason}`, "warning");
|
|
420
|
-
},
|
|
421
|
-
onAcknowledged: (completions, deliveredAt) => {
|
|
422
|
-
if (generation !== runtimeGeneration) return;
|
|
423
|
-
for (const completion of completions) {
|
|
424
|
-
void nextRegistry
|
|
425
|
-
.markCompletionDelivered(completion.completionId, deliveredAt)
|
|
426
|
-
.catch((error: unknown) => {
|
|
427
|
-
if (!ctx.hasUI || generation !== runtimeGeneration) return;
|
|
428
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
429
|
-
ctx.ui.notify(`Subagent completion acknowledgement failed: ${reason}`, "warning");
|
|
430
|
-
});
|
|
431
|
-
}
|
|
432
|
-
},
|
|
433
|
-
},
|
|
434
|
-
);
|
|
435
|
-
const sessionPeerBroker = new modules.peerCommunication.PeerCommunicationBroker({
|
|
436
|
-
getRegistry: () => nextRegistry,
|
|
437
|
-
sendRoot: ({ message, senderPath }) => {
|
|
438
|
-
pi.appendEntry("pi-subagent-peer-message", {
|
|
439
|
-
messageId: message.id,
|
|
440
|
-
senderId: message.senderId,
|
|
441
|
-
senderPath,
|
|
442
|
-
content: modules.context.redactPrivateText(message.content),
|
|
443
|
-
});
|
|
444
|
-
pi.sendMessage(
|
|
445
|
-
{
|
|
446
|
-
customType: "pi-subagent-peer-message",
|
|
447
|
-
content: [
|
|
448
|
-
"Message Type: SUBAGENT_PEER_MESSAGE",
|
|
449
|
-
"Protocol: pi-subagents:v1",
|
|
450
|
-
`Message ID: ${message.id}`,
|
|
451
|
-
`Sender ID: ${message.senderId}`,
|
|
452
|
-
`Sender Path: ${senderPath}`,
|
|
453
|
-
"Payload:",
|
|
454
|
-
message.content,
|
|
455
|
-
].join("\n"),
|
|
456
|
-
display: true,
|
|
457
|
-
details: { ...message, senderPath },
|
|
458
|
-
},
|
|
459
|
-
{ deliverAs: "steer", triggerTurn: false },
|
|
460
|
-
);
|
|
461
|
-
},
|
|
462
|
-
dispatch: (recipient, message) => transport.deliverMessage?.(recipient, message) ?? false,
|
|
463
|
-
});
|
|
464
|
-
transport = modules.transport.createStatefulTransport({
|
|
465
|
-
kind: transportKind,
|
|
466
|
-
modelRegistry: ctx.modelRegistry,
|
|
467
|
-
getParentRuntime: () => ({ ...parentRuntime }),
|
|
468
|
-
getSettings: getCurrentSettings,
|
|
469
|
-
createInProcessSession: dependencies.createInProcessSession,
|
|
470
|
-
peerRuntime: sessionPeerBroker,
|
|
471
|
-
loadTransport: dependencies.loadTransport,
|
|
472
|
-
});
|
|
473
|
-
nextRegistry = new modules.registry.AgentRegistry(transport, {
|
|
474
|
-
maxAgents: nextLimits.maxAgents,
|
|
475
|
-
maxActiveTurns: nextLimits.maxActiveTurns,
|
|
476
|
-
maxDepth: nextLimits.maxDepth,
|
|
477
|
-
maxChildrenPerAgent: nextLimits.maxChildrenPerAgent,
|
|
478
|
-
maxMailboxMessages: sessionSettings.maxMailboxMessages,
|
|
479
|
-
maxMailboxMessageBytes: sessionSettings.maxMailboxMessageBytes,
|
|
480
|
-
idleTtlMs: sessionSettings.idleTtlMs,
|
|
481
|
-
onChange: async (agents) => {
|
|
482
|
-
if (generation !== runtimeGeneration) return;
|
|
483
|
-
await sessionPersistence.save(agents);
|
|
484
|
-
if (generation !== runtimeGeneration) return;
|
|
485
|
-
for (const agent of agents) {
|
|
486
|
-
for (const message of agent.mailbox) {
|
|
487
|
-
if (seenMessageIds.has(message.id)) continue;
|
|
488
|
-
seenMessageIds.add(message.id);
|
|
489
|
-
pi.appendEntry("pi-subagent-message", {
|
|
490
|
-
senderId: message.senderId,
|
|
491
|
-
recipientId: message.recipientId,
|
|
492
|
-
content: modules.context.redactPrivateText(message.content).slice(0, 160),
|
|
493
|
-
});
|
|
494
|
-
if (
|
|
495
|
-
agent.state === "running" &&
|
|
496
|
-
message.deduplicationKey?.startsWith("completion:")
|
|
497
|
-
) {
|
|
498
|
-
try {
|
|
499
|
-
await transport.deliverMessage?.(agent, {
|
|
500
|
-
...message,
|
|
501
|
-
content: modules.context.redactPrivateText(message.content),
|
|
502
|
-
});
|
|
503
|
-
} catch {
|
|
504
|
-
// The durable parent mailbox remains the retry path for the next turn.
|
|
505
|
-
}
|
|
506
|
-
if (generation !== runtimeGeneration) return;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
},
|
|
511
|
-
onTurnComplete: (completion) => {
|
|
512
|
-
if (generation === runtimeGeneration && completion.recipientId === "root") {
|
|
513
|
-
sessionBroker.enqueue(completion);
|
|
514
|
-
}
|
|
515
|
-
},
|
|
516
|
-
});
|
|
517
|
-
const persisted = sessionPersistence.load();
|
|
518
|
-
const orphanCleanupFailures = await modules.lifecycle.cleanupPersistedWorkspaces(
|
|
519
|
-
persisted,
|
|
520
|
-
currentWorkspaceManager,
|
|
521
|
-
);
|
|
522
|
-
if (generation !== runtimeGeneration) {
|
|
523
|
-
sessionBroker.close();
|
|
524
|
-
await sessionPeerBroker.close();
|
|
525
|
-
await modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);
|
|
526
|
-
return;
|
|
527
|
-
}
|
|
528
|
-
if (ctx.hasUI && orphanCleanupFailures > 0) {
|
|
529
|
-
ctx.ui.notify("Some orphaned subagent worktrees could not be cleaned", "warning");
|
|
530
|
-
}
|
|
531
|
-
const restored = persisted
|
|
532
|
-
.filter(
|
|
533
|
-
(agent) =>
|
|
534
|
-
agent.workspaceMode !== "worktree" &&
|
|
535
|
-
((agent.agentScope !== "project" && agent.agentScope !== "both") ||
|
|
536
|
-
ctx.isProjectTrusted()),
|
|
537
|
-
)
|
|
538
|
-
.flatMap((agent) => {
|
|
539
|
-
try {
|
|
540
|
-
const target = modules.cwdPolicy.resolveSubagentTarget({
|
|
541
|
-
workspace: ctx.cwd,
|
|
542
|
-
requestedCwd: agent.cwd,
|
|
543
|
-
currentProjectTrusted: ctx.isProjectTrusted(),
|
|
544
|
-
});
|
|
545
|
-
return [
|
|
546
|
-
{ ...agent, cwd: target.cwd, target: modules.cwdPolicy.targetPolicyAudit(target) },
|
|
547
|
-
];
|
|
548
|
-
} catch {
|
|
549
|
-
return [];
|
|
550
|
-
}
|
|
551
|
-
});
|
|
552
|
-
for (const agent of restored) {
|
|
553
|
-
for (const message of agent.mailbox) seenMessageIds.add(message.id);
|
|
554
|
-
}
|
|
555
|
-
nextRegistry.restore(restored);
|
|
556
|
-
if (generation !== runtimeGeneration) {
|
|
557
|
-
sessionBroker.close();
|
|
558
|
-
await sessionPeerBroker.close();
|
|
559
|
-
await modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
registry = nextRegistry;
|
|
563
|
-
persistence = sessionPersistence;
|
|
564
|
-
completionBroker = sessionBroker;
|
|
565
|
-
peerBroker = sessionPeerBroker;
|
|
566
|
-
for (const completion of nextRegistry.listPendingCompletions()) {
|
|
567
|
-
if (completion.recipientId === "root") sessionBroker.enqueue(completion);
|
|
568
|
-
}
|
|
569
|
-
runtimeLimits = nextLimits;
|
|
570
|
-
refreshSpawnToolRegistration?.();
|
|
571
|
-
const sweepEveryMs = Math.max(
|
|
572
|
-
1_000,
|
|
573
|
-
Math.min(sessionSettings.idleTtlMs ?? 60 * 60 * 1000, 60_000),
|
|
574
|
-
);
|
|
575
|
-
sweepTimer = setInterval(() => {
|
|
576
|
-
void nextRegistry.sweepExpired().catch((error: unknown) => {
|
|
577
|
-
if (!ctx.hasUI || generation !== runtimeGeneration) return;
|
|
578
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
579
|
-
ctx.ui.notify(`Subagent expiry cleanup failed: ${reason}`, "warning");
|
|
580
|
-
});
|
|
581
|
-
}, sweepEveryMs);
|
|
582
|
-
sweepTimer.unref();
|
|
583
|
-
};
|
|
584
|
-
const transition = runtimeTransition.then(initialize, initialize);
|
|
585
|
-
runtimeTransition = transition.catch(() => undefined);
|
|
586
|
-
await transition;
|
|
587
|
-
});
|
|
588
|
-
|
|
589
|
-
pi.on("agent_start", () => {
|
|
590
|
-
completionBroker?.onParentTurnStart();
|
|
591
|
-
});
|
|
592
|
-
|
|
593
|
-
pi.on("context", (event) => {
|
|
594
|
-
completionBroker?.onParentContext(event.messages);
|
|
595
|
-
});
|
|
596
|
-
|
|
597
|
-
pi.on("agent_settled", () => {
|
|
598
|
-
completionBroker?.onParentSettled();
|
|
599
|
-
});
|
|
600
|
-
|
|
601
|
-
pi.on("model_select", (event) => {
|
|
602
|
-
parentRuntime.model = event.model;
|
|
603
|
-
});
|
|
604
|
-
|
|
605
|
-
pi.on("thinking_level_select", (event) => {
|
|
606
|
-
parentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(event.level);
|
|
607
|
-
});
|
|
608
|
-
|
|
609
|
-
pi.on("session_shutdown", async (_event, ctx) => {
|
|
610
|
-
runtimeGeneration++;
|
|
611
|
-
completionBroker?.close();
|
|
612
|
-
completionBroker = undefined;
|
|
613
|
-
const previousPeerBroker = peerBroker;
|
|
614
|
-
peerBroker = undefined;
|
|
615
|
-
if (sweepTimer) clearInterval(sweepTimer);
|
|
616
|
-
sweepTimer = undefined;
|
|
617
|
-
const previousRegistry = registry;
|
|
618
|
-
registry = undefined;
|
|
619
|
-
persistence = undefined;
|
|
620
|
-
isolatedAgents.clear();
|
|
621
|
-
seenMessageIds.clear();
|
|
622
|
-
pendingIdempotentSpawns.clear();
|
|
623
|
-
const shutdown = async () => {
|
|
624
|
-
await previousPeerBroker?.close();
|
|
625
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
626
|
-
const { disposeStatefulRuntime } = await import("./stateful-lifecycle.js");
|
|
627
|
-
const errors = await disposeStatefulRuntime(previousRegistry, currentWorkspaceManager);
|
|
628
|
-
if (errors.length > 0 && ctx.hasUI) {
|
|
629
|
-
ctx.ui.notify(`Subagent shutdown cleanup reported ${errors.length} error(s).`, "warning");
|
|
630
|
-
}
|
|
631
|
-
};
|
|
632
|
-
const transition = runtimeTransition.then(shutdown, shutdown);
|
|
633
|
-
runtimeTransition = transition.catch(() => undefined);
|
|
634
|
-
await transition;
|
|
635
|
-
});
|
|
636
|
-
|
|
637
|
-
const baseSpawnDescription = () =>
|
|
638
|
-
`Start an addressable background subagent with an opaque agentId and canonical taskPath, plus an optional thinking level and execution budgets chosen for the task difficulty, return immediately with an agentId, and receive its completion asynchronously. Detached capacity: ${runtimeLimits.maxAgents} retained agents, ${runtimeLimits.maxActiveTurns} active turns, ${runtimeLimits.maxChildrenPerAgent} direct children per agent, and depth ${runtimeLimits.maxDepth}. Working-directory target policy: ${dependencies.getSettings?.()?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY}. This controls launch targets and protected project resources, not filesystem access or sandboxing.`;
|
|
639
|
-
const spawnTool = defineTool({
|
|
640
|
-
name: "subagent_spawn",
|
|
641
|
-
label: "Spawn Subagent",
|
|
642
|
-
description: appendAgentCatalog(baseSpawnDescription(), agentCatalog),
|
|
643
|
-
promptSnippet: "Start a reusable detached subagent; completion is delivered asynchronously",
|
|
644
|
-
promptGuidelines: createSpawnPromptGuidelines(completionDelivery, blockingEnabled),
|
|
645
|
-
parameters: Type.Object({
|
|
646
|
-
agent: Type.String({ minLength: 1 }),
|
|
647
|
-
taskName: Type.Optional(
|
|
648
|
-
Type.String({
|
|
649
|
-
minLength: 1,
|
|
650
|
-
maxLength: MAX_TASK_NAME_LENGTH,
|
|
651
|
-
pattern: "^[a-z0-9_]+$",
|
|
652
|
-
description:
|
|
653
|
-
"Canonical path segment for this task; use lowercase letters, digits, and underscores.",
|
|
654
|
-
}),
|
|
655
|
-
),
|
|
656
|
-
task: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
|
|
657
|
-
thinkingLevel: Type.Optional(StatefulThinkingLevelSchema),
|
|
658
|
-
timeoutMs: Type.Optional(StatefulTimeoutSchema),
|
|
659
|
-
...StatefulTurnLimitFields,
|
|
660
|
-
cwd: Type.Optional(Type.String()),
|
|
661
|
-
agentScope: Type.Optional(ScopeSchema),
|
|
662
|
-
confirmProjectAgents: Type.Optional(Type.Boolean({ default: true })),
|
|
663
|
-
context: Type.Optional(ContextModeSchema),
|
|
664
|
-
contextEntryIds: Type.Optional(
|
|
665
|
-
Type.Array(Type.String(), { description: "Optional selected session entry IDs." }),
|
|
666
|
-
),
|
|
667
|
-
parentId: Type.Optional(
|
|
668
|
-
Type.String({ description: "Optional parent agent ID or canonical task path." }),
|
|
669
|
-
),
|
|
670
|
-
allowConcurrentWrites: Type.Optional(
|
|
671
|
-
Type.Boolean({
|
|
672
|
-
description:
|
|
673
|
-
"Deprecated compatibility field; shared-workspace concurrency is allowed by default.",
|
|
674
|
-
}),
|
|
675
|
-
),
|
|
676
|
-
workspaceMode: Type.Optional(
|
|
677
|
-
StringEnum(["shared", "worktree"] as const, {
|
|
678
|
-
description: "Use the shared workspace (default) or an opt-in disposable Git worktree.",
|
|
679
|
-
}),
|
|
680
|
-
),
|
|
681
|
-
contract: Type.Optional(DelegationContractSchema),
|
|
682
|
-
idempotencyKey: Type.Optional(
|
|
683
|
-
Type.String({
|
|
684
|
-
minLength: 1,
|
|
685
|
-
maxLength: MAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,
|
|
686
|
-
description: "Reuse the same retained agent for an exact accepted spawn retry.",
|
|
687
|
-
}),
|
|
688
|
-
),
|
|
689
|
-
resultFormat: Type.Optional(
|
|
690
|
-
StringEnum(SUBAGENT_RESULT_FORMATS, {
|
|
691
|
-
description:
|
|
692
|
-
"Use text (default), structured-v1, or the evidence-preserving structured-v2 completion contract.",
|
|
693
|
-
}),
|
|
694
|
-
),
|
|
695
|
-
}),
|
|
696
|
-
...createStatefulToolRenderer("spawn"),
|
|
697
|
-
async execute(_id, params, signal, _update, ctx) {
|
|
698
|
-
const generation = runtimeGeneration;
|
|
699
|
-
const capturedRegistry = registry;
|
|
700
|
-
let modules: StatefulSpawnModules;
|
|
701
|
-
try {
|
|
702
|
-
modules = await loadStatefulSpawnModules();
|
|
703
|
-
} catch (error) {
|
|
704
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
705
|
-
throw error;
|
|
706
|
-
}
|
|
707
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
708
|
-
let currentWorkspaceManager: WorkspaceManager;
|
|
709
|
-
try {
|
|
710
|
-
currentWorkspaceManager = await getWorkspaceManager();
|
|
711
|
-
} catch (error) {
|
|
712
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
713
|
-
throw error;
|
|
714
|
-
}
|
|
715
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
716
|
-
const scope = (params.agentScope ?? "user") as AgentScope;
|
|
717
|
-
const resultFormat = (params.resultFormat ?? "text") as SubagentResultFormat;
|
|
718
|
-
const contract = modules.delegationContract.normalizeDelegationContract(params.contract);
|
|
719
|
-
if (params.contract !== undefined && !contract) {
|
|
720
|
-
throw new Error(
|
|
721
|
-
"subagent_spawn contract must be a valid pi-subagents:delegation:v2 object",
|
|
722
|
-
);
|
|
723
|
-
}
|
|
724
|
-
modules.runtimePolicy.assertSubagentDepthAllowed();
|
|
725
|
-
assertSpawnIdempotencyKey(params.idempotencyKey);
|
|
726
|
-
const currentSettings = getCurrentSettings();
|
|
727
|
-
const target = modules.cwdPolicy.resolveSubagentTarget({
|
|
728
|
-
workspace: ctx.cwd,
|
|
729
|
-
requestedCwd: params.cwd,
|
|
730
|
-
currentProjectTrusted: ctx.isProjectTrusted(),
|
|
731
|
-
});
|
|
732
|
-
modules.cwdPolicy.assertDelegationTargetAllowed(
|
|
733
|
-
target,
|
|
734
|
-
currentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY,
|
|
735
|
-
);
|
|
736
|
-
const cwd = target.cwd;
|
|
737
|
-
const mode = resolveSpawnContextMode(params.context, params.contextEntryIds);
|
|
738
|
-
const snapshot = modules.context.buildContextSnapshot(
|
|
739
|
-
ctx.sessionManager.getBranch(),
|
|
740
|
-
mode,
|
|
741
|
-
DEFAULT_MAX_CONTEXT_BYTES,
|
|
742
|
-
params.contextEntryIds,
|
|
743
|
-
);
|
|
744
|
-
if ((scope === "project" || scope === "both") && !ctx.isProjectTrusted()) {
|
|
745
|
-
throw new Error("Project-local subagent definitions require a trusted project");
|
|
746
|
-
}
|
|
747
|
-
const resolvedAgents = modules.agents.discoverAgents(cwd, scope, currentSettings).agents;
|
|
748
|
-
const resolvedAgent = resolvedAgents.find((agent) => agent.name === params.agent);
|
|
749
|
-
if (!resolvedAgent) {
|
|
750
|
-
const available = resolvedAgents.map((agent) => agent.name).join(", ") || "none";
|
|
751
|
-
throw new Error(`Unknown subagent ${params.agent}. Available agents: ${available}`);
|
|
752
|
-
}
|
|
753
|
-
const targetSnapshot = modules.cwdPolicy.targetPolicyAudit(target);
|
|
754
|
-
const { executionPlan, semanticSnapshot } =
|
|
755
|
-
await modules.retainedSemanticState.buildRetainedSemanticState({
|
|
756
|
-
agent: resolvedAgent,
|
|
757
|
-
contract,
|
|
758
|
-
target: targetSnapshot,
|
|
759
|
-
cwd,
|
|
760
|
-
workspaceMode: params.workspaceMode === "worktree" ? "worktree" : "shared",
|
|
761
|
-
transport: transportKind,
|
|
762
|
-
resultFormat,
|
|
763
|
-
thinkingLevel: params.thinkingLevel,
|
|
764
|
-
timeoutMs: params.timeoutMs,
|
|
765
|
-
taskGeneration: 1,
|
|
766
|
-
});
|
|
767
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
768
|
-
const requestHash = modules.spawnIdempotency.hashSpawnRequest({
|
|
769
|
-
agent: params.agent,
|
|
770
|
-
taskName: params.taskName,
|
|
771
|
-
task: params.task,
|
|
772
|
-
cwd,
|
|
773
|
-
agentScope: scope,
|
|
774
|
-
thinkingLevel: params.thinkingLevel,
|
|
775
|
-
timeoutMs: params.timeoutMs,
|
|
776
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
777
|
-
maxTurns: params.maxTurns,
|
|
778
|
-
maxToolCalls: params.maxToolCalls,
|
|
779
|
-
parentId: params.parentId,
|
|
780
|
-
context: snapshot.text || undefined,
|
|
781
|
-
contextSourceIds: snapshot.sourceIds,
|
|
782
|
-
workspaceMode: params.workspaceMode ?? "shared",
|
|
783
|
-
allowConcurrentWrites: params.allowConcurrentWrites ?? false,
|
|
784
|
-
contract,
|
|
785
|
-
resultFormat,
|
|
786
|
-
});
|
|
787
|
-
if (!capturedRegistry) {
|
|
788
|
-
throw new Error("Stateful subagents are not initialized for this session");
|
|
789
|
-
}
|
|
790
|
-
const ownedRegistry = capturedRegistry;
|
|
791
|
-
const retained = ownedRegistry.findBySpawnIdempotencyKey(params.idempotencyKey, requestHash);
|
|
792
|
-
if (retained) return result(retained, `Reused ${retained.agent} as ${retained.id}.`);
|
|
793
|
-
const foundPending = params.idempotencyKey
|
|
794
|
-
? pendingIdempotentSpawns.get(params.idempotencyKey)
|
|
795
|
-
: undefined;
|
|
796
|
-
if (
|
|
797
|
-
params.idempotencyKey &&
|
|
798
|
-
foundPending &&
|
|
799
|
-
foundPending.generation !== generation &&
|
|
800
|
-
pendingIdempotentSpawns.get(params.idempotencyKey) === foundPending
|
|
801
|
-
) {
|
|
802
|
-
pendingIdempotentSpawns.delete(params.idempotencyKey);
|
|
803
|
-
}
|
|
804
|
-
const pending = foundPending?.generation === generation ? foundPending : undefined;
|
|
805
|
-
if (pending) {
|
|
806
|
-
if (pending.requestHash !== requestHash) {
|
|
807
|
-
throw new Error("The subagent_spawn idempotencyKey is pending with different parameters");
|
|
808
|
-
}
|
|
809
|
-
const agent = await waitForOwnedSpawn(pending.promise, signal);
|
|
810
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
811
|
-
return result(agent, `Reused ${agent.agent} as ${agent.id}.`);
|
|
812
|
-
}
|
|
813
|
-
let resolvePending: ((agent: ManagedAgent) => void) | undefined;
|
|
814
|
-
let rejectPending: ((error: unknown) => void) | undefined;
|
|
815
|
-
let ownedPending: PendingIdempotentSpawn | undefined;
|
|
816
|
-
if (params.idempotencyKey) {
|
|
817
|
-
const promise = new Promise<ManagedAgent>((resolve, reject) => {
|
|
818
|
-
resolvePending = resolve;
|
|
819
|
-
rejectPending = reject;
|
|
820
|
-
});
|
|
821
|
-
void promise.catch(() => undefined);
|
|
822
|
-
ownedPending = { generation, requestHash, promise };
|
|
823
|
-
pendingIdempotentSpawns.set(params.idempotencyKey, ownedPending);
|
|
824
|
-
}
|
|
825
|
-
try {
|
|
826
|
-
await confirmProjectAgent(
|
|
827
|
-
params.agent,
|
|
828
|
-
scope,
|
|
829
|
-
params.confirmProjectAgents ?? true,
|
|
830
|
-
ctx,
|
|
831
|
-
cwd,
|
|
832
|
-
currentSettings,
|
|
833
|
-
);
|
|
834
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
835
|
-
if (params.workspaceMode === "worktree" && resolvedAgent.source === "project") {
|
|
836
|
-
throw new Error("Project-local subagent definitions cannot run in a detached worktree");
|
|
837
|
-
}
|
|
838
|
-
const requestedCwd = cwd;
|
|
839
|
-
const workspaceOwner = `pending-${randomUUID()}`;
|
|
840
|
-
const workspace =
|
|
841
|
-
params.workspaceMode === "worktree"
|
|
842
|
-
? await currentWorkspaceManager.create(workspaceOwner, requestedCwd)
|
|
843
|
-
: undefined;
|
|
844
|
-
try {
|
|
845
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
846
|
-
} catch (error) {
|
|
847
|
-
if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
848
|
-
throw error;
|
|
849
|
-
}
|
|
850
|
-
let agent: ManagedAgent | undefined;
|
|
851
|
-
try {
|
|
852
|
-
const capabilityGrant = modules.capabilityGrant.issueCapabilityGrant(
|
|
853
|
-
executionPlan,
|
|
854
|
-
Date.now(),
|
|
855
|
-
Math.max(1, (params.timeoutMs ?? resolvedAgent.timeoutMs ?? 600_000) + 60_000),
|
|
856
|
-
);
|
|
857
|
-
agent = await ownedRegistry.spawn({
|
|
858
|
-
agent: params.agent,
|
|
859
|
-
taskName: params.taskName,
|
|
860
|
-
task: params.task,
|
|
861
|
-
cwd: workspace?.path ?? requestedCwd,
|
|
862
|
-
agentScope: scope,
|
|
863
|
-
thinkingLevel: params.thinkingLevel,
|
|
864
|
-
timeoutMs: params.timeoutMs,
|
|
865
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
866
|
-
maxTurns: params.maxTurns,
|
|
867
|
-
maxToolCalls: params.maxToolCalls,
|
|
868
|
-
parentId: params.parentId,
|
|
869
|
-
context: snapshot.text || undefined,
|
|
870
|
-
contextSourceIds: snapshot.sourceIds,
|
|
871
|
-
contextTruncated: snapshot.truncated,
|
|
872
|
-
contextTurns: snapshot.turns,
|
|
873
|
-
contextBytes: Buffer.byteLength(snapshot.text, "utf8"),
|
|
874
|
-
workspaceMode: workspace ? "worktree" : undefined,
|
|
875
|
-
spawnIdempotencyKey: params.idempotencyKey,
|
|
876
|
-
spawnRequestHash: params.idempotencyKey ? requestHash : undefined,
|
|
877
|
-
contract,
|
|
878
|
-
resultFormat: resultFormat === "text" ? undefined : resultFormat,
|
|
879
|
-
executionPlan,
|
|
880
|
-
capabilityGrant,
|
|
881
|
-
semanticSnapshot,
|
|
882
|
-
semanticCompatibility: { status: "compatible", changedComponents: [] },
|
|
883
|
-
target: targetSnapshot,
|
|
884
|
-
});
|
|
885
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
886
|
-
} catch (error) {
|
|
887
|
-
if (agent) await ownedRegistry.closeTree(agent.id).catch(() => undefined);
|
|
888
|
-
if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
889
|
-
throw error;
|
|
890
|
-
}
|
|
891
|
-
if (!agent) throw new Error("Subagent spawn completed without a retained agent");
|
|
892
|
-
if (workspace && agent.cwd === workspace.path) isolatedAgents.set(agent.id, workspaceOwner);
|
|
893
|
-
else if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
894
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
895
|
-
resolvePending?.(agent);
|
|
896
|
-
const deliveryNote =
|
|
897
|
-
completionDelivery === "auto-resume"
|
|
898
|
-
? "Auto-resume will request synthesis after completion."
|
|
899
|
-
: "The current response must not depend on the result because next-turn delivery will not wake an idle root.";
|
|
900
|
-
return result(
|
|
901
|
-
agent,
|
|
902
|
-
`Spawned ${agent.agent} as ${agent.taskPath ?? agent.id} (${agent.id}). Continue the identified non-overlapping local work immediately; do not merely announce the spawn or end while useful local work remains. Only an explicit user-requested specialist model, tool-profile, or isolation exception may lack concurrent local work. ${deliveryNote} Do not poll for progress.`,
|
|
903
|
-
);
|
|
904
|
-
} catch (error) {
|
|
905
|
-
rejectPending?.(error);
|
|
906
|
-
throw error;
|
|
907
|
-
} finally {
|
|
908
|
-
if (
|
|
909
|
-
params.idempotencyKey &&
|
|
910
|
-
ownedPending &&
|
|
911
|
-
pendingIdempotentSpawns.get(params.idempotencyKey) === ownedPending
|
|
912
|
-
) {
|
|
913
|
-
pendingIdempotentSpawns.delete(params.idempotencyKey);
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
},
|
|
917
|
-
});
|
|
918
|
-
refreshSpawnToolRegistration = () => {
|
|
919
|
-
spawnTool.description = appendAgentCatalog(baseSpawnDescription(), agentCatalog);
|
|
920
|
-
spawnTool.promptGuidelines = createSpawnPromptGuidelines(completionDelivery, blockingEnabled);
|
|
921
|
-
pi.registerTool(spawnTool);
|
|
922
|
-
};
|
|
923
|
-
refreshSpawnToolRegistration();
|
|
924
|
-
|
|
925
|
-
pi.registerTool({
|
|
926
|
-
name: "subagent_send",
|
|
927
|
-
label: "Send Subagent Follow-up",
|
|
928
|
-
description:
|
|
929
|
-
"Send follow-up work to a reusable retained subagent and start a new turn. Semantic resource skew requires explicit revalidation. Use subagent_mailbox for queue-only messages.",
|
|
930
|
-
promptSnippet: "Start a new detached follow-up turn on a retained subagent",
|
|
931
|
-
parameters: Type.Object({
|
|
932
|
-
agentId: Type.String({ description: "Retained agent ID or canonical task path." }),
|
|
933
|
-
task: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
|
|
934
|
-
timeoutMs: Type.Optional(
|
|
935
|
-
Type.Integer({
|
|
936
|
-
minimum: 1,
|
|
937
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
938
|
-
description:
|
|
939
|
-
"Optional work deadline for this follow-up turn. On expiry, Pi aborts the work and makes one separately bounded summary attempt.",
|
|
940
|
-
}),
|
|
941
|
-
),
|
|
942
|
-
...StatefulTurnLimitFields,
|
|
943
|
-
revalidate: Type.Optional(
|
|
944
|
-
Type.Boolean({
|
|
945
|
-
description:
|
|
946
|
-
"Accept the current semantic resource snapshot after a reported mismatch before starting this follow-up.",
|
|
947
|
-
}),
|
|
948
|
-
),
|
|
949
|
-
allowConcurrentWrites: Type.Optional(
|
|
950
|
-
Type.Boolean({
|
|
951
|
-
description:
|
|
952
|
-
"Deprecated compatibility field; shared-workspace concurrency is allowed by default.",
|
|
953
|
-
}),
|
|
954
|
-
),
|
|
955
|
-
}),
|
|
956
|
-
...createStatefulToolRenderer("send"),
|
|
957
|
-
async execute(_id, params, signal, _update, ctx) {
|
|
958
|
-
const generation = runtimeGeneration;
|
|
959
|
-
const ownedRegistry = requireRegistry();
|
|
960
|
-
let modules: StatefulSpawnModules;
|
|
961
|
-
try {
|
|
962
|
-
modules = await loadStatefulSpawnModules();
|
|
963
|
-
} catch (error) {
|
|
964
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
965
|
-
throw error;
|
|
966
|
-
}
|
|
967
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
968
|
-
const currentSettings = getCurrentSettings();
|
|
969
|
-
const existing = ownedRegistry.get(params.agentId);
|
|
970
|
-
if (!existing) throw new Error(`Unknown subagent: ${params.agentId}`);
|
|
971
|
-
const currentAgent = modules.agents
|
|
972
|
-
.discoverAgents(existing.cwd, existing.agentScope ?? "user", currentSettings)
|
|
973
|
-
.agents.find((agent) => agent.name === existing.agent);
|
|
974
|
-
if (!currentAgent) throw new Error(`Unknown retained subagent definition: ${existing.agent}`);
|
|
975
|
-
const resolvedFollowUpTarget =
|
|
976
|
-
existing.workspaceMode === "worktree"
|
|
977
|
-
? undefined
|
|
978
|
-
: modules.cwdPolicy.resolveSubagentTarget({
|
|
979
|
-
workspace: ctx.cwd,
|
|
980
|
-
requestedCwd: existing.cwd,
|
|
981
|
-
currentProjectTrusted: ctx.isProjectTrusted(),
|
|
982
|
-
});
|
|
983
|
-
if (resolvedFollowUpTarget) {
|
|
984
|
-
modules.cwdPolicy.assertDelegationTargetAllowed(
|
|
985
|
-
resolvedFollowUpTarget,
|
|
986
|
-
currentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY,
|
|
987
|
-
);
|
|
988
|
-
}
|
|
989
|
-
if (existing.workspaceMode === "worktree" && !existing.target) {
|
|
990
|
-
throw new Error("Retained worktree is missing its trusted target snapshot");
|
|
991
|
-
}
|
|
992
|
-
const currentTarget =
|
|
993
|
-
existing.workspaceMode === "worktree" && existing.target
|
|
994
|
-
? existing.target
|
|
995
|
-
: modules.cwdPolicy.targetPolicyAudit(
|
|
996
|
-
resolvedFollowUpTarget as NonNullable<typeof resolvedFollowUpTarget>,
|
|
997
|
-
);
|
|
998
|
-
const { executionPlan: currentPlan, semanticSnapshot: currentSnapshot } =
|
|
999
|
-
await modules.retainedSemanticState.buildRetainedSemanticState({
|
|
1000
|
-
agent: currentAgent,
|
|
1001
|
-
contract: existing.contract,
|
|
1002
|
-
target: currentTarget,
|
|
1003
|
-
cwd: existing.cwd,
|
|
1004
|
-
workspaceMode: existing.workspaceMode === "worktree" ? "worktree" : "shared",
|
|
1005
|
-
transport: transportKind,
|
|
1006
|
-
resultFormat: existing.resultFormat ?? "text",
|
|
1007
|
-
thinkingLevel: existing.thinkingLevel,
|
|
1008
|
-
timeoutMs: params.timeoutMs ?? existing.timeoutMs,
|
|
1009
|
-
taskGeneration: (existing.executionPlan?.taskGeneration ?? 0) + 1,
|
|
1010
|
-
cancellationLineage: [
|
|
1011
|
-
...(existing.executionPlan?.cancellationLineage ?? []),
|
|
1012
|
-
...(existing.state === "interrupted" && existing.executionPlan?.id
|
|
1013
|
-
? [existing.executionPlan.id]
|
|
1014
|
-
: []),
|
|
1015
|
-
],
|
|
1016
|
-
});
|
|
1017
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1018
|
-
const compatibility = existing.semanticSnapshot
|
|
1019
|
-
? modules.semanticSnapshot.evaluateSemanticCompatibility(
|
|
1020
|
-
existing.semanticSnapshot,
|
|
1021
|
-
currentSnapshot,
|
|
1022
|
-
)
|
|
1023
|
-
: { status: "warning" as const, changedComponents: ["legacy-missing-snapshot"] };
|
|
1024
|
-
if (
|
|
1025
|
-
(compatibility.status === "needs-revalidation" || compatibility.status === "rejected") &&
|
|
1026
|
-
params.revalidate !== true
|
|
1027
|
-
) {
|
|
1028
|
-
throw new Error(
|
|
1029
|
-
`Subagent semantic resources changed; retry with revalidate: true after reviewing: ${compatibility.changedComponents.join(", ")}`,
|
|
1030
|
-
);
|
|
1031
|
-
}
|
|
1032
|
-
await confirmProjectAgent(
|
|
1033
|
-
existing.agent,
|
|
1034
|
-
existing.agentScope ?? "user",
|
|
1035
|
-
false,
|
|
1036
|
-
ctx,
|
|
1037
|
-
existing.cwd,
|
|
1038
|
-
currentSettings,
|
|
1039
|
-
);
|
|
1040
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1041
|
-
const currentGrant = modules.capabilityGrant.issueCapabilityGrant(
|
|
1042
|
-
currentPlan,
|
|
1043
|
-
Date.now(),
|
|
1044
|
-
Math.max(1, (params.timeoutMs ?? existing.timeoutMs ?? 600_000) + 60_000),
|
|
1045
|
-
);
|
|
1046
|
-
await ownedRegistry.updateSemanticState(
|
|
1047
|
-
existing.id,
|
|
1048
|
-
currentPlan,
|
|
1049
|
-
currentGrant,
|
|
1050
|
-
currentSnapshot,
|
|
1051
|
-
params.revalidate === true && compatibility.status !== "compatible"
|
|
1052
|
-
? { status: "warning", changedComponents: compatibility.changedComponents }
|
|
1053
|
-
: compatibility,
|
|
1054
|
-
);
|
|
1055
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1056
|
-
const agent = await ownedRegistry.followUp(params.agentId, params.task, {
|
|
1057
|
-
timeoutMs: params.timeoutMs,
|
|
1058
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
1059
|
-
maxTurns: params.maxTurns,
|
|
1060
|
-
maxToolCalls: params.maxToolCalls,
|
|
1061
|
-
});
|
|
1062
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1063
|
-
return result(agent, `Started follow-up for ${agent.id}.`);
|
|
1064
|
-
},
|
|
1065
|
-
});
|
|
1066
|
-
|
|
1067
|
-
pi.registerTool({
|
|
1068
|
-
name: "subagent_manage",
|
|
1069
|
-
label: "Manage Subagents",
|
|
1070
|
-
description:
|
|
1071
|
-
"Interrupt active work while keeping an agent reusable, or close agents and release their resources. Use subagent_inspect for every read-only list, detail, status, and diagnostic operation.",
|
|
1072
|
-
promptSnippet: "Interrupt or close retained detached subagents",
|
|
1073
|
-
parameters: ManageParamsSchema,
|
|
1074
|
-
...createStatefulToolRenderer("manage"),
|
|
1075
|
-
async execute(_id, params, signal): Promise<StatefulActionToolResult> {
|
|
1076
|
-
const generation = runtimeGeneration;
|
|
1077
|
-
const ownedRegistry = requireRegistry();
|
|
1078
|
-
let currentWorkspaceManager: WorkspaceManager;
|
|
1079
|
-
try {
|
|
1080
|
-
currentWorkspaceManager = await getWorkspaceManager();
|
|
1081
|
-
} catch (error) {
|
|
1082
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1083
|
-
throw error;
|
|
1084
|
-
}
|
|
1085
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1086
|
-
const ownedAgent = (agentId: string): ManagedAgent => {
|
|
1087
|
-
const value = ownedRegistry.get(agentId);
|
|
1088
|
-
if (!value) throw new Error(`Unknown subagent: ${agentId}`);
|
|
1089
|
-
return value;
|
|
1090
|
-
};
|
|
1091
|
-
const operation = validateManageParams(params);
|
|
1092
|
-
const agentId = operation.agentId;
|
|
1093
|
-
if (operation.action === "interrupt") {
|
|
1094
|
-
if (operation.subtree) {
|
|
1095
|
-
const agents = await ownedRegistry.interruptTree(agentId);
|
|
1096
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1097
|
-
return {
|
|
1098
|
-
content: [{ type: "text", text: `Interrupted ${agents.length} active agent(s).` }],
|
|
1099
|
-
details: {
|
|
1100
|
-
agent: summarizeStatefulAgent(ownedAgent(agentId)),
|
|
1101
|
-
agents: agents.map(summarizeStatefulAgent),
|
|
1102
|
-
},
|
|
1103
|
-
};
|
|
1104
|
-
}
|
|
1105
|
-
const agent = await ownedRegistry.interrupt(agentId);
|
|
1106
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1107
|
-
return result(agent, `Interrupted ${agent.id}; it remains reusable.`);
|
|
1108
|
-
}
|
|
1109
|
-
const existing = ownedRegistry.get(agentId);
|
|
1110
|
-
if (existing?.state === "closed" && !operation.subtree) {
|
|
1111
|
-
const pendingOwner = isolatedAgents.get(existing.id);
|
|
1112
|
-
if (pendingOwner) await currentWorkspaceManager.cleanup(pendingOwner);
|
|
1113
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1114
|
-
isolatedAgents.delete(existing.id);
|
|
1115
|
-
return result(existing, `Closed ${existing.id}.`);
|
|
1116
|
-
}
|
|
1117
|
-
if (operation.subtree) {
|
|
1118
|
-
let agents: ManagedAgent[];
|
|
1119
|
-
try {
|
|
1120
|
-
agents = await ownedRegistry.closeTree(agentId);
|
|
1121
|
-
} finally {
|
|
1122
|
-
await cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);
|
|
1123
|
-
}
|
|
1124
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1125
|
-
return {
|
|
1126
|
-
content: [{ type: "text", text: `Closed ${agents.length} agent(s).` }],
|
|
1127
|
-
details: {
|
|
1128
|
-
agent: summarizeStatefulAgent(ownedAgent(agentId)),
|
|
1129
|
-
agents: agents.map(summarizeStatefulAgent),
|
|
1130
|
-
},
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
let agent: ManagedAgent;
|
|
1134
|
-
try {
|
|
1135
|
-
agent = await ownedRegistry.close(agentId);
|
|
1136
|
-
} finally {
|
|
1137
|
-
await cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);
|
|
1138
|
-
}
|
|
1139
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1140
|
-
return result(agent, `Closed ${agent.id}.`);
|
|
1141
|
-
},
|
|
1142
|
-
});
|
|
1143
|
-
|
|
1144
|
-
pi.registerTool({
|
|
1145
|
-
name: "subagent_mailbox",
|
|
1146
|
-
label: "Subagent Mailbox",
|
|
1147
|
-
description:
|
|
1148
|
-
"Queue a bounded message without starting a turn, or read unread mailbox messages. Read acknowledges returned messages by default; use subagent_inspect for metadata-only unread counts.",
|
|
1149
|
-
promptSnippet: "Send or read queue-only detached-subagent mailbox messages",
|
|
1150
|
-
parameters: MailboxParamsSchema,
|
|
1151
|
-
...createStatefulToolRenderer("mailbox"),
|
|
1152
|
-
async execute(_id, params, signal): Promise<StatefulActionToolResult> {
|
|
1153
|
-
const generation = runtimeGeneration;
|
|
1154
|
-
const ownedRegistry = requireRegistry();
|
|
1155
|
-
const operation = validateMailboxParams(params);
|
|
1156
|
-
if (operation.action === "send") {
|
|
1157
|
-
const message = await ownedRegistry.sendMessage(
|
|
1158
|
-
operation.agentId,
|
|
1159
|
-
operation.message,
|
|
1160
|
-
operation.senderId,
|
|
1161
|
-
operation.deduplicationKey,
|
|
1162
|
-
);
|
|
1163
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1164
|
-
return {
|
|
1165
|
-
content: [{ type: "text", text: `Queued ${message.id} for ${message.recipientId}.` }],
|
|
1166
|
-
details: { message },
|
|
1167
|
-
};
|
|
1168
|
-
}
|
|
1169
|
-
const messages = await ownedRegistry.readMessages(
|
|
1170
|
-
operation.agentId,
|
|
1171
|
-
operation.acknowledge,
|
|
1172
|
-
operation.limit,
|
|
1173
|
-
);
|
|
1174
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1175
|
-
const summaries = messages.map((message) => ({
|
|
1176
|
-
...message,
|
|
1177
|
-
content: truncateUtf8(message.content, MAX_TOOL_MESSAGE_BYTES).text,
|
|
1178
|
-
}));
|
|
1179
|
-
const text = summaries.length
|
|
1180
|
-
? summaries
|
|
1181
|
-
.map((message) => `${message.id} from ${message.senderId}: ${message.content}`)
|
|
1182
|
-
.join("\n")
|
|
1183
|
-
: "No unread messages.";
|
|
1184
|
-
return {
|
|
1185
|
-
content: [{ type: "text", text: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text }],
|
|
1186
|
-
details: { messages: summaries },
|
|
1187
|
-
};
|
|
1188
|
-
},
|
|
1189
|
-
});
|
|
1190
|
-
|
|
1191
|
-
return controller;
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
function normalizeContextMode(value: "none" | "all" | "summary" | number | undefined): ContextMode {
|
|
1195
|
-
if (value === undefined) return "none";
|
|
1196
|
-
if (value === "none" || value === "all" || value === "summary") return value;
|
|
1197
|
-
return Math.max(1, Math.floor(value));
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
export function resolveSpawnContextMode(
|
|
1201
|
-
value: "none" | "all" | "summary" | number | undefined,
|
|
1202
|
-
contextEntryIds: readonly string[] | undefined,
|
|
1203
|
-
): ContextMode {
|
|
1204
|
-
if (value === undefined && contextEntryIds !== undefined) return "all";
|
|
1205
|
-
return normalizeContextMode(value);
|
|
1206
|
-
}
|
|
1207
|
-
|
|
1208
|
-
async function cleanupClosedWorkspaces(
|
|
1209
|
-
registry: AgentRegistry,
|
|
1210
|
-
isolatedAgents: Map<string, string>,
|
|
1211
|
-
workspaceManager: WorkspaceManager,
|
|
1212
|
-
): Promise<void> {
|
|
1213
|
-
for (const [agentId, owner] of [...isolatedAgents]) {
|
|
1214
|
-
if (registry.get(agentId)?.state !== "closed") continue;
|
|
1215
|
-
await workspaceManager.cleanup(owner);
|
|
1216
|
-
isolatedAgents.delete(agentId);
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
function appendAgentCatalog(baseDescription: string, catalog: string): string {
|
|
1221
|
-
return catalog ? `${baseDescription}\n\n${catalog}` : baseDescription;
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
function result(agent: ManagedAgent, text: string) {
|
|
1225
|
-
return {
|
|
1226
|
-
content: [{ type: "text" as const, text }],
|
|
1227
|
-
details: { agent: summarizeStatefulAgent(agent) },
|
|
1228
|
-
};
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
function normalizeRuntimeThinkingLevel(value: string): ParentRuntimeSnapshot["thinkingLevel"] {
|
|
1232
|
-
return isThinkingLevel(value) ? value : "off";
|
|
1233
|
-
}
|
|
1234
|
-
|
|
1235
1
|
export {
|
|
1236
2
|
buildDetachedCompletionMessage,
|
|
1237
3
|
CompletionDeliveryBroker,
|
|
@@ -1242,3 +8,5 @@ export {
|
|
|
1242
8
|
buildStatefulTurnPrompt,
|
|
1243
9
|
resolveStatefulTurnTimeout,
|
|
1244
10
|
} from "./stateful-prompt.js";
|
|
11
|
+
export * from "./stateful-registration.js";
|
|
12
|
+
export { isWriteCapable } from "./stateful-safety.js";
|