@narumitw/pi-subagents 2.1.4 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +187 -1228
- package/dist/child-communication-bridge.ts +136 -0
- package/dist/child-communication-bridge.ts.map +7 -0
- package/dist/chunks/chunk-UKTWUQRM.js +667 -0
- package/dist/chunks/chunk-UKTWUQRM.js.map +7 -0
- package/dist/index.ts +1448 -1614
- package/dist/index.ts.map +4 -4
- package/docs/design-principles.md +31 -0
- package/docs/ipc-transport-idea.md +103 -0
- package/docs/tools.md +109 -0
- package/package.json +11 -19
- package/src/broker-credentials.ts +71 -0
- package/src/child-communication-bridge.ts +153 -0
- package/src/child-communication-tools.ts +147 -0
- package/src/completion-renderer.ts +60 -0
- package/src/index.ts +1 -1
- package/src/message-broker.ts +628 -0
- package/src/model-output.ts +42 -0
- package/src/process.ts +688 -0
- package/src/runtime.ts +538 -0
- package/src/subagents.ts +33 -34
- package/src/tools.ts +416 -0
- package/src/types.ts +85 -0
- package/src/widget.ts +130 -0
- package/dist/chunks/auto-transport-FUUKFDIG.ts +0 -109
- package/dist/chunks/auto-transport-FUUKFDIG.ts.map +0 -7
- package/dist/chunks/capability-grant-PR72SWWS.ts +0 -19
- package/dist/chunks/capability-grant-PR72SWWS.ts.map +0 -7
- package/dist/chunks/child-peer-bridge.ts +0 -108
- package/dist/chunks/child-peer-bridge.ts.map +0 -7
- package/dist/chunks/chunk-2LMJU25E.ts +0 -1641
- package/dist/chunks/chunk-2LMJU25E.ts.map +0 -7
- package/dist/chunks/chunk-47SK2QYC.ts +0 -56
- package/dist/chunks/chunk-47SK2QYC.ts.map +0 -7
- package/dist/chunks/chunk-4AQSF7AS.ts +0 -29
- package/dist/chunks/chunk-4AQSF7AS.ts.map +0 -7
- package/dist/chunks/chunk-5DGRMKNV.ts +0 -126
- package/dist/chunks/chunk-5DGRMKNV.ts.map +0 -7
- package/dist/chunks/chunk-6H6TBBED.ts +0 -108
- package/dist/chunks/chunk-6H6TBBED.ts.map +0 -7
- package/dist/chunks/chunk-6KJ34M6S.ts +0 -159
- package/dist/chunks/chunk-6KJ34M6S.ts.map +0 -7
- package/dist/chunks/chunk-6NSJVPXX.ts +0 -480
- package/dist/chunks/chunk-6NSJVPXX.ts.map +0 -7
- package/dist/chunks/chunk-7AAJEUSL.ts +0 -238
- package/dist/chunks/chunk-7AAJEUSL.ts.map +0 -7
- package/dist/chunks/chunk-BFK2Z4ZF.ts +0 -189
- package/dist/chunks/chunk-BFK2Z4ZF.ts.map +0 -7
- package/dist/chunks/chunk-BOAXY55Y.ts +0 -153
- package/dist/chunks/chunk-BOAXY55Y.ts.map +0 -7
- package/dist/chunks/chunk-D4CR7T73.ts +0 -353
- package/dist/chunks/chunk-D4CR7T73.ts.map +0 -7
- package/dist/chunks/chunk-FEVPWRMU.ts +0 -300
- package/dist/chunks/chunk-FEVPWRMU.ts.map +0 -7
- package/dist/chunks/chunk-G6VZTCFH.ts +0 -70
- package/dist/chunks/chunk-G6VZTCFH.ts.map +0 -7
- package/dist/chunks/chunk-H3FP6DLR.ts +0 -160
- package/dist/chunks/chunk-H3FP6DLR.ts.map +0 -7
- package/dist/chunks/chunk-HA36LPCO.ts +0 -130
- package/dist/chunks/chunk-HA36LPCO.ts.map +0 -7
- package/dist/chunks/chunk-HOP5FXDT.ts +0 -27
- package/dist/chunks/chunk-HOP5FXDT.ts.map +0 -7
- package/dist/chunks/chunk-IGAMVWFN.ts +0 -139
- package/dist/chunks/chunk-IGAMVWFN.ts.map +0 -7
- package/dist/chunks/chunk-ILEQ27AL.ts +0 -45
- package/dist/chunks/chunk-ILEQ27AL.ts.map +0 -7
- package/dist/chunks/chunk-ITVWPNU4.ts +0 -819
- package/dist/chunks/chunk-ITVWPNU4.ts.map +0 -7
- package/dist/chunks/chunk-IWC32VPY.ts +0 -172
- package/dist/chunks/chunk-IWC32VPY.ts.map +0 -7
- package/dist/chunks/chunk-JSZIP73U.ts +0 -362
- package/dist/chunks/chunk-JSZIP73U.ts.map +0 -7
- package/dist/chunks/chunk-JU6LUNLP.ts +0 -380
- package/dist/chunks/chunk-JU6LUNLP.ts.map +0 -7
- package/dist/chunks/chunk-KMGKCEO4.ts +0 -38
- package/dist/chunks/chunk-KMGKCEO4.ts.map +0 -7
- package/dist/chunks/chunk-LASD73CM.ts +0 -339
- package/dist/chunks/chunk-LASD73CM.ts.map +0 -7
- package/dist/chunks/chunk-LEOYDZI3.ts +0 -22
- package/dist/chunks/chunk-LEOYDZI3.ts.map +0 -7
- package/dist/chunks/chunk-LL4LP2T7.ts +0 -737
- package/dist/chunks/chunk-LL4LP2T7.ts.map +0 -7
- package/dist/chunks/chunk-N2T5IN4X.ts +0 -18
- package/dist/chunks/chunk-N2T5IN4X.ts.map +0 -7
- package/dist/chunks/chunk-N7BLVXKK.ts +0 -73
- package/dist/chunks/chunk-N7BLVXKK.ts.map +0 -7
- package/dist/chunks/chunk-NLT67IZS.ts +0 -322
- package/dist/chunks/chunk-NLT67IZS.ts.map +0 -7
- package/dist/chunks/chunk-NTRPLF46.ts +0 -63
- package/dist/chunks/chunk-NTRPLF46.ts.map +0 -7
- package/dist/chunks/chunk-ONDTY4EL.ts +0 -91
- package/dist/chunks/chunk-ONDTY4EL.ts.map +0 -7
- package/dist/chunks/chunk-OVPHFGKO.ts +0 -1769
- package/dist/chunks/chunk-OVPHFGKO.ts.map +0 -7
- package/dist/chunks/chunk-P7OH4XMF.ts +0 -60
- package/dist/chunks/chunk-P7OH4XMF.ts.map +0 -7
- package/dist/chunks/chunk-PBZMBTNJ.ts +0 -422
- package/dist/chunks/chunk-PBZMBTNJ.ts.map +0 -7
- package/dist/chunks/chunk-PGLSFLYW.ts +0 -52
- package/dist/chunks/chunk-PGLSFLYW.ts.map +0 -7
- package/dist/chunks/chunk-RRR66UWR.ts +0 -28
- package/dist/chunks/chunk-RRR66UWR.ts.map +0 -7
- package/dist/chunks/chunk-RSUXZD6S.ts +0 -275
- package/dist/chunks/chunk-RSUXZD6S.ts.map +0 -7
- package/dist/chunks/chunk-RTCVYIZA.ts +0 -221
- package/dist/chunks/chunk-RTCVYIZA.ts.map +0 -7
- package/dist/chunks/chunk-RY2AEGMZ.ts +0 -34
- package/dist/chunks/chunk-RY2AEGMZ.ts.map +0 -7
- package/dist/chunks/chunk-SWGQLFSD.ts +0 -60
- package/dist/chunks/chunk-SWGQLFSD.ts.map +0 -7
- package/dist/chunks/chunk-TM2R67J3.ts +0 -52
- package/dist/chunks/chunk-TM2R67J3.ts.map +0 -7
- package/dist/chunks/chunk-TMZRHIIK.ts +0 -497
- package/dist/chunks/chunk-TMZRHIIK.ts.map +0 -7
- package/dist/chunks/chunk-TZ34IQ3M.ts +0 -59
- package/dist/chunks/chunk-TZ34IQ3M.ts.map +0 -7
- package/dist/chunks/chunk-UMBPMVJW.ts +0 -22
- package/dist/chunks/chunk-UMBPMVJW.ts.map +0 -7
- package/dist/chunks/chunk-VDG7LTYE.ts +0 -80
- package/dist/chunks/chunk-VDG7LTYE.ts.map +0 -7
- package/dist/chunks/chunk-X4NMONPE.ts +0 -73
- package/dist/chunks/chunk-X4NMONPE.ts.map +0 -7
- package/dist/chunks/chunk-YPJEN6NU.ts +0 -65
- package/dist/chunks/chunk-YPJEN6NU.ts.map +0 -7
- package/dist/chunks/chunk-YU53SHA7.ts +0 -328
- package/dist/chunks/chunk-YU53SHA7.ts.map +0 -7
- package/dist/chunks/completion-delivery-RSJU6BXL.ts +0 -17
- package/dist/chunks/completion-delivery-RSJU6BXL.ts.map +0 -7
- package/dist/chunks/config-status-FKGDECZ3.ts +0 -35
- package/dist/chunks/config-status-FKGDECZ3.ts.map +0 -7
- package/dist/chunks/config-ui-ABHYNGQ7.ts +0 -1212
- package/dist/chunks/config-ui-ABHYNGQ7.ts.map +0 -7
- package/dist/chunks/consult-LJU3IQY5.ts +0 -519
- package/dist/chunks/consult-LJU3IQY5.ts.map +0 -7
- package/dist/chunks/context-QDKLVQXE.ts +0 -11
- package/dist/chunks/context-QDKLVQXE.ts.map +0 -7
- package/dist/chunks/create-stateful-transport-JWC2EFYL.ts +0 -130
- package/dist/chunks/create-stateful-transport-JWC2EFYL.ts.map +0 -7
- package/dist/chunks/cwd-policy-NB6XZ5GF.ts +0 -17
- package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +0 -7
- package/dist/chunks/delegation-contract-LA56I5DT.ts +0 -24
- package/dist/chunks/delegation-contract-LA56I5DT.ts.map +0 -7
- package/dist/chunks/discovery-MIFB2U4Y.ts +0 -12
- package/dist/chunks/discovery-MIFB2U4Y.ts.map +0 -7
- package/dist/chunks/execution-Q2JZLKJA.ts +0 -4037
- package/dist/chunks/execution-Q2JZLKJA.ts.map +0 -7
- package/dist/chunks/in-process-transport-HJ6TZXC3.ts +0 -39
- package/dist/chunks/in-process-transport-HJ6TZXC3.ts.map +0 -7
- package/dist/chunks/inspect-UH2TKH6E.ts +0 -634
- package/dist/chunks/inspect-UH2TKH6E.ts.map +0 -7
- package/dist/chunks/peer-communication-KL36Z6CO.ts +0 -294
- package/dist/chunks/peer-communication-KL36Z6CO.ts.map +0 -7
- package/dist/chunks/persistence-UY3PY6E5.ts +0 -348
- package/dist/chunks/persistence-UY3PY6E5.ts.map +0 -7
- package/dist/chunks/registry-BT54L6CY.ts +0 -1445
- package/dist/chunks/registry-BT54L6CY.ts.map +0 -7
- package/dist/chunks/retained-semantic-state-GM75FZGE.ts +0 -81
- package/dist/chunks/retained-semantic-state-GM75FZGE.ts.map +0 -7
- package/dist/chunks/rpc-transport-7R7DVCEB.ts +0 -1222
- package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +0 -7
- package/dist/chunks/runtime-policy-5YELCOVC.ts +0 -15
- package/dist/chunks/runtime-policy-5YELCOVC.ts.map +0 -7
- package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +0 -19
- package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +0 -7
- package/dist/chunks/spawn-idempotency-BNHOSMZW.ts +0 -13
- package/dist/chunks/spawn-idempotency-BNHOSMZW.ts.map +0 -7
- package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +0 -15
- package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +0 -7
- package/dist/chunks/subprocess-transport-VHZJRBTW.ts +0 -160
- package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +0 -7
- package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +0 -164
- package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +0 -7
- package/dist/chunks/workspace-WDKLN72J.ts +0 -11
- package/dist/chunks/workspace-WDKLN72J.ts.map +0 -7
- package/docs/async-runtime-protocol.md +0 -84
- package/docs/implementation-notes/pi-subagents-capability-matrix.md +0 -62
- package/docs/implementation-notes/pi-subagents-current-direction.md +0 -99
- package/docs/implementation-notes/pi-subagents-rpc-v1.md +0 -139
- package/docs/pi-subagents-diagrams.md +0 -183
- package/src/adaptive-scheduler.ts +0 -224
- package/src/admission-policy.ts +0 -78
- package/src/agent-projection.ts +0 -53
- package/src/agents/built-ins.ts +0 -71
- package/src/agents/catalog.ts +0 -241
- package/src/agents/discovery.ts +0 -265
- package/src/agents/types.ts +0 -100
- package/src/agents.ts +0 -51
- package/src/auto-transport.ts +0 -121
- package/src/blocking-status.ts +0 -63
- package/src/cached-module-loader.ts +0 -18
- package/src/capabilities.ts +0 -145
- package/src/capability-grant.ts +0 -115
- package/src/capability-router.ts +0 -107
- package/src/child-peer-bridge.ts +0 -124
- package/src/child-peer-tools.ts +0 -132
- package/src/completion-delivery.ts +0 -409
- package/src/completion-render.ts +0 -190
- package/src/completion-requirement.ts +0 -479
- package/src/completion-routing.ts +0 -24
- package/src/config-registration.ts +0 -114
- package/src/config-status.ts +0 -217
- package/src/config-ui.ts +0 -983
- package/src/consult-policy.ts +0 -15
- package/src/consult-registration.ts +0 -125
- package/src/consult-render.ts +0 -194
- package/src/consult-resources.ts +0 -51
- package/src/consult-tool.ts +0 -95
- package/src/consult.ts +0 -566
- package/src/context.ts +0 -126
- package/src/create-stateful-transport.ts +0 -157
- package/src/cwd-policy.ts +0 -183
- package/src/delegation-contract.ts +0 -463
- package/src/execution/budget.ts +0 -56
- package/src/execution/runtime-policy.ts +0 -19
- package/src/execution-plan.ts +0 -322
- package/src/execution-ui.ts +0 -259
- package/src/execution.ts +0 -1679
- package/src/in-process-transport.ts +0 -941
- package/src/inspect-registration.ts +0 -64
- package/src/inspect-render.ts +0 -334
- package/src/inspect-tool.ts +0 -45
- package/src/inspect.ts +0 -769
- package/src/integration-controller.ts +0 -98
- package/src/limits.ts +0 -75
- package/src/orchestration-metrics.ts +0 -116
- package/src/outcome.ts +0 -61
- package/src/panel-child-group.ts +0 -35
- package/src/panel-contract.ts +0 -343
- package/src/panel-evidence.ts +0 -59
- package/src/panel-execution.ts +0 -769
- package/src/panel-failure.ts +0 -56
- package/src/panel-planning.ts +0 -175
- package/src/panel-presets.ts +0 -3
- package/src/panel-prompts.ts +0 -132
- package/src/panel-reconciliation.ts +0 -57
- package/src/panel-render.ts +0 -103
- package/src/parallel-limit-ui.ts +0 -113
- package/src/params.ts +0 -278
- package/src/peer-communication.ts +0 -352
- package/src/peer-transport.ts +0 -49
- package/src/persistence.ts +0 -522
- package/src/pi-args.ts +0 -43
- package/src/pi-invocation.ts +0 -168
- package/src/process-control.ts +0 -43
- package/src/prompt-resources.ts +0 -38
- package/src/prompt-source-safety.ts +0 -48
- package/src/protocol.ts +0 -76
- package/src/registry-types.ts +0 -204
- package/src/registry.ts +0 -1698
- package/src/render-common.ts +0 -252
- package/src/render.ts +0 -704
- package/src/result-contract.ts +0 -431
- package/src/retained-semantic-state.ts +0 -100
- package/src/rpc-timeout-finalization.ts +0 -207
- package/src/rpc-transport-metadata.ts +0 -65
- package/src/rpc-transport.ts +0 -1035
- package/src/rpc-turn-capture.ts +0 -217
- package/src/runner-outcome.ts +0 -31
- package/src/runner-result.ts +0 -55
- package/src/runner-types.ts +0 -102
- package/src/runner-usage.ts +0 -48
- package/src/runner.ts +0 -866
- package/src/safe-text.ts +0 -67
- package/src/semantic-snapshot.ts +0 -214
- package/src/session-guidance-contract.ts +0 -399
- package/src/settings/inspection.ts +0 -302
- package/src/settings/schema.ts +0 -195
- package/src/settings-reader.ts +0 -215
- package/src/settings.ts +0 -452
- package/src/spawn-idempotency.ts +0 -68
- package/src/stateful-agent-view.ts +0 -85
- package/src/stateful-config.ts +0 -13
- package/src/stateful-guidance.ts +0 -29
- package/src/stateful-lifecycle.ts +0 -74
- package/src/stateful-limit-ui.ts +0 -249
- package/src/stateful-limits.ts +0 -96
- package/src/stateful-prompt.ts +0 -49
- package/src/stateful-registration.ts +0 -1320
- package/src/stateful-render.ts +0 -318
- package/src/stateful-safety.ts +0 -47
- package/src/stateful-tool-params.ts +0 -215
- package/src/stateful.ts +0 -12
- package/src/subagent-details.ts +0 -43
- package/src/subagents-extension.ts +0 -372
- package/src/subprocess-transport.ts +0 -145
- package/src/supervision.ts +0 -104
- package/src/task-path.ts +0 -65
- package/src/timeout-checkpoint.ts +0 -305
- package/src/timeout-finalization.ts +0 -75
- package/src/tool-schema-compatibility.ts +0 -73
- package/src/transport-types.ts +0 -74
- package/src/transport-ui.ts +0 -135
- package/src/transport.ts +0 -43
- package/src/turn-budget.ts +0 -109
- package/src/usage-format.ts +0 -42
- package/src/usage-recording-config.ts +0 -13
- package/src/usage-recording-store.ts +0 -183
- package/src/usage-recording.ts +0 -478
- package/src/verification-harness.ts +0 -516
- package/src/verification-policy.ts +0 -67
- package/src/verification-receipt.ts +0 -275
- package/src/verified-execution-benchmark.ts +0 -86
- package/src/verified-execution-contract.ts +0 -191
- package/src/verified-execution-schema.ts +0 -32
- package/src/work-item-ledger.ts +0 -1404
- package/src/work-item-persistence.ts +0 -254
- package/src/workflow-completion-controller.ts +0 -397
- package/src/workflow-planning.ts +0 -172
- package/src/workflow-tree-identity.ts +0 -289
- package/src/workflow-ui.ts +0 -69
- package/src/workflow-verification.ts +0 -296
- package/src/workspace.ts +0 -174
|
@@ -1,1641 +0,0 @@
|
|
|
1
|
-
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
-
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
-
import {
|
|
4
|
-
grammarSafeToolObject
|
|
5
|
-
} from "./chunk-TZ34IQ3M.ts";
|
|
6
|
-
import {
|
|
7
|
-
MAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,
|
|
8
|
-
assertSpawnIdempotencyKey
|
|
9
|
-
} from "./chunk-ILEQ27AL.ts";
|
|
10
|
-
import {
|
|
11
|
-
assertCurrentSpawn,
|
|
12
|
-
waitForOwnedSpawn
|
|
13
|
-
} from "./chunk-P7OH4XMF.ts";
|
|
14
|
-
import {
|
|
15
|
-
MAX_TASK_NAME_LENGTH
|
|
16
|
-
} from "./chunk-N7BLVXKK.ts";
|
|
17
|
-
import {
|
|
18
|
-
MAX_SUBAGENT_TOOL_CALLS,
|
|
19
|
-
MAX_SUBAGENT_TURNS
|
|
20
|
-
} from "./chunk-ONDTY4EL.ts";
|
|
21
|
-
import {
|
|
22
|
-
confirmProjectAgent
|
|
23
|
-
} from "./chunk-TM2R67J3.ts";
|
|
24
|
-
import {
|
|
25
|
-
SUBAGENT_RESULT_FORMATS
|
|
26
|
-
} from "./chunk-RSUXZD6S.ts";
|
|
27
|
-
import {
|
|
28
|
-
DEFAULT_DELEGATION_CWD_POLICY,
|
|
29
|
-
readSubagentSettings
|
|
30
|
-
} from "./chunk-TMZRHIIK.ts";
|
|
31
|
-
import {
|
|
32
|
-
resolveStatefulLimits
|
|
33
|
-
} from "./chunk-VDG7LTYE.ts";
|
|
34
|
-
import {
|
|
35
|
-
THINKING_LEVELS,
|
|
36
|
-
isThinkingLevel
|
|
37
|
-
} from "./chunk-4AQSF7AS.ts";
|
|
38
|
-
import {
|
|
39
|
-
COLLAPSED_LIST_LIMIT,
|
|
40
|
-
expansionHint,
|
|
41
|
-
recordList,
|
|
42
|
-
recordValue,
|
|
43
|
-
renderFallbackResult,
|
|
44
|
-
safeBlock,
|
|
45
|
-
safeLine,
|
|
46
|
-
statusBadge,
|
|
47
|
-
stringValue,
|
|
48
|
-
textResult,
|
|
49
|
-
toolHeader
|
|
50
|
-
} from "./chunk-BFK2Z4ZF.ts";
|
|
51
|
-
import {
|
|
52
|
-
CompletionRequirementModeSchema,
|
|
53
|
-
completionRequirementsFromBranch
|
|
54
|
-
} from "./chunk-NLT67IZS.ts";
|
|
55
|
-
import {
|
|
56
|
-
DelegationContractSchema
|
|
57
|
-
} from "./chunk-JSZIP73U.ts";
|
|
58
|
-
import {
|
|
59
|
-
DEFAULT_MAX_CONTEXT_BYTES,
|
|
60
|
-
MAX_SUBAGENT_TIMEOUT_MS,
|
|
61
|
-
MAX_TOOL_MESSAGE_BYTES,
|
|
62
|
-
truncateUtf8
|
|
63
|
-
} from "./chunk-H3FP6DLR.ts";
|
|
64
|
-
|
|
65
|
-
// src/stateful-agent-view.ts
|
|
66
|
-
function formatStatefulAgentLine(agent, now = Date.now()) {
|
|
67
|
-
const elapsedSeconds = Math.max(0, Math.floor((now - agent.updatedAt) / 1e3));
|
|
68
|
-
const task = agent.currentTask ? ` \u2014 ${sanitizeStatusLine(agent.currentTask, 80)}` : "";
|
|
69
|
-
const unread = agent.mailbox.filter((message) => !message.readAt).length;
|
|
70
|
-
const indent = " ".repeat(agent.depth);
|
|
71
|
-
return `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} \xB7 ${sanitizeStatusLine(agent.agent, 128)} \xB7 ${agentStateLabel(agent.state)} \xB7 updated ${elapsedSeconds}s ago \xB7 ${unread} unread${task}`;
|
|
72
|
-
}
|
|
73
|
-
function summarizeStatefulAgent(agent) {
|
|
74
|
-
return {
|
|
75
|
-
id: agent.id,
|
|
76
|
-
taskName: agent.taskName,
|
|
77
|
-
taskPath: agent.taskPath,
|
|
78
|
-
agent: agent.agent,
|
|
79
|
-
parentId: agent.parentId,
|
|
80
|
-
rootId: agent.rootId,
|
|
81
|
-
depth: agent.depth,
|
|
82
|
-
children: [...agent.children],
|
|
83
|
-
state: agent.state,
|
|
84
|
-
createdAt: agent.createdAt,
|
|
85
|
-
updatedAt: agent.updatedAt,
|
|
86
|
-
cwd: agent.cwd,
|
|
87
|
-
workspaceMode: agent.workspaceMode ?? "shared",
|
|
88
|
-
thinkingLevel: agent.thinkingLevel,
|
|
89
|
-
timeoutMs: agent.timeoutMs,
|
|
90
|
-
currentTimeoutMs: agent.currentTimeoutMs,
|
|
91
|
-
idleTimeoutMs: agent.idleTimeoutMs,
|
|
92
|
-
currentIdleTimeoutMs: agent.currentIdleTimeoutMs,
|
|
93
|
-
maxTurns: agent.maxTurns,
|
|
94
|
-
currentMaxTurns: agent.currentMaxTurns,
|
|
95
|
-
maxToolCalls: agent.maxToolCalls,
|
|
96
|
-
currentMaxToolCalls: agent.currentMaxToolCalls,
|
|
97
|
-
currentTask: agent.currentTask ? truncateUtf8(agent.currentTask, MAX_TOOL_MESSAGE_BYTES).text : void 0,
|
|
98
|
-
historyCount: agent.history.length,
|
|
99
|
-
unreadMessages: agent.mailbox.filter((message) => !message.readAt).length,
|
|
100
|
-
context: {
|
|
101
|
-
turns: agent.contextTurns ?? 0,
|
|
102
|
-
sources: agent.contextSourceIds?.length ?? 0,
|
|
103
|
-
bytes: agent.contextBytes ?? 0,
|
|
104
|
-
truncated: agent.contextTruncated === true
|
|
105
|
-
},
|
|
106
|
-
resultFormat: agent.resultFormat ?? "text",
|
|
107
|
-
completionRequirements: (agent.completionRequirements ?? []).map((record) => ({
|
|
108
|
-
...record
|
|
109
|
-
})),
|
|
110
|
-
structuredResult: agent.structuredResult,
|
|
111
|
-
termination: agent.termination,
|
|
112
|
-
outcome: agent.outcome,
|
|
113
|
-
executionPlan: agent.executionPlan,
|
|
114
|
-
capabilityGrant: agent.capabilityGrant,
|
|
115
|
-
semanticCompatibility: agent.semanticCompatibility,
|
|
116
|
-
semanticSnapshotDigest: agent.semanticSnapshot?.digest,
|
|
117
|
-
telemetry: agent.telemetry,
|
|
118
|
-
error: agent.error ? truncateUtf8(agent.error, MAX_TOOL_MESSAGE_BYTES).text : void 0,
|
|
119
|
-
target: agent.target,
|
|
120
|
-
policy: agent.policy
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
function agentStateLabel(state) {
|
|
124
|
-
switch (state) {
|
|
125
|
-
case "running":
|
|
126
|
-
return "working";
|
|
127
|
-
case "completed":
|
|
128
|
-
return "finished";
|
|
129
|
-
default:
|
|
130
|
-
return state;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
function sanitizeStatusLine(value, maxLength) {
|
|
134
|
-
return value.slice(0, maxLength).replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ").replace(/\s+/gu, " ").trim();
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// src/stateful-config.ts
|
|
138
|
-
function resolveStatefulTransportKind(value) {
|
|
139
|
-
return value ?? "subprocess";
|
|
140
|
-
}
|
|
141
|
-
function resolveCompletionDelivery(value) {
|
|
142
|
-
return value ?? "next-turn";
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// src/stateful-registration.ts
|
|
146
|
-
import { randomUUID } from "node:crypto";
|
|
147
|
-
import { StringEnum as StringEnum2 } from "@earendil-works/pi-ai";
|
|
148
|
-
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
149
|
-
import { Type as Type2 } from "typebox";
|
|
150
|
-
|
|
151
|
-
// src/stateful-guidance.ts
|
|
152
|
-
function createSpawnPromptGuidelines(blockingEnabled = true) {
|
|
153
|
-
return [
|
|
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.",
|
|
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.",
|
|
156
|
-
"Give subagent_spawn a concise unique taskName using lowercase letters, digits, and underscores so the retained agent has a stable canonical task path.",
|
|
157
|
-
"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.",
|
|
158
|
-
"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.",
|
|
159
|
-
"For an ordinary subagent_spawn, omit contract; use a delegation contract only when explicit acceptance, authority, evidence, or admission semantics are required.",
|
|
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.",
|
|
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.",
|
|
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.',
|
|
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.",
|
|
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.",
|
|
166
|
-
"Use a single subagent_spawn without concurrent main-agent work only for an explicit user-requested specialist model, tool profile, or isolation boundary.",
|
|
167
|
-
...blockingEnabled ? [
|
|
168
|
-
"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.",
|
|
169
|
-
"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."
|
|
170
|
-
] : [],
|
|
171
|
-
"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.",
|
|
172
|
-
"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.",
|
|
173
|
-
"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.",
|
|
174
|
-
"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.",
|
|
175
|
-
'Consume and synthesize available subagent_spawn completion messages; use subagent_manage with action "interrupt" or "close" for agents that are no longer needed.',
|
|
176
|
-
'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.'
|
|
177
|
-
];
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// src/stateful-render.ts
|
|
181
|
-
import { Text } from "@earendil-works/pi-tui";
|
|
182
|
-
function createStatefulToolRenderer(tool) {
|
|
183
|
-
return {
|
|
184
|
-
renderCall(args, theme) {
|
|
185
|
-
return renderStatefulCall(tool, recordValue(args) ?? {}, theme);
|
|
186
|
-
},
|
|
187
|
-
renderResult(result2, options, theme, context) {
|
|
188
|
-
return renderStatefulResult(tool, result2, options, theme, context);
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
function renderStatefulCall(tool, args, theme) {
|
|
193
|
-
if (tool === "spawn") {
|
|
194
|
-
const metadata2 = [
|
|
195
|
-
`[${safeLine(args.agentScope, "user", 64)}]`,
|
|
196
|
-
"detached",
|
|
197
|
-
safeLine(args.workspaceMode, "shared", 64)
|
|
198
|
-
];
|
|
199
|
-
if (typeof args.thinkingLevel === "string") metadata2.push(`thinking:${args.thinkingLevel}`);
|
|
200
|
-
if (typeof args.timeoutMs === "number") metadata2.push(`timeout:${args.timeoutMs}ms`);
|
|
201
|
-
if (typeof args.idleTimeoutMs === "number") metadata2.push(`idle:${args.idleTimeoutMs}ms`);
|
|
202
|
-
if (typeof args.maxTurns === "number") metadata2.push(`turns:${args.maxTurns}`);
|
|
203
|
-
if (typeof args.maxToolCalls === "number") metadata2.push(`tools:${args.maxToolCalls}`);
|
|
204
|
-
return new Text(
|
|
205
|
-
[
|
|
206
|
-
toolHeader(theme, "subagent_spawn", args.agent, metadata2),
|
|
207
|
-
` ${theme.fg("dim", safeLine(args.task, "...", 2 * 1024))}`
|
|
208
|
-
].join("\n"),
|
|
209
|
-
0,
|
|
210
|
-
0
|
|
211
|
-
);
|
|
212
|
-
}
|
|
213
|
-
if (tool === "send") {
|
|
214
|
-
const metadata2 = ["follow-up"];
|
|
215
|
-
if (typeof args.timeoutMs === "number") metadata2.push(`timeout:${args.timeoutMs}ms`);
|
|
216
|
-
if (typeof args.idleTimeoutMs === "number") metadata2.push(`idle:${args.idleTimeoutMs}ms`);
|
|
217
|
-
if (typeof args.maxTurns === "number") metadata2.push(`turns:${args.maxTurns}`);
|
|
218
|
-
if (typeof args.maxToolCalls === "number") metadata2.push(`tools:${args.maxToolCalls}`);
|
|
219
|
-
return new Text(
|
|
220
|
-
[
|
|
221
|
-
toolHeader(theme, "subagent_send", args.agentId, metadata2),
|
|
222
|
-
` ${theme.fg("dim", safeLine(args.task, "...", 2 * 1024))}`
|
|
223
|
-
].join("\n"),
|
|
224
|
-
0,
|
|
225
|
-
0
|
|
226
|
-
);
|
|
227
|
-
}
|
|
228
|
-
if (tool === "await") {
|
|
229
|
-
const metadata2 = ["blocking"];
|
|
230
|
-
if (typeof args.timeoutMs === "number") metadata2.push(`timeout:${args.timeoutMs}ms`);
|
|
231
|
-
return new Text(toolHeader(theme, "subagent_await", args.agentId, metadata2), 0, 0);
|
|
232
|
-
}
|
|
233
|
-
if (tool === "manage") {
|
|
234
|
-
const metadata2 = [];
|
|
235
|
-
if (typeof args.agentId === "string") metadata2.push(`id:${safeLine(args.agentId, "", 256)}`);
|
|
236
|
-
if (args.subtree === true) metadata2.push("subtree");
|
|
237
|
-
return new Text(toolHeader(theme, "subagent_manage", args.action, metadata2), 0, 0);
|
|
238
|
-
}
|
|
239
|
-
const metadata = [`id:${safeLine(args.agentId, "...", 256)}`];
|
|
240
|
-
if (args.action === "read") {
|
|
241
|
-
metadata.push(args.acknowledge === false ? "leave unread" : "acknowledge");
|
|
242
|
-
}
|
|
243
|
-
const lines = [toolHeader(theme, "subagent_mailbox", args.action, metadata)];
|
|
244
|
-
if (args.action === "send") {
|
|
245
|
-
lines.push(` ${theme.fg("dim", safeLine(args.message, "...", 2 * 1024))}`);
|
|
246
|
-
}
|
|
247
|
-
return new Text(lines.join("\n"), 0, 0);
|
|
248
|
-
}
|
|
249
|
-
function renderStatefulResult(tool, result2, options, theme, context) {
|
|
250
|
-
const details = recordValue(result2.details);
|
|
251
|
-
const args = recordValue(context.args) ?? {};
|
|
252
|
-
if (!details) return renderFallbackResult(result2, options, theme, context.isError);
|
|
253
|
-
if (tool === "spawn" || tool === "send" || tool === "await") {
|
|
254
|
-
const agent = recordValue(details.agent);
|
|
255
|
-
if (!agent) return renderFallbackResult(result2, options, theme, context.isError);
|
|
256
|
-
if (tool === "await" && details.timedOut === true) {
|
|
257
|
-
return new Text(renderAwaitTimeout(agent, result2, options.expanded, theme), 0, 0);
|
|
258
|
-
}
|
|
259
|
-
return new Text(renderAgentResult(agent, result2, options.expanded, theme), 0, 0);
|
|
260
|
-
}
|
|
261
|
-
if (tool === "manage") {
|
|
262
|
-
return new Text(renderManageResult(args, details, result2, options.expanded, theme), 0, 0);
|
|
263
|
-
}
|
|
264
|
-
return new Text(renderMailboxResult(args, details, options.expanded, theme), 0, 0);
|
|
265
|
-
}
|
|
266
|
-
function renderAgentResult(agent, result2, expanded, theme) {
|
|
267
|
-
const state = safeLine(agent.state, "unknown", 128);
|
|
268
|
-
const lines = [
|
|
269
|
-
`${statusBadge(theme, lifecycleStatus(state))} \xB7 ${theme.fg("accent", safeLine(agent.id, "agent", 256))} \xB7 ${theme.fg("toolOutput", safeLine(agent.agent, "subagent", 256))} \xB7 ${theme.fg("muted", state)}`
|
|
270
|
-
];
|
|
271
|
-
const thinking = stringValue(agent.thinkingLevel);
|
|
272
|
-
const timeout = typeof agent.currentTimeoutMs === "number" ? agent.currentTimeoutMs : typeof agent.timeoutMs === "number" ? agent.timeoutMs : 0;
|
|
273
|
-
const idleTimeout = typeof agent.currentIdleTimeoutMs === "number" ? agent.currentIdleTimeoutMs : typeof agent.idleTimeoutMs === "number" ? agent.idleTimeoutMs : 0;
|
|
274
|
-
const maxTurns = typeof agent.currentMaxTurns === "number" ? agent.currentMaxTurns : typeof agent.maxTurns === "number" ? agent.maxTurns : 0;
|
|
275
|
-
const maxToolCalls = typeof agent.currentMaxToolCalls === "number" ? agent.currentMaxToolCalls : typeof agent.maxToolCalls === "number" ? agent.maxToolCalls : 0;
|
|
276
|
-
const unread = typeof agent.unreadMessages === "number" ? agent.unreadMessages : 0;
|
|
277
|
-
if (thinking || timeout || idleTimeout || maxTurns || maxToolCalls || unread > 0) {
|
|
278
|
-
lines.push(
|
|
279
|
-
theme.fg(
|
|
280
|
-
"dim",
|
|
281
|
-
[
|
|
282
|
-
thinking && `thinking:${safeLine(thinking, "", 128)}`,
|
|
283
|
-
timeout && `timeout:${timeout}ms`,
|
|
284
|
-
idleTimeout && `idle:${idleTimeout}ms`,
|
|
285
|
-
maxTurns && `turns:${maxTurns}`,
|
|
286
|
-
maxToolCalls && `tools:${maxToolCalls}`,
|
|
287
|
-
unread > 0 && `unread:${unread}`
|
|
288
|
-
].filter(Boolean).join(" \xB7 ")
|
|
289
|
-
)
|
|
290
|
-
);
|
|
291
|
-
}
|
|
292
|
-
if (expanded) {
|
|
293
|
-
const task = safeBlock(agent.currentTask, "", 2 * 1024).trim();
|
|
294
|
-
const error = safeBlock(agent.error, "", 2 * 1024).trim();
|
|
295
|
-
if (task) lines.push(theme.fg("dim", `task: ${task}`));
|
|
296
|
-
if (error) lines.push(theme.fg("error", `error: ${error}`));
|
|
297
|
-
const content = safeBlock(textResult(result2), "", 8 * 1024).trim();
|
|
298
|
-
if (content) lines.push(theme.fg("toolOutput", content));
|
|
299
|
-
} else lines.push(expansionHint());
|
|
300
|
-
return lines.join("\n");
|
|
301
|
-
}
|
|
302
|
-
function renderAwaitTimeout(agent, result2, expanded, theme) {
|
|
303
|
-
const lines = [
|
|
304
|
-
`${statusBadge(theme, "running")} \xB7 ${theme.fg("accent", safeLine(agent.id, "agent", 256))} \xB7 ${theme.fg("warning", "wait timed out")} \xB7 ${theme.fg("muted", safeLine(agent.state, "unknown", 128))}`
|
|
305
|
-
];
|
|
306
|
-
if (expanded) {
|
|
307
|
-
const content = safeBlock(textResult(result2), "", 8 * 1024).trim();
|
|
308
|
-
if (content) lines.push(theme.fg("toolOutput", content));
|
|
309
|
-
} else lines.push(expansionHint());
|
|
310
|
-
return lines.join("\n");
|
|
311
|
-
}
|
|
312
|
-
function renderManageResult(args, details, result2, expanded, theme) {
|
|
313
|
-
const action = safeLine(args.action, "action", 128);
|
|
314
|
-
const agents = recordList(details.agents);
|
|
315
|
-
const primary = recordValue(details.agent);
|
|
316
|
-
if (action === "list") {
|
|
317
|
-
const lines2 = [
|
|
318
|
-
`${statusBadge(theme, "completed")} \xB7 list \xB7 ${agents.length} agent${agents.length === 1 ? "" : "s"}`
|
|
319
|
-
];
|
|
320
|
-
const selected2 = expanded ? agents : agents.slice(0, COLLAPSED_LIST_LIMIT);
|
|
321
|
-
for (const agent of selected2) lines2.push(formatAgentLine(agent, theme, expanded));
|
|
322
|
-
if (agents.length === 0) lines2.push(theme.fg("muted", "(no retained agents)"));
|
|
323
|
-
if (agents.length > selected2.length)
|
|
324
|
-
lines2.push(theme.fg("muted", `\u2026 ${agents.length - selected2.length} omitted`));
|
|
325
|
-
if (!expanded && agents.length > 0) lines2.push(expansionHint());
|
|
326
|
-
return lines2.join("\n");
|
|
327
|
-
}
|
|
328
|
-
const subtree = args.subtree === true;
|
|
329
|
-
const affected = subtree ? agents.length : agents.length > 0 ? agents.length : primary ? 1 : 0;
|
|
330
|
-
const status = action === "interrupt" ? "interrupted" : "closed";
|
|
331
|
-
const lines = [
|
|
332
|
-
`${statusBadge(theme, status)} \xB7 ${affected} agent${affected === 1 ? "" : "s"}${subtree ? theme.fg("muted", " \xB7 subtree") : ""}`
|
|
333
|
-
];
|
|
334
|
-
const selected = agents.length > 0 ? agents : !subtree && primary ? [primary] : [];
|
|
335
|
-
for (const agent of expanded ? selected : selected.slice(0, COLLAPSED_LIST_LIMIT)) {
|
|
336
|
-
lines.push(formatAgentLine(agent, theme, expanded));
|
|
337
|
-
}
|
|
338
|
-
if (selected.length === 0) {
|
|
339
|
-
const content = safeBlock(textResult(result2), "(no output)", 8 * 1024);
|
|
340
|
-
lines.push(theme.fg("toolOutput", content));
|
|
341
|
-
}
|
|
342
|
-
if (!expanded && selected.length > 0) lines.push(expansionHint());
|
|
343
|
-
return lines.join("\n");
|
|
344
|
-
}
|
|
345
|
-
function renderMailboxResult(args, details, expanded, theme) {
|
|
346
|
-
const action = safeLine(args.action, "action", 64);
|
|
347
|
-
if (action === "send") {
|
|
348
|
-
const message = recordValue(details.message);
|
|
349
|
-
if (!message) return `${statusBadge(theme, "completed")} \xB7 Queued message`;
|
|
350
|
-
const lines2 = [
|
|
351
|
-
`${theme.fg("success", "\u2713")} ${theme.fg("success", "Queued")} \xB7 ${theme.fg("accent", safeLine(message.id, "message", 256))} \xB7 ${theme.fg("muted", `to ${safeLine(message.recipientId, safeLine(args.agentId), 256)}`)}`
|
|
352
|
-
];
|
|
353
|
-
if (expanded) {
|
|
354
|
-
lines2.push(theme.fg("toolOutput", safeBlock(message.content, "(empty message)", 2 * 1024)));
|
|
355
|
-
} else lines2.push(expansionHint());
|
|
356
|
-
return lines2.join("\n");
|
|
357
|
-
}
|
|
358
|
-
const messages = recordList(details.messages);
|
|
359
|
-
const acknowledged = args.acknowledge === false ? "left unread" : "acknowledged";
|
|
360
|
-
const lines = [
|
|
361
|
-
`${statusBadge(theme, "completed")} \xB7 ${messages.length} message${messages.length === 1 ? "" : "s"} \xB7 ${acknowledged}`
|
|
362
|
-
];
|
|
363
|
-
const selected = expanded ? messages : messages.slice(0, COLLAPSED_LIST_LIMIT);
|
|
364
|
-
for (const message of selected) {
|
|
365
|
-
const content = expanded ? safeBlock(message.content, "(empty message)", 2 * 1024) : safeLine(message.content, "(empty message)", 512);
|
|
366
|
-
lines.push(
|
|
367
|
-
`${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)}`
|
|
368
|
-
);
|
|
369
|
-
}
|
|
370
|
-
if (messages.length === 0) lines.push(theme.fg("muted", "(no unread messages)"));
|
|
371
|
-
if (messages.length > selected.length)
|
|
372
|
-
lines.push(theme.fg("muted", `\u2026 ${messages.length - selected.length} omitted`));
|
|
373
|
-
if (!expanded && messages.length > 0) lines.push(expansionHint());
|
|
374
|
-
return lines.join("\n");
|
|
375
|
-
}
|
|
376
|
-
function formatAgentLine(agent, theme, expanded) {
|
|
377
|
-
const unread = typeof agent.unreadMessages === "number" ? agent.unreadMessages : 0;
|
|
378
|
-
const lines = [
|
|
379
|
-
`${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", ` \xB7 unread:${unread}`) : ""}`
|
|
380
|
-
];
|
|
381
|
-
if (expanded) {
|
|
382
|
-
const task = safeBlock(agent.currentTask, "", 2 * 1024).trim();
|
|
383
|
-
const error = safeBlock(agent.error, "", 2 * 1024).trim();
|
|
384
|
-
if (task) lines.push(` ${theme.fg("dim", `task: ${task}`)}`);
|
|
385
|
-
if (error) lines.push(` ${theme.fg("error", `error: ${error}`)}`);
|
|
386
|
-
}
|
|
387
|
-
return lines.join("\n");
|
|
388
|
-
}
|
|
389
|
-
function lifecycleStatus(state) {
|
|
390
|
-
switch (state) {
|
|
391
|
-
case "starting":
|
|
392
|
-
return "starting";
|
|
393
|
-
case "running":
|
|
394
|
-
return "running";
|
|
395
|
-
case "idle":
|
|
396
|
-
return "idle";
|
|
397
|
-
case "partial":
|
|
398
|
-
case "blocked":
|
|
399
|
-
case "needs-input":
|
|
400
|
-
case "abstained":
|
|
401
|
-
case "stale":
|
|
402
|
-
return "warning";
|
|
403
|
-
case "failed":
|
|
404
|
-
return "failed";
|
|
405
|
-
case "interrupted":
|
|
406
|
-
return "interrupted";
|
|
407
|
-
case "closed":
|
|
408
|
-
return "closed";
|
|
409
|
-
default:
|
|
410
|
-
return "completed";
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
// src/stateful-tool-params.ts
|
|
415
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
416
|
-
import { Type } from "typebox";
|
|
417
|
-
var MANAGE_ACTIONS = ["interrupt", "close"];
|
|
418
|
-
var MAILBOX_ACTIONS = ["send", "read"];
|
|
419
|
-
var MAX_MAILBOX_MESSAGE_LENGTH = 16 * 1024;
|
|
420
|
-
var ManageParamsSchema = Type.Object(
|
|
421
|
-
{
|
|
422
|
-
action: StringEnum(MANAGE_ACTIONS, {
|
|
423
|
-
description: "Interrupt active work or close an agent and release its resources."
|
|
424
|
-
}),
|
|
425
|
-
agentId: Type.Optional(
|
|
426
|
-
Type.String({
|
|
427
|
-
minLength: 1,
|
|
428
|
-
description: "Required agent ID or canonical task path for interrupt and close."
|
|
429
|
-
})
|
|
430
|
-
),
|
|
431
|
-
subtree: Type.Optional(
|
|
432
|
-
Type.Boolean({
|
|
433
|
-
default: false,
|
|
434
|
-
description: "Interrupt or close the target and all descendants child-first."
|
|
435
|
-
})
|
|
436
|
-
)
|
|
437
|
-
},
|
|
438
|
-
{ additionalProperties: false }
|
|
439
|
-
);
|
|
440
|
-
var MailboxParamsSchema = Type.Object(
|
|
441
|
-
{
|
|
442
|
-
action: StringEnum(MAILBOX_ACTIONS, {
|
|
443
|
-
description: "Use send for queue-only delivery or read to inspect unread mailbox messages."
|
|
444
|
-
}),
|
|
445
|
-
agentId: Type.String({
|
|
446
|
-
minLength: 1,
|
|
447
|
-
description: "Mailbox owner or recipient agent ID or canonical task path."
|
|
448
|
-
}),
|
|
449
|
-
message: Type.Optional(
|
|
450
|
-
Type.String({
|
|
451
|
-
minLength: 1,
|
|
452
|
-
maxLength: MAX_MAILBOX_MESSAGE_LENGTH,
|
|
453
|
-
description: "Message content required by send; sending does not start a turn."
|
|
454
|
-
})
|
|
455
|
-
),
|
|
456
|
-
senderId: Type.Optional(
|
|
457
|
-
Type.String({ description: "Optional sender agent ID or canonical task path." })
|
|
458
|
-
),
|
|
459
|
-
deduplicationKey: Type.Optional(
|
|
460
|
-
Type.String({ maxLength: 256, description: "Optional idempotency key for send." })
|
|
461
|
-
),
|
|
462
|
-
acknowledge: Type.Optional(
|
|
463
|
-
Type.Boolean({ default: true, description: "Mark returned read messages as acknowledged." })
|
|
464
|
-
),
|
|
465
|
-
limit: Type.Optional(
|
|
466
|
-
Type.Number({ minimum: 1, maximum: 20, default: 20, description: "Maximum messages." })
|
|
467
|
-
)
|
|
468
|
-
},
|
|
469
|
-
{ additionalProperties: false }
|
|
470
|
-
);
|
|
471
|
-
function validateManageParams(params) {
|
|
472
|
-
const values = parameterRecord(params, "subagent_manage");
|
|
473
|
-
assertKnownKeys("subagent_manage", values, ["action", "agentId", "subtree"]);
|
|
474
|
-
const action = values.action;
|
|
475
|
-
if (action === "list") {
|
|
476
|
-
throw new Error(
|
|
477
|
-
'subagent_manage no longer supports "list"; use subagent_inspect action "list_runs"'
|
|
478
|
-
);
|
|
479
|
-
}
|
|
480
|
-
if (typeof action !== "string" || !MANAGE_ACTIONS.includes(action)) {
|
|
481
|
-
throw new Error(`subagent_manage action must be one of: ${MANAGE_ACTIONS.join(", ")}`);
|
|
482
|
-
}
|
|
483
|
-
assertRequiredString("subagent_manage", action, values, "agentId");
|
|
484
|
-
assertOptionalBoolean("subagent_manage", action, values, "subtree");
|
|
485
|
-
return {
|
|
486
|
-
action,
|
|
487
|
-
agentId: values.agentId,
|
|
488
|
-
...values.subtree === void 0 ? {} : { subtree: values.subtree }
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
function validateMailboxParams(params) {
|
|
492
|
-
const values = parameterRecord(params, "subagent_mailbox");
|
|
493
|
-
assertKnownKeys("subagent_mailbox", values, [
|
|
494
|
-
"action",
|
|
495
|
-
"agentId",
|
|
496
|
-
"message",
|
|
497
|
-
"senderId",
|
|
498
|
-
"deduplicationKey",
|
|
499
|
-
"acknowledge",
|
|
500
|
-
"limit"
|
|
501
|
-
]);
|
|
502
|
-
const action = values.action;
|
|
503
|
-
if (typeof action !== "string" || !MAILBOX_ACTIONS.includes(action)) {
|
|
504
|
-
throw new Error(`subagent_mailbox action must be one of: ${MAILBOX_ACTIONS.join(", ")}`);
|
|
505
|
-
}
|
|
506
|
-
if (action === "send") {
|
|
507
|
-
assertRequiredString("subagent_mailbox", action, values, "agentId");
|
|
508
|
-
assertRequiredString("subagent_mailbox", action, values, "message");
|
|
509
|
-
const message = values.message;
|
|
510
|
-
if (message.length > MAX_MAILBOX_MESSAGE_LENGTH) {
|
|
511
|
-
throw new Error(
|
|
512
|
-
`subagent_mailbox action "send" requires message at most ${MAX_MAILBOX_MESSAGE_LENGTH} characters`
|
|
513
|
-
);
|
|
514
|
-
}
|
|
515
|
-
assertOptionalString("subagent_mailbox", action, values, "senderId");
|
|
516
|
-
assertOptionalString("subagent_mailbox", action, values, "deduplicationKey");
|
|
517
|
-
if (typeof values.deduplicationKey === "string" && values.deduplicationKey.length > 256) {
|
|
518
|
-
throw new Error(
|
|
519
|
-
'subagent_mailbox action "send" requires deduplicationKey at most 256 characters'
|
|
520
|
-
);
|
|
521
|
-
}
|
|
522
|
-
return {
|
|
523
|
-
action,
|
|
524
|
-
agentId: values.agentId,
|
|
525
|
-
message,
|
|
526
|
-
...values.senderId === void 0 ? {} : { senderId: values.senderId },
|
|
527
|
-
...values.deduplicationKey === void 0 ? {} : { deduplicationKey: values.deduplicationKey }
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
assertRequiredString("subagent_mailbox", action, values, "agentId");
|
|
531
|
-
assertOptionalBoolean("subagent_mailbox", action, values, "acknowledge");
|
|
532
|
-
if (values.limit !== void 0 && (typeof values.limit !== "number" || !Number.isFinite(values.limit) || values.limit < 1 || values.limit > 20)) {
|
|
533
|
-
throw new Error('subagent_mailbox action "read" requires limit between 1 and 20');
|
|
534
|
-
}
|
|
535
|
-
return {
|
|
536
|
-
action,
|
|
537
|
-
agentId: values.agentId,
|
|
538
|
-
...values.acknowledge === void 0 ? {} : { acknowledge: values.acknowledge },
|
|
539
|
-
...values.limit === void 0 ? {} : { limit: values.limit }
|
|
540
|
-
};
|
|
541
|
-
}
|
|
542
|
-
function parameterRecord(params, toolName) {
|
|
543
|
-
if (!params || typeof params !== "object" || Array.isArray(params)) {
|
|
544
|
-
throw new Error(`${toolName} parameters must be an object`);
|
|
545
|
-
}
|
|
546
|
-
return params;
|
|
547
|
-
}
|
|
548
|
-
function assertKnownKeys(toolName, values, allowed) {
|
|
549
|
-
const unexpected = Object.keys(values).find(
|
|
550
|
-
(key) => values[key] !== void 0 && !allowed.includes(key)
|
|
551
|
-
);
|
|
552
|
-
if (unexpected) throw new Error(`${toolName} does not accept ${unexpected}`);
|
|
553
|
-
}
|
|
554
|
-
function assertRequiredString(toolName, action, values, key) {
|
|
555
|
-
const value = values[key];
|
|
556
|
-
if (value === void 0) throw new Error(`${toolName} action "${action}" requires ${key}`);
|
|
557
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
558
|
-
throw new Error(`${toolName} action "${action}" requires ${key} to be a non-empty string`);
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
function assertOptionalString(toolName, action, values, key) {
|
|
562
|
-
if (values[key] !== void 0 && typeof values[key] !== "string") {
|
|
563
|
-
throw new Error(`${toolName} action "${action}" requires ${key} to be a string`);
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
function assertOptionalBoolean(toolName, action, values, key) {
|
|
567
|
-
if (values[key] !== void 0 && typeof values[key] !== "boolean") {
|
|
568
|
-
throw new Error(`${toolName} action "${action}" requires ${key} to be a boolean`);
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
// src/stateful-registration.ts
|
|
573
|
-
var statefulSessionModules;
|
|
574
|
-
var statefulSpawnModules;
|
|
575
|
-
var workspaceModule;
|
|
576
|
-
function loadStatefulSessionModules() {
|
|
577
|
-
statefulSessionModules ??= Promise.all([
|
|
578
|
-
import("./completion-delivery-RSJU6BXL.ts"),
|
|
579
|
-
import("./peer-communication-KL36Z6CO.ts"),
|
|
580
|
-
import("./context-QDKLVQXE.ts"),
|
|
581
|
-
import("./create-stateful-transport-JWC2EFYL.ts"),
|
|
582
|
-
import("./cwd-policy-NB6XZ5GF.ts"),
|
|
583
|
-
import("./persistence-UY3PY6E5.ts"),
|
|
584
|
-
import("./registry-BT54L6CY.ts"),
|
|
585
|
-
import("./stateful-lifecycle-JAR6K55H.ts")
|
|
586
|
-
]).then(
|
|
587
|
-
([
|
|
588
|
-
broker,
|
|
589
|
-
peerCommunication,
|
|
590
|
-
context,
|
|
591
|
-
transport,
|
|
592
|
-
cwdPolicy,
|
|
593
|
-
persistence,
|
|
594
|
-
registry,
|
|
595
|
-
lifecycle
|
|
596
|
-
]) => ({
|
|
597
|
-
broker,
|
|
598
|
-
peerCommunication,
|
|
599
|
-
context,
|
|
600
|
-
transport,
|
|
601
|
-
cwdPolicy,
|
|
602
|
-
persistence,
|
|
603
|
-
registry,
|
|
604
|
-
lifecycle
|
|
605
|
-
})
|
|
606
|
-
).catch((error) => {
|
|
607
|
-
statefulSessionModules = void 0;
|
|
608
|
-
throw error;
|
|
609
|
-
});
|
|
610
|
-
return statefulSessionModules;
|
|
611
|
-
}
|
|
612
|
-
function loadStatefulSpawnModules() {
|
|
613
|
-
statefulSpawnModules ??= Promise.all([
|
|
614
|
-
import("./discovery-MIFB2U4Y.ts"),
|
|
615
|
-
import("./capability-grant-PR72SWWS.ts"),
|
|
616
|
-
import("./context-QDKLVQXE.ts"),
|
|
617
|
-
import("./cwd-policy-NB6XZ5GF.ts"),
|
|
618
|
-
import("./delegation-contract-LA56I5DT.ts"),
|
|
619
|
-
import("./runtime-policy-5YELCOVC.ts"),
|
|
620
|
-
import("./retained-semantic-state-GM75FZGE.ts"),
|
|
621
|
-
import("./semantic-snapshot-WPJ3UAFW.ts"),
|
|
622
|
-
import("./spawn-idempotency-BNHOSMZW.ts")
|
|
623
|
-
]).then(
|
|
624
|
-
([
|
|
625
|
-
agents,
|
|
626
|
-
capabilityGrant,
|
|
627
|
-
context,
|
|
628
|
-
cwdPolicy,
|
|
629
|
-
delegationContract,
|
|
630
|
-
runtimePolicy,
|
|
631
|
-
retainedSemanticState,
|
|
632
|
-
semanticSnapshot,
|
|
633
|
-
spawnIdempotency
|
|
634
|
-
]) => ({
|
|
635
|
-
agents,
|
|
636
|
-
capabilityGrant,
|
|
637
|
-
context,
|
|
638
|
-
cwdPolicy,
|
|
639
|
-
delegationContract,
|
|
640
|
-
runtimePolicy,
|
|
641
|
-
retainedSemanticState,
|
|
642
|
-
semanticSnapshot,
|
|
643
|
-
spawnIdempotency
|
|
644
|
-
})
|
|
645
|
-
).catch((error) => {
|
|
646
|
-
statefulSpawnModules = void 0;
|
|
647
|
-
throw error;
|
|
648
|
-
});
|
|
649
|
-
return statefulSpawnModules;
|
|
650
|
-
}
|
|
651
|
-
async function loadWorkspaceModule() {
|
|
652
|
-
workspaceModule ??= import("./workspace-WDKLN72J.ts").catch((error) => {
|
|
653
|
-
workspaceModule = void 0;
|
|
654
|
-
throw error;
|
|
655
|
-
});
|
|
656
|
-
return workspaceModule;
|
|
657
|
-
}
|
|
658
|
-
var ContextModeSchema = Type2.Union([
|
|
659
|
-
StringEnum2(["none", "all", "summary"]),
|
|
660
|
-
Type2.Number({ minimum: 1, description: "Include the most recent N user turns." })
|
|
661
|
-
]);
|
|
662
|
-
var ScopeSchema = StringEnum2(["user", "project", "both"], {
|
|
663
|
-
description: '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.',
|
|
664
|
-
default: "user"
|
|
665
|
-
});
|
|
666
|
-
var StatefulThinkingLevelSchema = StringEnum2(THINKING_LEVELS, {
|
|
667
|
-
description: "Optional requested Pi thinking level selected for this task difficulty; retained for every turn of the spawned agent."
|
|
668
|
-
});
|
|
669
|
-
var StatefulTimeoutSchema = Type2.Integer({
|
|
670
|
-
minimum: 1,
|
|
671
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
672
|
-
description: "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."
|
|
673
|
-
});
|
|
674
|
-
var DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS = 3e4;
|
|
675
|
-
var SubagentAwaitParams = Type2.Object({
|
|
676
|
-
agentId: Type2.String({
|
|
677
|
-
minLength: 1,
|
|
678
|
-
description: "Retained agent ID or canonical task path."
|
|
679
|
-
}),
|
|
680
|
-
timeoutMs: Type2.Optional(
|
|
681
|
-
Type2.Integer({
|
|
682
|
-
minimum: 1,
|
|
683
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
684
|
-
description: "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."
|
|
685
|
-
})
|
|
686
|
-
)
|
|
687
|
-
});
|
|
688
|
-
var StatefulTurnLimitFields = {
|
|
689
|
-
idleTimeoutMs: Type2.Optional(
|
|
690
|
-
Type2.Integer({
|
|
691
|
-
minimum: 1,
|
|
692
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
693
|
-
description: "Maximum milliseconds without a completed assistant turn or tool result; retained as the agent default."
|
|
694
|
-
})
|
|
695
|
-
),
|
|
696
|
-
maxTurns: Type2.Optional(
|
|
697
|
-
Type2.Integer({
|
|
698
|
-
minimum: 1,
|
|
699
|
-
maximum: MAX_SUBAGENT_TURNS,
|
|
700
|
-
description: "Maximum unfinished assistant turns; retained as the agent default. Omit rather than guessing a tight bound."
|
|
701
|
-
})
|
|
702
|
-
),
|
|
703
|
-
maxToolCalls: Type2.Optional(
|
|
704
|
-
Type2.Integer({
|
|
705
|
-
minimum: 1,
|
|
706
|
-
maximum: MAX_SUBAGENT_TOOL_CALLS,
|
|
707
|
-
description: "Maximum tool calls; retained as the agent default. Omit rather than guessing a tight bound."
|
|
708
|
-
})
|
|
709
|
-
)
|
|
710
|
-
};
|
|
711
|
-
function registerStatefulSubagents(pi, dependencies = {}) {
|
|
712
|
-
const settings = Object.hasOwn(dependencies, "settings") ? dependencies.settings ?? {} : readSubagentSettings()?.stateful ?? {};
|
|
713
|
-
const blockingEnabled = dependencies.blockingEnabled !== false;
|
|
714
|
-
const enabled = settings.enabled !== false;
|
|
715
|
-
const transportKind = resolveStatefulTransportKind(settings.transport);
|
|
716
|
-
let completionDelivery = resolveCompletionDelivery(settings.completionDelivery);
|
|
717
|
-
let runtimeLimits = resolveStatefulLimits(settings);
|
|
718
|
-
let completionBroker;
|
|
719
|
-
let peerBroker;
|
|
720
|
-
let registry;
|
|
721
|
-
let persistence;
|
|
722
|
-
let sweepTimer;
|
|
723
|
-
let runtimeGeneration = 0;
|
|
724
|
-
let runtimeTransition = Promise.resolve();
|
|
725
|
-
let workspaceManager = dependencies.workspaceManager;
|
|
726
|
-
const getWorkspaceManager = async () => {
|
|
727
|
-
if (workspaceManager) return workspaceManager;
|
|
728
|
-
const { WorkspaceManager } = await loadWorkspaceModule();
|
|
729
|
-
workspaceManager = new WorkspaceManager();
|
|
730
|
-
return workspaceManager;
|
|
731
|
-
};
|
|
732
|
-
const isolatedAgents = /* @__PURE__ */ new Map();
|
|
733
|
-
const seenMessageIds = /* @__PURE__ */ new Set();
|
|
734
|
-
const pendingIdempotentSpawns = /* @__PURE__ */ new Map();
|
|
735
|
-
const parentRuntime = { model: void 0, thinkingLevel: "off" };
|
|
736
|
-
const getCurrentSettings = () => dependencies.getSettings ? dependencies.getSettings() : readSubagentSettings();
|
|
737
|
-
const getCurrentStatefulSettings = () => dependencies.getSettings ? dependencies.getSettings()?.stateful ?? {} : settings;
|
|
738
|
-
const clearAgents = async () => {
|
|
739
|
-
const generation = runtimeGeneration;
|
|
740
|
-
const currentRegistry = registry;
|
|
741
|
-
const currentPersistence = persistence;
|
|
742
|
-
if (!currentRegistry) return 0;
|
|
743
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
744
|
-
const count = currentRegistry.list().length;
|
|
745
|
-
const clear = async () => {
|
|
746
|
-
await currentRegistry.closeAll();
|
|
747
|
-
if (generation !== runtimeGeneration) return;
|
|
748
|
-
await currentWorkspaceManager.cleanupAll();
|
|
749
|
-
isolatedAgents.clear();
|
|
750
|
-
seenMessageIds.clear();
|
|
751
|
-
await currentPersistence?.delete();
|
|
752
|
-
};
|
|
753
|
-
const transition = runtimeTransition.then(clear, clear);
|
|
754
|
-
runtimeTransition = transition.catch(() => void 0);
|
|
755
|
-
await transition;
|
|
756
|
-
return count;
|
|
757
|
-
};
|
|
758
|
-
const controller = {
|
|
759
|
-
getCompletionDelivery() {
|
|
760
|
-
return completionDelivery;
|
|
761
|
-
},
|
|
762
|
-
setCompletionDelivery(value) {
|
|
763
|
-
completionDelivery = value;
|
|
764
|
-
completionBroker?.setDelivery(value);
|
|
765
|
-
},
|
|
766
|
-
getRuntimeStatus() {
|
|
767
|
-
const counts = registry?.inspectionCounts() ?? { activeAgents: 0, retainedAgents: 0 };
|
|
768
|
-
return {
|
|
769
|
-
enabled,
|
|
770
|
-
initialized: registry !== void 0,
|
|
771
|
-
transport: transportKind,
|
|
772
|
-
completionDelivery,
|
|
773
|
-
limits: { ...runtimeLimits },
|
|
774
|
-
...counts
|
|
775
|
-
};
|
|
776
|
-
},
|
|
777
|
-
listAgents(includeClosed = false) {
|
|
778
|
-
return registry?.list(includeClosed) ?? [];
|
|
779
|
-
},
|
|
780
|
-
listRunInspection(includeClosed = false) {
|
|
781
|
-
return registry?.listInspection(includeClosed) ?? [];
|
|
782
|
-
},
|
|
783
|
-
getRunInspection(agentId) {
|
|
784
|
-
return registry?.getInspection(agentId);
|
|
785
|
-
},
|
|
786
|
-
clearAgents
|
|
787
|
-
};
|
|
788
|
-
if (!enabled) return controller;
|
|
789
|
-
const requireRegistry = () => {
|
|
790
|
-
if (!registry) throw new Error("Stateful subagents are not initialized for this session");
|
|
791
|
-
return registry;
|
|
792
|
-
};
|
|
793
|
-
pi.on("session_start", async (event, ctx) => {
|
|
794
|
-
const generation = ++runtimeGeneration;
|
|
795
|
-
completionBroker?.close();
|
|
796
|
-
completionBroker = void 0;
|
|
797
|
-
const previousPeerBroker = peerBroker;
|
|
798
|
-
peerBroker = void 0;
|
|
799
|
-
if (sweepTimer) clearInterval(sweepTimer);
|
|
800
|
-
sweepTimer = void 0;
|
|
801
|
-
const previousRegistry = registry;
|
|
802
|
-
registry = void 0;
|
|
803
|
-
persistence = void 0;
|
|
804
|
-
isolatedAgents.clear();
|
|
805
|
-
seenMessageIds.clear();
|
|
806
|
-
pendingIdempotentSpawns.clear();
|
|
807
|
-
const initialize = async () => {
|
|
808
|
-
await previousPeerBroker?.close();
|
|
809
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
810
|
-
const modules = await loadStatefulSessionModules();
|
|
811
|
-
const cleanupErrors = await modules.lifecycle.disposeStatefulRuntime(
|
|
812
|
-
previousRegistry,
|
|
813
|
-
currentWorkspaceManager
|
|
814
|
-
);
|
|
815
|
-
if (generation !== runtimeGeneration) return;
|
|
816
|
-
if (cleanupErrors.length > 0 && ctx.hasUI) {
|
|
817
|
-
ctx.ui.notify(
|
|
818
|
-
`Previous subagent runtime cleanup reported ${cleanupErrors.length} error(s).`,
|
|
819
|
-
"warning"
|
|
820
|
-
);
|
|
821
|
-
}
|
|
822
|
-
parentRuntime.model = ctx.model;
|
|
823
|
-
parentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(pi.getThinkingLevel());
|
|
824
|
-
const sessionSettings = getCurrentStatefulSettings();
|
|
825
|
-
const nextLimits = resolveStatefulLimits(sessionSettings);
|
|
826
|
-
const owner = ctx.sessionManager.getSessionId?.() ?? ctx.sessionManager.getSessionFile?.() ?? `ephemeral:${ctx.cwd}`;
|
|
827
|
-
const sessionPersistence = new modules.persistence.AgentPersistence(owner, {
|
|
828
|
-
retentionDays: sessionSettings.retentionDays,
|
|
829
|
-
maxStoredAgents: nextLimits.maxStoredAgents
|
|
830
|
-
});
|
|
831
|
-
let nextRegistry;
|
|
832
|
-
let transport;
|
|
833
|
-
const sessionBroker = new modules.broker.CompletionDeliveryBroker(
|
|
834
|
-
pi,
|
|
835
|
-
ctx,
|
|
836
|
-
completionDelivery,
|
|
837
|
-
{
|
|
838
|
-
onDeliveryError: (error) => {
|
|
839
|
-
if (!ctx.hasUI) return;
|
|
840
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
841
|
-
ctx.ui.notify(`Subagent completion delivery failed: ${reason}`, "warning");
|
|
842
|
-
},
|
|
843
|
-
onDeliveryAttempt: (completions, input) => {
|
|
844
|
-
if (generation !== runtimeGeneration) return;
|
|
845
|
-
for (const completion of completions) {
|
|
846
|
-
dependencies.usageRecording?.recordCompletionDeliveryAttempt(completion, input);
|
|
847
|
-
}
|
|
848
|
-
},
|
|
849
|
-
onAcknowledged: (completions, deliveredAt) => {
|
|
850
|
-
if (generation !== runtimeGeneration) return;
|
|
851
|
-
for (const completion of completions) {
|
|
852
|
-
dependencies.usageRecording?.recordCompletionVisible(completion);
|
|
853
|
-
void nextRegistry.markCompletionDelivered(completion.completionId, deliveredAt).catch((error) => {
|
|
854
|
-
if (!ctx.hasUI || generation !== runtimeGeneration) return;
|
|
855
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
856
|
-
ctx.ui.notify(`Subagent completion acknowledgement failed: ${reason}`, "warning");
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
);
|
|
862
|
-
const sessionPeerBroker = new modules.peerCommunication.PeerCommunicationBroker({
|
|
863
|
-
getRegistry: () => nextRegistry,
|
|
864
|
-
sendRoot: ({ message, senderPath }) => {
|
|
865
|
-
pi.appendEntry("pi-subagent-peer-message", {
|
|
866
|
-
messageId: message.id,
|
|
867
|
-
senderId: message.senderId,
|
|
868
|
-
senderPath,
|
|
869
|
-
content: modules.context.redactPrivateText(message.content)
|
|
870
|
-
});
|
|
871
|
-
pi.sendMessage(
|
|
872
|
-
{
|
|
873
|
-
customType: "pi-subagent-peer-message",
|
|
874
|
-
content: [
|
|
875
|
-
"Message Type: SUBAGENT_PEER_MESSAGE",
|
|
876
|
-
"Protocol: pi-subagents:v1",
|
|
877
|
-
`Message ID: ${message.id}`,
|
|
878
|
-
`Sender ID: ${message.senderId}`,
|
|
879
|
-
`Sender Path: ${senderPath}`,
|
|
880
|
-
"Payload:",
|
|
881
|
-
message.content
|
|
882
|
-
].join("\n"),
|
|
883
|
-
display: true,
|
|
884
|
-
details: { ...message, senderPath }
|
|
885
|
-
},
|
|
886
|
-
{ deliverAs: "steer", triggerTurn: false }
|
|
887
|
-
);
|
|
888
|
-
},
|
|
889
|
-
dispatch: (recipient, message) => transport.deliverMessage?.(recipient, message) ?? false
|
|
890
|
-
});
|
|
891
|
-
transport = modules.transport.createStatefulTransport({
|
|
892
|
-
kind: transportKind,
|
|
893
|
-
modelRegistry: ctx.modelRegistry,
|
|
894
|
-
getParentRuntime: () => ({ ...parentRuntime }),
|
|
895
|
-
getSettings: getCurrentSettings,
|
|
896
|
-
createInProcessSession: dependencies.createInProcessSession,
|
|
897
|
-
peerRuntime: sessionPeerBroker,
|
|
898
|
-
loadTransport: dependencies.loadTransport
|
|
899
|
-
});
|
|
900
|
-
nextRegistry = new modules.registry.AgentRegistry(transport, {
|
|
901
|
-
maxAgents: nextLimits.maxAgents,
|
|
902
|
-
maxActiveTurns: nextLimits.maxActiveTurns,
|
|
903
|
-
maxDepth: nextLimits.maxDepth,
|
|
904
|
-
maxChildrenPerAgent: nextLimits.maxChildrenPerAgent,
|
|
905
|
-
maxMailboxMessages: sessionSettings.maxMailboxMessages,
|
|
906
|
-
maxMailboxMessageBytes: sessionSettings.maxMailboxMessageBytes,
|
|
907
|
-
idleTtlMs: sessionSettings.idleTtlMs,
|
|
908
|
-
onChange: async (agents) => {
|
|
909
|
-
if (generation !== runtimeGeneration) return;
|
|
910
|
-
await sessionPersistence.save(agents);
|
|
911
|
-
if (generation !== runtimeGeneration) return;
|
|
912
|
-
dependencies.usageRecording?.observeAgents(agents);
|
|
913
|
-
for (const agent of agents) {
|
|
914
|
-
for (const message of agent.mailbox) {
|
|
915
|
-
if (seenMessageIds.has(message.id)) continue;
|
|
916
|
-
seenMessageIds.add(message.id);
|
|
917
|
-
pi.appendEntry("pi-subagent-message", {
|
|
918
|
-
senderId: message.senderId,
|
|
919
|
-
recipientId: message.recipientId,
|
|
920
|
-
content: modules.context.redactPrivateText(message.content).slice(0, 160)
|
|
921
|
-
});
|
|
922
|
-
if (agent.state === "running" && message.deduplicationKey?.startsWith("completion:")) {
|
|
923
|
-
try {
|
|
924
|
-
await transport.deliverMessage?.(agent, {
|
|
925
|
-
...message,
|
|
926
|
-
content: modules.context.redactPrivateText(message.content)
|
|
927
|
-
});
|
|
928
|
-
} catch {
|
|
929
|
-
}
|
|
930
|
-
if (generation !== runtimeGeneration) return;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
},
|
|
935
|
-
onTurnComplete: (completion) => {
|
|
936
|
-
if (generation !== runtimeGeneration) return;
|
|
937
|
-
dependencies.usageRecording?.recordChildCompletion(completion);
|
|
938
|
-
if (completion.recipientId === "root") sessionBroker.enqueue(completion);
|
|
939
|
-
}
|
|
940
|
-
});
|
|
941
|
-
const persisted = sessionPersistence.load();
|
|
942
|
-
const orphanCleanupFailures = await modules.lifecycle.cleanupPersistedWorkspaces(
|
|
943
|
-
persisted,
|
|
944
|
-
currentWorkspaceManager
|
|
945
|
-
);
|
|
946
|
-
if (generation !== runtimeGeneration) {
|
|
947
|
-
sessionBroker.close();
|
|
948
|
-
await sessionPeerBroker.close();
|
|
949
|
-
await modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);
|
|
950
|
-
return;
|
|
951
|
-
}
|
|
952
|
-
if (ctx.hasUI && orphanCleanupFailures > 0) {
|
|
953
|
-
ctx.ui.notify("Some orphaned subagent worktrees could not be cleaned", "warning");
|
|
954
|
-
}
|
|
955
|
-
const restored = persisted.filter(
|
|
956
|
-
(agent) => agent.workspaceMode !== "worktree" && (agent.agentScope !== "project" && agent.agentScope !== "both" || ctx.isProjectTrusted())
|
|
957
|
-
).flatMap((agent) => {
|
|
958
|
-
try {
|
|
959
|
-
const target = modules.cwdPolicy.resolveSubagentTarget({
|
|
960
|
-
workspace: ctx.cwd,
|
|
961
|
-
requestedCwd: agent.cwd,
|
|
962
|
-
currentProjectTrusted: ctx.isProjectTrusted()
|
|
963
|
-
});
|
|
964
|
-
return [
|
|
965
|
-
{ ...agent, cwd: target.cwd, target: modules.cwdPolicy.targetPolicyAudit(target) }
|
|
966
|
-
];
|
|
967
|
-
} catch {
|
|
968
|
-
return [];
|
|
969
|
-
}
|
|
970
|
-
});
|
|
971
|
-
for (const agent of restored) {
|
|
972
|
-
for (const message of agent.mailbox) seenMessageIds.add(message.id);
|
|
973
|
-
}
|
|
974
|
-
nextRegistry.restore(restored);
|
|
975
|
-
const branchRequirements = completionRequirementsFromBranch(ctx.sessionManager.getBranch());
|
|
976
|
-
const branchOwnsRequirementState = branchRequirements.observedState || event.reason === "fork" || event.reason === "new";
|
|
977
|
-
nextRegistry.reconcileCompletionRequirements(
|
|
978
|
-
branchRequirements.records,
|
|
979
|
-
branchOwnsRequirementState
|
|
980
|
-
);
|
|
981
|
-
if (branchOwnsRequirementState) {
|
|
982
|
-
try {
|
|
983
|
-
await sessionPersistence.save(nextRegistry.list(true));
|
|
984
|
-
} catch (error) {
|
|
985
|
-
if (generation === runtimeGeneration && ctx.hasUI) {
|
|
986
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
987
|
-
ctx.ui.notify(
|
|
988
|
-
`Subagent requirement reconciliation could not be persisted yet: ${reason}`,
|
|
989
|
-
"warning"
|
|
990
|
-
);
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
|
-
if (generation !== runtimeGeneration) {
|
|
995
|
-
sessionBroker.close();
|
|
996
|
-
await sessionPeerBroker.close();
|
|
997
|
-
await modules.lifecycle.disposeStatefulRuntime(nextRegistry, currentWorkspaceManager);
|
|
998
|
-
return;
|
|
999
|
-
}
|
|
1000
|
-
registry = nextRegistry;
|
|
1001
|
-
persistence = sessionPersistence;
|
|
1002
|
-
completionBroker = sessionBroker;
|
|
1003
|
-
peerBroker = sessionPeerBroker;
|
|
1004
|
-
for (const completion of nextRegistry.listPendingCompletions()) {
|
|
1005
|
-
if (completion.recipientId === "root") sessionBroker.enqueue(completion);
|
|
1006
|
-
}
|
|
1007
|
-
runtimeLimits = nextLimits;
|
|
1008
|
-
const sweepEveryMs = Math.max(
|
|
1009
|
-
1e3,
|
|
1010
|
-
Math.min(sessionSettings.idleTtlMs ?? 60 * 60 * 1e3, 6e4)
|
|
1011
|
-
);
|
|
1012
|
-
sweepTimer = setInterval(() => {
|
|
1013
|
-
void nextRegistry.sweepExpired().catch((error) => {
|
|
1014
|
-
if (!ctx.hasUI || generation !== runtimeGeneration) return;
|
|
1015
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
1016
|
-
ctx.ui.notify(`Subagent expiry cleanup failed: ${reason}`, "warning");
|
|
1017
|
-
});
|
|
1018
|
-
}, sweepEveryMs);
|
|
1019
|
-
sweepTimer.unref();
|
|
1020
|
-
};
|
|
1021
|
-
const transition = runtimeTransition.then(initialize, initialize);
|
|
1022
|
-
runtimeTransition = transition.catch(() => void 0);
|
|
1023
|
-
await transition;
|
|
1024
|
-
});
|
|
1025
|
-
pi.on("agent_start", () => {
|
|
1026
|
-
completionBroker?.onParentTurnStart();
|
|
1027
|
-
});
|
|
1028
|
-
pi.on("context", (event) => {
|
|
1029
|
-
completionBroker?.onParentContext(event.messages);
|
|
1030
|
-
});
|
|
1031
|
-
pi.on("agent_settled", () => {
|
|
1032
|
-
completionBroker?.onParentSettled();
|
|
1033
|
-
});
|
|
1034
|
-
pi.on("model_select", (event) => {
|
|
1035
|
-
parentRuntime.model = event.model;
|
|
1036
|
-
});
|
|
1037
|
-
pi.on("thinking_level_select", (event) => {
|
|
1038
|
-
parentRuntime.thinkingLevel = normalizeRuntimeThinkingLevel(event.level);
|
|
1039
|
-
});
|
|
1040
|
-
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1041
|
-
runtimeGeneration++;
|
|
1042
|
-
completionBroker?.close();
|
|
1043
|
-
completionBroker = void 0;
|
|
1044
|
-
const previousPeerBroker = peerBroker;
|
|
1045
|
-
peerBroker = void 0;
|
|
1046
|
-
if (sweepTimer) clearInterval(sweepTimer);
|
|
1047
|
-
sweepTimer = void 0;
|
|
1048
|
-
const previousRegistry = registry;
|
|
1049
|
-
registry = void 0;
|
|
1050
|
-
persistence = void 0;
|
|
1051
|
-
isolatedAgents.clear();
|
|
1052
|
-
seenMessageIds.clear();
|
|
1053
|
-
pendingIdempotentSpawns.clear();
|
|
1054
|
-
const shutdown = async () => {
|
|
1055
|
-
await previousPeerBroker?.close();
|
|
1056
|
-
const currentWorkspaceManager = await getWorkspaceManager();
|
|
1057
|
-
const { disposeStatefulRuntime } = await import("./stateful-lifecycle-JAR6K55H.ts");
|
|
1058
|
-
const errors = await disposeStatefulRuntime(previousRegistry, currentWorkspaceManager);
|
|
1059
|
-
if (errors.length > 0 && ctx.hasUI) {
|
|
1060
|
-
ctx.ui.notify(`Subagent shutdown cleanup reported ${errors.length} error(s).`, "warning");
|
|
1061
|
-
}
|
|
1062
|
-
};
|
|
1063
|
-
const transition = runtimeTransition.then(shutdown, shutdown);
|
|
1064
|
-
runtimeTransition = transition.catch(() => void 0);
|
|
1065
|
-
await transition;
|
|
1066
|
-
});
|
|
1067
|
-
const spawnTool = defineTool({
|
|
1068
|
-
name: "subagent_spawn",
|
|
1069
|
-
label: "Spawn Subagent",
|
|
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.",
|
|
1071
|
-
promptSnippet: "Start a reusable detached subagent; completion is delivered asynchronously",
|
|
1072
|
-
promptGuidelines: createSpawnPromptGuidelines(blockingEnabled),
|
|
1073
|
-
parameters: grammarSafeToolObject({
|
|
1074
|
-
agent: Type2.String({ minLength: 1 }),
|
|
1075
|
-
taskName: Type2.Optional(
|
|
1076
|
-
Type2.String({
|
|
1077
|
-
minLength: 1,
|
|
1078
|
-
maxLength: MAX_TASK_NAME_LENGTH,
|
|
1079
|
-
pattern: "^[a-z0-9_]+$",
|
|
1080
|
-
description: "Canonical path segment for this task; use lowercase letters, digits, and underscores."
|
|
1081
|
-
})
|
|
1082
|
-
),
|
|
1083
|
-
task: Type2.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
|
|
1084
|
-
thinkingLevel: Type2.Optional(StatefulThinkingLevelSchema),
|
|
1085
|
-
timeoutMs: Type2.Optional(StatefulTimeoutSchema),
|
|
1086
|
-
...StatefulTurnLimitFields,
|
|
1087
|
-
cwd: Type2.Optional(Type2.String()),
|
|
1088
|
-
agentScope: Type2.Optional(ScopeSchema),
|
|
1089
|
-
confirmProjectAgents: Type2.Optional(Type2.Boolean({ default: true })),
|
|
1090
|
-
context: Type2.Optional(ContextModeSchema),
|
|
1091
|
-
contextEntryIds: Type2.Optional(
|
|
1092
|
-
Type2.Array(Type2.String(), { description: "Optional selected session entry IDs." })
|
|
1093
|
-
),
|
|
1094
|
-
parentId: Type2.Optional(
|
|
1095
|
-
Type2.String({ description: "Optional parent agent ID or canonical task path." })
|
|
1096
|
-
),
|
|
1097
|
-
allowConcurrentWrites: Type2.Optional(
|
|
1098
|
-
Type2.Boolean({
|
|
1099
|
-
description: "Deprecated compatibility field; shared-workspace concurrency is allowed by default."
|
|
1100
|
-
})
|
|
1101
|
-
),
|
|
1102
|
-
workspaceMode: Type2.Optional(
|
|
1103
|
-
StringEnum2(["shared", "worktree"], {
|
|
1104
|
-
description: "Use the shared workspace (default) or an opt-in disposable Git worktree."
|
|
1105
|
-
})
|
|
1106
|
-
),
|
|
1107
|
-
contract: Type2.Optional(DelegationContractSchema),
|
|
1108
|
-
idempotencyKey: Type2.Optional(
|
|
1109
|
-
Type2.String({
|
|
1110
|
-
minLength: 1,
|
|
1111
|
-
maxLength: MAX_SPAWN_IDEMPOTENCY_KEY_LENGTH,
|
|
1112
|
-
description: "Reuse the same retained agent for an exact accepted spawn retry."
|
|
1113
|
-
})
|
|
1114
|
-
),
|
|
1115
|
-
resultFormat: Type2.Optional(
|
|
1116
|
-
StringEnum2(SUBAGENT_RESULT_FORMATS, {
|
|
1117
|
-
description: "Use text (default), structured-v1, or the evidence-preserving structured-v2 completion contract."
|
|
1118
|
-
})
|
|
1119
|
-
),
|
|
1120
|
-
completionRequirement: Type2.Optional(CompletionRequirementModeSchema)
|
|
1121
|
-
}),
|
|
1122
|
-
...createStatefulToolRenderer("spawn"),
|
|
1123
|
-
async execute(_id, params, signal, _update, ctx) {
|
|
1124
|
-
const generation = runtimeGeneration;
|
|
1125
|
-
const capturedRegistry = registry;
|
|
1126
|
-
let modules;
|
|
1127
|
-
try {
|
|
1128
|
-
modules = await loadStatefulSpawnModules();
|
|
1129
|
-
} catch (error) {
|
|
1130
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1131
|
-
throw error;
|
|
1132
|
-
}
|
|
1133
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1134
|
-
let currentWorkspaceManager;
|
|
1135
|
-
try {
|
|
1136
|
-
currentWorkspaceManager = await getWorkspaceManager();
|
|
1137
|
-
} catch (error) {
|
|
1138
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1139
|
-
throw error;
|
|
1140
|
-
}
|
|
1141
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1142
|
-
const scope = params.agentScope ?? "user";
|
|
1143
|
-
const resultFormat = params.resultFormat ?? "text";
|
|
1144
|
-
const contract = modules.delegationContract.normalizeDelegationContract(params.contract);
|
|
1145
|
-
if (params.contract !== void 0 && !contract) {
|
|
1146
|
-
throw new Error(
|
|
1147
|
-
"subagent_spawn contract must be a valid pi-subagents:delegation:v2 object"
|
|
1148
|
-
);
|
|
1149
|
-
}
|
|
1150
|
-
modules.runtimePolicy.assertSubagentDepthAllowed();
|
|
1151
|
-
assertSpawnIdempotencyKey(params.idempotencyKey);
|
|
1152
|
-
const currentSettings = getCurrentSettings();
|
|
1153
|
-
const target = modules.cwdPolicy.resolveSubagentTarget({
|
|
1154
|
-
workspace: ctx.cwd,
|
|
1155
|
-
requestedCwd: params.cwd,
|
|
1156
|
-
currentProjectTrusted: ctx.isProjectTrusted()
|
|
1157
|
-
});
|
|
1158
|
-
modules.cwdPolicy.assertDelegationTargetAllowed(
|
|
1159
|
-
target,
|
|
1160
|
-
currentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY
|
|
1161
|
-
);
|
|
1162
|
-
const cwd = target.cwd;
|
|
1163
|
-
const mode = resolveSpawnContextMode(params.context, params.contextEntryIds);
|
|
1164
|
-
const snapshot = modules.context.buildContextSnapshot(
|
|
1165
|
-
ctx.sessionManager.getBranch(),
|
|
1166
|
-
mode,
|
|
1167
|
-
DEFAULT_MAX_CONTEXT_BYTES,
|
|
1168
|
-
params.contextEntryIds
|
|
1169
|
-
);
|
|
1170
|
-
if ((scope === "project" || scope === "both") && !ctx.isProjectTrusted()) {
|
|
1171
|
-
throw new Error("Project-local subagent definitions require a trusted project");
|
|
1172
|
-
}
|
|
1173
|
-
const resolvedAgents = modules.agents.discoverAgents(cwd, scope, currentSettings).agents;
|
|
1174
|
-
const resolvedAgent = resolvedAgents.find((agent) => agent.name === params.agent);
|
|
1175
|
-
if (!resolvedAgent) {
|
|
1176
|
-
const available = resolvedAgents.map((agent) => agent.name).join(", ") || "none";
|
|
1177
|
-
throw new Error(`Unknown subagent ${params.agent}. Available agents: ${available}`);
|
|
1178
|
-
}
|
|
1179
|
-
const targetSnapshot = modules.cwdPolicy.targetPolicyAudit(target);
|
|
1180
|
-
const { executionPlan, semanticSnapshot } = await modules.retainedSemanticState.buildRetainedSemanticState({
|
|
1181
|
-
agent: resolvedAgent,
|
|
1182
|
-
contract,
|
|
1183
|
-
target: targetSnapshot,
|
|
1184
|
-
cwd,
|
|
1185
|
-
workspaceMode: params.workspaceMode === "worktree" ? "worktree" : "shared",
|
|
1186
|
-
transport: transportKind,
|
|
1187
|
-
resultFormat,
|
|
1188
|
-
thinkingLevel: params.thinkingLevel,
|
|
1189
|
-
timeoutMs: params.timeoutMs,
|
|
1190
|
-
taskGeneration: 1
|
|
1191
|
-
});
|
|
1192
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1193
|
-
const requestHash = modules.spawnIdempotency.hashSpawnRequest({
|
|
1194
|
-
agent: params.agent,
|
|
1195
|
-
taskName: params.taskName,
|
|
1196
|
-
task: params.task,
|
|
1197
|
-
cwd,
|
|
1198
|
-
agentScope: scope,
|
|
1199
|
-
thinkingLevel: params.thinkingLevel,
|
|
1200
|
-
timeoutMs: params.timeoutMs,
|
|
1201
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
1202
|
-
maxTurns: params.maxTurns,
|
|
1203
|
-
maxToolCalls: params.maxToolCalls,
|
|
1204
|
-
parentId: params.parentId,
|
|
1205
|
-
context: snapshot.text || void 0,
|
|
1206
|
-
contextSourceIds: snapshot.sourceIds,
|
|
1207
|
-
workspaceMode: params.workspaceMode ?? "shared",
|
|
1208
|
-
allowConcurrentWrites: params.allowConcurrentWrites ?? false,
|
|
1209
|
-
contract,
|
|
1210
|
-
resultFormat,
|
|
1211
|
-
completionRequirement: params.completionRequirement ?? "background"
|
|
1212
|
-
});
|
|
1213
|
-
if (!capturedRegistry) {
|
|
1214
|
-
throw new Error("Stateful subagents are not initialized for this session");
|
|
1215
|
-
}
|
|
1216
|
-
const ownedRegistry = capturedRegistry;
|
|
1217
|
-
const retained = ownedRegistry.findBySpawnIdempotencyKey(params.idempotencyKey, requestHash);
|
|
1218
|
-
if (retained) return result(retained, `Reused ${retained.agent} as ${retained.id}.`);
|
|
1219
|
-
const foundPending = params.idempotencyKey ? pendingIdempotentSpawns.get(params.idempotencyKey) : void 0;
|
|
1220
|
-
if (params.idempotencyKey && foundPending && foundPending.generation !== generation && pendingIdempotentSpawns.get(params.idempotencyKey) === foundPending) {
|
|
1221
|
-
pendingIdempotentSpawns.delete(params.idempotencyKey);
|
|
1222
|
-
}
|
|
1223
|
-
const pending = foundPending?.generation === generation ? foundPending : void 0;
|
|
1224
|
-
if (pending) {
|
|
1225
|
-
if (pending.requestHash !== requestHash) {
|
|
1226
|
-
throw new Error("The subagent_spawn idempotencyKey is pending with different parameters");
|
|
1227
|
-
}
|
|
1228
|
-
const agent = await waitForOwnedSpawn(pending.promise, signal);
|
|
1229
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1230
|
-
return result(agent, `Reused ${agent.agent} as ${agent.id}.`);
|
|
1231
|
-
}
|
|
1232
|
-
let resolvePending;
|
|
1233
|
-
let rejectPending;
|
|
1234
|
-
let ownedPending;
|
|
1235
|
-
if (params.idempotencyKey) {
|
|
1236
|
-
const promise = new Promise((resolve, reject) => {
|
|
1237
|
-
resolvePending = resolve;
|
|
1238
|
-
rejectPending = reject;
|
|
1239
|
-
});
|
|
1240
|
-
void promise.catch(() => void 0);
|
|
1241
|
-
ownedPending = { generation, requestHash, promise };
|
|
1242
|
-
pendingIdempotentSpawns.set(params.idempotencyKey, ownedPending);
|
|
1243
|
-
}
|
|
1244
|
-
try {
|
|
1245
|
-
await confirmProjectAgent(
|
|
1246
|
-
params.agent,
|
|
1247
|
-
scope,
|
|
1248
|
-
params.confirmProjectAgents ?? true,
|
|
1249
|
-
ctx,
|
|
1250
|
-
cwd,
|
|
1251
|
-
currentSettings
|
|
1252
|
-
);
|
|
1253
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1254
|
-
if (params.workspaceMode === "worktree" && resolvedAgent.source === "project") {
|
|
1255
|
-
throw new Error("Project-local subagent definitions cannot run in a detached worktree");
|
|
1256
|
-
}
|
|
1257
|
-
const requestedCwd = cwd;
|
|
1258
|
-
const workspaceOwner = `pending-${randomUUID()}`;
|
|
1259
|
-
const workspace = params.workspaceMode === "worktree" ? await currentWorkspaceManager.create(workspaceOwner, requestedCwd) : void 0;
|
|
1260
|
-
try {
|
|
1261
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1262
|
-
} catch (error) {
|
|
1263
|
-
if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
1264
|
-
throw error;
|
|
1265
|
-
}
|
|
1266
|
-
let agent;
|
|
1267
|
-
try {
|
|
1268
|
-
const capabilityGrant = modules.capabilityGrant.issueCapabilityGrant(
|
|
1269
|
-
executionPlan,
|
|
1270
|
-
Date.now(),
|
|
1271
|
-
Math.max(1, (params.timeoutMs ?? resolvedAgent.timeoutMs ?? 6e5) + 6e4)
|
|
1272
|
-
);
|
|
1273
|
-
agent = await ownedRegistry.spawn({
|
|
1274
|
-
agent: params.agent,
|
|
1275
|
-
taskName: params.taskName,
|
|
1276
|
-
task: params.task,
|
|
1277
|
-
cwd: workspace?.path ?? requestedCwd,
|
|
1278
|
-
agentScope: scope,
|
|
1279
|
-
thinkingLevel: params.thinkingLevel,
|
|
1280
|
-
timeoutMs: params.timeoutMs,
|
|
1281
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
1282
|
-
maxTurns: params.maxTurns,
|
|
1283
|
-
maxToolCalls: params.maxToolCalls,
|
|
1284
|
-
parentId: params.parentId,
|
|
1285
|
-
context: snapshot.text || void 0,
|
|
1286
|
-
contextSourceIds: snapshot.sourceIds,
|
|
1287
|
-
contextTruncated: snapshot.truncated,
|
|
1288
|
-
contextTurns: snapshot.turns,
|
|
1289
|
-
contextBytes: Buffer.byteLength(snapshot.text, "utf8"),
|
|
1290
|
-
workspaceMode: workspace ? "worktree" : void 0,
|
|
1291
|
-
spawnIdempotencyKey: params.idempotencyKey,
|
|
1292
|
-
spawnRequestHash: params.idempotencyKey ? requestHash : void 0,
|
|
1293
|
-
contract,
|
|
1294
|
-
resultFormat: resultFormat === "text" ? void 0 : resultFormat,
|
|
1295
|
-
completionRequirement: params.completionRequirement ?? "background",
|
|
1296
|
-
executionPlan,
|
|
1297
|
-
capabilityGrant,
|
|
1298
|
-
semanticSnapshot,
|
|
1299
|
-
semanticCompatibility: { status: "compatible", changedComponents: [] },
|
|
1300
|
-
target: targetSnapshot
|
|
1301
|
-
});
|
|
1302
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1303
|
-
} catch (error) {
|
|
1304
|
-
if (agent) await ownedRegistry.closeTree(agent.id).catch(() => void 0);
|
|
1305
|
-
if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
1306
|
-
throw error;
|
|
1307
|
-
}
|
|
1308
|
-
if (!agent) throw new Error("Subagent spawn completed without a retained agent");
|
|
1309
|
-
if (workspace && agent.cwd === workspace.path) isolatedAgents.set(agent.id, workspaceOwner);
|
|
1310
|
-
else if (workspace) await currentWorkspaceManager.cleanup(workspaceOwner);
|
|
1311
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1312
|
-
resolvePending?.(agent);
|
|
1313
|
-
const deliveryNote = completionDelivery === "auto-resume" ? "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." : "The current response must not depend on the result because next-turn delivery will not wake an idle root.";
|
|
1314
|
-
const requirementNote = params.completionRequirement === "required" ? "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." : "This run is background work and does not block the parent final answer.";
|
|
1315
|
-
return result(
|
|
1316
|
-
agent,
|
|
1317
|
-
`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.`
|
|
1318
|
-
);
|
|
1319
|
-
} catch (error) {
|
|
1320
|
-
rejectPending?.(error);
|
|
1321
|
-
throw error;
|
|
1322
|
-
} finally {
|
|
1323
|
-
if (params.idempotencyKey && ownedPending && pendingIdempotentSpawns.get(params.idempotencyKey) === ownedPending) {
|
|
1324
|
-
pendingIdempotentSpawns.delete(params.idempotencyKey);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
});
|
|
1329
|
-
pi.registerTool(spawnTool);
|
|
1330
|
-
pi.registerTool({
|
|
1331
|
-
name: "subagent_send",
|
|
1332
|
-
label: "Send Subagent Follow-up",
|
|
1333
|
-
description: "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.",
|
|
1334
|
-
promptSnippet: "Start a new detached follow-up turn on a retained subagent",
|
|
1335
|
-
parameters: Type2.Object({
|
|
1336
|
-
agentId: Type2.String({ description: "Retained agent ID or canonical task path." }),
|
|
1337
|
-
task: Type2.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
|
|
1338
|
-
timeoutMs: Type2.Optional(
|
|
1339
|
-
Type2.Integer({
|
|
1340
|
-
minimum: 1,
|
|
1341
|
-
maximum: MAX_SUBAGENT_TIMEOUT_MS,
|
|
1342
|
-
description: "Optional work deadline for this follow-up turn. On expiry, Pi aborts the work and makes one separately bounded summary attempt."
|
|
1343
|
-
})
|
|
1344
|
-
),
|
|
1345
|
-
...StatefulTurnLimitFields,
|
|
1346
|
-
completionRequirement: Type2.Optional(CompletionRequirementModeSchema),
|
|
1347
|
-
revalidate: Type2.Optional(
|
|
1348
|
-
Type2.Boolean({
|
|
1349
|
-
description: "Accept the current semantic resource snapshot after a reported mismatch before starting this follow-up."
|
|
1350
|
-
})
|
|
1351
|
-
),
|
|
1352
|
-
allowConcurrentWrites: Type2.Optional(
|
|
1353
|
-
Type2.Boolean({
|
|
1354
|
-
description: "Deprecated compatibility field; shared-workspace concurrency is allowed by default."
|
|
1355
|
-
})
|
|
1356
|
-
)
|
|
1357
|
-
}),
|
|
1358
|
-
...createStatefulToolRenderer("send"),
|
|
1359
|
-
async execute(_id, params, signal, _update, ctx) {
|
|
1360
|
-
const generation = runtimeGeneration;
|
|
1361
|
-
const ownedRegistry = requireRegistry();
|
|
1362
|
-
let modules;
|
|
1363
|
-
try {
|
|
1364
|
-
modules = await loadStatefulSpawnModules();
|
|
1365
|
-
} catch (error) {
|
|
1366
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1367
|
-
throw error;
|
|
1368
|
-
}
|
|
1369
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1370
|
-
const currentSettings = getCurrentSettings();
|
|
1371
|
-
const existing = ownedRegistry.get(params.agentId);
|
|
1372
|
-
if (!existing) throw new Error(`Unknown subagent: ${params.agentId}`);
|
|
1373
|
-
const currentAgent = modules.agents.discoverAgents(existing.cwd, existing.agentScope ?? "user", currentSettings).agents.find((agent2) => agent2.name === existing.agent);
|
|
1374
|
-
if (!currentAgent) throw new Error(`Unknown retained subagent definition: ${existing.agent}`);
|
|
1375
|
-
const resolvedFollowUpTarget = existing.workspaceMode === "worktree" ? void 0 : modules.cwdPolicy.resolveSubagentTarget({
|
|
1376
|
-
workspace: ctx.cwd,
|
|
1377
|
-
requestedCwd: existing.cwd,
|
|
1378
|
-
currentProjectTrusted: ctx.isProjectTrusted()
|
|
1379
|
-
});
|
|
1380
|
-
if (resolvedFollowUpTarget) {
|
|
1381
|
-
modules.cwdPolicy.assertDelegationTargetAllowed(
|
|
1382
|
-
resolvedFollowUpTarget,
|
|
1383
|
-
currentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY
|
|
1384
|
-
);
|
|
1385
|
-
}
|
|
1386
|
-
if (existing.workspaceMode === "worktree" && !existing.target) {
|
|
1387
|
-
throw new Error("Retained worktree is missing its trusted target snapshot");
|
|
1388
|
-
}
|
|
1389
|
-
const currentTarget = existing.workspaceMode === "worktree" && existing.target ? existing.target : modules.cwdPolicy.targetPolicyAudit(
|
|
1390
|
-
resolvedFollowUpTarget
|
|
1391
|
-
);
|
|
1392
|
-
const { executionPlan: currentPlan, semanticSnapshot: currentSnapshot } = await modules.retainedSemanticState.buildRetainedSemanticState({
|
|
1393
|
-
agent: currentAgent,
|
|
1394
|
-
contract: existing.contract,
|
|
1395
|
-
target: currentTarget,
|
|
1396
|
-
cwd: existing.cwd,
|
|
1397
|
-
workspaceMode: existing.workspaceMode === "worktree" ? "worktree" : "shared",
|
|
1398
|
-
transport: transportKind,
|
|
1399
|
-
resultFormat: existing.resultFormat ?? "text",
|
|
1400
|
-
thinkingLevel: existing.thinkingLevel,
|
|
1401
|
-
timeoutMs: params.timeoutMs ?? existing.timeoutMs,
|
|
1402
|
-
taskGeneration: (existing.executionPlan?.taskGeneration ?? 0) + 1,
|
|
1403
|
-
cancellationLineage: [
|
|
1404
|
-
...existing.executionPlan?.cancellationLineage ?? [],
|
|
1405
|
-
...existing.state === "interrupted" && existing.executionPlan?.id ? [existing.executionPlan.id] : []
|
|
1406
|
-
]
|
|
1407
|
-
});
|
|
1408
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1409
|
-
const compatibility = existing.semanticSnapshot ? modules.semanticSnapshot.evaluateSemanticCompatibility(
|
|
1410
|
-
existing.semanticSnapshot,
|
|
1411
|
-
currentSnapshot
|
|
1412
|
-
) : { status: "warning", changedComponents: ["legacy-missing-snapshot"] };
|
|
1413
|
-
if ((compatibility.status === "needs-revalidation" || compatibility.status === "rejected") && params.revalidate !== true) {
|
|
1414
|
-
throw new Error(
|
|
1415
|
-
`Subagent semantic resources changed; retry with revalidate: true after reviewing: ${compatibility.changedComponents.join(", ")}`
|
|
1416
|
-
);
|
|
1417
|
-
}
|
|
1418
|
-
await confirmProjectAgent(
|
|
1419
|
-
existing.agent,
|
|
1420
|
-
existing.agentScope ?? "user",
|
|
1421
|
-
false,
|
|
1422
|
-
ctx,
|
|
1423
|
-
existing.cwd,
|
|
1424
|
-
currentSettings
|
|
1425
|
-
);
|
|
1426
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1427
|
-
const currentGrant = modules.capabilityGrant.issueCapabilityGrant(
|
|
1428
|
-
currentPlan,
|
|
1429
|
-
Date.now(),
|
|
1430
|
-
Math.max(1, (params.timeoutMs ?? existing.timeoutMs ?? 6e5) + 6e4)
|
|
1431
|
-
);
|
|
1432
|
-
await ownedRegistry.updateSemanticState(
|
|
1433
|
-
existing.id,
|
|
1434
|
-
currentPlan,
|
|
1435
|
-
currentGrant,
|
|
1436
|
-
currentSnapshot,
|
|
1437
|
-
params.revalidate === true && compatibility.status !== "compatible" ? { status: "warning", changedComponents: compatibility.changedComponents } : compatibility
|
|
1438
|
-
);
|
|
1439
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1440
|
-
const agent = await ownedRegistry.followUp(params.agentId, params.task, {
|
|
1441
|
-
timeoutMs: params.timeoutMs,
|
|
1442
|
-
idleTimeoutMs: params.idleTimeoutMs,
|
|
1443
|
-
maxTurns: params.maxTurns,
|
|
1444
|
-
maxToolCalls: params.maxToolCalls,
|
|
1445
|
-
completionRequirement: params.completionRequirement ?? "background"
|
|
1446
|
-
});
|
|
1447
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1448
|
-
return result(agent, `Started follow-up for ${agent.id}.`);
|
|
1449
|
-
}
|
|
1450
|
-
});
|
|
1451
|
-
if (blockingEnabled) {
|
|
1452
|
-
pi.registerTool({
|
|
1453
|
-
name: "subagent_await",
|
|
1454
|
-
label: "Await Subagent",
|
|
1455
|
-
description: "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.",
|
|
1456
|
-
promptSnippet: "Intentionally block until one retained subagent settles or the wait times out",
|
|
1457
|
-
promptGuidelines: [
|
|
1458
|
-
"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.",
|
|
1459
|
-
"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."
|
|
1460
|
-
],
|
|
1461
|
-
parameters: SubagentAwaitParams,
|
|
1462
|
-
...createStatefulToolRenderer("await"),
|
|
1463
|
-
async execute(_id, params, signal) {
|
|
1464
|
-
const generation = runtimeGeneration;
|
|
1465
|
-
const timeoutMs = params.timeoutMs ?? DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS;
|
|
1466
|
-
const waited = await requireRegistry().wait(params.agentId, timeoutMs, signal);
|
|
1467
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1468
|
-
return awaitResult(waited.agent, waited.timedOut, timeoutMs);
|
|
1469
|
-
}
|
|
1470
|
-
});
|
|
1471
|
-
}
|
|
1472
|
-
pi.registerTool({
|
|
1473
|
-
name: "subagent_manage",
|
|
1474
|
-
label: "Manage Subagents",
|
|
1475
|
-
description: "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.",
|
|
1476
|
-
promptSnippet: "Interrupt or close retained detached subagents",
|
|
1477
|
-
parameters: ManageParamsSchema,
|
|
1478
|
-
...createStatefulToolRenderer("manage"),
|
|
1479
|
-
async execute(_id, params, signal) {
|
|
1480
|
-
const generation = runtimeGeneration;
|
|
1481
|
-
const ownedRegistry = requireRegistry();
|
|
1482
|
-
let currentWorkspaceManager;
|
|
1483
|
-
try {
|
|
1484
|
-
currentWorkspaceManager = await getWorkspaceManager();
|
|
1485
|
-
} catch (error) {
|
|
1486
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1487
|
-
throw error;
|
|
1488
|
-
}
|
|
1489
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1490
|
-
const ownedAgent = (agentId2) => {
|
|
1491
|
-
const value = ownedRegistry.get(agentId2);
|
|
1492
|
-
if (!value) throw new Error(`Unknown subagent: ${agentId2}`);
|
|
1493
|
-
return value;
|
|
1494
|
-
};
|
|
1495
|
-
const operation = validateManageParams(params);
|
|
1496
|
-
const agentId = operation.agentId;
|
|
1497
|
-
if (operation.action === "interrupt") {
|
|
1498
|
-
if (operation.subtree) {
|
|
1499
|
-
const agents = await ownedRegistry.interruptTree(agentId);
|
|
1500
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1501
|
-
return {
|
|
1502
|
-
content: [{ type: "text", text: `Interrupted ${agents.length} active agent(s).` }],
|
|
1503
|
-
details: {
|
|
1504
|
-
agent: summarizeStatefulAgent(ownedAgent(agentId)),
|
|
1505
|
-
agents: agents.map(summarizeStatefulAgent)
|
|
1506
|
-
}
|
|
1507
|
-
};
|
|
1508
|
-
}
|
|
1509
|
-
const agent2 = await ownedRegistry.interrupt(agentId);
|
|
1510
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1511
|
-
return result(agent2, `Interrupted ${agent2.id}; it remains reusable.`);
|
|
1512
|
-
}
|
|
1513
|
-
const existing = ownedRegistry.get(agentId);
|
|
1514
|
-
if (existing?.state === "closed" && !operation.subtree) {
|
|
1515
|
-
const pendingOwner = isolatedAgents.get(existing.id);
|
|
1516
|
-
if (pendingOwner) await currentWorkspaceManager.cleanup(pendingOwner);
|
|
1517
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1518
|
-
isolatedAgents.delete(existing.id);
|
|
1519
|
-
return result(existing, `Closed ${existing.id}.`);
|
|
1520
|
-
}
|
|
1521
|
-
if (operation.subtree) {
|
|
1522
|
-
let agents;
|
|
1523
|
-
try {
|
|
1524
|
-
agents = await ownedRegistry.closeTree(agentId);
|
|
1525
|
-
} finally {
|
|
1526
|
-
await cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);
|
|
1527
|
-
}
|
|
1528
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1529
|
-
return {
|
|
1530
|
-
content: [{ type: "text", text: `Closed ${agents.length} agent(s).` }],
|
|
1531
|
-
details: {
|
|
1532
|
-
agent: summarizeStatefulAgent(ownedAgent(agentId)),
|
|
1533
|
-
agents: agents.map(summarizeStatefulAgent)
|
|
1534
|
-
}
|
|
1535
|
-
};
|
|
1536
|
-
}
|
|
1537
|
-
let agent;
|
|
1538
|
-
try {
|
|
1539
|
-
agent = await ownedRegistry.close(agentId);
|
|
1540
|
-
} finally {
|
|
1541
|
-
await cleanupClosedWorkspaces(ownedRegistry, isolatedAgents, currentWorkspaceManager);
|
|
1542
|
-
}
|
|
1543
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1544
|
-
return result(agent, `Closed ${agent.id}.`);
|
|
1545
|
-
}
|
|
1546
|
-
});
|
|
1547
|
-
pi.registerTool({
|
|
1548
|
-
name: "subagent_mailbox",
|
|
1549
|
-
label: "Subagent Mailbox",
|
|
1550
|
-
description: "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.",
|
|
1551
|
-
promptSnippet: "Send or read queue-only detached-subagent mailbox messages",
|
|
1552
|
-
parameters: MailboxParamsSchema,
|
|
1553
|
-
...createStatefulToolRenderer("mailbox"),
|
|
1554
|
-
async execute(_id, params, signal) {
|
|
1555
|
-
const generation = runtimeGeneration;
|
|
1556
|
-
const ownedRegistry = requireRegistry();
|
|
1557
|
-
const operation = validateMailboxParams(params);
|
|
1558
|
-
if (operation.action === "send") {
|
|
1559
|
-
const message = await ownedRegistry.sendMessage(
|
|
1560
|
-
operation.agentId,
|
|
1561
|
-
operation.message,
|
|
1562
|
-
operation.senderId,
|
|
1563
|
-
operation.deduplicationKey
|
|
1564
|
-
);
|
|
1565
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1566
|
-
return {
|
|
1567
|
-
content: [{ type: "text", text: `Queued ${message.id} for ${message.recipientId}.` }],
|
|
1568
|
-
details: { message }
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
const messages = await ownedRegistry.readMessages(
|
|
1572
|
-
operation.agentId,
|
|
1573
|
-
operation.acknowledge,
|
|
1574
|
-
operation.limit
|
|
1575
|
-
);
|
|
1576
|
-
assertCurrentSpawn(signal, generation, runtimeGeneration);
|
|
1577
|
-
const summaries = messages.map((message) => ({
|
|
1578
|
-
...message,
|
|
1579
|
-
content: truncateUtf8(message.content, MAX_TOOL_MESSAGE_BYTES).text
|
|
1580
|
-
}));
|
|
1581
|
-
const text = summaries.length ? summaries.map((message) => `${message.id} from ${message.senderId}: ${message.content}`).join("\n") : "No unread messages.";
|
|
1582
|
-
return {
|
|
1583
|
-
content: [{ type: "text", text: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text }],
|
|
1584
|
-
details: { messages: summaries }
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
});
|
|
1588
|
-
return controller;
|
|
1589
|
-
}
|
|
1590
|
-
function normalizeContextMode(value) {
|
|
1591
|
-
if (value === void 0) return "none";
|
|
1592
|
-
if (value === "none" || value === "all" || value === "summary") return value;
|
|
1593
|
-
return Math.max(1, Math.floor(value));
|
|
1594
|
-
}
|
|
1595
|
-
function resolveSpawnContextMode(value, contextEntryIds) {
|
|
1596
|
-
if (value === void 0 && contextEntryIds !== void 0) return "all";
|
|
1597
|
-
return normalizeContextMode(value);
|
|
1598
|
-
}
|
|
1599
|
-
async function cleanupClosedWorkspaces(registry, isolatedAgents, workspaceManager) {
|
|
1600
|
-
for (const [agentId, owner] of [...isolatedAgents]) {
|
|
1601
|
-
if (registry.get(agentId)?.state !== "closed") continue;
|
|
1602
|
-
await workspaceManager.cleanup(owner);
|
|
1603
|
-
isolatedAgents.delete(agentId);
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
function result(agent, text) {
|
|
1607
|
-
return {
|
|
1608
|
-
content: [{ type: "text", text }],
|
|
1609
|
-
details: { agent: summarizeStatefulAgent(agent) }
|
|
1610
|
-
};
|
|
1611
|
-
}
|
|
1612
|
-
function awaitResult(agent, timedOut, timeoutMs) {
|
|
1613
|
-
const latestTurn = agent.history.at(-1);
|
|
1614
|
-
const output = timedOut ? "" : truncateUtf8(latestTurn?.output ?? "", DEFAULT_MAX_CONTEXT_BYTES).text;
|
|
1615
|
-
const error = timedOut ? "" : truncateUtf8(agent.error ?? "", MAX_TOOL_MESSAGE_BYTES).text;
|
|
1616
|
-
const text = timedOut ? `Stopped waiting for ${agent.taskPath ?? agent.id} after ${timeoutMs}ms; it remains ${agent.state}. The wait did not interrupt or close the subagent.` : [`Subagent ${agent.taskPath ?? agent.id} settled as ${agent.state}.`, output || error].filter(Boolean).join("\n\n");
|
|
1617
|
-
return {
|
|
1618
|
-
content: [
|
|
1619
|
-
{
|
|
1620
|
-
type: "text",
|
|
1621
|
-
text: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text
|
|
1622
|
-
}
|
|
1623
|
-
],
|
|
1624
|
-
details: {
|
|
1625
|
-
agent: summarizeStatefulAgent(agent),
|
|
1626
|
-
timedOut,
|
|
1627
|
-
timeoutMs,
|
|
1628
|
-
...output ? { output } : {},
|
|
1629
|
-
...error ? { error } : {}
|
|
1630
|
-
}
|
|
1631
|
-
};
|
|
1632
|
-
}
|
|
1633
|
-
function normalizeRuntimeThinkingLevel(value) {
|
|
1634
|
-
return isThinkingLevel(value) ? value : "off";
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1637
|
-
export {
|
|
1638
|
-
formatStatefulAgentLine,
|
|
1639
|
-
registerStatefulSubagents
|
|
1640
|
-
};
|
|
1641
|
-
//# sourceMappingURL=chunk-2LMJU25E.ts.map
|