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