@narumitw/pi-subagents 2.1.0 → 2.1.1
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 +21 -12
- package/dist/chunks/{chunk-PABJJYP6.ts → chunk-2LMJU25E.ts} +12 -41
- package/dist/chunks/chunk-2LMJU25E.ts.map +7 -0
- package/dist/chunks/{chunk-FXI45N3J.ts → chunk-6NSJVPXX.ts} +4 -14
- package/dist/chunks/{chunk-FXI45N3J.ts.map → chunk-6NSJVPXX.ts.map} +2 -2
- package/dist/chunks/{chunk-VBDGNNLM.ts → chunk-NLT67IZS.ts} +137 -29
- package/dist/chunks/chunk-NLT67IZS.ts.map +7 -0
- package/dist/chunks/{chunk-DIHBUR2E.ts → chunk-YU53SHA7.ts} +2 -2
- package/dist/chunks/{completion-delivery-JVLNQRWX.ts → completion-delivery-RSJU6BXL.ts} +3 -3
- package/dist/chunks/{config-ui-DDKERQHI.ts → config-ui-ABHYNGQ7.ts} +4 -4
- package/dist/chunks/{consult-PQ6PRAKC.ts → consult-LJU3IQY5.ts} +2 -2
- package/dist/chunks/{persistence-XHPJBZL7.ts → persistence-UY3PY6E5.ts} +2 -2
- package/dist/chunks/{registry-XDXPECWF.ts → registry-BT54L6CY.ts} +2 -2
- package/dist/index.ts +263 -60
- package/dist/index.ts.map +3 -3
- package/docs/async-runtime-protocol.md +16 -2
- package/package.json +1 -1
- package/src/completion-requirement.ts +201 -30
- package/src/consult-registration.ts +4 -12
- package/src/session-guidance-contract.ts +309 -0
- package/src/stateful-guidance.ts +3 -20
- package/src/stateful-registration.ts +4 -31
- package/src/subagents-extension.ts +56 -66
- package/dist/chunks/chunk-PABJJYP6.ts.map +0 -7
- package/dist/chunks/chunk-VBDGNNLM.ts.map +0 -7
- /package/dist/chunks/{chunk-DIHBUR2E.ts.map → chunk-YU53SHA7.ts.map} +0 -0
- /package/dist/chunks/{completion-delivery-JVLNQRWX.ts.map → completion-delivery-RSJU6BXL.ts.map} +0 -0
- /package/dist/chunks/{config-ui-DDKERQHI.ts.map → config-ui-ABHYNGQ7.ts.map} +0 -0
- /package/dist/chunks/{consult-PQ6PRAKC.ts.map → consult-LJU3IQY5.ts.map} +0 -0
- /package/dist/chunks/{persistence-XHPJBZL7.ts.map → persistence-UY3PY6E5.ts.map} +0 -0
- /package/dist/chunks/{registry-XDXPECWF.ts.map → registry-BT54L6CY.ts.map} +0 -0
package/README.md
CHANGED
|
@@ -156,10 +156,11 @@ It does not pretend to stream the background child after the tool call has compl
|
|
|
156
156
|
Custom transcript rendering is TUI presentation only.
|
|
157
157
|
Tool names, parameter schemas, model-facing final content/details, errors, completion delivery, and print/JSON/RPC final output remain unchanged; JSON/RPC observers may see additive bounded consultation partial-progress details.
|
|
158
158
|
|
|
159
|
-
After each session starts,
|
|
159
|
+
After each session starts, one hidden versioned `pi-subagents` session-guidance message publishes the bounded parent-facing catalog and effective non-secret delegation policies.
|
|
160
160
|
Entries show the source (`built-in`, `user`, or `project`), required `agentScope`, declared capability identifiers, configured tools, filesystem authority, and supported result formats; the `agent` parameters remain unconstrained strings for cwd and scope flexibility.
|
|
161
161
|
The catalog also warns that enforced path, network, and secret guarantees are unsupported.
|
|
162
162
|
It is rebuilt on `/reload` or the next session start, and omitted entries are reported explicitly when the catalog exceeds its metadata bounds.
|
|
163
|
+
The registered tool descriptions, schemas, and prompt metadata remain stable until a reload changes the configured tool surface.
|
|
163
164
|
|
|
164
165
|
Choose the API by lifecycle:
|
|
165
166
|
|
|
@@ -233,10 +234,10 @@ For real isolation, run Pi in a container, VM, micro-VM, or OS sandbox with only
|
|
|
233
234
|
## 🧭 Proactive use
|
|
234
235
|
|
|
235
236
|
When registered, deprecated `subagent` advertises its migration paths and limits compatibility use to existing callers or explicit requests whose orchestration semantics lack a detached replacement.
|
|
236
|
-
When stateful lifecycle tools are registered, `subagent_spawn`
|
|
237
|
-
Changing
|
|
237
|
+
When stateful lifecycle tools are registered, stable `subagent_spawn` metadata explains both delivery modes and the session-guidance message identifies the active completion policy.
|
|
238
|
+
Changing a live policy through `/subagents settings` appends a superseding session-guidance message for the next turn without starting a model turn.
|
|
238
239
|
|
|
239
|
-
The
|
|
240
|
+
The current session-guidance message advertises the agent catalog automatically, so no preliminary list call is needed.
|
|
240
241
|
Each entry exposes the exact declared capability and tool identifiers needed by an enforced contract, plus filesystem authority and result formats.
|
|
241
242
|
Agents without a valid capability manifest are labeled `undeclared` instead of implying support.
|
|
242
243
|
Built-ins and user agents appear under the default `agentScope: "user"`.
|
|
@@ -244,7 +245,7 @@ Trusted project agents appear separately and explicitly require `agentScope: "pr
|
|
|
244
245
|
If a project definition shares a name with a user or built-in definition, the user version is the default and the project version is used only for `"project"`/`"both"`.
|
|
245
246
|
A user override of a built-in also shows the built-in fallback available with `agentScope: "project"`; `"both"` keeps the user definition.
|
|
246
247
|
The catalog is bounded and reports its omission count; metadata discovery also caps files and bytes read per scope.
|
|
247
|
-
|
|
248
|
+
Each newer session-guidance message explicitly supersedes earlier guidance while preserving the existing conversation prefix.
|
|
248
249
|
|
|
249
250
|
Delegation guidance:
|
|
250
251
|
|
|
@@ -646,7 +647,12 @@ Every turn receives an executor-owned `runId`, monotonically increasing agent-lo
|
|
|
646
647
|
A caller can set `completionRequirement: "required"` on a spawn or follow-up to bind final-answer dependency state to that exact run and generation.
|
|
647
648
|
Required state moves from `pending` to `available` after durable terminal completion and to `visible` only after the intended parent context observes the exact completion ID.
|
|
648
649
|
Interruption, close, stale restore, and shutdown terminalize unfinished requirements explicitly instead of silently dropping them.
|
|
649
|
-
Tool-result details preserve fork-sensitive requirement evidence, inspection projects bounded requirement state
|
|
650
|
+
Tool-result details preserve fork-sensitive requirement evidence, and inspection projects bounded requirement state.
|
|
651
|
+
The successful tool handoff and delivered completion messages are the ordinary model-visible source of requirement state.
|
|
652
|
+
When a resumed session terminalizes an in-flight required run and the retained transcript still contains its pending handoff, one hidden append-only transition supersedes that stale evidence before the next model turn.
|
|
653
|
+
This also covers compacted contexts that retain the handoff.
|
|
654
|
+
If leading compaction or branch summaries remove the handoff, one canonical hidden fallback is restored at a fixed boundary immediately after the summaries.
|
|
655
|
+
That restored fallback remains fixed for the summary epoch while later cancellation transitions or completion messages supersede it at the conversation tail.
|
|
650
656
|
The runtime rejects a sixty-fifth unresolved required run before acceptance so every unresolved exact identity fits in the bounded parent context.
|
|
651
657
|
The terminal completion and recipient are persisted before delivery, simultaneous root completions are batched, and the root broker allows at most one in-flight wake until that parent turn starts.
|
|
652
658
|
In TUI mode, completion messages show a compact task and payload summary while collapsed; use the configured tool-output expansion action (`Ctrl+O` by default) to show or hide the complete message globally.
|
|
@@ -772,10 +778,12 @@ It never reloads automatically, because reload can interrupt retained detached w
|
|
|
772
778
|
Lowering retained, depth, or stored capacity shows a projected recovery warning when current records would be omitted.
|
|
773
779
|
Restored parents that already exceed a lowered `maxChildrenPerAgent` remain available, but they cannot gain another child until they fall below the configured limit.
|
|
774
780
|
`cwdPolicy.consultation` defaults to `"anywhere"`, `cwdPolicy.delegation` defaults to `"trusted-targets"`, and `consult.resources` defaults to `"project-context"`.
|
|
775
|
-
The Settings UI applies a saved change immediately to subsequent launches and
|
|
781
|
+
The Settings UI applies a saved live change immediately to subsequent launches and appends a superseding session-guidance message; manual edits take effect on session start or `/reload`.
|
|
776
782
|
The UI explicitly states that target/trust settings are not filesystem sandboxing and directs trust changes to Pi `/trust`.
|
|
777
|
-
When stateful tools are enabled, their membership
|
|
778
|
-
|
|
783
|
+
When stateful tools are enabled, their membership and provider-visible definitions stay fixed across spawn, completion, interrupt, close, mailbox, catalog, and live-policy transitions.
|
|
784
|
+
Ordinary turns preserve the normalized provider-visible prefix, while a new guidance message or required-completion transition starts an explicit append-only prefix epoch.
|
|
785
|
+
Compaction restoration inserts deterministic guidance and requirement fallbacks after leading summaries and retains each restored message for that summary epoch while later tail messages supersede it.
|
|
786
|
+
These rules preserve cache-eligible prefixes but do not guarantee a provider-reported cache hit.
|
|
779
787
|
|
|
780
788
|
| Tool | Purpose |
|
|
781
789
|
| --- | --- |
|
|
@@ -1063,13 +1071,13 @@ An omitted field keeps the agent's default tools; blank, `null`, or `[]` explici
|
|
|
1063
1071
|
`capabilityManifest` is optional for legacy custom agents and never grants authority by itself.
|
|
1064
1072
|
Explicit workflow routing can match declared capabilities, configured tools, filesystem authority, verification roles, and low/medium/high cost or latency hints.
|
|
1065
1073
|
A missing or malformed manifest remains unknown and cannot satisfy a capability-routed task.
|
|
1066
|
-
The parent-facing
|
|
1074
|
+
The parent-facing session-guidance message exposes contract-relevant catalog declarations before the first delegation decision.
|
|
1067
1075
|
Use those identifiers exactly; enforced `readPaths`, `writePaths`, network, and secret guarantees are currently unsupported and require an external enforcement boundary.
|
|
1068
1076
|
A rejected enforced contract reports both contract repair and stop as recovery choices, but repair is safe only when the unsupported fields were descriptive rather than required protection.
|
|
1069
1077
|
|
|
1070
1078
|
`agentScope` is a top-level tool argument supplied per invocation.
|
|
1071
1079
|
It is not a setting in `~/.pi/agent/pi-subagents.json` and does not belong in agent frontmatter.
|
|
1072
|
-
The parent-facing
|
|
1080
|
+
The parent-facing session-guidance contract discovers these definitions after session start and labels their source and required scope.
|
|
1073
1081
|
Edit agent files and run `/reload` (or start a new session) to refresh the catalog; there is no live filesystem watcher.
|
|
1074
1082
|
The scope selects which custom agent directories are loaded; built-in agents remain available in every scope:
|
|
1075
1083
|
|
|
@@ -1282,7 +1290,8 @@ packages/pi-subagents/
|
|
|
1282
1290
|
│ ├── usage-recording.ts # Opt-in content-free event collection and local identities
|
|
1283
1291
|
│ ├── usage-recording-store.ts # Private per-runtime JSONL writers and retention pruning
|
|
1284
1292
|
│ ├── completion-delivery.ts # Top-level completion batching and optional idle-root wake
|
|
1285
|
-
│ ├──
|
|
1293
|
+
│ ├── session-guidance-contract.ts # Append-only catalog and effective-policy guidance
|
|
1294
|
+
│ ├── completion-requirement.ts # Exact required-run tracking and fixed-boundary fallback
|
|
1286
1295
|
│ ├── completion-routing.ts # Direct-parent and live-ancestor recipient selection
|
|
1287
1296
|
│ ├── task-path.ts # Canonical retained-agent task identity and resolution
|
|
1288
1297
|
│ ├── peer-communication.ts # Session peer routing and authenticated loopback broker
|
|
@@ -50,9 +50,8 @@ import {
|
|
|
50
50
|
} from "./chunk-BFK2Z4ZF.ts";
|
|
51
51
|
import {
|
|
52
52
|
CompletionRequirementModeSchema,
|
|
53
|
-
completionRequirementsFromBranch
|
|
54
|
-
|
|
55
|
-
} from "./chunk-VBDGNNLM.ts";
|
|
53
|
+
completionRequirementsFromBranch
|
|
54
|
+
} from "./chunk-NLT67IZS.ts";
|
|
56
55
|
import {
|
|
57
56
|
DelegationContractSchema
|
|
58
57
|
} from "./chunk-JSZIP73U.ts";
|
|
@@ -150,8 +149,7 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
|
150
149
|
import { Type as Type2 } from "typebox";
|
|
151
150
|
|
|
152
151
|
// src/stateful-guidance.ts
|
|
153
|
-
function createSpawnPromptGuidelines(
|
|
154
|
-
const deliveryGuidance = completionDelivery === "auto-resume" ? blockingEnabled ? "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result; do not choose blocking parallel fan-out merely to keep delegation in the same turn." : "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result." : blockingEnabled ? "With subagent_spawn completion delivery set to next-turn (the default), prefer one subagent_spawn for broad asynchronous research or consequential independent review only when the current response does not depend on its result; when it does, use subagent_spawn only with useful overlap and call subagent_await after that overlap is complete. Do not migrate new work to the deprecated subagent tool." : "With subagent_spawn completion delivery set to next-turn (the default), use subagent_spawn only when the current response does not depend on its result; complete final-answer-dependent work directly because an idle root is not awakened.";
|
|
152
|
+
function createSpawnPromptGuidelines(blockingEnabled = true) {
|
|
155
153
|
return [
|
|
156
154
|
"Do not use subagent_spawn for simple or critical-path work that the main agent can perform directly. The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
|
|
157
155
|
"Before one ordinary subagent_spawn, identify concrete useful non-overlapping main-agent work you can start immediately and a supported completion integration path. If none exists, perform the task directly instead of calling subagent_spawn.",
|
|
@@ -161,10 +159,8 @@ function createSpawnPromptGuidelines(completionDelivery, blockingEnabled = true)
|
|
|
161
159
|
"For an ordinary subagent_spawn, omit contract; use a delegation contract only when explicit acceptance, authority, evidence, or admission semantics are required.",
|
|
162
160
|
"Do not set subagent_spawn contract enforcement to enforce with requestedAuthority readPaths, writePaths, network, or secrets; those guarantees are unsupported and reject before child launch, while capabilities and tools remain enforceable.",
|
|
163
161
|
"If subagent_spawn rejects an unsupported guarantee, retry once with those fields removed or enforcement set to audit only when they were advisory; when any field is a required security boundary, stop instead of weakening it.",
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
'Track every final-answer-dependent subagent_spawn by setting completionRequirement to "required" and retaining its returned agentId or taskPath; treat interim output as progress, and synthesize only after every corresponding completion message is visible or terminal.'
|
|
167
|
-
] : [],
|
|
162
|
+
"Read the current pi-subagents session-guidance message before choosing detached completion behavior. With next-turn delivery, use subagent_spawn only when the current response does not depend on its result unless useful overlap ends with an intentional subagent_await. With auto-resume delivery, final-answer-dependent detached work may continue asynchronously.",
|
|
163
|
+
'Track every final-answer-dependent subagent_spawn by setting completionRequirement to "required" and retaining its returned agentId or taskPath; treat interim output as progress, and synthesize only after every corresponding completion message is visible or terminal.',
|
|
168
164
|
"Keep ordinary review in the main agent with a review skill and deterministic checks; use subagent_spawn for detached review only when consequential independent verification has concrete parallel value.",
|
|
169
165
|
"Use a single subagent_spawn for a bounded implementation slice with clear ownership only when it can run beside the identified main-agent work.",
|
|
170
166
|
"Use a single subagent_spawn without concurrent main-agent work only for an explicit user-requested specialist model, tool profile, or isolation boundary.",
|
|
@@ -579,13 +575,13 @@ var statefulSpawnModules;
|
|
|
579
575
|
var workspaceModule;
|
|
580
576
|
function loadStatefulSessionModules() {
|
|
581
577
|
statefulSessionModules ??= Promise.all([
|
|
582
|
-
import("./completion-delivery-
|
|
578
|
+
import("./completion-delivery-RSJU6BXL.ts"),
|
|
583
579
|
import("./peer-communication-KL36Z6CO.ts"),
|
|
584
580
|
import("./context-QDKLVQXE.ts"),
|
|
585
581
|
import("./create-stateful-transport-JWC2EFYL.ts"),
|
|
586
582
|
import("./cwd-policy-NB6XZ5GF.ts"),
|
|
587
|
-
import("./persistence-
|
|
588
|
-
import("./registry-
|
|
583
|
+
import("./persistence-UY3PY6E5.ts"),
|
|
584
|
+
import("./registry-BT54L6CY.ts"),
|
|
589
585
|
import("./stateful-lifecycle-JAR6K55H.ts")
|
|
590
586
|
]).then(
|
|
591
587
|
([
|
|
@@ -719,10 +715,8 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
719
715
|
const transportKind = resolveStatefulTransportKind(settings.transport);
|
|
720
716
|
let completionDelivery = resolveCompletionDelivery(settings.completionDelivery);
|
|
721
717
|
let runtimeLimits = resolveStatefulLimits(settings);
|
|
722
|
-
let agentCatalog = "";
|
|
723
718
|
let completionBroker;
|
|
724
719
|
let peerBroker;
|
|
725
|
-
let refreshSpawnToolRegistration;
|
|
726
720
|
let registry;
|
|
727
721
|
let persistence;
|
|
728
722
|
let sweepTimer;
|
|
@@ -768,14 +762,6 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
768
762
|
setCompletionDelivery(value) {
|
|
769
763
|
completionDelivery = value;
|
|
770
764
|
completionBroker?.setDelivery(value);
|
|
771
|
-
refreshSpawnToolRegistration?.();
|
|
772
|
-
},
|
|
773
|
-
setAgentCatalog(value) {
|
|
774
|
-
agentCatalog = value;
|
|
775
|
-
refreshSpawnToolRegistration?.();
|
|
776
|
-
},
|
|
777
|
-
refreshSettingsGuidance() {
|
|
778
|
-
refreshSpawnToolRegistration?.();
|
|
779
765
|
},
|
|
780
766
|
getRuntimeStatus() {
|
|
781
767
|
const counts = registry?.inspectionCounts() ?? { activeAgents: 0, retainedAgents: 0 };
|
|
@@ -1019,7 +1005,6 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
1019
1005
|
if (completion.recipientId === "root") sessionBroker.enqueue(completion);
|
|
1020
1006
|
}
|
|
1021
1007
|
runtimeLimits = nextLimits;
|
|
1022
|
-
refreshSpawnToolRegistration?.();
|
|
1023
1008
|
const sweepEveryMs = Math.max(
|
|
1024
1009
|
1e3,
|
|
1025
1010
|
Math.min(sessionSettings.idleTtlMs ?? 60 * 60 * 1e3, 6e4)
|
|
@@ -1042,9 +1027,6 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
1042
1027
|
});
|
|
1043
1028
|
pi.on("context", (event) => {
|
|
1044
1029
|
completionBroker?.onParentContext(event.messages);
|
|
1045
|
-
const agents = registry?.list() ?? [];
|
|
1046
|
-
const messages = reconcileRequiredCompletionContext(event.messages, agents);
|
|
1047
|
-
if (messages !== event.messages) return { messages };
|
|
1048
1030
|
});
|
|
1049
1031
|
pi.on("agent_settled", () => {
|
|
1050
1032
|
completionBroker?.onParentSettled();
|
|
@@ -1082,13 +1064,12 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
1082
1064
|
runtimeTransition = transition.catch(() => void 0);
|
|
1083
1065
|
await transition;
|
|
1084
1066
|
});
|
|
1085
|
-
const baseSpawnDescription = () => `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.`;
|
|
1086
1067
|
const spawnTool = defineTool({
|
|
1087
1068
|
name: "subagent_spawn",
|
|
1088
1069
|
label: "Spawn Subagent",
|
|
1089
|
-
description:
|
|
1070
|
+
description: "Start an addressable background subagent with an opaque agentId and canonical taskPath, an optional thinking level and execution budgets chosen for the task difficulty, and asynchronous completion delivery. The current bounded capacity, completion policy, working-directory policy, and available agent definitions are published in the pi-subagents session-guidance message. Working-directory policy controls launch targets and protected project resources, not filesystem access or sandboxing.",
|
|
1090
1071
|
promptSnippet: "Start a reusable detached subagent; completion is delivered asynchronously",
|
|
1091
|
-
promptGuidelines: createSpawnPromptGuidelines(
|
|
1072
|
+
promptGuidelines: createSpawnPromptGuidelines(blockingEnabled),
|
|
1092
1073
|
parameters: grammarSafeToolObject({
|
|
1093
1074
|
agent: Type2.String({ minLength: 1 }),
|
|
1094
1075
|
taskName: Type2.Optional(
|
|
@@ -1345,12 +1326,7 @@ function registerStatefulSubagents(pi, dependencies = {}) {
|
|
|
1345
1326
|
}
|
|
1346
1327
|
}
|
|
1347
1328
|
});
|
|
1348
|
-
|
|
1349
|
-
spawnTool.description = appendAgentCatalog(baseSpawnDescription(), agentCatalog);
|
|
1350
|
-
spawnTool.promptGuidelines = createSpawnPromptGuidelines(completionDelivery, blockingEnabled);
|
|
1351
|
-
pi.registerTool(spawnTool);
|
|
1352
|
-
};
|
|
1353
|
-
refreshSpawnToolRegistration();
|
|
1329
|
+
pi.registerTool(spawnTool);
|
|
1354
1330
|
pi.registerTool({
|
|
1355
1331
|
name: "subagent_send",
|
|
1356
1332
|
label: "Send Subagent Follow-up",
|
|
@@ -1627,11 +1603,6 @@ async function cleanupClosedWorkspaces(registry, isolatedAgents, workspaceManage
|
|
|
1627
1603
|
isolatedAgents.delete(agentId);
|
|
1628
1604
|
}
|
|
1629
1605
|
}
|
|
1630
|
-
function appendAgentCatalog(baseDescription, catalog) {
|
|
1631
|
-
return catalog ? `${baseDescription}
|
|
1632
|
-
|
|
1633
|
-
${catalog}` : baseDescription;
|
|
1634
|
-
}
|
|
1635
1606
|
function result(agent, text) {
|
|
1636
1607
|
return {
|
|
1637
1608
|
content: [{ type: "text", text }],
|
|
@@ -1667,4 +1638,4 @@ export {
|
|
|
1667
1638
|
formatStatefulAgentLine,
|
|
1668
1639
|
registerStatefulSubagents
|
|
1669
1640
|
};
|
|
1670
|
-
//# sourceMappingURL=chunk-
|
|
1641
|
+
//# sourceMappingURL=chunk-2LMJU25E.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/stateful-agent-view.ts", "../../src/stateful-config.ts", "../../src/stateful-registration.ts", "../../src/stateful-guidance.ts", "../../src/stateful-render.ts", "../../src/stateful-tool-params.ts"],
|
|
4
|
+
"sourcesContent": ["import { MAX_TOOL_MESSAGE_BYTES, truncateUtf8 } from \"./limits.js\";\nimport type { ManagedAgent } from \"./registry.js\";\n\nexport function formatStatefulAgentLine(agent: ManagedAgent, now = Date.now()): string {\n\tconst elapsedSeconds = Math.max(0, Math.floor((now - agent.updatedAt) / 1000));\n\tconst task = agent.currentTask ? ` \u2014 ${sanitizeStatusLine(agent.currentTask, 80)}` : \"\";\n\tconst unread = agent.mailbox.filter((message) => !message.readAt).length;\n\tconst indent = \" \".repeat(agent.depth);\n\treturn `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} \u00B7 ${sanitizeStatusLine(agent.agent, 128)} \u00B7 ${agentStateLabel(agent.state)} \u00B7 updated ${elapsedSeconds}s ago \u00B7 ${unread} unread${task}`;\n}\n\nexport function summarizeStatefulAgent(agent: ManagedAgent) {\n\treturn {\n\t\tid: agent.id,\n\t\ttaskName: agent.taskName,\n\t\ttaskPath: agent.taskPath,\n\t\tagent: agent.agent,\n\t\tparentId: agent.parentId,\n\t\trootId: agent.rootId,\n\t\tdepth: agent.depth,\n\t\tchildren: [...agent.children],\n\t\tstate: agent.state,\n\t\tcreatedAt: agent.createdAt,\n\t\tupdatedAt: agent.updatedAt,\n\t\tcwd: agent.cwd,\n\t\tworkspaceMode: agent.workspaceMode ?? \"shared\",\n\t\tthinkingLevel: agent.thinkingLevel,\n\t\ttimeoutMs: agent.timeoutMs,\n\t\tcurrentTimeoutMs: agent.currentTimeoutMs,\n\t\tidleTimeoutMs: agent.idleTimeoutMs,\n\t\tcurrentIdleTimeoutMs: agent.currentIdleTimeoutMs,\n\t\tmaxTurns: agent.maxTurns,\n\t\tcurrentMaxTurns: agent.currentMaxTurns,\n\t\tmaxToolCalls: agent.maxToolCalls,\n\t\tcurrentMaxToolCalls: agent.currentMaxToolCalls,\n\t\tcurrentTask: agent.currentTask\n\t\t\t? truncateUtf8(agent.currentTask, MAX_TOOL_MESSAGE_BYTES).text\n\t\t\t: undefined,\n\t\thistoryCount: agent.history.length,\n\t\tunreadMessages: agent.mailbox.filter((message) => !message.readAt).length,\n\t\tcontext: {\n\t\t\tturns: agent.contextTurns ?? 0,\n\t\t\tsources: agent.contextSourceIds?.length ?? 0,\n\t\t\tbytes: agent.contextBytes ?? 0,\n\t\t\ttruncated: agent.contextTruncated === true,\n\t\t},\n\t\tresultFormat: agent.resultFormat ?? \"text\",\n\t\tcompletionRequirements: (agent.completionRequirements ?? []).map((record) => ({\n\t\t\t...record,\n\t\t})),\n\t\tstructuredResult: agent.structuredResult,\n\t\ttermination: agent.termination,\n\t\toutcome: agent.outcome,\n\t\texecutionPlan: agent.executionPlan,\n\t\tcapabilityGrant: agent.capabilityGrant,\n\t\tsemanticCompatibility: agent.semanticCompatibility,\n\t\tsemanticSnapshotDigest: agent.semanticSnapshot?.digest,\n\t\ttelemetry: agent.telemetry,\n\t\terror: agent.error ? truncateUtf8(agent.error, MAX_TOOL_MESSAGE_BYTES).text : undefined,\n\t\ttarget: agent.target,\n\t\tpolicy: agent.policy,\n\t};\n}\n\nfunction agentStateLabel(state: ManagedAgent[\"state\"]): string {\n\tswitch (state) {\n\t\tcase \"running\":\n\t\t\treturn \"working\";\n\t\tcase \"completed\":\n\t\t\treturn \"finished\";\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\nfunction sanitizeStatusLine(value: string, maxLength: number): string {\n\treturn (\n\t\tvalue\n\t\t\t.slice(0, maxLength)\n\t\t\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Escape untrusted terminal controls.\n\t\t\t.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, \" \")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim()\n\t);\n}\n", "import type { CompletionDelivery, SubagentTransportKind } from \"./agents/types.js\";\n\nexport function resolveStatefulTransportKind(\n\tvalue: SubagentTransportKind | undefined,\n): SubagentTransportKind {\n\treturn value ?? \"subprocess\";\n}\n\nexport function resolveCompletionDelivery(\n\tvalue: CompletionDelivery | undefined,\n): CompletionDelivery {\n\treturn value ?? \"next-turn\";\n}\n", "/**\n * Stateful registration remains one lifecycle owner so session replacement, persistence,\n * capability revocation, workspace cleanup, and completion delivery cannot reorder.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { StringEnum } from \"@earendil-works/pi-ai\";\nimport { defineTool, type ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Type } from \"typebox\";\nimport {\n\ttype AgentScope,\n\ttype CompletionDelivery,\n\tisThinkingLevel,\n\ttype SubagentRuntimeSettings,\n\ttype SubagentSettings,\n\ttype SubagentTransportKind,\n\tTHINKING_LEVELS,\n} from \"./agents/types.js\";\nimport type { CompletionDeliveryBroker } from \"./completion-delivery.js\";\nimport {\n\tCompletionRequirementModeSchema,\n\tcompletionRequirementsFromBranch,\n} from \"./completion-requirement.js\";\nimport type { ContextMode } from \"./context.js\";\nimport type { CreateStatefulTransportOptions } from \"./create-stateful-transport.js\";\nimport { DelegationContractSchema } from \"./delegation-contract.js\";\nimport type { ChildSessionFactory, ParentRuntimeSnapshot } from \"./in-process-transport.js\";\nimport {\n\tDEFAULT_MAX_CONTEXT_BYTES,\n\tMAX_SUBAGENT_TIMEOUT_MS,\n\tMAX_TOOL_MESSAGE_BYTES,\n\ttruncateUtf8,\n} from \"./limits.js\";\nimport type { AgentPersistence } from \"./persistence.js\";\nimport type {\n\tAgentRegistry,\n\tAgentRunInspectionDetail,\n\tAgentRunInspectionSummary,\n\tManagedAgent,\n} from \"./registry.js\";\nimport { SUBAGENT_RESULT_FORMATS, type SubagentResultFormat } from \"./result-contract.js\";\nimport { DEFAULT_DELEGATION_CWD_POLICY } from \"./settings/inspection.js\";\nimport { readSubagentSettings } from \"./settings-reader.js\";\nimport {\n\tassertSpawnIdempotencyKey,\n\tMAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,\n} from \"./spawn-idempotency.js\";\nimport { summarizeStatefulAgent } from \"./stateful-agent-view.js\";\nimport { resolveCompletionDelivery, resolveStatefulTransportKind } from \"./stateful-config.js\";\nimport { createSpawnPromptGuidelines } from \"./stateful-guidance.js\";\nimport { assertCurrentSpawn, waitForOwnedSpawn } from \"./stateful-lifecycle.js\";\nimport { resolveStatefulLimits, type StatefulLimits } from \"./stateful-limits.js\";\nimport { createStatefulToolRenderer } from \"./stateful-render.js\";\nimport { confirmProjectAgent } from \"./stateful-safety.js\";\nimport {\n\tMailboxParamsSchema,\n\tManageParamsSchema,\n\tvalidateMailboxParams,\n\tvalidateManageParams,\n} from \"./stateful-tool-params.js\";\nimport { MAX_TASK_NAME_LENGTH } from \"./task-path.js\";\nimport { grammarSafeToolObject } from \"./tool-schema-compatibility.js\";\nimport { MAX_SUBAGENT_TOOL_CALLS, MAX_SUBAGENT_TURNS } from \"./turn-budget.js\";\nimport type { UsageRecordingController } from \"./usage-recording.js\";\nimport type { WorkspaceManager } from \"./workspace.js\";\n\ntype CwdPolicyModule = typeof import(\"./cwd-policy.js\");\ntype StateLifecycleModule = typeof import(\"./stateful-lifecycle.js\");\n\ntype StatefulSessionModules = {\n\tbroker: typeof import(\"./completion-delivery.js\");\n\tpeerCommunication: typeof import(\"./peer-communication.js\");\n\tcontext: typeof import(\"./context.js\");\n\ttransport: typeof import(\"./create-stateful-transport.js\");\n\tcwdPolicy: CwdPolicyModule;\n\tpersistence: typeof import(\"./persistence.js\");\n\tregistry: typeof import(\"./registry.js\");\n\tlifecycle: StateLifecycleModule;\n};\n\ntype StatefulSpawnModules = {\n\tagents: typeof import(\"./agents/discovery.js\");\n\tcapabilityGrant: typeof import(\"./capability-grant.js\");\n\tcontext: typeof import(\"./context.js\");\n\tcwdPolicy: CwdPolicyModule;\n\tdelegationContract: typeof import(\"./delegation-contract.js\");\n\truntimePolicy: typeof import(\"./execution/runtime-policy.js\");\n\tretainedSemanticState: typeof import(\"./retained-semantic-state.js\");\n\tsemanticSnapshot: typeof import(\"./semantic-snapshot.js\");\n\tspawnIdempotency: typeof import(\"./spawn-idempotency.js\");\n};\n\nlet statefulSessionModules: Promise<StatefulSessionModules> | undefined;\nlet statefulSpawnModules: Promise<StatefulSpawnModules> | undefined;\nlet workspaceModule: Promise<typeof import(\"./workspace.js\")> | undefined;\n\nfunction loadStatefulSessionModules(): Promise<StatefulSessionModules> {\n\tstatefulSessionModules ??= Promise.all([\n\t\timport(\"./completion-delivery.js\"),\n\t\timport(\"./peer-communication.js\"),\n\t\timport(\"./context.js\"),\n\t\timport(\"./create-stateful-transport.js\"),\n\t\timport(\"./cwd-policy.js\"),\n\t\timport(\"./persistence.js\"),\n\t\timport(\"./registry.js\"),\n\t\timport(\"./stateful-lifecycle.js\"),\n\t])\n\t\t.then(\n\t\t\t([\n\t\t\t\tbroker,\n\t\t\t\tpeerCommunication,\n\t\t\t\tcontext,\n\t\t\t\ttransport,\n\t\t\t\tcwdPolicy,\n\t\t\t\tpersistence,\n\t\t\t\tregistry,\n\t\t\t\tlifecycle,\n\t\t\t]) => ({\n\t\t\t\tbroker,\n\t\t\t\tpeerCommunication,\n\t\t\t\tcontext,\n\t\t\t\ttransport,\n\t\t\t\tcwdPolicy,\n\t\t\t\tpersistence,\n\t\t\t\tregistry,\n\t\t\t\tlifecycle,\n\t\t\t}),\n\t\t)\n\t\t.catch((error: unknown) => {\n\t\t\tstatefulSessionModules = undefined;\n\t\t\tthrow error;\n\t\t});\n\treturn statefulSessionModules;\n}\n\nfunction loadStatefulSpawnModules(): Promise<StatefulSpawnModules> {\n\tstatefulSpawnModules ??= Promise.all([\n\t\timport(\"./agents/discovery.js\"),\n\t\timport(\"./capability-grant.js\"),\n\t\timport(\"./context.js\"),\n\t\timport(\"./cwd-policy.js\"),\n\t\timport(\"./delegation-contract.js\"),\n\t\timport(\"./execution/runtime-policy.js\"),\n\t\timport(\"./retained-semantic-state.js\"),\n\t\timport(\"./semantic-snapshot.js\"),\n\t\timport(\"./spawn-idempotency.js\"),\n\t])\n\t\t.then(\n\t\t\t([\n\t\t\t\tagents,\n\t\t\t\tcapabilityGrant,\n\t\t\t\tcontext,\n\t\t\t\tcwdPolicy,\n\t\t\t\tdelegationContract,\n\t\t\t\truntimePolicy,\n\t\t\t\tretainedSemanticState,\n\t\t\t\tsemanticSnapshot,\n\t\t\t\tspawnIdempotency,\n\t\t\t]) => ({\n\t\t\t\tagents,\n\t\t\t\tcapabilityGrant,\n\t\t\t\tcontext,\n\t\t\t\tcwdPolicy,\n\t\t\t\tdelegationContract,\n\t\t\t\truntimePolicy,\n\t\t\t\tretainedSemanticState,\n\t\t\t\tsemanticSnapshot,\n\t\t\t\tspawnIdempotency,\n\t\t\t}),\n\t\t)\n\t\t.catch((error: unknown) => {\n\t\t\tstatefulSpawnModules = undefined;\n\t\t\tthrow error;\n\t\t});\n\treturn statefulSpawnModules;\n}\n\nasync function loadWorkspaceModule(): Promise<typeof import(\"./workspace.js\")> {\n\tworkspaceModule ??= import(\"./workspace.js\").catch((error: unknown) => {\n\t\tworkspaceModule = undefined;\n\t\tthrow error;\n\t});\n\treturn workspaceModule;\n}\n\nconst ContextModeSchema = Type.Union([\n\tStringEnum([\"none\", \"all\", \"summary\"] as const),\n\tType.Number({ minimum: 1, description: \"Include the most recent N user turns.\" }),\n]);\nconst ScopeSchema = StringEnum([\"user\", \"project\", \"both\"] as const, {\n\tdescription:\n\t\t'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.',\n\tdefault: \"user\",\n});\nconst StatefulThinkingLevelSchema = StringEnum(THINKING_LEVELS, {\n\tdescription:\n\t\t\"Optional requested Pi thinking level selected for this task difficulty; retained for every turn of the spawned agent.\",\n});\nconst StatefulTimeoutSchema = Type.Integer({\n\tminimum: 1,\n\tmaximum: MAX_SUBAGENT_TIMEOUT_MS,\n\tdescription:\n\t\t\"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.\",\n});\nconst DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS = 30_000;\nconst SubagentAwaitParams = Type.Object({\n\tagentId: Type.String({\n\t\tminLength: 1,\n\t\tdescription: \"Retained agent ID or canonical task path.\",\n\t}),\n\ttimeoutMs: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: MAX_SUBAGENT_TIMEOUT_MS,\n\t\t\tdescription:\n\t\t\t\t\"Maximum time to wait in milliseconds. A wait timeout stops only this tool call and does not interrupt or close the subagent. Defaults to 30000.\",\n\t\t}),\n\t),\n});\nconst StatefulTurnLimitFields = {\n\tidleTimeoutMs: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: MAX_SUBAGENT_TIMEOUT_MS,\n\t\t\tdescription:\n\t\t\t\t\"Maximum milliseconds without a completed assistant turn or tool result; retained as the agent default.\",\n\t\t}),\n\t),\n\tmaxTurns: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: MAX_SUBAGENT_TURNS,\n\t\t\tdescription:\n\t\t\t\t\"Maximum unfinished assistant turns; retained as the agent default. Omit rather than guessing a tight bound.\",\n\t\t}),\n\t),\n\tmaxToolCalls: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: MAX_SUBAGENT_TOOL_CALLS,\n\t\t\tdescription:\n\t\t\t\t\"Maximum tool calls; retained as the agent default. Omit rather than guessing a tight bound.\",\n\t\t}),\n\t),\n};\nexport interface StatefulSubagentDependencies {\n\tblockingEnabled?: boolean;\n\tcreateInProcessSession?: ChildSessionFactory;\n\tworkspaceManager?: WorkspaceManager;\n\tsettings?: SubagentRuntimeSettings;\n\tgetSettings?: () => SubagentSettings | undefined;\n\tloadTransport?: CreateStatefulTransportOptions[\"loadTransport\"];\n\tusageRecording?: UsageRecordingController;\n}\n\nexport interface StatefulSubagentRuntimeStatus {\n\tenabled: boolean;\n\tinitialized: boolean;\n\ttransport: SubagentTransportKind;\n\tcompletionDelivery: CompletionDelivery;\n\tlimits: StatefulLimits;\n\tactiveAgents: number;\n\tretainedAgents: number;\n}\n\nexport interface StatefulSubagentController {\n\tgetCompletionDelivery(): CompletionDelivery;\n\tsetCompletionDelivery(value: CompletionDelivery): void;\n\tgetRuntimeStatus(): StatefulSubagentRuntimeStatus;\n\tlistAgents(includeClosed?: boolean): ManagedAgent[];\n\tlistRunInspection(includeClosed?: boolean): AgentRunInspectionSummary[];\n\tgetRunInspection(agentId: string): AgentRunInspectionDetail | undefined;\n\tclearAgents(): Promise<number>;\n}\n\ninterface StatefulActionToolResult {\n\tcontent: Array<{ type: \"text\"; text: string }>;\n\tdetails: Record<string, unknown>;\n}\n\nexport function registerStatefulSubagents(\n\tpi: ExtensionAPI,\n\tdependencies: StatefulSubagentDependencies = {},\n): StatefulSubagentController {\n\tconst settings = Object.hasOwn(dependencies, \"settings\")\n\t\t? (dependencies.settings ?? {})\n\t\t: (readSubagentSettings()?.stateful ?? {});\n\tconst blockingEnabled = dependencies.blockingEnabled !== false;\n\tconst enabled = settings.enabled !== false;\n\tconst transportKind = resolveStatefulTransportKind(settings.transport);\n\tlet completionDelivery = resolveCompletionDelivery(settings.completionDelivery);\n\tlet runtimeLimits = resolveStatefulLimits(settings);\n\tlet completionBroker: CompletionDeliveryBroker | undefined;\n\tlet peerBroker: import(\"./peer-communication.js\").PeerCommunicationBroker | undefined;\n\tlet registry: AgentRegistry | undefined;\n\tlet persistence: AgentPersistence | undefined;\n\tlet sweepTimer: NodeJS.Timeout | undefined;\n\tlet runtimeGeneration = 0;\n\tlet runtimeTransition: Promise<void> = Promise.resolve();\n\tlet workspaceManager = dependencies.workspaceManager;\n\tconst getWorkspaceManager = async () => {\n\t\tif (workspaceManager) return workspaceManager;\n\t\tconst { WorkspaceManager } = await loadWorkspaceModule();\n\t\tworkspaceManager = new WorkspaceManager();\n\t\treturn workspaceManager;\n\t};\n\tconst isolatedAgents = new Map<string, string>();\n\tconst seenMessageIds = new Set<string>();\n\ttype PendingIdempotentSpawn = {\n\t\tgeneration: number;\n\t\trequestHash: string;\n\t\tpromise: Promise<ManagedAgent>;\n\t};\n\tconst pendingIdempotentSpawns = new Map<string, PendingIdempotentSpawn>();\n\tconst parentRuntime: ParentRuntimeSnapshot = { model: undefined, thinkingLevel: \"off\" };\n\tconst getCurrentSettings = () =>\n\t\tdependencies.getSettings ? dependencies.getSettings() : readSubagentSettings();\n\tconst getCurrentStatefulSettings = () =>\n\t\tdependencies.getSettings ? (dependencies.getSettings()?.stateful ?? {}) : settings;\n\n\tconst clearAgents = async (): Promise<number> => {\n\t\tconst generation = runtimeGeneration;\n\t\tconst currentRegistry = registry;\n\t\tconst currentPersistence = persistence;\n\t\tif (!currentRegistry) return 0;\n\t\tconst currentWorkspaceManager = await getWorkspaceManager();\n\t\tconst count = currentRegistry.list().length;\n\t\tconst clear = async () => {\n\t\t\tawait currentRegistry.closeAll();\n\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\tawait currentWorkspaceManager.cleanupAll();\n\t\t\tisolatedAgents.clear();\n\t\t\tseenMessageIds.clear();\n\t\t\tawait currentPersistence?.delete();\n\t\t};\n\t\tconst transition = runtimeTransition.then(clear, clear);\n\t\truntimeTransition = transition.catch(() => undefined);\n\t\tawait transition;\n\t\treturn count;\n\t};\n\tconst controller: StatefulSubagentController = {\n\t\tgetCompletionDelivery() {\n\t\t\treturn completionDelivery;\n\t\t},\n\t\tsetCompletionDelivery(value) {\n\t\t\tcompletionDelivery = value;\n\t\t\tcompletionBroker?.setDelivery(value);\n\t\t},\n\t\tgetRuntimeStatus() {\n\t\t\tconst counts = registry?.inspectionCounts() ?? { activeAgents: 0, retainedAgents: 0 };\n\t\t\treturn {\n\t\t\t\tenabled,\n\t\t\t\tinitialized: registry !== undefined,\n\t\t\t\ttransport: transportKind,\n\t\t\t\tcompletionDelivery,\n\t\t\t\tlimits: { ...runtimeLimits },\n\t\t\t\t...counts,\n\t\t\t};\n\t\t},\n\t\tlistAgents(includeClosed = false) {\n\t\t\treturn registry?.list(includeClosed) ?? [];\n\t\t},\n\t\tlistRunInspection(includeClosed = false) {\n\t\t\treturn registry?.listInspection(includeClosed) ?? [];\n\t\t},\n\t\tgetRunInspection(agentId) {\n\t\t\treturn registry?.getInspection(agentId);\n\t\t},\n\t\tclearAgents,\n\t};\n\tif (!enabled) return controller;\n\n\tconst requireRegistry = () => {\n\t\tif (!registry) throw new Error(\"Stateful subagents are not initialized for this session\");\n\t\treturn registry;\n\t};\n\tpi.on(\"session_start\", async (event, ctx) => {\n\t\tconst generation = ++runtimeGeneration;\n\t\tcompletionBroker?.close();\n\t\tcompletionBroker = undefined;\n\t\tconst previousPeerBroker = peerBroker;\n\t\tpeerBroker = undefined;\n\t\tif (sweepTimer) clearInterval(sweepTimer);\n\t\tsweepTimer = undefined;\n\t\tconst previousRegistry = registry;\n\t\tregistry = undefined;\n\t\tpersistence = undefined;\n\t\tisolatedAgents.clear();\n\t\tseenMessageIds.clear();\n\t\tpendingIdempotentSpawns.clear();\n\t\tconst initialize = async () => {\n\t\t\tawait previousPeerBroker?.close();\n\t\t\tconst currentWorkspaceManager = await getWorkspaceManager();\n\t\t\tconst modules = await loadStatefulSessionModules();\n\t\t\tconst cleanupErrors = await modules.lifecycle.disposeStatefulRuntime(\n\t\t\t\tpreviousRegistry,\n\t\t\t\tcurrentWorkspaceManager,\n\t\t\t);\n\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\tif (cleanupErrors.length > 0 && ctx.hasUI) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Previous subagent runtime cleanup reported ${cleanupErrors.length} error(s).`,\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tparentRuntime.model = ctx.model;\n\t\t\tparentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(pi.getThinkingLevel());\n\t\t\tconst sessionSettings = getCurrentStatefulSettings();\n\t\t\tconst nextLimits = resolveStatefulLimits(sessionSettings);\n\t\t\tconst owner =\n\t\t\t\tctx.sessionManager.getSessionId?.() ??\n\t\t\t\tctx.sessionManager.getSessionFile?.() ??\n\t\t\t\t`ephemeral:${ctx.cwd}`;\n\t\t\tconst sessionPersistence = new modules.persistence.AgentPersistence(owner, {\n\t\t\t\tretentionDays: sessionSettings.retentionDays,\n\t\t\t\tmaxStoredAgents: nextLimits.maxStoredAgents,\n\t\t\t});\n\t\t\tlet nextRegistry: AgentRegistry;\n\t\t\tlet transport: import(\"./transport.js\").SubagentTransport;\n\t\t\tconst sessionBroker = new modules.broker.CompletionDeliveryBroker(\n\t\t\t\tpi,\n\t\t\t\tctx,\n\t\t\t\tcompletionDelivery,\n\t\t\t\t{\n\t\t\t\t\tonDeliveryError: (error) => {\n\t\t\t\t\t\tif (!ctx.hasUI) return;\n\t\t\t\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tctx.ui.notify(`Subagent completion delivery failed: ${reason}`, \"warning\");\n\t\t\t\t\t},\n\t\t\t\t\tonDeliveryAttempt: (completions, input) => {\n\t\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\t\tfor (const completion of completions) {\n\t\t\t\t\t\t\tdependencies.usageRecording?.recordCompletionDeliveryAttempt(completion, input);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonAcknowledged: (completions, deliveredAt) => {\n\t\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\t\tfor (const completion of completions) {\n\t\t\t\t\t\t\tdependencies.usageRecording?.recordCompletionVisible(completion);\n\t\t\t\t\t\t\tvoid nextRegistry\n\t\t\t\t\t\t\t\t.markCompletionDelivered(completion.completionId, deliveredAt)\n\t\t\t\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\t\t\t\tif (!ctx.hasUI || generation !== runtimeGeneration) return;\n\t\t\t\t\t\t\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\t\t\t\tctx.ui.notify(`Subagent completion acknowledgement failed: ${reason}`, \"warning\");\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst sessionPeerBroker = new modules.peerCommunication.PeerCommunicationBroker({\n\t\t\t\tgetRegistry: () => nextRegistry,\n\t\t\t\tsendRoot: ({ message, senderPath }) => {\n\t\t\t\t\tpi.appendEntry(\"pi-subagent-peer-message\", {\n\t\t\t\t\t\tmessageId: message.id,\n\t\t\t\t\t\tsenderId: message.senderId,\n\t\t\t\t\t\tsenderPath,\n\t\t\t\t\t\tcontent: modules.context.redactPrivateText(message.content),\n\t\t\t\t\t});\n\t\t\t\t\tpi.sendMessage(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcustomType: \"pi-subagent-peer-message\",\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\"Message Type: SUBAGENT_PEER_MESSAGE\",\n\t\t\t\t\t\t\t\t\"Protocol: pi-subagents:v1\",\n\t\t\t\t\t\t\t\t`Message ID: ${message.id}`,\n\t\t\t\t\t\t\t\t`Sender ID: ${message.senderId}`,\n\t\t\t\t\t\t\t\t`Sender Path: ${senderPath}`,\n\t\t\t\t\t\t\t\t\"Payload:\",\n\t\t\t\t\t\t\t\tmessage.content,\n\t\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\t\tdetails: { ...message, senderPath },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ deliverAs: \"steer\", triggerTurn: false },\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tdispatch: (recipient, message) => transport.deliverMessage?.(recipient, message) ?? false,\n\t\t\t});\n\t\t\ttransport = modules.transport.createStatefulTransport({\n\t\t\t\tkind: transportKind,\n\t\t\t\tmodelRegistry: ctx.modelRegistry,\n\t\t\t\tgetParentRuntime: () => ({ ...parentRuntime }),\n\t\t\t\tgetSettings: getCurrentSettings,\n\t\t\t\tcreateInProcessSession: dependencies.createInProcessSession,\n\t\t\t\tpeerRuntime: sessionPeerBroker,\n\t\t\t\tloadTransport: dependencies.loadTransport,\n\t\t\t});\n\t\t\tnextRegistry = new modules.registry.AgentRegistry(transport, {\n\t\t\t\tmaxAgents: nextLimits.maxAgents,\n\t\t\t\tmaxActiveTurns: nextLimits.maxActiveTurns,\n\t\t\t\tmaxDepth: nextLimits.maxDepth,\n\t\t\t\tmaxChildrenPerAgent: nextLimits.maxChildrenPerAgent,\n\t\t\t\tmaxMailboxMessages: sessionSettings.maxMailboxMessages,\n\t\t\t\tmaxMailboxMessageBytes: sessionSettings.maxMailboxMessageBytes,\n\t\t\t\tidleTtlMs: sessionSettings.idleTtlMs,\n\t\t\t\tonChange: async (agents) => {\n\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\tawait sessionPersistence.save(agents);\n\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\tdependencies.usageRecording?.observeAgents(agents);\n\t\t\t\t\tfor (const agent of agents) {\n\t\t\t\t\t\tfor (const message of agent.mailbox) {\n\t\t\t\t\t\t\tif (seenMessageIds.has(message.id)) continue;\n\t\t\t\t\t\t\tseenMessageIds.add(message.id);\n\t\t\t\t\t\t\tpi.appendEntry(\"pi-subagent-message\", {\n\t\t\t\t\t\t\t\tsenderId: message.senderId,\n\t\t\t\t\t\t\t\trecipientId: message.recipientId,\n\t\t\t\t\t\t\t\tcontent: modules.context.redactPrivateText(message.content).slice(0, 160),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tagent.state === \"running\" &&\n\t\t\t\t\t\t\t\tmessage.deduplicationKey?.startsWith(\"completion:\")\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait transport.deliverMessage?.(agent, {\n\t\t\t\t\t\t\t\t\t\t...message,\n\t\t\t\t\t\t\t\t\t\tcontent: modules.context.redactPrivateText(message.content),\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t// The durable parent mailbox remains the retry path for the next turn.\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tonTurnComplete: (completion) => {\n\t\t\t\t\tif (generation !== runtimeGeneration) return;\n\t\t\t\t\tdependencies.usageRecording?.recordChildCompletion(completion);\n\t\t\t\t\tif (completion.recipientId === \"root\") sessionBroker.enqueue(completion);\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst persisted = sessionPersistence.load();\n\t\t\tconst orphanCleanupFailures = await modules.lifecycle.cleanupPersistedWorkspaces(\n\t\t\t\tpersisted,\n\t\t\t\tcurrentWorkspaceManager,\n\t\t\t);\n\t\t\tif (generation !== runtimeGeneration) {\n\t\t\t\tsessionBroker.close();\n\t\t\t\tawait sessionPeerBroker.close();\n\t\t\t\tawait modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (ctx.hasUI && orphanCleanupFailures > 0) {\n\t\t\t\tctx.ui.notify(\"Some orphaned subagent worktrees could not be cleaned\", \"warning\");\n\t\t\t}\n\t\t\tconst restored = persisted\n\t\t\t\t.filter(\n\t\t\t\t\t(agent) =>\n\t\t\t\t\t\tagent.workspaceMode !== \"worktree\" &&\n\t\t\t\t\t\t((agent.agentScope !== \"project\" && agent.agentScope !== \"both\") ||\n\t\t\t\t\t\t\tctx.isProjectTrusted()),\n\t\t\t\t)\n\t\t\t\t.flatMap((agent) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst target = modules.cwdPolicy.resolveSubagentTarget({\n\t\t\t\t\t\t\tworkspace: ctx.cwd,\n\t\t\t\t\t\t\trequestedCwd: agent.cwd,\n\t\t\t\t\t\t\tcurrentProjectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\t{ ...agent, cwd: target.cwd, target: modules.cwdPolicy.targetPolicyAudit(target) },\n\t\t\t\t\t\t];\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\tfor (const agent of restored) {\n\t\t\t\tfor (const message of agent.mailbox) seenMessageIds.add(message.id);\n\t\t\t}\n\t\t\tnextRegistry.restore(restored);\n\t\t\tconst branchRequirements = completionRequirementsFromBranch(ctx.sessionManager.getBranch());\n\t\t\tconst branchOwnsRequirementState =\n\t\t\t\tbranchRequirements.observedState || event.reason === \"fork\" || event.reason === \"new\";\n\t\t\tnextRegistry.reconcileCompletionRequirements(\n\t\t\t\tbranchRequirements.records,\n\t\t\t\tbranchOwnsRequirementState,\n\t\t\t);\n\t\t\tif (branchOwnsRequirementState) {\n\t\t\t\ttry {\n\t\t\t\t\tawait sessionPersistence.save(nextRegistry.list(true));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (generation === runtimeGeneration && ctx.hasUI) {\n\t\t\t\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\t`Subagent requirement reconciliation could not be persisted yet: ${reason}`,\n\t\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (generation !== runtimeGeneration) {\n\t\t\t\tsessionBroker.close();\n\t\t\t\tawait sessionPeerBroker.close();\n\t\t\t\tawait modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tregistry = nextRegistry;\n\t\t\tpersistence = sessionPersistence;\n\t\t\tcompletionBroker = sessionBroker;\n\t\t\tpeerBroker = sessionPeerBroker;\n\t\t\tfor (const completion of nextRegistry.listPendingCompletions()) {\n\t\t\t\tif (completion.recipientId === \"root\") sessionBroker.enqueue(completion);\n\t\t\t}\n\t\t\truntimeLimits = nextLimits;\n\t\t\tconst sweepEveryMs = Math.max(\n\t\t\t\t1_000,\n\t\t\t\tMath.min(sessionSettings.idleTtlMs ?? 60 * 60 * 1000, 60_000),\n\t\t\t);\n\t\t\tsweepTimer = setInterval(() => {\n\t\t\t\tvoid nextRegistry.sweepExpired().catch((error: unknown) => {\n\t\t\t\t\tif (!ctx.hasUI || generation !== runtimeGeneration) return;\n\t\t\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tctx.ui.notify(`Subagent expiry cleanup failed: ${reason}`, \"warning\");\n\t\t\t\t});\n\t\t\t}, sweepEveryMs);\n\t\t\tsweepTimer.unref();\n\t\t};\n\t\tconst transition = runtimeTransition.then(initialize, initialize);\n\t\truntimeTransition = transition.catch(() => undefined);\n\t\tawait transition;\n\t});\n\n\tpi.on(\"agent_start\", () => {\n\t\tcompletionBroker?.onParentTurnStart();\n\t});\n\n\tpi.on(\"context\", (event) => {\n\t\tcompletionBroker?.onParentContext(event.messages);\n\t});\n\n\tpi.on(\"agent_settled\", () => {\n\t\tcompletionBroker?.onParentSettled();\n\t});\n\n\tpi.on(\"model_select\", (event) => {\n\t\tparentRuntime.model = event.model;\n\t});\n\n\tpi.on(\"thinking_level_select\", (event) => {\n\t\tparentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(event.level);\n\t});\n\n\tpi.on(\"session_shutdown\", async (_event, ctx) => {\n\t\truntimeGeneration++;\n\t\tcompletionBroker?.close();\n\t\tcompletionBroker = undefined;\n\t\tconst previousPeerBroker = peerBroker;\n\t\tpeerBroker = undefined;\n\t\tif (sweepTimer) clearInterval(sweepTimer);\n\t\tsweepTimer = undefined;\n\t\tconst previousRegistry = registry;\n\t\tregistry = undefined;\n\t\tpersistence = undefined;\n\t\tisolatedAgents.clear();\n\t\tseenMessageIds.clear();\n\t\tpendingIdempotentSpawns.clear();\n\t\tconst shutdown = async () => {\n\t\t\tawait previousPeerBroker?.close();\n\t\t\tconst currentWorkspaceManager = await getWorkspaceManager();\n\t\t\tconst { disposeStatefulRuntime } = await import(\"./stateful-lifecycle.js\");\n\t\t\tconst errors = await disposeStatefulRuntime(previousRegistry, currentWorkspaceManager);\n\t\t\tif (errors.length > 0 && ctx.hasUI) {\n\t\t\t\tctx.ui.notify(`Subagent shutdown cleanup reported ${errors.length} error(s).`, \"warning\");\n\t\t\t}\n\t\t};\n\t\tconst transition = runtimeTransition.then(shutdown, shutdown);\n\t\truntimeTransition = transition.catch(() => undefined);\n\t\tawait transition;\n\t});\n\n\tconst spawnTool = defineTool({\n\t\tname: \"subagent_spawn\",\n\t\tlabel: \"Spawn Subagent\",\n\t\tdescription:\n\t\t\t\"Start an addressable background subagent with an opaque agentId and canonical taskPath, an optional thinking level and execution budgets chosen for the task difficulty, and asynchronous completion delivery. The current bounded capacity, completion policy, working-directory policy, and available agent definitions are published in the pi-subagents session-guidance message. Working-directory policy controls launch targets and protected project resources, not filesystem access or sandboxing.\",\n\t\tpromptSnippet: \"Start a reusable detached subagent; completion is delivered asynchronously\",\n\t\tpromptGuidelines: createSpawnPromptGuidelines(blockingEnabled),\n\t\tparameters: grammarSafeToolObject({\n\t\t\tagent: Type.String({ minLength: 1 }),\n\t\t\ttaskName: Type.Optional(\n\t\t\t\tType.String({\n\t\t\t\t\tminLength: 1,\n\t\t\t\t\tmaxLength: MAX_TASK_NAME_LENGTH,\n\t\t\t\t\tpattern: \"^[a-z0-9_]+$\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Canonical path segment for this task; use lowercase letters, digits, and underscores.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\ttask: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),\n\t\t\tthinkingLevel: Type.Optional(StatefulThinkingLevelSchema),\n\t\t\ttimeoutMs: Type.Optional(StatefulTimeoutSchema),\n\t\t\t...StatefulTurnLimitFields,\n\t\t\tcwd: Type.Optional(Type.String()),\n\t\t\tagentScope: Type.Optional(ScopeSchema),\n\t\t\tconfirmProjectAgents: Type.Optional(Type.Boolean({ default: true })),\n\t\t\tcontext: Type.Optional(ContextModeSchema),\n\t\t\tcontextEntryIds: Type.Optional(\n\t\t\t\tType.Array(Type.String(), { description: \"Optional selected session entry IDs.\" }),\n\t\t\t),\n\t\t\tparentId: Type.Optional(\n\t\t\t\tType.String({ description: \"Optional parent agent ID or canonical task path.\" }),\n\t\t\t),\n\t\t\tallowConcurrentWrites: Type.Optional(\n\t\t\t\tType.Boolean({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Deprecated compatibility field; shared-workspace concurrency is allowed by default.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\tworkspaceMode: Type.Optional(\n\t\t\t\tStringEnum([\"shared\", \"worktree\"] as const, {\n\t\t\t\t\tdescription: \"Use the shared workspace (default) or an opt-in disposable Git worktree.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\tcontract: Type.Optional(DelegationContractSchema),\n\t\t\tidempotencyKey: Type.Optional(\n\t\t\t\tType.String({\n\t\t\t\t\tminLength: 1,\n\t\t\t\t\tmaxLength: MAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,\n\t\t\t\t\tdescription: \"Reuse the same retained agent for an exact accepted spawn retry.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\tresultFormat: Type.Optional(\n\t\t\t\tStringEnum(SUBAGENT_RESULT_FORMATS, {\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Use text (default), structured-v1, or the evidence-preserving structured-v2 completion contract.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\tcompletionRequirement: Type.Optional(CompletionRequirementModeSchema),\n\t\t}),\n\t\t...createStatefulToolRenderer(\"spawn\"),\n\t\tasync execute(_id, params, signal, _update, ctx) {\n\t\t\tconst generation = runtimeGeneration;\n\t\t\tconst capturedRegistry = registry;\n\t\t\tlet modules: StatefulSpawnModules;\n\t\t\ttry {\n\t\t\t\tmodules = await loadStatefulSpawnModules();\n\t\t\t} catch (error) {\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tlet currentWorkspaceManager: WorkspaceManager;\n\t\t\ttry {\n\t\t\t\tcurrentWorkspaceManager = await getWorkspaceManager();\n\t\t\t} catch (error) {\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst scope = (params.agentScope ?? \"user\") as AgentScope;\n\t\t\tconst resultFormat = (params.resultFormat ?? \"text\") as SubagentResultFormat;\n\t\t\tconst contract = modules.delegationContract.normalizeDelegationContract(params.contract);\n\t\t\tif (params.contract !== undefined && !contract) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"subagent_spawn contract must be a valid pi-subagents:delegation:v2 object\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tmodules.runtimePolicy.assertSubagentDepthAllowed();\n\t\t\tassertSpawnIdempotencyKey(params.idempotencyKey);\n\t\t\tconst currentSettings = getCurrentSettings();\n\t\t\tconst target = modules.cwdPolicy.resolveSubagentTarget({\n\t\t\t\tworkspace: ctx.cwd,\n\t\t\t\trequestedCwd: params.cwd,\n\t\t\t\tcurrentProjectTrusted: ctx.isProjectTrusted(),\n\t\t\t});\n\t\t\tmodules.cwdPolicy.assertDelegationTargetAllowed(\n\t\t\t\ttarget,\n\t\t\t\tcurrentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY,\n\t\t\t);\n\t\t\tconst cwd = target.cwd;\n\t\t\tconst mode = resolveSpawnContextMode(params.context, params.contextEntryIds);\n\t\t\tconst snapshot = modules.context.buildContextSnapshot(\n\t\t\t\tctx.sessionManager.getBranch(),\n\t\t\t\tmode,\n\t\t\t\tDEFAULT_MAX_CONTEXT_BYTES,\n\t\t\t\tparams.contextEntryIds,\n\t\t\t);\n\t\t\tif ((scope === \"project\" || scope === \"both\") && !ctx.isProjectTrusted()) {\n\t\t\t\tthrow new Error(\"Project-local subagent definitions require a trusted project\");\n\t\t\t}\n\t\t\tconst resolvedAgents = modules.agents.discoverAgents(cwd, scope, currentSettings).agents;\n\t\t\tconst resolvedAgent = resolvedAgents.find((agent) => agent.name === params.agent);\n\t\t\tif (!resolvedAgent) {\n\t\t\t\tconst available = resolvedAgents.map((agent) => agent.name).join(\", \") || \"none\";\n\t\t\t\tthrow new Error(`Unknown subagent ${params.agent}. Available agents: ${available}`);\n\t\t\t}\n\t\t\tconst targetSnapshot = modules.cwdPolicy.targetPolicyAudit(target);\n\t\t\tconst { executionPlan, semanticSnapshot } =\n\t\t\t\tawait modules.retainedSemanticState.buildRetainedSemanticState({\n\t\t\t\t\tagent: resolvedAgent,\n\t\t\t\t\tcontract,\n\t\t\t\t\ttarget: targetSnapshot,\n\t\t\t\t\tcwd,\n\t\t\t\t\tworkspaceMode: params.workspaceMode === \"worktree\" ? \"worktree\" : \"shared\",\n\t\t\t\t\ttransport: transportKind,\n\t\t\t\t\tresultFormat,\n\t\t\t\t\tthinkingLevel: params.thinkingLevel,\n\t\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\t\ttaskGeneration: 1,\n\t\t\t\t});\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst requestHash = modules.spawnIdempotency.hashSpawnRequest({\n\t\t\t\tagent: params.agent,\n\t\t\t\ttaskName: params.taskName,\n\t\t\t\ttask: params.task,\n\t\t\t\tcwd,\n\t\t\t\tagentScope: scope,\n\t\t\t\tthinkingLevel: params.thinkingLevel,\n\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\tidleTimeoutMs: params.idleTimeoutMs,\n\t\t\t\tmaxTurns: params.maxTurns,\n\t\t\t\tmaxToolCalls: params.maxToolCalls,\n\t\t\t\tparentId: params.parentId,\n\t\t\t\tcontext: snapshot.text || undefined,\n\t\t\t\tcontextSourceIds: snapshot.sourceIds,\n\t\t\t\tworkspaceMode: params.workspaceMode ?? \"shared\",\n\t\t\t\tallowConcurrentWrites: params.allowConcurrentWrites ?? false,\n\t\t\t\tcontract,\n\t\t\t\tresultFormat,\n\t\t\t\tcompletionRequirement: params.completionRequirement ?? \"background\",\n\t\t\t});\n\t\t\tif (!capturedRegistry) {\n\t\t\t\tthrow new Error(\"Stateful subagents are not initialized for this session\");\n\t\t\t}\n\t\t\tconst ownedRegistry = capturedRegistry;\n\t\t\tconst retained = ownedRegistry.findBySpawnIdempotencyKey(params.idempotencyKey, requestHash);\n\t\t\tif (retained) return result(retained, `Reused ${retained.agent} as ${retained.id}.`);\n\t\t\tconst foundPending = params.idempotencyKey\n\t\t\t\t? pendingIdempotentSpawns.get(params.idempotencyKey)\n\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\tparams.idempotencyKey &&\n\t\t\t\tfoundPending &&\n\t\t\t\tfoundPending.generation !== generation &&\n\t\t\t\tpendingIdempotentSpawns.get(params.idempotencyKey) === foundPending\n\t\t\t) {\n\t\t\t\tpendingIdempotentSpawns.delete(params.idempotencyKey);\n\t\t\t}\n\t\t\tconst pending = foundPending?.generation === generation ? foundPending : undefined;\n\t\t\tif (pending) {\n\t\t\t\tif (pending.requestHash !== requestHash) {\n\t\t\t\t\tthrow new Error(\"The subagent_spawn idempotencyKey is pending with different parameters\");\n\t\t\t\t}\n\t\t\t\tconst agent = await waitForOwnedSpawn(pending.promise, signal);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\treturn result(agent, `Reused ${agent.agent} as ${agent.id}.`);\n\t\t\t}\n\t\t\tlet resolvePending: ((agent: ManagedAgent) => void) | undefined;\n\t\t\tlet rejectPending: ((error: unknown) => void) | undefined;\n\t\t\tlet ownedPending: PendingIdempotentSpawn | undefined;\n\t\t\tif (params.idempotencyKey) {\n\t\t\t\tconst promise = new Promise<ManagedAgent>((resolve, reject) => {\n\t\t\t\t\tresolvePending = resolve;\n\t\t\t\t\trejectPending = reject;\n\t\t\t\t});\n\t\t\t\tvoid promise.catch(() => undefined);\n\t\t\t\townedPending = { generation, requestHash, promise };\n\t\t\t\tpendingIdempotentSpawns.set(params.idempotencyKey, ownedPending);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait confirmProjectAgent(\n\t\t\t\t\tparams.agent,\n\t\t\t\t\tscope,\n\t\t\t\t\tparams.confirmProjectAgents ?? true,\n\t\t\t\t\tctx,\n\t\t\t\t\tcwd,\n\t\t\t\t\tcurrentSettings,\n\t\t\t\t);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tif (params.workspaceMode === \"worktree\" && resolvedAgent.source === \"project\") {\n\t\t\t\t\tthrow new Error(\"Project-local subagent definitions cannot run in a detached worktree\");\n\t\t\t\t}\n\t\t\t\tconst requestedCwd = cwd;\n\t\t\t\tconst workspaceOwner = `pending-${randomUUID()}`;\n\t\t\t\tconst workspace =\n\t\t\t\t\tparams.workspaceMode === \"worktree\"\n\t\t\t\t\t\t? await currentWorkspaceManager.create(workspaceOwner, requestedCwd)\n\t\t\t\t\t\t: undefined;\n\t\t\t\ttry {\n\t\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlet agent: ManagedAgent | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tconst capabilityGrant = modules.capabilityGrant.issueCapabilityGrant(\n\t\t\t\t\t\texecutionPlan,\n\t\t\t\t\t\tDate.now(),\n\t\t\t\t\t\tMath.max(1, (params.timeoutMs ?? resolvedAgent.timeoutMs ?? 600_000) + 60_000),\n\t\t\t\t\t);\n\t\t\t\t\tagent = await ownedRegistry.spawn({\n\t\t\t\t\t\tagent: params.agent,\n\t\t\t\t\t\ttaskName: params.taskName,\n\t\t\t\t\t\ttask: params.task,\n\t\t\t\t\t\tcwd: workspace?.path ?? requestedCwd,\n\t\t\t\t\t\tagentScope: scope,\n\t\t\t\t\t\tthinkingLevel: params.thinkingLevel,\n\t\t\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\t\t\tidleTimeoutMs: params.idleTimeoutMs,\n\t\t\t\t\t\tmaxTurns: params.maxTurns,\n\t\t\t\t\t\tmaxToolCalls: params.maxToolCalls,\n\t\t\t\t\t\tparentId: params.parentId,\n\t\t\t\t\t\tcontext: snapshot.text || undefined,\n\t\t\t\t\t\tcontextSourceIds: snapshot.sourceIds,\n\t\t\t\t\t\tcontextTruncated: snapshot.truncated,\n\t\t\t\t\t\tcontextTurns: snapshot.turns,\n\t\t\t\t\t\tcontextBytes: Buffer.byteLength(snapshot.text, \"utf8\"),\n\t\t\t\t\t\tworkspaceMode: workspace ? \"worktree\" : undefined,\n\t\t\t\t\t\tspawnIdempotencyKey: params.idempotencyKey,\n\t\t\t\t\t\tspawnRequestHash: params.idempotencyKey ? requestHash : undefined,\n\t\t\t\t\t\tcontract,\n\t\t\t\t\t\tresultFormat: resultFormat === \"text\" ? undefined : resultFormat,\n\t\t\t\t\t\tcompletionRequirement: params.completionRequirement ?? \"background\",\n\t\t\t\t\t\texecutionPlan,\n\t\t\t\t\t\tcapabilityGrant,\n\t\t\t\t\t\tsemanticSnapshot,\n\t\t\t\t\t\tsemanticCompatibility: { status: \"compatible\", changedComponents: [] },\n\t\t\t\t\t\ttarget: targetSnapshot,\n\t\t\t\t\t});\n\t\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (agent) await ownedRegistry.closeTree(agent.id).catch(() => undefined);\n\t\t\t\t\tif (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (!agent) throw new Error(\"Subagent spawn completed without a retained agent\");\n\t\t\t\tif (workspace && agent.cwd === workspace.path) isolatedAgents.set(agent.id, workspaceOwner);\n\t\t\t\telse if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tresolvePending?.(agent);\n\t\t\t\tconst deliveryNote =\n\t\t\t\t\tcompletionDelivery === \"auto-resume\"\n\t\t\t\t\t\t? \"Auto-resume steers completions into active parent work or requests synthesis when idle. Treat this response as progress, not final synthesis, until every final-answer-required completion message is visible. If local work is exhausted while required children remain active, emit at most one brief progress sentence and end the turn; do not repeat waiting updates or use the requested final format, verdict, or conclusion. Do not redo a running child's assigned work.\"\n\t\t\t\t\t\t: \"The current response must not depend on the result because next-turn delivery will not wake an idle root.\";\n\t\t\t\tconst requirementNote =\n\t\t\t\t\tparams.completionRequirement === \"required\"\n\t\t\t\t\t\t? \"This exact run is runtime-tracked as required until its completion becomes visible or reaches an explicit terminal state. Current Pi versions still cannot prevent already-streamed premature output.\"\n\t\t\t\t\t\t: \"This run is background work and does not block the parent final answer.\";\n\t\t\t\treturn result(\n\t\t\t\t\tagent,\n\t\t\t\t\t`Spawned ${agent.agent} as ${agent.taskPath ?? agent.id} (${agent.id}). ${requirementNote} 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.`,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\trejectPending?.(error);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tif (\n\t\t\t\t\tparams.idempotencyKey &&\n\t\t\t\t\townedPending &&\n\t\t\t\t\tpendingIdempotentSpawns.get(params.idempotencyKey) === ownedPending\n\t\t\t\t) {\n\t\t\t\t\tpendingIdempotentSpawns.delete(params.idempotencyKey);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n\tpi.registerTool(spawnTool);\n\n\tpi.registerTool({\n\t\tname: \"subagent_send\",\n\t\tlabel: \"Send Subagent Follow-up\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet: \"Start a new detached follow-up turn on a retained subagent\",\n\t\tparameters: Type.Object({\n\t\t\tagentId: Type.String({ description: \"Retained agent ID or canonical task path.\" }),\n\t\t\ttask: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),\n\t\t\ttimeoutMs: Type.Optional(\n\t\t\t\tType.Integer({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tmaximum: MAX_SUBAGENT_TIMEOUT_MS,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Optional work deadline for this follow-up turn. On expiry, Pi aborts the work and makes one separately bounded summary attempt.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\t...StatefulTurnLimitFields,\n\t\t\tcompletionRequirement: Type.Optional(CompletionRequirementModeSchema),\n\t\t\trevalidate: Type.Optional(\n\t\t\t\tType.Boolean({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Accept the current semantic resource snapshot after a reported mismatch before starting this follow-up.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t\tallowConcurrentWrites: Type.Optional(\n\t\t\t\tType.Boolean({\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Deprecated compatibility field; shared-workspace concurrency is allowed by default.\",\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t\t...createStatefulToolRenderer(\"send\"),\n\t\tasync execute(_id, params, signal, _update, ctx) {\n\t\t\tconst generation = runtimeGeneration;\n\t\t\tconst ownedRegistry = requireRegistry();\n\t\t\tlet modules: StatefulSpawnModules;\n\t\t\ttry {\n\t\t\t\tmodules = await loadStatefulSpawnModules();\n\t\t\t} catch (error) {\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst currentSettings = getCurrentSettings();\n\t\t\tconst existing = ownedRegistry.get(params.agentId);\n\t\t\tif (!existing) throw new Error(`Unknown subagent: ${params.agentId}`);\n\t\t\tconst currentAgent = modules.agents\n\t\t\t\t.discoverAgents(existing.cwd, existing.agentScope ?? \"user\", currentSettings)\n\t\t\t\t.agents.find((agent) => agent.name === existing.agent);\n\t\t\tif (!currentAgent) throw new Error(`Unknown retained subagent definition: ${existing.agent}`);\n\t\t\tconst resolvedFollowUpTarget =\n\t\t\t\texisting.workspaceMode === \"worktree\"\n\t\t\t\t\t? undefined\n\t\t\t\t\t: modules.cwdPolicy.resolveSubagentTarget({\n\t\t\t\t\t\t\tworkspace: ctx.cwd,\n\t\t\t\t\t\t\trequestedCwd: existing.cwd,\n\t\t\t\t\t\t\tcurrentProjectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t\t\t});\n\t\t\tif (resolvedFollowUpTarget) {\n\t\t\t\tmodules.cwdPolicy.assertDelegationTargetAllowed(\n\t\t\t\t\tresolvedFollowUpTarget,\n\t\t\t\t\tcurrentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (existing.workspaceMode === \"worktree\" && !existing.target) {\n\t\t\t\tthrow new Error(\"Retained worktree is missing its trusted target snapshot\");\n\t\t\t}\n\t\t\tconst currentTarget =\n\t\t\t\texisting.workspaceMode === \"worktree\" && existing.target\n\t\t\t\t\t? existing.target\n\t\t\t\t\t: modules.cwdPolicy.targetPolicyAudit(\n\t\t\t\t\t\t\tresolvedFollowUpTarget as NonNullable<typeof resolvedFollowUpTarget>,\n\t\t\t\t\t\t);\n\t\t\tconst { executionPlan: currentPlan, semanticSnapshot: currentSnapshot } =\n\t\t\t\tawait modules.retainedSemanticState.buildRetainedSemanticState({\n\t\t\t\t\tagent: currentAgent,\n\t\t\t\t\tcontract: existing.contract,\n\t\t\t\t\ttarget: currentTarget,\n\t\t\t\t\tcwd: existing.cwd,\n\t\t\t\t\tworkspaceMode: existing.workspaceMode === \"worktree\" ? \"worktree\" : \"shared\",\n\t\t\t\t\ttransport: transportKind,\n\t\t\t\t\tresultFormat: existing.resultFormat ?? \"text\",\n\t\t\t\t\tthinkingLevel: existing.thinkingLevel,\n\t\t\t\t\ttimeoutMs: params.timeoutMs ?? existing.timeoutMs,\n\t\t\t\t\ttaskGeneration: (existing.executionPlan?.taskGeneration ?? 0) + 1,\n\t\t\t\t\tcancellationLineage: [\n\t\t\t\t\t\t...(existing.executionPlan?.cancellationLineage ?? []),\n\t\t\t\t\t\t...(existing.state === \"interrupted\" && existing.executionPlan?.id\n\t\t\t\t\t\t\t? [existing.executionPlan.id]\n\t\t\t\t\t\t\t: []),\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst compatibility = existing.semanticSnapshot\n\t\t\t\t? modules.semanticSnapshot.evaluateSemanticCompatibility(\n\t\t\t\t\t\texisting.semanticSnapshot,\n\t\t\t\t\t\tcurrentSnapshot,\n\t\t\t\t\t)\n\t\t\t\t: { status: \"warning\" as const, changedComponents: [\"legacy-missing-snapshot\"] };\n\t\t\tif (\n\t\t\t\t(compatibility.status === \"needs-revalidation\" || compatibility.status === \"rejected\") &&\n\t\t\t\tparams.revalidate !== true\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Subagent semantic resources changed; retry with revalidate: true after reviewing: ${compatibility.changedComponents.join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait confirmProjectAgent(\n\t\t\t\texisting.agent,\n\t\t\t\texisting.agentScope ?? \"user\",\n\t\t\t\tfalse,\n\t\t\t\tctx,\n\t\t\t\texisting.cwd,\n\t\t\t\tcurrentSettings,\n\t\t\t);\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst currentGrant = modules.capabilityGrant.issueCapabilityGrant(\n\t\t\t\tcurrentPlan,\n\t\t\t\tDate.now(),\n\t\t\t\tMath.max(1, (params.timeoutMs ?? existing.timeoutMs ?? 600_000) + 60_000),\n\t\t\t);\n\t\t\tawait ownedRegistry.updateSemanticState(\n\t\t\t\texisting.id,\n\t\t\t\tcurrentPlan,\n\t\t\t\tcurrentGrant,\n\t\t\t\tcurrentSnapshot,\n\t\t\t\tparams.revalidate === true && compatibility.status !== \"compatible\"\n\t\t\t\t\t? { status: \"warning\", changedComponents: compatibility.changedComponents }\n\t\t\t\t\t: compatibility,\n\t\t\t);\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst agent = await ownedRegistry.followUp(params.agentId, params.task, {\n\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\tidleTimeoutMs: params.idleTimeoutMs,\n\t\t\t\tmaxTurns: params.maxTurns,\n\t\t\t\tmaxToolCalls: params.maxToolCalls,\n\t\t\t\tcompletionRequirement: params.completionRequirement ?? \"background\",\n\t\t\t});\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\treturn result(agent, `Started follow-up for ${agent.id}.`);\n\t\t},\n\t});\n\n\tif (blockingEnabled) {\n\t\tpi.registerTool({\n\t\t\tname: \"subagent_await\",\n\t\t\tlabel: \"Await Subagent\",\n\t\t\tdescription:\n\t\t\t\t\"Wait for one retained subagent's current turn to settle and return its latest bounded output. This blocks Pi from processing queued steering until the wait finishes. A wait timeout or caller cancellation stops only the wait and never interrupts or closes the subagent; use subagent_manage for lifecycle changes. Automatic completion delivery remains active and may later repeat the same at-least-once completion.\",\n\t\t\tpromptSnippet:\n\t\t\t\t\"Intentionally block until one retained subagent settles or the wait times out\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use subagent_await only when the retained result is required before the next action, useful overlapping main-agent work is complete, and blocking Pi is intentional.\",\n\t\t\t\t\"Do not repeatedly call subagent_await after a timeout; the subagent keeps running and completion delivery remains active. Use subagent_manage only when the user wants to interrupt or close it.\",\n\t\t\t],\n\t\t\tparameters: SubagentAwaitParams,\n\t\t\t...createStatefulToolRenderer(\"await\"),\n\t\t\tasync execute(_id, params, signal): Promise<StatefulActionToolResult> {\n\t\t\t\tconst generation = runtimeGeneration;\n\t\t\t\tconst timeoutMs = params.timeoutMs ?? DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS;\n\t\t\t\tconst waited = await requireRegistry().wait(params.agentId, timeoutMs, signal);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\treturn awaitResult(waited.agent, waited.timedOut, timeoutMs);\n\t\t\t},\n\t\t});\n\t}\n\n\tpi.registerTool({\n\t\tname: \"subagent_manage\",\n\t\tlabel: \"Manage Subagents\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet: \"Interrupt or close retained detached subagents\",\n\t\tparameters: ManageParamsSchema,\n\t\t...createStatefulToolRenderer(\"manage\"),\n\t\tasync execute(_id, params, signal): Promise<StatefulActionToolResult> {\n\t\t\tconst generation = runtimeGeneration;\n\t\t\tconst ownedRegistry = requireRegistry();\n\t\t\tlet currentWorkspaceManager: WorkspaceManager;\n\t\t\ttry {\n\t\t\t\tcurrentWorkspaceManager = await getWorkspaceManager();\n\t\t\t} catch (error) {\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst ownedAgent = (agentId: string): ManagedAgent => {\n\t\t\t\tconst value = ownedRegistry.get(agentId);\n\t\t\t\tif (!value) throw new Error(`Unknown subagent: ${agentId}`);\n\t\t\t\treturn value;\n\t\t\t};\n\t\t\tconst operation = validateManageParams(params);\n\t\t\tconst agentId = operation.agentId;\n\t\t\tif (operation.action === \"interrupt\") {\n\t\t\t\tif (operation.subtree) {\n\t\t\t\t\tconst agents = await ownedRegistry.interruptTree(agentId);\n\t\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Interrupted ${agents.length} active agent(s).` }],\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\tagent: summarizeStatefulAgent(ownedAgent(agentId)),\n\t\t\t\t\t\t\tagents: agents.map(summarizeStatefulAgent),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst agent = await ownedRegistry.interrupt(agentId);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\treturn result(agent, `Interrupted ${agent.id}; it remains reusable.`);\n\t\t\t}\n\t\t\tconst existing = ownedRegistry.get(agentId);\n\t\t\tif (existing?.state === \"closed\" && !operation.subtree) {\n\t\t\t\tconst pendingOwner = isolatedAgents.get(existing.id);\n\t\t\t\tif (pendingOwner) await currentWorkspaceManager.cleanup(pendingOwner);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\tisolatedAgents.delete(existing.id);\n\t\t\t\treturn result(existing, `Closed ${existing.id}.`);\n\t\t\t}\n\t\t\tif (operation.subtree) {\n\t\t\t\tlet agents: ManagedAgent[];\n\t\t\t\ttry {\n\t\t\t\t\tagents = await ownedRegistry.closeTree(agentId);\n\t\t\t\t} finally {\n\t\t\t\t\tawait cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);\n\t\t\t\t}\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Closed ${agents.length} agent(s).` }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tagent: summarizeStatefulAgent(ownedAgent(agentId)),\n\t\t\t\t\t\tagents: agents.map(summarizeStatefulAgent),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tlet agent: ManagedAgent;\n\t\t\ttry {\n\t\t\t\tagent = await ownedRegistry.close(agentId);\n\t\t\t} finally {\n\t\t\t\tawait cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);\n\t\t\t}\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\treturn result(agent, `Closed ${agent.id}.`);\n\t\t},\n\t});\n\n\tpi.registerTool({\n\t\tname: \"subagent_mailbox\",\n\t\tlabel: \"Subagent Mailbox\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet: \"Send or read queue-only detached-subagent mailbox messages\",\n\t\tparameters: MailboxParamsSchema,\n\t\t...createStatefulToolRenderer(\"mailbox\"),\n\t\tasync execute(_id, params, signal): Promise<StatefulActionToolResult> {\n\t\t\tconst generation = runtimeGeneration;\n\t\t\tconst ownedRegistry = requireRegistry();\n\t\t\tconst operation = validateMailboxParams(params);\n\t\t\tif (operation.action === \"send\") {\n\t\t\t\tconst message = await ownedRegistry.sendMessage(\n\t\t\t\t\toperation.agentId,\n\t\t\t\t\toperation.message,\n\t\t\t\t\toperation.senderId,\n\t\t\t\t\toperation.deduplicationKey,\n\t\t\t\t);\n\t\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Queued ${message.id} for ${message.recipientId}.` }],\n\t\t\t\t\tdetails: { message },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst messages = await ownedRegistry.readMessages(\n\t\t\t\toperation.agentId,\n\t\t\t\toperation.acknowledge,\n\t\t\t\toperation.limit,\n\t\t\t);\n\t\t\tassertCurrentSpawn(signal, generation, runtimeGeneration);\n\t\t\tconst summaries = messages.map((message) => ({\n\t\t\t\t...message,\n\t\t\t\tcontent: truncateUtf8(message.content, MAX_TOOL_MESSAGE_BYTES).text,\n\t\t\t}));\n\t\t\tconst text = summaries.length\n\t\t\t\t? summaries\n\t\t\t\t\t\t.map((message) => `${message.id} from ${message.senderId}: ${message.content}`)\n\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t: \"No unread messages.\";\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text }],\n\t\t\t\tdetails: { messages: summaries },\n\t\t\t};\n\t\t},\n\t});\n\n\treturn controller;\n}\n\nfunction normalizeContextMode(value: \"none\" | \"all\" | \"summary\" | number | undefined): ContextMode {\n\tif (value === undefined) return \"none\";\n\tif (value === \"none\" || value === \"all\" || value === \"summary\") return value;\n\treturn Math.max(1, Math.floor(value));\n}\n\nexport function resolveSpawnContextMode(\n\tvalue: \"none\" | \"all\" | \"summary\" | number | undefined,\n\tcontextEntryIds: readonly string[] | undefined,\n): ContextMode {\n\tif (value === undefined && contextEntryIds !== undefined) return \"all\";\n\treturn normalizeContextMode(value);\n}\n\nasync function cleanupClosedWorkspaces(\n\tregistry: AgentRegistry,\n\tisolatedAgents: Map<string, string>,\n\tworkspaceManager: WorkspaceManager,\n): Promise<void> {\n\tfor (const [agentId, owner] of [...isolatedAgents]) {\n\t\tif (registry.get(agentId)?.state !== \"closed\") continue;\n\t\tawait workspaceManager.cleanup(owner);\n\t\tisolatedAgents.delete(agentId);\n\t}\n}\n\nfunction result(agent: ManagedAgent, text: string) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text }],\n\t\tdetails: { agent: summarizeStatefulAgent(agent) },\n\t};\n}\n\nfunction awaitResult(agent: ManagedAgent, timedOut: boolean, timeoutMs: number) {\n\tconst latestTurn = agent.history.at(-1);\n\tconst output = timedOut\n\t\t? \"\"\n\t\t: truncateUtf8(latestTurn?.output ?? \"\", DEFAULT_MAX_CONTEXT_BYTES).text;\n\tconst error = timedOut ? \"\" : truncateUtf8(agent.error ?? \"\", MAX_TOOL_MESSAGE_BYTES).text;\n\tconst text = timedOut\n\t\t? `Stopped waiting for ${agent.taskPath ?? agent.id} after ${timeoutMs}ms; it remains ${agent.state}. The wait did not interrupt or close the subagent.`\n\t\t: [`Subagent ${agent.taskPath ?? agent.id} settled as ${agent.state}.`, output || error]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\"\\n\\n\");\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text,\n\t\t\t},\n\t\t],\n\t\tdetails: {\n\t\t\tagent: summarizeStatefulAgent(agent),\n\t\t\ttimedOut,\n\t\t\ttimeoutMs,\n\t\t\t...(output ? { output } : {}),\n\t\t\t...(error ? { error } : {}),\n\t\t},\n\t};\n}\n\nfunction normalizeRuntimeThinkingLevel(value: string): ParentRuntimeSnapshot[\"thinkingLevel\"] {\n\treturn isThinkingLevel(value) ? value : \"off\";\n}\n", "export function createSpawnPromptGuidelines(blockingEnabled = true): string[] {\n\treturn [\n\t\t\"Do not use subagent_spawn for simple or critical-path work that the main agent can perform directly. The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.\",\n\t\t\"Before one ordinary subagent_spawn, identify concrete useful non-overlapping main-agent work you can start immediately and a supported completion integration path. If none exists, perform the task directly instead of calling subagent_spawn.\",\n\t\t\"Give subagent_spawn a concise unique taskName using lowercase letters, digits, and underscores so the retained agent has a stable canonical task path.\",\n\t\t\"Set subagent_spawn thinkingLevel to the lowest sufficient thinking level for the delegated task: use off or minimal for extraction, formatting, or mechanical work; low for straightforward bounded work; medium for ordinary multi-step research or implementation; high for complex debugging, design, review, or cross-file analysis; xhigh for highly ambiguous, cross-system, or high-risk analysis; and max only for the hardest tasks when quality clearly outweighs latency and cost. Omit subagent_spawn thinkingLevel only to preserve the agent or child default.\",\n\t\t\"Set subagent_spawn timeoutMs to the shortest realistic work deadline for the task difficulty; use idleTimeoutMs for stalled work and maxTurns or maxToolCalls to stop repeated work without progress. Scope the task to the smallest named files or questions. When setting subagent_spawn maxTurns or maxToolCalls, leave sufficient headroom for discovery, evidence reads, and final synthesis; otherwise omit them instead of guessing speculative tight values. Split oversized tasks instead of extending budgets merely to compensate for broad scope.\",\n\t\t\"For an ordinary subagent_spawn, omit contract; use a delegation contract only when explicit acceptance, authority, evidence, or admission semantics are required.\",\n\t\t\"Do not set subagent_spawn contract enforcement to enforce with requestedAuthority readPaths, writePaths, network, or secrets; those guarantees are unsupported and reject before child launch, while capabilities and tools remain enforceable.\",\n\t\t\"If subagent_spawn rejects an unsupported guarantee, retry once with those fields removed or enforcement set to audit only when they were advisory; when any field is a required security boundary, stop instead of weakening it.\",\n\t\t\"Read the current pi-subagents session-guidance message before choosing detached completion behavior. With next-turn delivery, use subagent_spawn only when the current response does not depend on its result unless useful overlap ends with an intentional subagent_await. With auto-resume delivery, final-answer-dependent detached work may continue asynchronously.\",\n\t\t'Track every final-answer-dependent subagent_spawn by setting completionRequirement to \"required\" and retaining its returned agentId or taskPath; treat interim output as progress, and synthesize only after every corresponding completion message is visible or terminal.',\n\t\t\"Keep ordinary review in the main agent with a review skill and deterministic checks; use subagent_spawn for detached review only when consequential independent verification has concrete parallel value.\",\n\t\t\"Use a single subagent_spawn for a bounded implementation slice with clear ownership only when it can run beside the identified main-agent work.\",\n\t\t\"Use a single subagent_spawn without concurrent main-agent work only for an explicit user-requested specialist model, tool profile, or isolation boundary.\",\n\t\t...(blockingEnabled\n\t\t\t? [\n\t\t\t\t\t\"The subagent tool is deprecated; do not select it merely because synchronous output is required. Prefer subagent_spawn with supported completion delivery, and use subagent_await only after useful overlapping main-agent work is complete and an intentional join is required.\",\n\t\t\t\t\t\"Use deprecated subagent instead of subagent_spawn only for an existing caller or an explicit user request whose blocking chain, fan-in, panel, or workflow semantics do not yet have a detached replacement; queued steering cannot be processed until it returns.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t\"Add another subagent_spawn only for truly independent work with safe workspace concurrency and disjoint write ownership; shared workspaces permit concurrent writes by default, so use workspaceMode worktree when repository isolation is required. The main agent still owns integration.\",\n\t\t\"After subagent_spawn returns, immediately continue the identified local task; do not merely announce the spawn, wait, poll, or end the response while useful local work remains.\",\n\t\t\"When completionRequirement required subagent_spawn work remains active after local work is exhausted, emit at most one brief progress sentence and end the turn; do not repeat waiting updates or use the requested final format, verdict, or conclusion until every required completion is visible or terminal. Current Pi versions do not enforce a hard pre-display barrier.\",\n\t\t\"Do not duplicate assigned work from subagent_spawn while its retained agent is running; use a bounded parent fallback only after its completion reports failure or insufficient evidence.\",\n\t\t'Consume and synthesize available subagent_spawn completion messages; use subagent_manage with action \"interrupt\" or \"close\" for agents that are no longer needed.',\n\t\t'Completion from subagent_spawn is delivered automatically. Do not poll with subagent_inspect or subagent_mailbox action \"read\", repeatedly check progress, or duplicate the delegated work.',\n\t];\n}\n", "import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Theme, ToolRenderResultOptions } from \"@earendil-works/pi-coding-agent\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport {\n\tCOLLAPSED_LIST_LIMIT,\n\texpansionHint,\n\ttype RenderStatus,\n\trecordList,\n\trecordValue,\n\trenderFallbackResult,\n\tsafeBlock,\n\tsafeLine,\n\tstatusBadge,\n\tstringValue,\n\ttype ToolRendererContext,\n\ttextResult,\n\ttoolHeader,\n} from \"./render-common.js\";\n\nexport type StatefulRenderTool = \"spawn\" | \"send\" | \"await\" | \"manage\" | \"mailbox\";\n\nexport function createStatefulToolRenderer(tool: StatefulRenderTool) {\n\treturn {\n\t\trenderCall(args: unknown, theme: Theme) {\n\t\t\treturn renderStatefulCall(tool, recordValue(args) ?? {}, theme);\n\t\t},\n\t\trenderResult(\n\t\t\tresult: AgentToolResult<unknown>,\n\t\t\toptions: ToolRenderResultOptions,\n\t\t\ttheme: Theme,\n\t\t\tcontext: ToolRendererContext<unknown>,\n\t\t) {\n\t\t\treturn renderStatefulResult(tool, result, options, theme, context);\n\t\t},\n\t};\n}\n\nfunction renderStatefulCall(tool: StatefulRenderTool, args: Record<string, unknown>, theme: Theme) {\n\tif (tool === \"spawn\") {\n\t\tconst metadata = [\n\t\t\t`[${safeLine(args.agentScope, \"user\", 64)}]`,\n\t\t\t\"detached\",\n\t\t\tsafeLine(args.workspaceMode, \"shared\", 64),\n\t\t];\n\t\tif (typeof args.thinkingLevel === \"string\") metadata.push(`thinking:${args.thinkingLevel}`);\n\t\tif (typeof args.timeoutMs === \"number\") metadata.push(`timeout:${args.timeoutMs}ms`);\n\t\tif (typeof args.idleTimeoutMs === \"number\") metadata.push(`idle:${args.idleTimeoutMs}ms`);\n\t\tif (typeof args.maxTurns === \"number\") metadata.push(`turns:${args.maxTurns}`);\n\t\tif (typeof args.maxToolCalls === \"number\") metadata.push(`tools:${args.maxToolCalls}`);\n\t\treturn new Text(\n\t\t\t[\n\t\t\t\ttoolHeader(theme, \"subagent_spawn\", args.agent, metadata),\n\t\t\t\t` ${theme.fg(\"dim\", safeLine(args.task, \"...\", 2 * 1024))}`,\n\t\t\t].join(\"\\n\"),\n\t\t\t0,\n\t\t\t0,\n\t\t);\n\t}\n\tif (tool === \"send\") {\n\t\tconst metadata = [\"follow-up\"];\n\t\tif (typeof args.timeoutMs === \"number\") metadata.push(`timeout:${args.timeoutMs}ms`);\n\t\tif (typeof args.idleTimeoutMs === \"number\") metadata.push(`idle:${args.idleTimeoutMs}ms`);\n\t\tif (typeof args.maxTurns === \"number\") metadata.push(`turns:${args.maxTurns}`);\n\t\tif (typeof args.maxToolCalls === \"number\") metadata.push(`tools:${args.maxToolCalls}`);\n\t\treturn new Text(\n\t\t\t[\n\t\t\t\ttoolHeader(theme, \"subagent_send\", args.agentId, metadata),\n\t\t\t\t` ${theme.fg(\"dim\", safeLine(args.task, \"...\", 2 * 1024))}`,\n\t\t\t].join(\"\\n\"),\n\t\t\t0,\n\t\t\t0,\n\t\t);\n\t}\n\tif (tool === \"await\") {\n\t\tconst metadata = [\"blocking\"];\n\t\tif (typeof args.timeoutMs === \"number\") metadata.push(`timeout:${args.timeoutMs}ms`);\n\t\treturn new Text(toolHeader(theme, \"subagent_await\", args.agentId, metadata), 0, 0);\n\t}\n\tif (tool === \"manage\") {\n\t\tconst metadata: string[] = [];\n\t\tif (typeof args.agentId === \"string\") metadata.push(`id:${safeLine(args.agentId, \"\", 256)}`);\n\t\tif (args.subtree === true) metadata.push(\"subtree\");\n\t\treturn new Text(toolHeader(theme, \"subagent_manage\", args.action, metadata), 0, 0);\n\t}\n\tconst metadata = [`id:${safeLine(args.agentId, \"...\", 256)}`];\n\tif (args.action === \"read\") {\n\t\tmetadata.push(args.acknowledge === false ? \"leave unread\" : \"acknowledge\");\n\t}\n\tconst lines = [toolHeader(theme, \"subagent_mailbox\", args.action, metadata)];\n\tif (args.action === \"send\") {\n\t\tlines.push(` ${theme.fg(\"dim\", safeLine(args.message, \"...\", 2 * 1024))}`);\n\t}\n\treturn new Text(lines.join(\"\\n\"), 0, 0);\n}\n\nfunction renderStatefulResult(\n\ttool: StatefulRenderTool,\n\tresult: AgentToolResult<unknown>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcontext: ToolRendererContext<unknown>,\n) {\n\tconst details = recordValue(result.details);\n\tconst args = recordValue(context.args) ?? {};\n\tif (!details) return renderFallbackResult(result, options, theme, context.isError);\n\tif (tool === \"spawn\" || tool === \"send\" || tool === \"await\") {\n\t\tconst agent = recordValue(details.agent);\n\t\tif (!agent) return renderFallbackResult(result, options, theme, context.isError);\n\t\tif (tool === \"await\" && details.timedOut === true) {\n\t\t\treturn new Text(renderAwaitTimeout(agent, result, options.expanded, theme), 0, 0);\n\t\t}\n\t\treturn new Text(renderAgentResult(agent, result, options.expanded, theme), 0, 0);\n\t}\n\tif (tool === \"manage\") {\n\t\treturn new Text(renderManageResult(args, details, result, options.expanded, theme), 0, 0);\n\t}\n\treturn new Text(renderMailboxResult(args, details, options.expanded, theme), 0, 0);\n}\n\nfunction renderAgentResult(\n\tagent: Record<string, unknown>,\n\tresult: AgentToolResult<unknown>,\n\texpanded: boolean,\n\ttheme: Theme,\n): string {\n\tconst state = safeLine(agent.state, \"unknown\", 128);\n\tconst lines = [\n\t\t`${statusBadge(theme, lifecycleStatus(state))} \u00B7 ${theme.fg(\"accent\", safeLine(agent.id, \"agent\", 256))} \u00B7 ${theme.fg(\"toolOutput\", safeLine(agent.agent, \"subagent\", 256))} \u00B7 ${theme.fg(\"muted\", state)}`,\n\t];\n\tconst thinking = stringValue(agent.thinkingLevel);\n\tconst timeout =\n\t\ttypeof agent.currentTimeoutMs === \"number\"\n\t\t\t? agent.currentTimeoutMs\n\t\t\t: typeof agent.timeoutMs === \"number\"\n\t\t\t\t? agent.timeoutMs\n\t\t\t\t: 0;\n\tconst idleTimeout =\n\t\ttypeof agent.currentIdleTimeoutMs === \"number\"\n\t\t\t? agent.currentIdleTimeoutMs\n\t\t\t: typeof agent.idleTimeoutMs === \"number\"\n\t\t\t\t? agent.idleTimeoutMs\n\t\t\t\t: 0;\n\tconst maxTurns =\n\t\ttypeof agent.currentMaxTurns === \"number\"\n\t\t\t? agent.currentMaxTurns\n\t\t\t: typeof agent.maxTurns === \"number\"\n\t\t\t\t? agent.maxTurns\n\t\t\t\t: 0;\n\tconst maxToolCalls =\n\t\ttypeof agent.currentMaxToolCalls === \"number\"\n\t\t\t? agent.currentMaxToolCalls\n\t\t\t: typeof agent.maxToolCalls === \"number\"\n\t\t\t\t? agent.maxToolCalls\n\t\t\t\t: 0;\n\tconst unread = typeof agent.unreadMessages === \"number\" ? agent.unreadMessages : 0;\n\tif (thinking || timeout || idleTimeout || maxTurns || maxToolCalls || unread > 0) {\n\t\tlines.push(\n\t\t\ttheme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t[\n\t\t\t\t\tthinking && `thinking:${safeLine(thinking, \"\", 128)}`,\n\t\t\t\t\ttimeout && `timeout:${timeout}ms`,\n\t\t\t\t\tidleTimeout && `idle:${idleTimeout}ms`,\n\t\t\t\t\tmaxTurns && `turns:${maxTurns}`,\n\t\t\t\t\tmaxToolCalls && `tools:${maxToolCalls}`,\n\t\t\t\t\tunread > 0 && `unread:${unread}`,\n\t\t\t\t]\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.join(\" \u00B7 \"),\n\t\t\t),\n\t\t);\n\t}\n\tif (expanded) {\n\t\tconst task = safeBlock(agent.currentTask, \"\", 2 * 1024).trim();\n\t\tconst error = safeBlock(agent.error, \"\", 2 * 1024).trim();\n\t\tif (task) lines.push(theme.fg(\"dim\", `task: ${task}`));\n\t\tif (error) lines.push(theme.fg(\"error\", `error: ${error}`));\n\t\tconst content = safeBlock(textResult(result), \"\", 8 * 1024).trim();\n\t\tif (content) lines.push(theme.fg(\"toolOutput\", content));\n\t} else lines.push(expansionHint());\n\treturn lines.join(\"\\n\");\n}\n\nfunction renderAwaitTimeout(\n\tagent: Record<string, unknown>,\n\tresult: AgentToolResult<unknown>,\n\texpanded: boolean,\n\ttheme: Theme,\n): string {\n\tconst lines = [\n\t\t`${statusBadge(theme, \"running\")} \u00B7 ${theme.fg(\"accent\", safeLine(agent.id, \"agent\", 256))} \u00B7 ${theme.fg(\"warning\", \"wait timed out\")} \u00B7 ${theme.fg(\"muted\", safeLine(agent.state, \"unknown\", 128))}`,\n\t];\n\tif (expanded) {\n\t\tconst content = safeBlock(textResult(result), \"\", 8 * 1024).trim();\n\t\tif (content) lines.push(theme.fg(\"toolOutput\", content));\n\t} else lines.push(expansionHint());\n\treturn lines.join(\"\\n\");\n}\n\nfunction renderManageResult(\n\targs: Record<string, unknown>,\n\tdetails: Record<string, unknown>,\n\tresult: AgentToolResult<unknown>,\n\texpanded: boolean,\n\ttheme: Theme,\n): string {\n\tconst action = safeLine(args.action, \"action\", 128);\n\tconst agents = recordList(details.agents);\n\tconst primary = recordValue(details.agent);\n\tif (action === \"list\") {\n\t\tconst lines = [\n\t\t\t`${statusBadge(theme, \"completed\")} \u00B7 list \u00B7 ${agents.length} agent${agents.length === 1 ? \"\" : \"s\"}`,\n\t\t];\n\t\tconst selected = expanded ? agents : agents.slice(0, COLLAPSED_LIST_LIMIT);\n\t\tfor (const agent of selected) lines.push(formatAgentLine(agent, theme, expanded));\n\t\tif (agents.length === 0) lines.push(theme.fg(\"muted\", \"(no retained agents)\"));\n\t\tif (agents.length > selected.length)\n\t\t\tlines.push(theme.fg(\"muted\", `\u2026 ${agents.length - selected.length} omitted`));\n\t\tif (!expanded && agents.length > 0) lines.push(expansionHint());\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst subtree = args.subtree === true;\n\tconst affected = subtree ? agents.length : agents.length > 0 ? agents.length : primary ? 1 : 0;\n\tconst status: RenderStatus = action === \"interrupt\" ? \"interrupted\" : \"closed\";\n\tconst lines = [\n\t\t`${statusBadge(theme, status)} \u00B7 ${affected} agent${affected === 1 ? \"\" : \"s\"}${subtree ? theme.fg(\"muted\", \" \u00B7 subtree\") : \"\"}`,\n\t];\n\tconst selected = agents.length > 0 ? agents : !subtree && primary ? [primary] : [];\n\tfor (const agent of expanded ? selected : selected.slice(0, COLLAPSED_LIST_LIMIT)) {\n\t\tlines.push(formatAgentLine(agent, theme, expanded));\n\t}\n\tif (selected.length === 0) {\n\t\tconst content = safeBlock(textResult(result), \"(no output)\", 8 * 1024);\n\t\tlines.push(theme.fg(\"toolOutput\", content));\n\t}\n\tif (!expanded && selected.length > 0) lines.push(expansionHint());\n\treturn lines.join(\"\\n\");\n}\n\nfunction renderMailboxResult(\n\targs: Record<string, unknown>,\n\tdetails: Record<string, unknown>,\n\texpanded: boolean,\n\ttheme: Theme,\n): string {\n\tconst action = safeLine(args.action, \"action\", 64);\n\tif (action === \"send\") {\n\t\tconst message = recordValue(details.message);\n\t\tif (!message) return `${statusBadge(theme, \"completed\")} \u00B7 Queued message`;\n\t\tconst lines = [\n\t\t\t`${theme.fg(\"success\", \"\u2713\")} ${theme.fg(\"success\", \"Queued\")} \u00B7 ${theme.fg(\"accent\", safeLine(message.id, \"message\", 256))} \u00B7 ${theme.fg(\"muted\", `to ${safeLine(message.recipientId, safeLine(args.agentId), 256)}`)}`,\n\t\t];\n\t\tif (expanded) {\n\t\t\tlines.push(theme.fg(\"toolOutput\", safeBlock(message.content, \"(empty message)\", 2 * 1024)));\n\t\t} else lines.push(expansionHint());\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst messages = recordList(details.messages);\n\tconst acknowledged = args.acknowledge === false ? \"left unread\" : \"acknowledged\";\n\tconst lines = [\n\t\t`${statusBadge(theme, \"completed\")} \u00B7 ${messages.length} message${messages.length === 1 ? \"\" : \"s\"} \u00B7 ${acknowledged}`,\n\t];\n\tconst selected = expanded ? messages : messages.slice(0, COLLAPSED_LIST_LIMIT);\n\tfor (const message of selected) {\n\t\tconst content = expanded\n\t\t\t? safeBlock(message.content, \"(empty message)\", 2 * 1024)\n\t\t\t: safeLine(message.content, \"(empty message)\", 512);\n\t\tlines.push(\n\t\t\t`${theme.fg(\"muted\", \"\u2022 \")}${theme.fg(\"accent\", safeLine(message.id, \"message\", 256))} ${theme.fg(\"muted\", `from ${safeLine(message.senderId, \"unknown\", 256)}: `)}${theme.fg(\"toolOutput\", content)}`,\n\t\t);\n\t}\n\tif (messages.length === 0) lines.push(theme.fg(\"muted\", \"(no unread messages)\"));\n\tif (messages.length > selected.length)\n\t\tlines.push(theme.fg(\"muted\", `\u2026 ${messages.length - selected.length} omitted`));\n\tif (!expanded && messages.length > 0) lines.push(expansionHint());\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatAgentLine(agent: Record<string, unknown>, theme: Theme, expanded: boolean): string {\n\tconst unread = typeof agent.unreadMessages === \"number\" ? agent.unreadMessages : 0;\n\tconst lines = [\n\t\t`${theme.fg(\"muted\", \"\u2022 \")}${theme.fg(\"accent\", safeLine(agent.id, \"agent\", 256))} ${theme.fg(\"toolOutput\", safeLine(agent.agent, \"subagent\", 256))} ${theme.fg(\"muted\", safeLine(agent.state, \"unknown\", 128))}${unread > 0 ? theme.fg(\"warning\", ` \u00B7 unread:${unread}`) : \"\"}`,\n\t];\n\tif (expanded) {\n\t\tconst task = safeBlock(agent.currentTask, \"\", 2 * 1024).trim();\n\t\tconst error = safeBlock(agent.error, \"\", 2 * 1024).trim();\n\t\tif (task) lines.push(` ${theme.fg(\"dim\", `task: ${task}`)}`);\n\t\tif (error) lines.push(` ${theme.fg(\"error\", `error: ${error}`)}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction lifecycleStatus(state: string): RenderStatus {\n\tswitch (state) {\n\t\tcase \"starting\":\n\t\t\treturn \"starting\";\n\t\tcase \"running\":\n\t\t\treturn \"running\";\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"partial\":\n\t\tcase \"blocked\":\n\t\tcase \"needs-input\":\n\t\tcase \"abstained\":\n\t\tcase \"stale\":\n\t\t\treturn \"warning\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"interrupted\":\n\t\t\treturn \"interrupted\";\n\t\tcase \"closed\":\n\t\t\treturn \"closed\";\n\t\tdefault:\n\t\t\treturn \"completed\";\n\t}\n}\n", "import { StringEnum } from \"@earendil-works/pi-ai\";\nimport { Type } from \"typebox\";\n\nconst MANAGE_ACTIONS = [\"interrupt\", \"close\"] as const;\nconst MAILBOX_ACTIONS = [\"send\", \"read\"] as const;\nconst MAX_MAILBOX_MESSAGE_LENGTH = 16 * 1024;\n\nexport const ManageParamsSchema = Type.Object(\n\t{\n\t\taction: StringEnum(MANAGE_ACTIONS, {\n\t\t\tdescription: \"Interrupt active work or close an agent and release its resources.\",\n\t\t}),\n\t\tagentId: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tdescription: \"Required agent ID or canonical task path for interrupt and close.\",\n\t\t\t}),\n\t\t),\n\t\tsubtree: Type.Optional(\n\t\t\tType.Boolean({\n\t\t\t\tdefault: false,\n\t\t\t\tdescription: \"Interrupt or close the target and all descendants child-first.\",\n\t\t\t}),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport const MailboxParamsSchema = Type.Object(\n\t{\n\t\taction: StringEnum(MAILBOX_ACTIONS, {\n\t\t\tdescription: \"Use send for queue-only delivery or read to inspect unread mailbox messages.\",\n\t\t}),\n\t\tagentId: Type.String({\n\t\t\tminLength: 1,\n\t\t\tdescription: \"Mailbox owner or recipient agent ID or canonical task path.\",\n\t\t}),\n\t\tmessage: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_MAILBOX_MESSAGE_LENGTH,\n\t\t\t\tdescription: \"Message content required by send; sending does not start a turn.\",\n\t\t\t}),\n\t\t),\n\t\tsenderId: Type.Optional(\n\t\t\tType.String({ description: \"Optional sender agent ID or canonical task path.\" }),\n\t\t),\n\t\tdeduplicationKey: Type.Optional(\n\t\t\tType.String({ maxLength: 256, description: \"Optional idempotency key for send.\" }),\n\t\t),\n\t\tacknowledge: Type.Optional(\n\t\t\tType.Boolean({ default: true, description: \"Mark returned read messages as acknowledged.\" }),\n\t\t),\n\t\tlimit: Type.Optional(\n\t\t\tType.Number({ minimum: 1, maximum: 20, default: 20, description: \"Maximum messages.\" }),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type ValidatedManageParams = {\n\taction: \"interrupt\" | \"close\";\n\tagentId: string;\n\tsubtree?: boolean;\n};\n\nexport type ValidatedMailboxParams =\n\t| {\n\t\t\taction: \"send\";\n\t\t\tagentId: string;\n\t\t\tmessage: string;\n\t\t\tsenderId?: string;\n\t\t\tdeduplicationKey?: string;\n\t }\n\t| { action: \"read\"; agentId: string; acknowledge?: boolean; limit?: number };\n\nexport function validateManageParams(params: unknown): ValidatedManageParams {\n\tconst values = parameterRecord(params, \"subagent_manage\");\n\tassertKnownKeys(\"subagent_manage\", values, [\"action\", \"agentId\", \"subtree\"]);\n\tconst action = values.action;\n\tif (action === \"list\") {\n\t\tthrow new Error(\n\t\t\t'subagent_manage no longer supports \"list\"; use subagent_inspect action \"list_runs\"',\n\t\t);\n\t}\n\tif (\n\t\ttypeof action !== \"string\" ||\n\t\t!MANAGE_ACTIONS.includes(action as (typeof MANAGE_ACTIONS)[number])\n\t) {\n\t\tthrow new Error(`subagent_manage action must be one of: ${MANAGE_ACTIONS.join(\", \")}`);\n\t}\n\tassertRequiredString(\"subagent_manage\", action, values, \"agentId\");\n\tassertOptionalBoolean(\"subagent_manage\", action, values, \"subtree\");\n\treturn {\n\t\taction,\n\t\tagentId: values.agentId,\n\t\t...(values.subtree === undefined ? {} : { subtree: values.subtree }),\n\t} as ValidatedManageParams;\n}\n\nexport function validateMailboxParams(params: unknown): ValidatedMailboxParams {\n\tconst values = parameterRecord(params, \"subagent_mailbox\");\n\tassertKnownKeys(\"subagent_mailbox\", values, [\n\t\t\"action\",\n\t\t\"agentId\",\n\t\t\"message\",\n\t\t\"senderId\",\n\t\t\"deduplicationKey\",\n\t\t\"acknowledge\",\n\t\t\"limit\",\n\t]);\n\tconst action = values.action;\n\tif (\n\t\ttypeof action !== \"string\" ||\n\t\t!MAILBOX_ACTIONS.includes(action as (typeof MAILBOX_ACTIONS)[number])\n\t) {\n\t\tthrow new Error(`subagent_mailbox action must be one of: ${MAILBOX_ACTIONS.join(\", \")}`);\n\t}\n\tif (action === \"send\") {\n\t\tassertRequiredString(\"subagent_mailbox\", action, values, \"agentId\");\n\t\tassertRequiredString(\"subagent_mailbox\", action, values, \"message\");\n\t\tconst message = values.message as string;\n\t\tif (message.length > MAX_MAILBOX_MESSAGE_LENGTH) {\n\t\t\tthrow new Error(\n\t\t\t\t`subagent_mailbox action \"send\" requires message at most ${MAX_MAILBOX_MESSAGE_LENGTH} characters`,\n\t\t\t);\n\t\t}\n\t\tassertOptionalString(\"subagent_mailbox\", action, values, \"senderId\");\n\t\tassertOptionalString(\"subagent_mailbox\", action, values, \"deduplicationKey\");\n\t\tif (typeof values.deduplicationKey === \"string\" && values.deduplicationKey.length > 256) {\n\t\t\tthrow new Error(\n\t\t\t\t'subagent_mailbox action \"send\" requires deduplicationKey at most 256 characters',\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\taction,\n\t\t\tagentId: values.agentId,\n\t\t\tmessage,\n\t\t\t...(values.senderId === undefined ? {} : { senderId: values.senderId }),\n\t\t\t...(values.deduplicationKey === undefined\n\t\t\t\t? {}\n\t\t\t\t: { deduplicationKey: values.deduplicationKey }),\n\t\t} as ValidatedMailboxParams;\n\t}\n\tassertRequiredString(\"subagent_mailbox\", action, values, \"agentId\");\n\tassertOptionalBoolean(\"subagent_mailbox\", action, values, \"acknowledge\");\n\tif (\n\t\tvalues.limit !== undefined &&\n\t\t(typeof values.limit !== \"number\" ||\n\t\t\t!Number.isFinite(values.limit) ||\n\t\t\tvalues.limit < 1 ||\n\t\t\tvalues.limit > 20)\n\t) {\n\t\tthrow new Error('subagent_mailbox action \"read\" requires limit between 1 and 20');\n\t}\n\treturn {\n\t\taction,\n\t\tagentId: values.agentId,\n\t\t...(values.acknowledge === undefined ? {} : { acknowledge: values.acknowledge }),\n\t\t...(values.limit === undefined ? {} : { limit: values.limit }),\n\t} as ValidatedMailboxParams;\n}\n\nfunction parameterRecord(params: unknown, toolName: string): Record<string, unknown> {\n\tif (!params || typeof params !== \"object\" || Array.isArray(params)) {\n\t\tthrow new Error(`${toolName} parameters must be an object`);\n\t}\n\treturn params as Record<string, unknown>;\n}\n\nfunction assertKnownKeys(\n\ttoolName: string,\n\tvalues: Record<string, unknown>,\n\tallowed: readonly string[],\n): void {\n\tconst unexpected = Object.keys(values).find(\n\t\t(key) => values[key] !== undefined && !allowed.includes(key),\n\t);\n\tif (unexpected) throw new Error(`${toolName} does not accept ${unexpected}`);\n}\n\nfunction assertRequiredString(\n\ttoolName: string,\n\taction: string,\n\tvalues: Record<string, unknown>,\n\tkey: string,\n): void {\n\tconst value = values[key];\n\tif (value === undefined) throw new Error(`${toolName} action \"${action}\" requires ${key}`);\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new Error(`${toolName} action \"${action}\" requires ${key} to be a non-empty string`);\n\t}\n}\n\nfunction assertOptionalString(\n\ttoolName: string,\n\taction: string,\n\tvalues: Record<string, unknown>,\n\tkey: string,\n): void {\n\tif (values[key] !== undefined && typeof values[key] !== \"string\") {\n\t\tthrow new Error(`${toolName} action \"${action}\" requires ${key} to be a string`);\n\t}\n}\n\nfunction assertOptionalBoolean(\n\ttoolName: string,\n\taction: string,\n\tvalues: Record<string, unknown>,\n\tkey: string,\n): void {\n\tif (values[key] !== undefined && typeof values[key] !== \"boolean\") {\n\t\tthrow new Error(`${toolName} action \"${action}\" requires ${key} to be a boolean`);\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,wBAAwB,OAAqB,MAAM,KAAK,IAAI,GAAW;AACtF,QAAM,iBAAiB,KAAK,IAAI,GAAG,KAAK,OAAO,MAAM,MAAM,aAAa,GAAI,CAAC;AAC7E,QAAM,OAAO,MAAM,cAAc,WAAM,mBAAmB,MAAM,aAAa,EAAE,CAAC,KAAK;AACrF,QAAM,SAAS,MAAM,QAAQ,OAAO,CAAC,YAAY,CAAC,QAAQ,MAAM,EAAE;AAClE,QAAM,SAAS,KAAK,OAAO,MAAM,KAAK;AACtC,SAAO,GAAG,MAAM,GAAG,mBAAmB,MAAM,YAAY,MAAM,IAAI,GAAG,CAAC,SAAM,mBAAmB,MAAM,OAAO,GAAG,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aAAa,MAAM,SAAS,IAAI,sBAAsB,EAAE;AACtF,QAAM,OAAO,WACV,uBAAuB,MAAM,YAAY,MAAM,EAAE,UAAU,SAAS,kBAAkB,MAAM,KAAK,wDACjG,CAAC,YAAY,MAAM,YAAY,MAAM,EAAE,eAAe,MAAM,KAAK,KAAK,UAAU,KAAK,EACpF,OAAO,OAAO,EACd,KAAK,MAAM;AACf,SAAO;AAAA,IACN,SAAS;AAAA,MACR;AAAA,QACC,MAAM;AAAA,QACN,MAAM,aAAa,MAAM,yBAAyB,EAAE;AAAA,MACrD;AAAA,IACD;AAAA,IACA,SAAS;AAAA,MACR,OAAO,uBAAuB,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,MAC3B,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;AAAA,IAC1B;AAAA,EACD;AACD;AAEA,SAAS,8BAA8B,OAAuD;AAC7F,SAAO,gBAAgB,KAAK,IAAI,QAAQ;AACzC;",
|
|
6
|
+
"names": ["StringEnum", "Type", "result", "metadata", "lines", "selected", "Type", "StringEnum", "agent", "agentId"]
|
|
7
|
+
}
|
|
@@ -8,10 +8,6 @@ import {
|
|
|
8
8
|
BUILT_IN_AGENTS,
|
|
9
9
|
discoverAgents
|
|
10
10
|
} from "./chunk-LASD73CM.ts";
|
|
11
|
-
import {
|
|
12
|
-
DEFAULT_CONSULTATION_CWD_POLICY,
|
|
13
|
-
DEFAULT_CONSULT_RESOURCE_POLICY
|
|
14
|
-
} from "./chunk-TMZRHIIK.ts";
|
|
15
11
|
import {
|
|
16
12
|
THINKING_LEVELS,
|
|
17
13
|
resolveAgentToolNames
|
|
@@ -372,7 +368,7 @@ function safeNumber(value) {
|
|
|
372
368
|
// src/consult-registration.ts
|
|
373
369
|
function registerSubagentConsult(pi, options, dependencies = {}) {
|
|
374
370
|
const loadExecution = cachedModuleLoader(
|
|
375
|
-
dependencies.loadExecution ?? (() => import("./consult-
|
|
371
|
+
dependencies.loadExecution ?? (() => import("./consult-LJU3IQY5.ts"))
|
|
376
372
|
);
|
|
377
373
|
let generation = 0;
|
|
378
374
|
const active = /* @__PURE__ */ new Set();
|
|
@@ -390,11 +386,11 @@ function registerSubagentConsult(pi, options, dependencies = {}) {
|
|
|
390
386
|
};
|
|
391
387
|
pi.on("session_start", () => cancelAndWaitForWork("Subagent consultation session replaced"));
|
|
392
388
|
pi.on("session_shutdown", () => cancelAndWaitForWork("Subagent consultation session shut down"));
|
|
393
|
-
const
|
|
389
|
+
const description = "Run one ephemeral subagent synchronously under enforced read-only tool and resource policies and return its answer. The child can use only the effective subset of Pi's built-in read, grep, find, and ls tools. Shell commands, file writes, extension tools, detached lifecycle operations, and persistent agent state are disabled. The current working-directory policy, trusted-target resource policy, and available agent definitions are published in the pi-subagents session-guidance message. Allowed targets without effective trust inherit no target or project resources. This is not a filesystem sandbox.";
|
|
394
390
|
const definition = {
|
|
395
391
|
name: "subagent_consult",
|
|
396
392
|
label: "Consult Read-only Subagent",
|
|
397
|
-
description
|
|
393
|
+
description,
|
|
398
394
|
promptSnippet: "Consult one constrained read-only subagent and wait for its answer",
|
|
399
395
|
promptGuidelines: [
|
|
400
396
|
"Use subagent_consult only for bounded read-only evidence gathering when an independent perspective is worth making the main agent wait.",
|
|
@@ -451,12 +447,6 @@ function registerSubagentConsult(pi, options, dependencies = {}) {
|
|
|
451
447
|
if (event.toolName !== "subagent_consult") return;
|
|
452
448
|
if (event.details?.isError) return { isError: true };
|
|
453
449
|
});
|
|
454
|
-
return (catalog) => {
|
|
455
|
-
definition.description = catalog ? `${baseDescription()}
|
|
456
|
-
|
|
457
|
-
${catalog}` : baseDescription();
|
|
458
|
-
pi.registerTool(definition);
|
|
459
|
-
};
|
|
460
450
|
}
|
|
461
451
|
function combineAbortSignals(external, owned) {
|
|
462
452
|
if (!external) return { signal: owned, dispose() {
|
|
@@ -487,4 +477,4 @@ export {
|
|
|
487
477
|
SubagentConsultParams,
|
|
488
478
|
registerSubagentConsult
|
|
489
479
|
};
|
|
490
|
-
//# sourceMappingURL=chunk-
|
|
480
|
+
//# sourceMappingURL=chunk-6NSJVPXX.ts.map
|