@qlzt/dsh-subagent 0.0.0-stage → 0.2.1-alpha.2
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/LICENSE +21 -0
- package/README.i18n.yaml +94 -0
- package/README.md +215 -2
- package/README.zh.md +216 -0
- package/lib/index.js +3333 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +991 -0
- package/lib/typert.remote-client.d.ts +25 -0
- package/lib/typert.remote-client.js +114 -0
- package/lib/types/activation.d.ts +114 -0
- package/lib/types/activation.js +112 -0
- package/lib/types/archive-admission.d.ts +16 -0
- package/lib/types/archive-admission.js +151 -0
- package/lib/types/assistant-output.d.ts +48 -0
- package/lib/types/assistant-output.js +73 -0
- package/lib/types/catalog.d.ts +92 -0
- package/lib/types/catalog.js +113 -0
- package/lib/types/child-agent.d.ts +154 -0
- package/lib/types/child-agent.js +211 -0
- package/lib/types/client.d.ts +8 -0
- package/lib/types/client.js +7 -0
- package/lib/types/continuation-messages.d.ts +63 -0
- package/lib/types/continuation-messages.js +114 -0
- package/lib/types/control-types.d.ts +142 -0
- package/lib/types/control-types.js +8 -0
- package/lib/types/control.d.ts +45 -0
- package/lib/types/control.js +79 -0
- package/lib/types/depth.d.ts +31 -0
- package/lib/types/depth.js +39 -0
- package/lib/types/descriptor.d.ts +105 -0
- package/lib/types/descriptor.js +192 -0
- package/lib/types/error.d.ts +11 -0
- package/lib/types/error.js +14 -0
- package/lib/types/index.d.ts +319 -0
- package/lib/types/index.js +455 -0
- package/lib/types/internal.d.ts +58 -0
- package/lib/types/internal.js +58 -0
- package/lib/types/lifecycle.d.ts +83 -0
- package/lib/types/lifecycle.js +115 -0
- package/lib/types/list-children.d.ts +36 -0
- package/lib/types/list-children.js +166 -0
- package/lib/types/manager.d.ts +247 -0
- package/lib/types/manager.js +1294 -0
- package/lib/types/out-of-process.d.ts +92 -0
- package/lib/types/out-of-process.js +178 -0
- package/lib/types/projection-types.d.ts +85 -0
- package/lib/types/projection-types.js +7 -0
- package/lib/types/projection.d.ts +100 -0
- package/lib/types/projection.js +157 -0
- package/lib/types/structured.d.ts +49 -0
- package/lib/types/structured.js +130 -0
- package/lib/types/types.d.ts +353 -0
- package/lib/types/types.js +19 -0
- package/package.json +136 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,3333 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { scopeTarget } from "@qlzt/dsh-scope";
|
|
3
|
+
import { ToolArgsError, assertObjectJsonSchema, validateJsonSchemaValue } from "@qlzt/dsh-tools";
|
|
4
|
+
import { canonicalClientTimeZone } from "@qlzt/dsh-util-time";
|
|
5
|
+
import { Remote, RemoteError, TypertRemoteService } from "@qlzt/dsh-typert-protocol";
|
|
6
|
+
import { AttachmentError } from "@qlzt/dsh-attachment";
|
|
7
|
+
import { z as z$1 } from "zod";
|
|
8
|
+
import { HarnessError, ReasoningEffortId, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@qlzt/dsh-llm";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { foldConsumedWork } from "@qlzt/dsh-agent";
|
|
11
|
+
import { isAbsolute, resolve } from "node:path";
|
|
12
|
+
import { brandString } from "@qlzt/dsh-brand";
|
|
13
|
+
import { SessionLogOffset, SessionSeq } from "@qlzt/dsh-session";
|
|
14
|
+
import { assertNever, snapshotJsonValue } from "@qlzt/dsh-util-values";
|
|
15
|
+
import { appendChunkedList, chunkedListSchema, iterateChunkedList } from "@qlzt/dsh-chunked-list";
|
|
16
|
+
import { accessSync, constants, statSync } from "node:fs";
|
|
17
|
+
//#region lib/types/error.js
|
|
18
|
+
/**
|
|
19
|
+
* Typed failures shared by subagent service and provider operations.
|
|
20
|
+
*
|
|
21
|
+
* @module @qlzt/dsh-subagent
|
|
22
|
+
*/
|
|
23
|
+
/** Typed failure for the subagent seam. */
|
|
24
|
+
var SubagentError = class extends HarnessError {
|
|
25
|
+
constructor(message, code, options) {
|
|
26
|
+
super(message, code, options);
|
|
27
|
+
this.name = "SubagentError";
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region lib/types/control.js
|
|
32
|
+
/**
|
|
33
|
+
* Browser-facing subagent prompt and interrupt request validation plus the
|
|
34
|
+
* stable prompt failure codes returned by the Remote surface.
|
|
35
|
+
*
|
|
36
|
+
* @module @qlzt/dsh-subagent
|
|
37
|
+
*/
|
|
38
|
+
const SESSION_ID_SCHEMA = z$1.string().min(1);
|
|
39
|
+
const CONTROL_ID_SCHEMAS = {
|
|
40
|
+
"subagent.prompt": z$1.object({
|
|
41
|
+
parentSessionId: SESSION_ID_SCHEMA,
|
|
42
|
+
childSessionId: SESSION_ID_SCHEMA,
|
|
43
|
+
mode: z$1.literal("continuable"),
|
|
44
|
+
delivery: z$1.enum(["queue", "steer"])
|
|
45
|
+
}),
|
|
46
|
+
"subagent.interrupt": z$1.object({
|
|
47
|
+
parentSessionId: SESSION_ID_SCHEMA,
|
|
48
|
+
childSessionId: SESSION_ID_SCHEMA,
|
|
49
|
+
mode: z$1.literal("continuable")
|
|
50
|
+
})
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Apply the subagent payload checks that are stricter than generated
|
|
54
|
+
* branded-string codecs.
|
|
55
|
+
* @param method - method name carried in the failure message.
|
|
56
|
+
* @param payload - decoded control fields to validate.
|
|
57
|
+
* @throws {RemoteError} `gateway/bad-request` with the original Zod issues.
|
|
58
|
+
*/
|
|
59
|
+
function validateControlRequest(method, payload) {
|
|
60
|
+
const parsed = CONTROL_ID_SCHEMAS[method].safeParse(payload);
|
|
61
|
+
if (!parsed.success) throw new RemoteError("gateway/bad-request", `invalid payload for ${method}`, { issues: parsed.error.issues });
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Refuse one continuation prompt without exposing provider detail: admission
|
|
65
|
+
* failures the caller can act on keep their own code, everything else is
|
|
66
|
+
* internal.
|
|
67
|
+
* @param error - the thrown value.
|
|
68
|
+
* @param childSessionId - the addressed child.
|
|
69
|
+
* @param signal - the caller's cancellation.
|
|
70
|
+
* @returns Never — the refusal is thrown.
|
|
71
|
+
* @throws {RemoteError} always.
|
|
72
|
+
*/
|
|
73
|
+
function rejectPrompt(error, childSessionId, signal) {
|
|
74
|
+
if (isCancellation(error, signal)) throw new RemoteError("gateway/cancelled", "subagent prompt was cancelled", {}, { cause: error });
|
|
75
|
+
if (error instanceof AttachmentError) throw new RemoteError("subagent/attachment-invalid", error.message, { reason: error.code }, { cause: error });
|
|
76
|
+
if (error instanceof SubagentError) switch (error.code) {
|
|
77
|
+
case "MODEL_DOES_NOT_SUPPORT_IMAGES": throw new RemoteError("subagent/attachment-invalid", error.message, { reason: error.code }, { cause: error });
|
|
78
|
+
case "NOT_RESUMABLE": throw new RemoteError("subagent/not-resumable", "subagent cannot be resumed", { childSessionId }, { cause: error });
|
|
79
|
+
case "UNAUTHORIZED": throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
|
|
80
|
+
case "DRAINING":
|
|
81
|
+
case "ACTIVATION_CLOSING":
|
|
82
|
+
case "ACTIVATION_LIMIT_REACHED":
|
|
83
|
+
case "CONTINUATION_UNAVAILABLE":
|
|
84
|
+
case "PERSISTENCE_UNAVAILABLE": throw new RemoteError("subagent/delivery-unavailable", "subagent follow-up is temporarily unavailable", { childSessionId }, { cause: error });
|
|
85
|
+
default: break;
|
|
86
|
+
}
|
|
87
|
+
throw new RemoteError("gateway/internal", "subagent prompt failed", {}, { cause: error });
|
|
88
|
+
}
|
|
89
|
+
function isCancellation(error, signal) {
|
|
90
|
+
return signal.aborted || error instanceof SubagentError && error.code === "CANCELLED";
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region lib/types/depth.js
|
|
94
|
+
/**
|
|
95
|
+
* Delegation-depth accounting: the recursion budget a parent passes to its
|
|
96
|
+
* children. Kept apart from the service so composition helpers can read it
|
|
97
|
+
* without importing the registry.
|
|
98
|
+
*
|
|
99
|
+
* @module @qlzt/dsh-subagent/depth
|
|
100
|
+
*/
|
|
101
|
+
/**
|
|
102
|
+
* Read an agent's delegation depth, treating absence as top-level depth zero.
|
|
103
|
+
* The persisted session header is authoritative and monotone: runtime
|
|
104
|
+
* `AgentOptions.subagentDepth` may DEEPEN the count but can never lower it —
|
|
105
|
+
* a resumed child arrives with fresh options, and counting it from zero would
|
|
106
|
+
* let it delegate as if it were top-level.
|
|
107
|
+
* @param agent - the agent whose header and options carry the depth.
|
|
108
|
+
* @returns its non-negative safe-integer depth.
|
|
109
|
+
* @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.
|
|
110
|
+
*/
|
|
111
|
+
function delegationDepthOf(agent) {
|
|
112
|
+
const runtime = agent.options.subagentDepth;
|
|
113
|
+
if (runtime !== void 0 && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) throw new TypeError("agent subagentDepth must be a non-negative safe integer");
|
|
114
|
+
return Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Reject a recursion cap that cannot represent an exact delegation depth.
|
|
118
|
+
* @param maxDepth - the optional runtime value to validate.
|
|
119
|
+
*/
|
|
120
|
+
function assertSubagentMaxDepth(maxDepth) {
|
|
121
|
+
if (maxDepth !== void 0 && (typeof maxDepth !== "number" || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || Object.is(maxDepth, -0))) throw new TypeError("subagent maxDepth must be a non-negative safe integer");
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region lib/types/types.js
|
|
125
|
+
/**
|
|
126
|
+
* The seam's consumer-facing contracts: request, result, and capability types
|
|
127
|
+
* for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
|
|
128
|
+
* payloads that plugins and hosts observe. Internal control interfaces belong
|
|
129
|
+
* with their implementation — the lifecycle observer in `./lifecycle.ts`, the
|
|
130
|
+
* manager host in `./manager.ts` — so this module stays the published
|
|
131
|
+
* surface rather than a bag of everything type-shaped.
|
|
132
|
+
*
|
|
133
|
+
* @module @qlzt/dsh-subagent/types
|
|
134
|
+
*/
|
|
135
|
+
/**
|
|
136
|
+
* Brand a string as a {@link SubagentRunId}.
|
|
137
|
+
* @param id - the raw run id.
|
|
138
|
+
* @returns the same string, branded.
|
|
139
|
+
*/
|
|
140
|
+
function SubagentRunId(id) {
|
|
141
|
+
return id;
|
|
142
|
+
}
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region lib/types/lifecycle.js
|
|
145
|
+
/**
|
|
146
|
+
* Lifecycle-edge publication for managed subagent activations.
|
|
147
|
+
*
|
|
148
|
+
* Public event payloads live in `./types.ts`; the package-private observer
|
|
149
|
+
* retains only the identity shared by each start/end pair.
|
|
150
|
+
*
|
|
151
|
+
* @module @qlzt/dsh-subagent/lifecycle
|
|
152
|
+
*/
|
|
153
|
+
/**
|
|
154
|
+
* Build the contained lifecycle emitter this seam publishes every edge through.
|
|
155
|
+
* Every listener is independently contained: a synchronous throw or a rejected
|
|
156
|
+
* returned promise is logged without starving peer listeners, changing the run,
|
|
157
|
+
* or — for provider removal, which fires from a disposer — breaking teardown.
|
|
158
|
+
* @param ctx - the service's own context, owning dispatch and the logger.
|
|
159
|
+
* @param carrier - resolve the scoped dispatch carrier for one delegating parent.
|
|
160
|
+
* @returns the emitter both observers and the provider registry publish through.
|
|
161
|
+
*/
|
|
162
|
+
function createLifecycleEmitter(ctx, carrier) {
|
|
163
|
+
return (name, info, parent) => {
|
|
164
|
+
const dispatchArgs = parent === void 0 ? [name, info] : [
|
|
165
|
+
carrier(parent),
|
|
166
|
+
name,
|
|
167
|
+
info
|
|
168
|
+
];
|
|
169
|
+
for (const callback of ctx.events.dispatch("emit", dispatchArgs)) try {
|
|
170
|
+
const returned = callback(info);
|
|
171
|
+
Promise.resolve(returned).catch((error) => {
|
|
172
|
+
ctx.logger.warn(`subagent: ${name} listener rejected: ${renderThrown(error)}`);
|
|
173
|
+
});
|
|
174
|
+
} catch (error) {
|
|
175
|
+
ctx.logger.warn(`subagent: ${name} listener threw: ${renderThrown(error)}`);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Build the observer for one local or external activation's residency epoch. Creation failure before residency emits no lifecycle edge.
|
|
181
|
+
* @param emit - the contained lifecycle emitter.
|
|
182
|
+
* @param provider - the provider name recorded in the durable descriptor.
|
|
183
|
+
* @param childId - the durable child session id.
|
|
184
|
+
* @param parent - the exact live direct parent keying scoped dispatch.
|
|
185
|
+
* @returns the observer whose edges this epoch publishes.
|
|
186
|
+
*/
|
|
187
|
+
function createActivationObserver(emit, provider, childId, parent) {
|
|
188
|
+
const identity = {
|
|
189
|
+
runId: SubagentRunId(randomUUID()),
|
|
190
|
+
provider,
|
|
191
|
+
id: childId,
|
|
192
|
+
local: false
|
|
193
|
+
};
|
|
194
|
+
return {
|
|
195
|
+
start: (child) => {
|
|
196
|
+
identity.local = child !== void 0;
|
|
197
|
+
emit("subagent/start", identity, parent);
|
|
198
|
+
},
|
|
199
|
+
settle: ({ stopReason, output }) => {
|
|
200
|
+
emit("subagent/end", {
|
|
201
|
+
...identity,
|
|
202
|
+
stopReason,
|
|
203
|
+
...output.length === 0 ? {} : { lastAssistantMessage: output }
|
|
204
|
+
}, parent);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Why this child's epoch ended, for the terminal lifecycle edge and the
|
|
210
|
+
* manager's own parent delivery. The child's own log is authoritative:
|
|
211
|
+
* teardown succeeding says nothing about whether the model errored, hit its
|
|
212
|
+
* token ceiling, or was cancelled, so deriving the reason from disposal would
|
|
213
|
+
* report failed work as completed.
|
|
214
|
+
*
|
|
215
|
+
* {@link foldConsumedWork} supplies both halves the raw turn sequence cannot:
|
|
216
|
+
* which turn accounts for the work this epoch consumed, and whether accepted
|
|
217
|
+
* work was cancelled after it without any turn opening over it. A recorded
|
|
218
|
+
* failure still wins over a cancellation — stopping a child that had already
|
|
219
|
+
* failed does not turn its failure into a cancellation.
|
|
220
|
+
* @param events - this epoch's own event suffix.
|
|
221
|
+
* @returns its terminal stop reason; `completed` only for an epoch that both
|
|
222
|
+
* closed cleanly and had nothing left to run.
|
|
223
|
+
*/
|
|
224
|
+
function epochStopReason(events) {
|
|
225
|
+
const { end, droppedUnrun } = foldConsumedWork(events);
|
|
226
|
+
switch (end?.data.reason.kind) {
|
|
227
|
+
case "max-tokens": return "max-tokens";
|
|
228
|
+
case "aborted":
|
|
229
|
+
case "interrupted": return "aborted";
|
|
230
|
+
case "error": return "error";
|
|
231
|
+
case "blocked": return "refusal";
|
|
232
|
+
case void 0:
|
|
233
|
+
case "completed": return droppedUnrun ? "aborted" : "completed";
|
|
234
|
+
/* v8 ignore next 4 -- `forked` appears only in constructor seed history, while
|
|
235
|
+
* this function reads an epoch-owned suffix. `TurnEndReason` is merge-extensible,
|
|
236
|
+
* so a backend-added variant cannot be listed; treating an unnameable reason as
|
|
237
|
+
* success would report failed work as completed. */
|
|
238
|
+
default: return "error";
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Render any listener-thrown value without letting coercion escape containment. */
|
|
242
|
+
function renderThrown(value) {
|
|
243
|
+
try {
|
|
244
|
+
return value instanceof Error ? `${value.name}: ${value.message}` : String(value);
|
|
245
|
+
} catch {
|
|
246
|
+
return "<unrenderable thrown value>";
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
//#endregion
|
|
250
|
+
//#region lib/types/child-agent.js
|
|
251
|
+
/**
|
|
252
|
+
* Shared in-process child composition: the delegation-depth budget, the
|
|
253
|
+
* durable session metadata, the resolved child `AgentOptions`, the delegated
|
|
254
|
+
* policy seed, and the scoped setup used by local activations.
|
|
255
|
+
*
|
|
256
|
+
* @module @qlzt/dsh-subagent/child-agent
|
|
257
|
+
*/
|
|
258
|
+
/** Thrown when starting a child would exceed the requested depth cap. */
|
|
259
|
+
var SubagentDepthError = class extends Error {
|
|
260
|
+
attemptedDepth;
|
|
261
|
+
maxDepth;
|
|
262
|
+
constructor(attemptedDepth, maxDepth) {
|
|
263
|
+
super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`);
|
|
264
|
+
this.attemptedDepth = attemptedDepth;
|
|
265
|
+
this.maxDepth = maxDepth;
|
|
266
|
+
this.name = "SubagentDepthError";
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* Resolve the child's delegation depth from its parent and enforce an optional
|
|
271
|
+
* cap. The persisted parent header is the monotone floor, so a resumed parent
|
|
272
|
+
* cannot delegate as if it were top-level.
|
|
273
|
+
* @param parent - the delegating parent agent.
|
|
274
|
+
* @param maxDepth - optional absolute cap the resolved depth must not exceed.
|
|
275
|
+
* @returns the child's non-negative safe-integer depth.
|
|
276
|
+
* @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.
|
|
277
|
+
* @throws {RangeError} when the resolved depth leaves the safe-integer range.
|
|
278
|
+
*/
|
|
279
|
+
function resolveChildDepth(parent, maxDepth) {
|
|
280
|
+
const childDepth = delegationDepthOf(parent) + 1;
|
|
281
|
+
if (!Number.isSafeInteger(childDepth)) throw new RangeError("subagent child depth exceeds the safe-integer range");
|
|
282
|
+
if (maxDepth !== void 0 && childDepth > maxDepth) throw new SubagentDepthError(childDepth, maxDepth);
|
|
283
|
+
return childDepth;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Resolve the parent values inherited by a child. The latest request header
|
|
287
|
+
* owns provider, model, and reasoning effort after request-time selection;
|
|
288
|
+
* creation options remain the fallback before the first request and retain
|
|
289
|
+
* the configured output-token limit.
|
|
290
|
+
* @param parent - delegating parent Agent.
|
|
291
|
+
* @returns detached Agent options for child-option merging.
|
|
292
|
+
*/
|
|
293
|
+
function parentAgentOptionsForDelegation(parent) {
|
|
294
|
+
const requestConfig = parent.session.requestHeader()?.config;
|
|
295
|
+
if (requestConfig === void 0) return { ...parent.options };
|
|
296
|
+
const { provider: _createdProvider, model: _createdModel, reasoningEffort: _createdReasoningEffort, ...createdOptions } = parent.options;
|
|
297
|
+
return {
|
|
298
|
+
...createdOptions,
|
|
299
|
+
provider: requestConfig.provider,
|
|
300
|
+
model: requestConfig.model,
|
|
301
|
+
...requestConfig.reasoningEffort === void 0 ? {} : { reasoningEffort: requestConfig.reasoningEffort }
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Resolve the child's `AgentOptions`: the parent's provider/model,
|
|
306
|
+
* reasoning-effort, and maxTokens values unless the request overrides them,
|
|
307
|
+
* stamped with the child's own delegation depth. Changing the route without
|
|
308
|
+
* naming an effort clears the parent's route-owned effort so the selected
|
|
309
|
+
* model resolves its own default.
|
|
310
|
+
* @param parent - the delegating parent whose route the child inherits.
|
|
311
|
+
* @param requested - per-child overrides, if any.
|
|
312
|
+
* @param childDepth - the resolved delegation depth to stamp.
|
|
313
|
+
* @returns the resolved options for `ctx.agents.create()`.
|
|
314
|
+
*/
|
|
315
|
+
function resolveChildAgentOptions(parent, requested, childDepth) {
|
|
316
|
+
const parentOptions = parentAgentOptionsForDelegation(parent);
|
|
317
|
+
const parentProvider = parentOptions.provider;
|
|
318
|
+
const parentModel = parentOptions.model;
|
|
319
|
+
const parentReasoningEffort = parentOptions.reasoningEffort;
|
|
320
|
+
const parentMaxTokens = parentOptions.maxTokens;
|
|
321
|
+
const resolved = {
|
|
322
|
+
...parentProvider !== void 0 ? { provider: parentProvider } : {},
|
|
323
|
+
...parentModel !== void 0 ? { model: parentModel } : {},
|
|
324
|
+
...parentReasoningEffort !== void 0 ? { reasoningEffort: parentReasoningEffort } : {},
|
|
325
|
+
...parentMaxTokens !== void 0 ? { maxTokens: parentMaxTokens } : {},
|
|
326
|
+
...requested,
|
|
327
|
+
subagentDepth: childDepth
|
|
328
|
+
};
|
|
329
|
+
if ((resolved.provider !== parentProvider || resolved.model !== parentModel) && requested?.reasoningEffort === void 0) delete resolved.reasoningEffort;
|
|
330
|
+
return resolved;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Build the child session's durable creation metadata: the parent's workspace,
|
|
334
|
+
* its direct lineage, coarse product origin, the recursion budget that must
|
|
335
|
+
* survive persistence, the seed boundary that separates inherited parent
|
|
336
|
+
* history from child work, and the composition the child runs under.
|
|
337
|
+
*
|
|
338
|
+
* The preset is read from the parent's LIVE scope chain rather than from its
|
|
339
|
+
* header, because a parent that switched preset while blank runs on the newer
|
|
340
|
+
* composition and its header still names the older one. Recording it is what
|
|
341
|
+
* makes a child's history reconstructable: without it a cold read of the child
|
|
342
|
+
* resolves the deployment default and rebuilds turns under a tool set the
|
|
343
|
+
* child never had.
|
|
344
|
+
* @param parent - the delegating parent agent.
|
|
345
|
+
* @param childDepth - the resolved delegation depth to persist.
|
|
346
|
+
* @param isSeeded - whether this child inherits a parent-log prefix, including an explicitly empty one.
|
|
347
|
+
* @returns the `meta` for `ctx.agents.create()`.
|
|
348
|
+
*/
|
|
349
|
+
function childSessionMeta(parent, childDepth, isSeeded) {
|
|
350
|
+
const parentHeader = parent.session.header;
|
|
351
|
+
const agentPreset = parent.ctx.get("agentPresets")?.composedPreset(parent.ctx);
|
|
352
|
+
return {
|
|
353
|
+
...parentHeader.cwd !== void 0 ? { cwd: parentHeader.cwd } : {},
|
|
354
|
+
...agentPreset === void 0 ? {} : { agentPreset },
|
|
355
|
+
parentSession: parentHeader.id,
|
|
356
|
+
isSeeded,
|
|
357
|
+
origin: "subagent",
|
|
358
|
+
delegationDepth: childDepth
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Model-facing delegation-scope statement for every in-process child. A
|
|
363
|
+
* runtime-context contribution rather than a system-prompt section, so the
|
|
364
|
+
* deployment's system prompt stays uniform across parents and children.
|
|
365
|
+
*/
|
|
366
|
+
const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.";
|
|
367
|
+
/**
|
|
368
|
+
* Compose one child inside its creation window: join its parent's preset,
|
|
369
|
+
* register the fixed delegation-scope statement, then apply the child's own
|
|
370
|
+
* shadowing persona section and tool restriction, all owned by the child's
|
|
371
|
+
* scope and therefore invisible to its parent and siblings. Creation and cold
|
|
372
|
+
* resume both pass through here.
|
|
373
|
+
*
|
|
374
|
+
* The join comes first and the child's own registrations second, which is the
|
|
375
|
+
* order the layering already implies — the nearest scope wins a name, and a
|
|
376
|
+
* per-child restriction intersects with everything its chain admits — but
|
|
377
|
+
* stating it here keeps the two steps from being read as independent.
|
|
378
|
+
*
|
|
379
|
+
* The join and the per-child registrations live in ONE call because a child
|
|
380
|
+
* composed without the join is exactly the defect this function exists to
|
|
381
|
+
* prevent: with every model-facing row on the agent plane, a child that joins
|
|
382
|
+
* no preset sees an empty tool registry and none of its parent's prompt
|
|
383
|
+
* sections. Taking the parent as a parameter is what makes that omission
|
|
384
|
+
* unrepresentable at the call sites.
|
|
385
|
+
* @param childCtx - the child agent's scoped creation context.
|
|
386
|
+
* @param parent - the delegating parent whose composition the child joins.
|
|
387
|
+
* @param composition - the per-child persona and tool filter to install.
|
|
388
|
+
*/
|
|
389
|
+
function applyChildComposition(childCtx, parent, composition) {
|
|
390
|
+
childCtx.get("agentPresets")?.composeFrom(childCtx, parent.ctx);
|
|
391
|
+
childCtx.systemPrompt.context({
|
|
392
|
+
name: "subagent:delegation",
|
|
393
|
+
order: childCtx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
|
|
394
|
+
text: SUBAGENT_DELEGATION_CONTEXT
|
|
395
|
+
});
|
|
396
|
+
if (composition.persona !== void 0) childCtx.systemPrompt.section({
|
|
397
|
+
name: "deployment:persona-prefix",
|
|
398
|
+
order: childCtx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
|
|
399
|
+
text: composition.persona
|
|
400
|
+
});
|
|
401
|
+
if (composition.toolFilter !== void 0) childCtx.tools.restrict(composition.toolFilter);
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Capture the permission state to seed into one delegation. Call synchronously before
|
|
405
|
+
* the child start's first await: a later parent switch belongs to the
|
|
406
|
+
* parent's future, not to this child. Auto and Full access identities are
|
|
407
|
+
* inherited only through the in-process DSH path so either can replace a stale
|
|
408
|
+
* same-bundle fork value. Only the parent session's explicit sandbox override
|
|
409
|
+
* is captured — never deployment defaults or one-shot grants — and the approval
|
|
410
|
+
* policy is pinned to `'never'` regardless of the parent's own policy.
|
|
411
|
+
* @param parent - the delegating parent agent.
|
|
412
|
+
* @returns the sandbox override (or `undefined` without one) and the approval pin.
|
|
413
|
+
*/
|
|
414
|
+
function captureDelegatedPolicyOverrides(parent) {
|
|
415
|
+
const preset = parent.ctx.get("permissionPresets")?.current(parent.session);
|
|
416
|
+
return {
|
|
417
|
+
permissionPreset: preset === "auto" || preset === "danger-full-access" ? preset : void 0,
|
|
418
|
+
sandboxMode: parent.ctx.get("sandboxPolicy")?.overrideOf(parent.session),
|
|
419
|
+
approvalPolicy: parent.ctx.get("approval") === void 0 ? void 0 : "never"
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Append the captured delegation policy onto the child's own log as
|
|
424
|
+
* `source: 'delegation'` events inside the unpublished creation window, so the
|
|
425
|
+
* child's effective policy is reconstructable from its log alone. Appends land
|
|
426
|
+
* after any fork seed, so fresh policy wins stale seed state; later child
|
|
427
|
+
* switches still win over these events.
|
|
428
|
+
* @param childSession - the unpublished child's session.
|
|
429
|
+
* @param overrides - the policy captured at delegation.
|
|
430
|
+
*/
|
|
431
|
+
function appendDelegatedPolicyOverrides(childSession, overrides) {
|
|
432
|
+
if (overrides.sandboxMode !== void 0) childSession.append("sandbox/mode", {
|
|
433
|
+
mode: overrides.sandboxMode,
|
|
434
|
+
source: "delegation"
|
|
435
|
+
});
|
|
436
|
+
if (overrides.approvalPolicy !== void 0) childSession.append("approval/policy", {
|
|
437
|
+
policy: overrides.approvalPolicy,
|
|
438
|
+
source: "delegation"
|
|
439
|
+
});
|
|
440
|
+
if (overrides.permissionPreset !== void 0) childSession.append("permission/preset", { preset: overrides.permissionPreset });
|
|
441
|
+
}
|
|
442
|
+
//#endregion
|
|
443
|
+
//#region lib/types/continuation-messages.js
|
|
444
|
+
/**
|
|
445
|
+
* Model-visible messages owned by continuable-subagent orchestration.
|
|
446
|
+
*
|
|
447
|
+
* @module @qlzt/dsh-subagent/continuation-messages
|
|
448
|
+
*/
|
|
449
|
+
/** Build durable attribution for one adjacent-Agent message. */
|
|
450
|
+
function agentMessageSource(sender) {
|
|
451
|
+
return {
|
|
452
|
+
kind: "agent-message",
|
|
453
|
+
form: "relay",
|
|
454
|
+
senderSessionId: sender.id
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Build the model-visible and durable representation of one adjacent-Agent message.
|
|
459
|
+
* @param sender - exact live Agent that authored the message.
|
|
460
|
+
* @param content - model-visible message blocks supplied by the sender.
|
|
461
|
+
* @returns the durable user-message representation delivered to the recipient.
|
|
462
|
+
*/
|
|
463
|
+
function createAgentMessage(sender, content) {
|
|
464
|
+
return createUserMessage({
|
|
465
|
+
content: [{
|
|
466
|
+
type: "text",
|
|
467
|
+
text: `Agent ${sender.id} sent a message: `
|
|
468
|
+
}, ...content],
|
|
469
|
+
source: agentMessageSource(sender)
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Append adjacent-Agent return guidance to a continuable child's initial task.
|
|
474
|
+
* @param parentId - durable parent session id named in the guidance.
|
|
475
|
+
* @param prompt - initial model-visible task blocks.
|
|
476
|
+
* @returns task blocks followed by the continuable return guidance.
|
|
477
|
+
*/
|
|
478
|
+
function withContinuableReturnGuidance(parentId, prompt) {
|
|
479
|
+
const encodedParentId = JSON.stringify(parentId);
|
|
480
|
+
return [...prompt, {
|
|
481
|
+
type: "text",
|
|
482
|
+
text: `Your parent agent id is ${encodedParentId}. Before you finish, send your result to that agent with send_message({ agent_id: ${encodedParentId}, message: "<self-contained result>" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn.`
|
|
483
|
+
}];
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* One line telling a parent that a background child is finished and why, in
|
|
487
|
+
* the parent's own task vocabulary.
|
|
488
|
+
* @param childId - the durable child the parent knows by id.
|
|
489
|
+
* @param stopReason - how the child's last ordinary turn ended.
|
|
490
|
+
* @param continuable - whether the child accepts a later message.
|
|
491
|
+
* @returns the model-facing opening line of the settlement notice.
|
|
492
|
+
*/
|
|
493
|
+
function settlementSummary(childId, stopReason, continuable) {
|
|
494
|
+
const subject = `Background subagent ${childId}`;
|
|
495
|
+
switch (stopReason) {
|
|
496
|
+
case "completed": return continuable ? `${subject} finished and will do no further work unless you send it more.` : `${subject} finished. It cannot receive follow-up messages.`;
|
|
497
|
+
case "aborted": return `${subject} was stopped before it finished.`;
|
|
498
|
+
case "max-tokens": return `${subject} ran out of room before it finished.`;
|
|
499
|
+
case "refusal": return `${subject} declined the task.`;
|
|
500
|
+
case "error": return `${subject} failed before it finished.`;
|
|
501
|
+
/* v8 ignore next 4 -- `SubagentResult['stopReason']` is merge-extensible, so this arm
|
|
502
|
+
* needs a backend that adds a variant; an unnameable ending is reported as unfinished
|
|
503
|
+
* rather than silently as success. */
|
|
504
|
+
default: return `${subject} ended abnormally (${String(stopReason)}) before it finished.`;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Build the runtime-owned settlement notice from the child's nonempty closing text.
|
|
509
|
+
* @param childId - durable child session id named in the notice.
|
|
510
|
+
* @param terminal - recorded terminal state for the settled Activation.
|
|
511
|
+
* @param continuable - whether the child can accept another task.
|
|
512
|
+
* @returns the durable user-message representation delivered to the parent.
|
|
513
|
+
*/
|
|
514
|
+
function createSettlementMessage(childId, terminal, continuable = true) {
|
|
515
|
+
const summary = settlementSummary(childId, terminal.stopReason, continuable);
|
|
516
|
+
const closingText = terminal.output.flatMap((block) => block.type === "text" && block.text.length > 0 ? [block] : []);
|
|
517
|
+
return createUserMessage({
|
|
518
|
+
content: [
|
|
519
|
+
{
|
|
520
|
+
type: "text",
|
|
521
|
+
text: summary
|
|
522
|
+
},
|
|
523
|
+
...closingText.length === 0 ? [{
|
|
524
|
+
type: "text",
|
|
525
|
+
text: "It left no closing message."
|
|
526
|
+
}] : [{
|
|
527
|
+
type: "text",
|
|
528
|
+
text: "Its closing message:"
|
|
529
|
+
}, ...closingText],
|
|
530
|
+
...terminal.structured !== void 0 ? [{
|
|
531
|
+
type: "text",
|
|
532
|
+
text: `Structured result: ${JSON.stringify(terminal.structured)}`
|
|
533
|
+
}] : [],
|
|
534
|
+
...terminal.diagnostic !== void 0 ? [{
|
|
535
|
+
type: "text",
|
|
536
|
+
text: terminal.diagnostic
|
|
537
|
+
}] : []
|
|
538
|
+
],
|
|
539
|
+
source: {
|
|
540
|
+
kind: "subagent-settled",
|
|
541
|
+
form: "notice",
|
|
542
|
+
summary: boundContextSummary(summary),
|
|
543
|
+
senderSessionId: childId
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
//#endregion
|
|
548
|
+
//#region lib/types/descriptor.js
|
|
549
|
+
/**
|
|
550
|
+
* The durable subagent-child descriptor: the versioned, model-hidden
|
|
551
|
+
* `subagent/descriptor` session event that identifies every session-backed
|
|
552
|
+
* subagent, including historical one-shot records. The manager appends each
|
|
553
|
+
* continuable child's descriptor inside its initial turn, preserving the
|
|
554
|
+
* declared composition required for cold resume.
|
|
555
|
+
*
|
|
556
|
+
* The descriptor deliberately snapshots explicit fields rather than the
|
|
557
|
+
* merge-extensible `AgentOptions` object: an unrelated extension value cannot
|
|
558
|
+
* make continuation fail merely because it is not JSON, and later composition
|
|
559
|
+
* inputs require a deliberate {@link SUBAGENT_DESCRIPTOR_VERSION} change. It
|
|
560
|
+
* omits `subagentDepth` — cold resume trusts the persisted header's
|
|
561
|
+
* `delegationDepth` as the monotone floor — and `outputSchema`, which belongs
|
|
562
|
+
* to one activation's result contract rather than durable child composition.
|
|
563
|
+
* Per-activation knobs such as `maxTokens` are omitted for the same reason as
|
|
564
|
+
* `outputSchema`: they budget one activation. Cold resume requires the exact
|
|
565
|
+
* live parent for authorization but reconstructs child options only from the
|
|
566
|
+
* durable descriptor, so it neither restores the prior budget nor inherits
|
|
567
|
+
* the parent's current one; the resumed route's defaults apply instead.
|
|
568
|
+
*
|
|
569
|
+
* @module @qlzt/dsh-subagent/descriptor
|
|
570
|
+
*/
|
|
571
|
+
/**
|
|
572
|
+
* The current descriptor format version, stamped into every appended
|
|
573
|
+
* `subagent/descriptor` event and required verbatim by {@link foldSubagentDescriptor}.
|
|
574
|
+
* Supporting another composition input is a deliberate version change, never
|
|
575
|
+
* an implicit extra field.
|
|
576
|
+
*/
|
|
577
|
+
const SUBAGENT_DESCRIPTOR_VERSION = 3;
|
|
578
|
+
const DESCRIPTOR_BASE_KEYS = [
|
|
579
|
+
"version",
|
|
580
|
+
"mode",
|
|
581
|
+
"provider",
|
|
582
|
+
"label"
|
|
583
|
+
];
|
|
584
|
+
const ONE_SHOT_DESCRIPTOR_KEYS = new Set(DESCRIPTOR_BASE_KEYS);
|
|
585
|
+
const CONTINUABLE_DESCRIPTOR_KEYS = new Set([
|
|
586
|
+
...DESCRIPTOR_BASE_KEYS,
|
|
587
|
+
"agentProvider",
|
|
588
|
+
"agentModel",
|
|
589
|
+
"agentReasoningEffort",
|
|
590
|
+
"persona",
|
|
591
|
+
"toolFilter"
|
|
592
|
+
]);
|
|
593
|
+
const TOOL_FILTER_KEYS = new Set(["allow", "deny"]);
|
|
594
|
+
/** Whether a persisted JSON value is an object record. */
|
|
595
|
+
function isRecord(value) {
|
|
596
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
597
|
+
}
|
|
598
|
+
/** Reject fields outside one versioned record's declared schema. */
|
|
599
|
+
function assertKnownKeys(value, keys, path) {
|
|
600
|
+
const unknown = Object.keys(value).find((key) => !keys.has(key));
|
|
601
|
+
if (unknown !== void 0) throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`);
|
|
602
|
+
}
|
|
603
|
+
/** Read one optional string field from a persisted descriptor record. */
|
|
604
|
+
function optionalString(value, key) {
|
|
605
|
+
if (!Object.hasOwn(value, key)) return void 0;
|
|
606
|
+
const field = value[key];
|
|
607
|
+
if (typeof field !== "string") throw new Error(`persisted subagent descriptor ${key} must be a string`);
|
|
608
|
+
return field;
|
|
609
|
+
}
|
|
610
|
+
/** Read one optional string-array field from a persisted tool restriction. */
|
|
611
|
+
function optionalStringArray(value, key) {
|
|
612
|
+
if (!Object.hasOwn(value, key)) return void 0;
|
|
613
|
+
const field = value[key];
|
|
614
|
+
if (!Array.isArray(field)) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
|
|
615
|
+
const items = field;
|
|
616
|
+
if (items.some((item) => typeof item !== "string")) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
|
|
617
|
+
return items;
|
|
618
|
+
}
|
|
619
|
+
/** Validate and reconstruct a persisted tool restriction. */
|
|
620
|
+
function parseToolFilter(value) {
|
|
621
|
+
if (!isRecord(value)) throw new Error("persisted subagent descriptor toolFilter must be an object");
|
|
622
|
+
assertKnownKeys(value, TOOL_FILTER_KEYS, "toolFilter");
|
|
623
|
+
const allow = optionalStringArray(value, "allow");
|
|
624
|
+
const deny = optionalStringArray(value, "deny");
|
|
625
|
+
if (allow === void 0 && deny === void 0) throw new Error("persisted subagent descriptor toolFilter must declare allow and/or deny");
|
|
626
|
+
return {
|
|
627
|
+
...allow !== void 0 ? { allow } : {},
|
|
628
|
+
...deny !== void 0 ? { deny } : {}
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
/** Validate one persisted descriptor payload for the current runtime. */
|
|
632
|
+
function parseSubagentDescriptor(value) {
|
|
633
|
+
if (!isRecord(value)) throw new Error("persisted subagent descriptor payload must be an object");
|
|
634
|
+
const version = value["version"];
|
|
635
|
+
if (typeof version !== "number") throw new Error("persisted subagent descriptor version must be a number");
|
|
636
|
+
if (version !== 3) return void 0;
|
|
637
|
+
const mode = value["mode"];
|
|
638
|
+
if (mode !== "one-shot" && mode !== "continuable") throw new Error("persisted subagent descriptor mode must be \"one-shot\" or \"continuable\"");
|
|
639
|
+
assertKnownKeys(value, mode === "one-shot" ? ONE_SHOT_DESCRIPTOR_KEYS : CONTINUABLE_DESCRIPTOR_KEYS, "payload");
|
|
640
|
+
const provider = value["provider"];
|
|
641
|
+
if (typeof provider !== "string") throw new Error("persisted subagent descriptor provider must be a string");
|
|
642
|
+
if (mode === "one-shot") {
|
|
643
|
+
const label = optionalString(value, "label");
|
|
644
|
+
return {
|
|
645
|
+
version: 3,
|
|
646
|
+
mode,
|
|
647
|
+
provider,
|
|
648
|
+
...label !== void 0 ? { label } : {}
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
const label = value["label"];
|
|
652
|
+
if (typeof label !== "string") throw new Error("persisted subagent descriptor label must be a string");
|
|
653
|
+
const agentProvider = optionalString(value, "agentProvider");
|
|
654
|
+
const agentModel = optionalString(value, "agentModel");
|
|
655
|
+
const agentReasoningEffort = optionalString(value, "agentReasoningEffort");
|
|
656
|
+
const persona = optionalString(value, "persona");
|
|
657
|
+
const toolFilter = Object.hasOwn(value, "toolFilter") ? parseToolFilter(value["toolFilter"]) : void 0;
|
|
658
|
+
return {
|
|
659
|
+
version: 3,
|
|
660
|
+
mode,
|
|
661
|
+
provider,
|
|
662
|
+
label,
|
|
663
|
+
...agentProvider !== void 0 ? { agentProvider } : {},
|
|
664
|
+
...agentModel !== void 0 ? { agentModel } : {},
|
|
665
|
+
...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {},
|
|
666
|
+
...persona !== void 0 ? { persona } : {},
|
|
667
|
+
...toolFilter !== void 0 ? { toolFilter } : {}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Validate and detach a continuable descriptor input.
|
|
672
|
+
* @param input - the caller-collected continuable composition fields.
|
|
673
|
+
* @returns the versioned, detached continuable descriptor payload.
|
|
674
|
+
* @throws when a field is not losslessly JSON-serializable.
|
|
675
|
+
*/
|
|
676
|
+
function snapshotSubagentDescriptor(input) {
|
|
677
|
+
const snapshot = snapshotJsonValue({
|
|
678
|
+
version: 3,
|
|
679
|
+
mode: input.mode,
|
|
680
|
+
provider: input.provider,
|
|
681
|
+
label: input.label,
|
|
682
|
+
...input.agentProvider !== void 0 ? { agentProvider: input.agentProvider } : {},
|
|
683
|
+
...input.agentModel !== void 0 ? { agentModel: input.agentModel } : {},
|
|
684
|
+
...input.agentReasoningEffort !== void 0 ? { agentReasoningEffort: input.agentReasoningEffort } : {},
|
|
685
|
+
...input.persona !== void 0 ? { persona: input.persona } : {},
|
|
686
|
+
...input.toolFilter !== void 0 ? { toolFilter: input.toolFilter } : {}
|
|
687
|
+
});
|
|
688
|
+
if (snapshot === void 0) throw new Error("subagent descriptor is not losslessly JSON-serializable");
|
|
689
|
+
return snapshot;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Fold a persisted child log to its supported descriptor. The first
|
|
693
|
+
* `subagent/descriptor` event is authoritative — the establishing provider
|
|
694
|
+
* appends exactly one, so a later same-type event cannot rewrite the declared
|
|
695
|
+
* composition.
|
|
696
|
+
* @param events - the loaded child session events.
|
|
697
|
+
* @returns the descriptor, or `undefined` when the log has none or its
|
|
698
|
+
* version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child cannot be
|
|
699
|
+
* classified by this runtime).
|
|
700
|
+
* @throws when a current-version persisted payload does not match its complete
|
|
701
|
+
* declared schema.
|
|
702
|
+
*/
|
|
703
|
+
function foldSubagentDescriptor(events) {
|
|
704
|
+
const event = events.find((candidate) => candidate.type === "subagent/descriptor");
|
|
705
|
+
if (event === void 0) return void 0;
|
|
706
|
+
return parseSubagentDescriptor(event.data);
|
|
707
|
+
}
|
|
708
|
+
const sessionIdSchema = z$1.string();
|
|
709
|
+
const oneShotCatalogSchema = z$1.object({
|
|
710
|
+
version: z$1.union([z$1.literal(0), z$1.literal(1)]),
|
|
711
|
+
childId: sessionIdSchema,
|
|
712
|
+
childCreatedAt: z$1.number().int().nonnegative(),
|
|
713
|
+
mode: z$1.literal("one-shot"),
|
|
714
|
+
label: z$1.string().optional()
|
|
715
|
+
}).strict();
|
|
716
|
+
const continuableCatalogSchema = z$1.object({
|
|
717
|
+
version: z$1.union([z$1.literal(0), z$1.literal(1)]),
|
|
718
|
+
childId: sessionIdSchema,
|
|
719
|
+
childCreatedAt: z$1.number().int().nonnegative(),
|
|
720
|
+
mode: z$1.literal("continuable"),
|
|
721
|
+
label: z$1.string()
|
|
722
|
+
}).strict();
|
|
723
|
+
const externalCatalogSchema = oneShotCatalogSchema.extend({
|
|
724
|
+
version: z$1.literal(2),
|
|
725
|
+
mode: z$1.literal("external")
|
|
726
|
+
});
|
|
727
|
+
const unknownCatalogSchema = oneShotCatalogSchema.extend({
|
|
728
|
+
version: z$1.literal(1),
|
|
729
|
+
mode: z$1.literal("unknown")
|
|
730
|
+
});
|
|
731
|
+
const eventDataSchema = z$1.union([
|
|
732
|
+
oneShotCatalogSchema,
|
|
733
|
+
externalCatalogSchema,
|
|
734
|
+
continuableCatalogSchema,
|
|
735
|
+
unknownCatalogSchema
|
|
736
|
+
]);
|
|
737
|
+
const viewSchema = z$1.array(z$1.union([
|
|
738
|
+
oneShotCatalogSchema.omit({
|
|
739
|
+
version: true,
|
|
740
|
+
childId: true,
|
|
741
|
+
childCreatedAt: true
|
|
742
|
+
}).extend({
|
|
743
|
+
id: sessionIdSchema,
|
|
744
|
+
createdAt: oneShotCatalogSchema.shape.childCreatedAt
|
|
745
|
+
}),
|
|
746
|
+
externalCatalogSchema.omit({
|
|
747
|
+
version: true,
|
|
748
|
+
childId: true,
|
|
749
|
+
childCreatedAt: true
|
|
750
|
+
}).extend({
|
|
751
|
+
id: sessionIdSchema,
|
|
752
|
+
createdAt: externalCatalogSchema.shape.childCreatedAt
|
|
753
|
+
}),
|
|
754
|
+
continuableCatalogSchema.omit({
|
|
755
|
+
version: true,
|
|
756
|
+
childId: true,
|
|
757
|
+
childCreatedAt: true
|
|
758
|
+
}).extend({
|
|
759
|
+
id: sessionIdSchema,
|
|
760
|
+
createdAt: continuableCatalogSchema.shape.childCreatedAt
|
|
761
|
+
}),
|
|
762
|
+
unknownCatalogSchema.omit({
|
|
763
|
+
version: true,
|
|
764
|
+
childId: true,
|
|
765
|
+
childCreatedAt: true
|
|
766
|
+
}).extend({
|
|
767
|
+
id: sessionIdSchema,
|
|
768
|
+
createdAt: unknownCatalogSchema.shape.childCreatedAt
|
|
769
|
+
})
|
|
770
|
+
]));
|
|
771
|
+
const stateSchema = z$1.object({
|
|
772
|
+
inheritedEventCount: z$1.number().int().nonnegative(),
|
|
773
|
+
head: chunkedListSchema(eventDataSchema).optional()
|
|
774
|
+
}).strict();
|
|
775
|
+
/**
|
|
776
|
+
* Materialize complete and unknown-mode child identities from parent catalog events.
|
|
777
|
+
* @param state - parent catalog fold state.
|
|
778
|
+
* @returns current direct-child rows in parent catalog event order.
|
|
779
|
+
*/
|
|
780
|
+
function subagentCatalogEntries(state) {
|
|
781
|
+
const entries = [];
|
|
782
|
+
for (const data of iterateChunkedList(state.head)) {
|
|
783
|
+
const { version: _version, childId, childCreatedAt, ...descriptor } = data;
|
|
784
|
+
entries.push({
|
|
785
|
+
id: childId,
|
|
786
|
+
createdAt: childCreatedAt,
|
|
787
|
+
...descriptor
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
return entries;
|
|
791
|
+
}
|
|
792
|
+
/** Parent-owned direct-child catalog projection; invalid own facts reject restoration. */
|
|
793
|
+
const subagentCatalogProjectionDefinition = {
|
|
794
|
+
key: "subagentCatalog",
|
|
795
|
+
stateSchema,
|
|
796
|
+
init: (_header, inheritedEventCount) => ({ inheritedEventCount }),
|
|
797
|
+
apply: (state, event) => {
|
|
798
|
+
if (event.type !== "subagent/catalog" || event.seq < state.inheritedEventCount) return state;
|
|
799
|
+
return {
|
|
800
|
+
...state,
|
|
801
|
+
head: appendChunkedList(state.head, eventDataSchema.parse(event.data))
|
|
802
|
+
};
|
|
803
|
+
},
|
|
804
|
+
stateVersion: 6,
|
|
805
|
+
wire: {
|
|
806
|
+
viewSchema,
|
|
807
|
+
view: subagentCatalogEntries
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
/**
|
|
811
|
+
* Append a complete direct-child discovery fact to its parent Session.
|
|
812
|
+
* @param parent - durable direct parent receiving the discovery fact.
|
|
813
|
+
* @param child - established child's immutable Session metadata.
|
|
814
|
+
* @param descriptor - mode-discriminated creation label frozen with the child.
|
|
815
|
+
*/
|
|
816
|
+
function establishCatalogChild(parent, child, descriptor) {
|
|
817
|
+
parent.append("subagent/catalog", {
|
|
818
|
+
version: 0,
|
|
819
|
+
childId: child.id,
|
|
820
|
+
childCreatedAt: child.createdAt,
|
|
821
|
+
mode: descriptor.mode,
|
|
822
|
+
label: descriptor.label
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
/** Catalog payload version emitted by external execution creation. */
|
|
826
|
+
const EXTERNAL_SUBAGENT_CATALOG_VERSION = 2;
|
|
827
|
+
/**
|
|
828
|
+
* Record an external execution without a local child Session.
|
|
829
|
+
* @param parent - durable direct parent receiving the discovery fact.
|
|
830
|
+
* @param childId - identity returned by the external provider.
|
|
831
|
+
* @param label - display label assigned by the caller.
|
|
832
|
+
*/
|
|
833
|
+
function establishExternalCatalogChild(parent, childId, label) {
|
|
834
|
+
parent.append("subagent/catalog", {
|
|
835
|
+
version: EXTERNAL_SUBAGENT_CATALOG_VERSION,
|
|
836
|
+
childId,
|
|
837
|
+
childCreatedAt: Date.now(),
|
|
838
|
+
mode: "external",
|
|
839
|
+
label
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
//#endregion
|
|
843
|
+
//#region lib/types/internal.js
|
|
844
|
+
/**
|
|
845
|
+
* Continuation integration markers and host adapters outside the public
|
|
846
|
+
* Service Definition and model-facing Agent messaging contract.
|
|
847
|
+
* @module @qlzt/dsh-subagent/internal
|
|
848
|
+
*/
|
|
849
|
+
/** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
|
|
850
|
+
const adjacentAgentSendMessageTool = Symbol.for("dsh.subagent.adjacentAgentSendMessageTool");
|
|
851
|
+
/**
|
|
852
|
+
* Test whether one visible definition is the standard adjacent-Agent messaging tool.
|
|
853
|
+
* @param definition - the scope-resolved `send_message` candidate.
|
|
854
|
+
* @returns whether the definition carries the internal standard-tool identity.
|
|
855
|
+
*/
|
|
856
|
+
function isAdjacentAgentSendMessageTool(definition) {
|
|
857
|
+
return definition !== void 0 && definition[adjacentAgentSendMessageTool] === true;
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* Process-stable symbol-keyed host delivery shared by the bundled runtime
|
|
861
|
+
* entry and this unbundled internal subpath.
|
|
862
|
+
* @internal
|
|
863
|
+
*/
|
|
864
|
+
const deliverSubagentPrompt = Symbol.for("dsh.subagent.deliverPrompt");
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region lib/types/structured.js
|
|
867
|
+
/**
|
|
868
|
+
* Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
|
|
869
|
+
* result capture for in-process subagents. Each child registers its real schema on its own
|
|
870
|
+
* scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
|
|
871
|
+
* contribution is ordinary reconstructed request state.
|
|
872
|
+
*
|
|
873
|
+
* Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
|
|
874
|
+
* waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
|
|
875
|
+
* guard prevent later calls from reopening a completed structured run.
|
|
876
|
+
* @module @qlzt/dsh-subagent/structured
|
|
877
|
+
*/
|
|
878
|
+
/** The model-facing tool name a structured child must call to finish. */
|
|
879
|
+
const STRUCTURED_OUTPUT_TOOL = "structured_output";
|
|
880
|
+
/**
|
|
881
|
+
* The instruction registered as the child's trailing scoped prompt section:
|
|
882
|
+
* the demand travels with the
|
|
883
|
+
* tool, as ordinary prompt state of exactly one agent.
|
|
884
|
+
*/
|
|
885
|
+
const STRUCTURED_OUTPUT_INSTRUCTION = `When you have your final answer, you MUST report it by calling the \`${STRUCTURED_OUTPUT_TOOL}\` tool with arguments matching its parameter schema exactly. Do not finish with a plain text answer: only the tool call counts as your result.`;
|
|
886
|
+
/**
|
|
887
|
+
* Attach the scoped capture tool, instruction, and enforcement to a child during
|
|
888
|
+
* its creation window. Child disposal removes every registration.
|
|
889
|
+
* @param childCtx - the child agent's scope context (`setup`'s argument).
|
|
890
|
+
* @param schema - the trusted, already-asserted schema subset to enforce (see
|
|
891
|
+
* `assertObjectJsonSchema` in dsh-tools).
|
|
892
|
+
* @param canComplete - whether accepted input and owned child work have finished.
|
|
893
|
+
* @returns the attachment handle (read `captured()` after the child settles).
|
|
894
|
+
*/
|
|
895
|
+
function attachStructuredRuntime(childCtx, schema, canComplete) {
|
|
896
|
+
/**
|
|
897
|
+
* Validated values staged by the capture tool body, awaiting THEIR OWN
|
|
898
|
+
* authoritative `tools/result` notification. The execution object's identity
|
|
899
|
+
* uniquely identifies a trip through the pipeline: adapter call ids may
|
|
900
|
+
* repeat across steps, but another execution can never reach this Map
|
|
901
|
+
* entry. This is distinct from the opaque `ToolExecutionToken` used to
|
|
902
|
+
* correlate nested transports. The final notification always deletes its own
|
|
903
|
+
* stage, whether the result succeeded or failed.
|
|
904
|
+
*/
|
|
905
|
+
const staged = /* @__PURE__ */ new Map();
|
|
906
|
+
/** Successful nested capture waiting for its enclosing transport to commit. */
|
|
907
|
+
let pending;
|
|
908
|
+
let captured;
|
|
909
|
+
const schemaEntry = {
|
|
910
|
+
name: STRUCTURED_OUTPUT_TOOL,
|
|
911
|
+
description: "Report your final structured result. Call this exactly once, when your answer is complete; the arguments must match this tool's parameter schema exactly.",
|
|
912
|
+
parameters: { ...schema }
|
|
913
|
+
};
|
|
914
|
+
childCtx.tools.register({
|
|
915
|
+
...schemaEntry,
|
|
916
|
+
output: {
|
|
917
|
+
schema: {
|
|
918
|
+
type: "object",
|
|
919
|
+
properties: { recorded: {
|
|
920
|
+
type: "boolean",
|
|
921
|
+
const: true
|
|
922
|
+
} },
|
|
923
|
+
required: ["recorded"],
|
|
924
|
+
additionalProperties: false
|
|
925
|
+
},
|
|
926
|
+
render: () => [{
|
|
927
|
+
type: "text",
|
|
928
|
+
text: "Structured output recorded."
|
|
929
|
+
}]
|
|
930
|
+
},
|
|
931
|
+
execute(args, exec) {
|
|
932
|
+
const violations = validateJsonSchemaValue(schema, args);
|
|
933
|
+
if (violations.length > 0) throw new ToolArgsError(violations);
|
|
934
|
+
if (!canComplete()) throw new Error("Wait for all delegated child tasks to finish and process pending messages before submitting structured output.");
|
|
935
|
+
staged.set(exec, { value: args });
|
|
936
|
+
exec.concludeTurn();
|
|
937
|
+
return Promise.resolve({ recorded: true });
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
childCtx.systemPrompt.section({
|
|
941
|
+
name: `tool:${STRUCTURED_OUTPUT_TOOL}`,
|
|
942
|
+
order: childCtx.systemPrompt.getSectionOrder("STRUCTURED_OUTPUT"),
|
|
943
|
+
text: STRUCTURED_OUTPUT_INSTRUCTION
|
|
944
|
+
});
|
|
945
|
+
childCtx.tools.guard((exec) => captured === void 0 && pending === void 0 ? void 0 : `structured output already recorded: the run is complete, so \`${exec.name}\` is not executed`);
|
|
946
|
+
childCtx.on("tools/result", function(exec, result) {
|
|
947
|
+
if (exec.name === "structured_output") {
|
|
948
|
+
const entry = staged.get(exec);
|
|
949
|
+
if (entry === void 0) return;
|
|
950
|
+
staged.delete(exec);
|
|
951
|
+
if (result.isError) return;
|
|
952
|
+
if (exec.parent === void 0) {
|
|
953
|
+
/* v8 ignore else -- sequential agent-loop dispatch lets the guard block every later supported call */
|
|
954
|
+
if (captured === void 0) captured = { value: entry.value };
|
|
955
|
+
} else if (captured === void 0 && pending === void 0) pending = {
|
|
956
|
+
parent: exec.parent,
|
|
957
|
+
value: entry.value
|
|
958
|
+
};
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
if (pending?.parent !== exec.token) return;
|
|
962
|
+
const entry = pending;
|
|
963
|
+
pending = void 0;
|
|
964
|
+
if (result.isError) return;
|
|
965
|
+
/* v8 ignore else -- PTC mode serializes outer executions, so the guard blocks every later supported call */
|
|
966
|
+
if (captured === void 0) captured = { value: entry.value };
|
|
967
|
+
});
|
|
968
|
+
return {
|
|
969
|
+
captured: () => captured,
|
|
970
|
+
acceptsInput: () => staged.size === 0 && pending === void 0 && captured === void 0
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region lib/types/assistant-output.js
|
|
975
|
+
/**
|
|
976
|
+
* Canonical selection of a child's final assistant output. Backend run results
|
|
977
|
+
* and `subagent/end.lastAssistantMessage` apply the same rule: select the last
|
|
978
|
+
* non-empty assistant message. An empty-content message records usage only
|
|
979
|
+
* when the loop appends it after a max-tokens step with no executable blocks,
|
|
980
|
+
* so it does not replace earlier output. If no non-empty message exists,
|
|
981
|
+
* select the accumulated assistant text. Selection is independent of the
|
|
982
|
+
* run's stop reason.
|
|
983
|
+
*
|
|
984
|
+
* @module @qlzt/dsh-subagent/assistant-output
|
|
985
|
+
*/
|
|
986
|
+
/**
|
|
987
|
+
* Incremental fold of the selection rule, for backends that observe a child's
|
|
988
|
+
* output as it streams: session-event backends {@link push} each event, and
|
|
989
|
+
* transports without session events (ACP content chunks) {@link pushText} raw
|
|
990
|
+
* text into the same streamed fallback.
|
|
991
|
+
*/
|
|
992
|
+
var AssistantOutputFold = class {
|
|
993
|
+
message;
|
|
994
|
+
partial = [];
|
|
995
|
+
/**
|
|
996
|
+
* Fold one session event: a non-empty assistant message becomes the
|
|
997
|
+
* candidate final answer, while its embedded stream and any log-only attempt
|
|
998
|
+
* extend the streamed fallback; every other event contributes nothing.
|
|
999
|
+
* @param event - the next observed session event.
|
|
1000
|
+
*/
|
|
1001
|
+
push(event) {
|
|
1002
|
+
if (event.type === "assistant/message") {
|
|
1003
|
+
const content = event.data.message.content;
|
|
1004
|
+
if (content.length > 0) this.message = content;
|
|
1005
|
+
}
|
|
1006
|
+
if (event.type === "assistant/message" || event.type === "assistant/attempt") this.pushText(joinAssistantStreamText(event.data.stream));
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Extend the streamed fallback with text observed outside session events.
|
|
1010
|
+
* @param text - the next streamed text piece (an empty piece is a no-op).
|
|
1011
|
+
*/
|
|
1012
|
+
pushText(text) {
|
|
1013
|
+
if (text.length > 0) this.partial.push(text);
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Select the final output folded so far.
|
|
1017
|
+
* @returns the last non-empty assistant message, else the accumulated
|
|
1018
|
+
* streamed text, or `undefined` when the child produced neither.
|
|
1019
|
+
*/
|
|
1020
|
+
collect() {
|
|
1021
|
+
if (this.message !== void 0) return this.message;
|
|
1022
|
+
const text = this.partial.join("");
|
|
1023
|
+
return text.length > 0 ? [{
|
|
1024
|
+
type: "text",
|
|
1025
|
+
text
|
|
1026
|
+
}] : void 0;
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
/**
|
|
1030
|
+
* Apply the selection rule to one complete child-owned event suffix.
|
|
1031
|
+
* @param events - the child-owned events (after any seed or epoch boundary).
|
|
1032
|
+
* @returns the selected output, or `undefined` when the child produced none.
|
|
1033
|
+
*/
|
|
1034
|
+
function finalAssistantOutput(events) {
|
|
1035
|
+
const fold = new AssistantOutputFold();
|
|
1036
|
+
for (const event of events) fold.push(event);
|
|
1037
|
+
return fold.collect();
|
|
1038
|
+
}
|
|
1039
|
+
//#endregion
|
|
1040
|
+
//#region lib/types/activation.js
|
|
1041
|
+
/** Execution-period records, capacity slots, child serialization, and local output capture.
|
|
1042
|
+
* @module @qlzt/dsh-subagent/activation
|
|
1043
|
+
*/
|
|
1044
|
+
/** Process-local slots shared through uninterrupted continuable parent links. */
|
|
1045
|
+
var ActivationPool = class {
|
|
1046
|
+
slots = /* @__PURE__ */ new Set();
|
|
1047
|
+
/**
|
|
1048
|
+
* Reserve before reconstruction; release also tolerates unpublished rollback.
|
|
1049
|
+
* @param capacity - the maximum simultaneous activations in this pool.
|
|
1050
|
+
* @returns an idempotent slot release.
|
|
1051
|
+
*/
|
|
1052
|
+
reserve(capacity) {
|
|
1053
|
+
if (this.slots.size >= capacity) throw new SubagentError(`subagent limit reached (active child limit: ${capacity}); wait for an existing child to finish or complete this work with the current agents`, "ACTIVATION_LIMIT_REACHED");
|
|
1054
|
+
const slot = Symbol();
|
|
1055
|
+
this.slots.add(slot);
|
|
1056
|
+
return () => {
|
|
1057
|
+
this.slots.delete(slot);
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
/**
|
|
1062
|
+
* Read the live Agent retained by local execution.
|
|
1063
|
+
* @param activation - the managed local or external execution.
|
|
1064
|
+
* @returns the local Agent, absent for an external run.
|
|
1065
|
+
*/
|
|
1066
|
+
function activationAgent(activation) {
|
|
1067
|
+
return activation.kind === "local" ? activation.handle.agent : void 0;
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Require local residency before accepting further input.
|
|
1071
|
+
* @param activation - execution targeted by message delivery.
|
|
1072
|
+
* @returns the local activation.
|
|
1073
|
+
* @throws when the external backend cannot accept another message.
|
|
1074
|
+
*/
|
|
1075
|
+
function requireLocalActivation(activation) {
|
|
1076
|
+
switch (activation.kind) {
|
|
1077
|
+
case "local": return activation;
|
|
1078
|
+
case "external": throw new SubagentError(`subagent "${activation.childId}" does not accept follow-up input`, "NOT_CONTINUABLE");
|
|
1079
|
+
/* v8 ignore next 2 -- Both execution kinds are handled above. */
|
|
1080
|
+
default: return assertNever(activation);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Retain local failures whose turn ending could not be committed.
|
|
1085
|
+
* @param activation - exact local Agent and epoch receiving the scoped observers.
|
|
1086
|
+
* @param wake - notify its settlement watcher when failure changes readiness.
|
|
1087
|
+
*/
|
|
1088
|
+
function observeLocalFailure(activation, wake) {
|
|
1089
|
+
const child = activation.handle.agent;
|
|
1090
|
+
child.ctx.on("agent/error", ({ agent }) => {
|
|
1091
|
+
if (agent !== child) return;
|
|
1092
|
+
activation.failureAt = child.session.seq;
|
|
1093
|
+
wake();
|
|
1094
|
+
});
|
|
1095
|
+
child.ctx.on("session/event", (session, event) => {
|
|
1096
|
+
if (session === child.session && event.type === "turn/end" && activation.failureAt !== void 0 && event.seq >= activation.failureAt) activation.failureAt = void 0;
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Capture local output and retain failures without a later committed turn ending.
|
|
1101
|
+
* @param activation - the settled local execution and any structured result.
|
|
1102
|
+
* @returns final output, stop reason, and committed structured value.
|
|
1103
|
+
*/
|
|
1104
|
+
function captureLocalResult(activation) {
|
|
1105
|
+
const events = activation.handle.agent.session.snapshotEvents(activation.outputStart);
|
|
1106
|
+
const output = finalAssistantOutput(events) ?? [];
|
|
1107
|
+
const stopReason = activation.failureAt === void 0 ? epochStopReason(events) : "error";
|
|
1108
|
+
const structured = activation.structured;
|
|
1109
|
+
if (structured !== void 0) {
|
|
1110
|
+
const captured = structured.captured();
|
|
1111
|
+
if (captured !== void 0) return {
|
|
1112
|
+
output,
|
|
1113
|
+
stopReason,
|
|
1114
|
+
structured: captured.value
|
|
1115
|
+
};
|
|
1116
|
+
if (stopReason === "completed") return {
|
|
1117
|
+
output,
|
|
1118
|
+
stopReason: "error"
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
return {
|
|
1122
|
+
output,
|
|
1123
|
+
stopReason
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
/** Serialize each durable child's delivery, release, and disposal. */
|
|
1127
|
+
var ChildLock = class {
|
|
1128
|
+
tails = /* @__PURE__ */ new Map();
|
|
1129
|
+
/**
|
|
1130
|
+
* Run `operation` after every previously queued operation for `childId`.
|
|
1131
|
+
* @param childId - the durable child whose operations are linearized.
|
|
1132
|
+
* @param operation - the critical section to run in order.
|
|
1133
|
+
* @returns the operation's own settlement.
|
|
1134
|
+
*/
|
|
1135
|
+
run(childId, operation) {
|
|
1136
|
+
const result = (this.tails.get(childId) ?? Promise.resolve()).then(operation, operation);
|
|
1137
|
+
const tail = result.then(() => void 0, () => void 0);
|
|
1138
|
+
this.tails.set(childId, tail);
|
|
1139
|
+
tail.then(() => {
|
|
1140
|
+
if (this.tails.get(childId) === tail) this.tails.delete(childId);
|
|
1141
|
+
});
|
|
1142
|
+
return result;
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
//#endregion
|
|
1146
|
+
//#region lib/types/manager.js
|
|
1147
|
+
/**
|
|
1148
|
+
* Owns subagent startup, message admission, cold resume, and execution lifetimes.
|
|
1149
|
+
* One child lock orders input acceptance and closure; one activation map owns
|
|
1150
|
+
* capacity, parent relationships, and resource release across all providers.
|
|
1151
|
+
*
|
|
1152
|
+
* @module @qlzt/dsh-subagent/manager
|
|
1153
|
+
*/
|
|
1154
|
+
var __addDisposableResource$2 = function(env, value, async) {
|
|
1155
|
+
if (value !== null && value !== void 0) {
|
|
1156
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
1157
|
+
var dispose, inner;
|
|
1158
|
+
if (async) {
|
|
1159
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
1160
|
+
dispose = value[Symbol.asyncDispose];
|
|
1161
|
+
}
|
|
1162
|
+
if (dispose === void 0) {
|
|
1163
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
1164
|
+
dispose = value[Symbol.dispose];
|
|
1165
|
+
if (async) inner = dispose;
|
|
1166
|
+
}
|
|
1167
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
1168
|
+
if (inner) dispose = function() {
|
|
1169
|
+
try {
|
|
1170
|
+
inner.call(this);
|
|
1171
|
+
} catch (e) {
|
|
1172
|
+
return Promise.reject(e);
|
|
1173
|
+
}
|
|
1174
|
+
};
|
|
1175
|
+
env.stack.push({
|
|
1176
|
+
value,
|
|
1177
|
+
dispose,
|
|
1178
|
+
async
|
|
1179
|
+
});
|
|
1180
|
+
} else if (async) env.stack.push({ async: true });
|
|
1181
|
+
return value;
|
|
1182
|
+
};
|
|
1183
|
+
var __disposeResources$2 = (function(SuppressedError) {
|
|
1184
|
+
return function(env) {
|
|
1185
|
+
function fail(e) {
|
|
1186
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
1187
|
+
env.hasError = true;
|
|
1188
|
+
}
|
|
1189
|
+
var r, s = 0;
|
|
1190
|
+
function next() {
|
|
1191
|
+
while (r = env.stack.pop()) try {
|
|
1192
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
1193
|
+
if (r.dispose) {
|
|
1194
|
+
var result = r.dispose.call(r.value);
|
|
1195
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
1196
|
+
fail(e);
|
|
1197
|
+
return next();
|
|
1198
|
+
});
|
|
1199
|
+
} else s |= 1;
|
|
1200
|
+
} catch (e) {
|
|
1201
|
+
fail(e);
|
|
1202
|
+
}
|
|
1203
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
1204
|
+
if (env.hasError) throw env.error;
|
|
1205
|
+
}
|
|
1206
|
+
return next();
|
|
1207
|
+
};
|
|
1208
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
1209
|
+
var e = new Error(message);
|
|
1210
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
1211
|
+
});
|
|
1212
|
+
/** Render only the safe outer message from execution or teardown failures. */
|
|
1213
|
+
function failureMessage(error) {
|
|
1214
|
+
return error instanceof Error ? error.message : "unknown teardown failure";
|
|
1215
|
+
}
|
|
1216
|
+
/** Own subagent requests and the resources of every live activation. */
|
|
1217
|
+
var SubagentManager = class {
|
|
1218
|
+
ctx;
|
|
1219
|
+
host;
|
|
1220
|
+
maxActiveSubagents;
|
|
1221
|
+
/** Child session id → its live Activation. Process-local, never durable. */
|
|
1222
|
+
resident = /* @__PURE__ */ new Map();
|
|
1223
|
+
/** Root identities retain their pool across child settlement without retaining dead roots. */
|
|
1224
|
+
rootPools = /* @__PURE__ */ new WeakMap();
|
|
1225
|
+
/** Materializations admitted before drain, tracked through publication or rollback. */
|
|
1226
|
+
materializations = /* @__PURE__ */ new Set();
|
|
1227
|
+
/** Per-child serializer shared by delivery, release, and disposal. */
|
|
1228
|
+
locks = new ChildLock();
|
|
1229
|
+
/** Structural Cordis owner of every Activation handle. */
|
|
1230
|
+
ownerCtx;
|
|
1231
|
+
/**
|
|
1232
|
+
* Exact roots whose host teardown has begun, with the live lineage members
|
|
1233
|
+
* observed under each root. Entries remain until that exact root leaves the
|
|
1234
|
+
* Agent registry, closing admission throughout its host's teardown without
|
|
1235
|
+
* poisoning a later same-id replacement.
|
|
1236
|
+
*/
|
|
1237
|
+
closingScopes = /* @__PURE__ */ new Map();
|
|
1238
|
+
draining = false;
|
|
1239
|
+
/**
|
|
1240
|
+
* Build one manager inside the service's Agent-injected context.
|
|
1241
|
+
* @param ctx - context providing Agents, Sessions, and teardown ownership.
|
|
1242
|
+
* @param host - provider dispatch and lifecycle observation owned by the service.
|
|
1243
|
+
* @param maxActiveSubagents - the current configured child capacity.
|
|
1244
|
+
*/
|
|
1245
|
+
constructor(ctx, host, maxActiveSubagents) {
|
|
1246
|
+
this.ctx = ctx;
|
|
1247
|
+
this.host = host;
|
|
1248
|
+
this.maxActiveSubagents = maxActiveSubagents;
|
|
1249
|
+
const scope = ctx.plugin(function activationOwner() {});
|
|
1250
|
+
this.ownerCtx = scope.ctx;
|
|
1251
|
+
ctx.on("agent/disposed", ({ agent }) => {
|
|
1252
|
+
this.closingScopes.delete(agent);
|
|
1253
|
+
});
|
|
1254
|
+
ctx.effect(function* () {
|
|
1255
|
+
yield scope.dispose;
|
|
1256
|
+
yield () => this.drain();
|
|
1257
|
+
}.bind(this), "subagents.manager()");
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Interrupt one live continuable child's current turn under the supplied authority.
|
|
1261
|
+
* @param targetSessionId - the durable child session id to interrupt.
|
|
1262
|
+
* @param authority - the human parent address or exact live ancestor Agent.
|
|
1263
|
+
*/
|
|
1264
|
+
interrupt(targetSessionId, authority) {
|
|
1265
|
+
if (authority.kind === "ancestor") {
|
|
1266
|
+
const caller = authority.agent;
|
|
1267
|
+
if (this.ctx.agents.get(caller.id) !== caller) throw new SubagentError(`interrupting "${targetSessionId}" requires the exact live ancestor agent`, "UNAUTHORIZED");
|
|
1268
|
+
if (caller.id === targetSessionId) throw new SubagentError(`agent "${caller.id}" cannot interrupt itself`, "UNAUTHORIZED");
|
|
1269
|
+
}
|
|
1270
|
+
const activation = this.resident.get(targetSessionId);
|
|
1271
|
+
if (activation === void 0) return;
|
|
1272
|
+
if (authority.kind === "user") {
|
|
1273
|
+
if (activation.parent.id !== authority.parentSessionId) throw new SubagentError(`subagent "${targetSessionId}" belongs to another parent session`, "UNAUTHORIZED");
|
|
1274
|
+
} else if (!activation.ancestry.has(authority.agent)) throw new SubagentError(`subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`, "UNAUTHORIZED");
|
|
1275
|
+
if (activation.closing !== void 0) return;
|
|
1276
|
+
const kind = authority.kind === "user" ? "user" : "parent";
|
|
1277
|
+
if (activation.kind === "local") activation.handle.agent.cancel({ kind }, { keepInbox: true });
|
|
1278
|
+
else {
|
|
1279
|
+
activation.controller.abort({ kind });
|
|
1280
|
+
this.dispose(activation).catch(() => void 0);
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Close admission, await every already-admitted materialization through
|
|
1285
|
+
* publication or rollback, then dispose the stable live Activation graph
|
|
1286
|
+
* child-first.
|
|
1287
|
+
*/
|
|
1288
|
+
async drain() {
|
|
1289
|
+
this.draining = true;
|
|
1290
|
+
for (const pending of this.materializations) pending.controller.abort();
|
|
1291
|
+
await Promise.all([...this.materializations].map((materialization) => materialization.settled));
|
|
1292
|
+
const owned = /* @__PURE__ */ new Set();
|
|
1293
|
+
for (const activation of this.resident.values()) for (const child of activation.ownedChildren) owned.add(child);
|
|
1294
|
+
const roots = [...this.resident.values()].filter((activation) => !owned.has(activation.childId));
|
|
1295
|
+
await this.disposeRoots(roots, "activation(s)");
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Join progressing child work, leaving idle parked inboxes resident.
|
|
1299
|
+
* @param parent - exact live parent whose descendants are observed.
|
|
1300
|
+
* @returns whether work was joined and the host must recheck parent completion.
|
|
1301
|
+
*/
|
|
1302
|
+
async waitForChildren(parent) {
|
|
1303
|
+
let observed = false;
|
|
1304
|
+
while (true) {
|
|
1305
|
+
const pending = [...this.materializations].filter((item) => item.lineage.includes(parent));
|
|
1306
|
+
const children = [...this.resident.values()].filter((item) => activationAgent(item) !== parent && item.ancestry.has(parent));
|
|
1307
|
+
observed ||= children.some((item) => item.kind === "local" && item.handle.agent.status !== "idle");
|
|
1308
|
+
await Promise.all(children.flatMap((item) => item.kind === "local" ? [item.handle.agent.whenIdle()] : []));
|
|
1309
|
+
const waits = pending.map((item) => item.settled);
|
|
1310
|
+
for (const item of children) {
|
|
1311
|
+
if (item.kind === "external" || item.closing !== void 0) {
|
|
1312
|
+
waits.push(item.result.promise.catch(() => void 0));
|
|
1313
|
+
continue;
|
|
1314
|
+
}
|
|
1315
|
+
if (item.handle.agent.status !== "idle") {
|
|
1316
|
+
waits.push(item.handle.agent.whenIdle());
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
if (item.ownedChildren.size > 0) {
|
|
1320
|
+
if ([...item.ownedChildren].some((id) => !this.resident.has(id))) waits.push(item.poke.promise);
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
const inbox = item.handle.agent.inbox;
|
|
1324
|
+
if (item.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) continue;
|
|
1325
|
+
waits.push(Promise.race([item.result.promise.catch(() => void 0), item.poke.promise]));
|
|
1326
|
+
}
|
|
1327
|
+
if (waits.length > 0) {
|
|
1328
|
+
observed = true;
|
|
1329
|
+
await Promise.all(waits);
|
|
1330
|
+
continue;
|
|
1331
|
+
}
|
|
1332
|
+
if ([...this.materializations].some((item) => item.lineage.includes(parent) && !pending.includes(item)) || [...this.resident.values()].some((item) => activationAgent(item) !== parent && item.ancestry.has(parent) && !children.includes(item))) continue;
|
|
1333
|
+
return observed;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* Stop the managed descendants of exact live host-owned parents.
|
|
1338
|
+
* @param parents - exact live roots whose managed descendants must stop.
|
|
1339
|
+
*/
|
|
1340
|
+
async drainDescendants(parents) {
|
|
1341
|
+
const roots = new Set(parents.filter((parent) => this.ctx.agents.get(parent.id) === parent));
|
|
1342
|
+
if (roots.size === 0) return;
|
|
1343
|
+
for (const root of roots) this.closingMembers(root).add(root);
|
|
1344
|
+
const targets = [];
|
|
1345
|
+
for (const activation of this.resident.values()) {
|
|
1346
|
+
const child = activationAgent(activation);
|
|
1347
|
+
const lineage = this.liveLineage(child ?? activation.parent);
|
|
1348
|
+
const owners = [...roots].filter((root) => child !== root && activation.ancestry.has(root));
|
|
1349
|
+
if (owners.length === 0) continue;
|
|
1350
|
+
targets.push(activation);
|
|
1351
|
+
for (const owner of owners) {
|
|
1352
|
+
const members = this.closingMembers(owner);
|
|
1353
|
+
if (child !== void 0) members.add(child);
|
|
1354
|
+
for (const agent of lineage) members.add(agent);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
const materializations = [...this.materializations].filter((materialization) => {
|
|
1358
|
+
const owners = [...roots].filter((root) => materialization.lineage.includes(root));
|
|
1359
|
+
for (const owner of owners) {
|
|
1360
|
+
const members = this.closingMembers(owner);
|
|
1361
|
+
for (const agent of materialization.lineage) members.add(agent);
|
|
1362
|
+
}
|
|
1363
|
+
if (owners.length > 0) materialization.controller.abort();
|
|
1364
|
+
return owners.length > 0;
|
|
1365
|
+
});
|
|
1366
|
+
const ownedTargets = /* @__PURE__ */ new Set();
|
|
1367
|
+
for (const activation of targets) for (const child of activation.ownedChildren) ownedTargets.add(child);
|
|
1368
|
+
const targetRoots = targets.filter((activation) => !ownedTargets.has(activation.childId));
|
|
1369
|
+
for (const activation of targets) this.dispose(activation).catch(() => void 0);
|
|
1370
|
+
await Promise.all(materializations.map((materialization) => materialization.settled));
|
|
1371
|
+
await this.disposeRoots(targetRoots, "scoped activation(s)");
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Release selected resident direct children of one exact live parent.
|
|
1375
|
+
* @param parent - exact live direct parent authorizing the selected release.
|
|
1376
|
+
* @param childIds - durable direct-child ids to release when resident.
|
|
1377
|
+
*/
|
|
1378
|
+
async drainChildren(parent, childIds) {
|
|
1379
|
+
if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("selected child teardown requires the exact live parent agent", "UNAUTHORIZED");
|
|
1380
|
+
const targets = [];
|
|
1381
|
+
for (const childId of new Set(childIds)) {
|
|
1382
|
+
const activation = this.resident.get(childId);
|
|
1383
|
+
if (activation === void 0) continue;
|
|
1384
|
+
if (activation.parent.id !== parent.id || !activation.ancestry.has(parent)) throw new SubagentError(`subagent "${childId}" is not a direct child of agent "${parent.id}"`, "UNAUTHORIZED");
|
|
1385
|
+
targets.push(activation);
|
|
1386
|
+
}
|
|
1387
|
+
for (const activation of targets) this.dispose(activation).catch(() => void 0);
|
|
1388
|
+
await this.disposeRoots(targets, "selected activation(s)");
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Start one continuable background child and resolve at initial inbox acceptance.
|
|
1392
|
+
* Every earlier failure disposes any created handle and rolls back Activation
|
|
1393
|
+
* and parent ownership without returning either id.
|
|
1394
|
+
* @param spec - provider, delegation request, and caller cancellation.
|
|
1395
|
+
* @returns the durable child id and accepted initial prompt message id.
|
|
1396
|
+
*/
|
|
1397
|
+
async startLocal(spec) {
|
|
1398
|
+
const request = spec.request;
|
|
1399
|
+
const parent = request.parent;
|
|
1400
|
+
this.assertAdmitting(parent);
|
|
1401
|
+
const persistence = spec.delivery === "caller" ? this.ctx.get("sessionPersistence") : this.requirePersistence();
|
|
1402
|
+
assertSubagentMaxDepth(request.maxDepth);
|
|
1403
|
+
const childId = spec.childId ?? brandString(randomUUID());
|
|
1404
|
+
this.assertChildIdAvailable(childId);
|
|
1405
|
+
const childDepth = resolveChildDepth(parent, request.maxDepth);
|
|
1406
|
+
const agentOptions = resolveChildAgentOptions(parent, request.agentOptions, childDepth);
|
|
1407
|
+
const agentProvider = agentOptions.provider;
|
|
1408
|
+
const agentModel = agentOptions.model;
|
|
1409
|
+
const agentReasoningEffort = agentOptions.reasoningEffort;
|
|
1410
|
+
const descriptor = snapshotSubagentDescriptor({
|
|
1411
|
+
mode: "continuable",
|
|
1412
|
+
provider: spec.provider,
|
|
1413
|
+
label: spec.label,
|
|
1414
|
+
...agentProvider !== void 0 ? { agentProvider } : {},
|
|
1415
|
+
...agentModel !== void 0 ? { agentModel } : {},
|
|
1416
|
+
...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {},
|
|
1417
|
+
...request.persona !== void 0 ? { persona: request.persona } : {},
|
|
1418
|
+
...request.toolFilter !== void 0 ? { toolFilter: request.toolFilter } : {}
|
|
1419
|
+
});
|
|
1420
|
+
const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
|
|
1421
|
+
const releaseHold = this.holdOwnership(parent, childId);
|
|
1422
|
+
try {
|
|
1423
|
+
const cwd = await this.resolveDirectory(request, spec.signal);
|
|
1424
|
+
const prepared = await this.host.prepareContinuable(spec.provider, {
|
|
1425
|
+
sessionId: childId,
|
|
1426
|
+
cwd,
|
|
1427
|
+
parent,
|
|
1428
|
+
signal: spec.signal
|
|
1429
|
+
});
|
|
1430
|
+
spec.signal.throwIfAborted();
|
|
1431
|
+
this.assertAdmitting(parent);
|
|
1432
|
+
const inheritedEventCount = SessionLogOffset(prepared.seed?.length ?? 0);
|
|
1433
|
+
const seed = prepared.seed;
|
|
1434
|
+
let established;
|
|
1435
|
+
const messageId = await this.locks.run(childId, async () => {
|
|
1436
|
+
spec.signal.throwIfAborted();
|
|
1437
|
+
this.assertAdmitting(parent);
|
|
1438
|
+
this.assertChildIdAvailable(childId);
|
|
1439
|
+
if (spec.childId !== void 0) {
|
|
1440
|
+
const persisted = await persistence?.stat(childId, { signal: spec.signal });
|
|
1441
|
+
spec.signal.throwIfAborted();
|
|
1442
|
+
this.assertAdmitting(parent);
|
|
1443
|
+
this.assertChildIdAvailable(childId);
|
|
1444
|
+
if (persisted !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
|
|
1445
|
+
}
|
|
1446
|
+
const activation = await this.materialize({
|
|
1447
|
+
kind: "local",
|
|
1448
|
+
childId,
|
|
1449
|
+
provider: spec.provider,
|
|
1450
|
+
parent,
|
|
1451
|
+
create: {
|
|
1452
|
+
cwd,
|
|
1453
|
+
seed,
|
|
1454
|
+
meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0),
|
|
1455
|
+
inheritedEventCount,
|
|
1456
|
+
delegatedPolicies,
|
|
1457
|
+
descriptor
|
|
1458
|
+
},
|
|
1459
|
+
agentOptions,
|
|
1460
|
+
composition: {
|
|
1461
|
+
persona: request.persona,
|
|
1462
|
+
toolFilter: request.toolFilter
|
|
1463
|
+
},
|
|
1464
|
+
signal: spec.signal,
|
|
1465
|
+
delivery: spec.delivery,
|
|
1466
|
+
outputSchema: spec.request.outputSchema
|
|
1467
|
+
});
|
|
1468
|
+
established = activation;
|
|
1469
|
+
const child = requireLocalActivation(activation).handle.agent;
|
|
1470
|
+
const childHeader = child.session.header;
|
|
1471
|
+
return await this.submitMaterialized(activation, spec.delivery !== "caller" && isAdjacentAgentSendMessageTool(this.ctx.get("tools")?.get("send_message", child)) ? withContinuableReturnGuidance(parent.id, request.prompt) : request.prompt, {
|
|
1472
|
+
source: { kind: "user" },
|
|
1473
|
+
signal: spec.signal,
|
|
1474
|
+
delivery: "queue"
|
|
1475
|
+
}, parent, () => {
|
|
1476
|
+
establishCatalogChild(parent.session, childHeader, descriptor);
|
|
1477
|
+
});
|
|
1478
|
+
});
|
|
1479
|
+
return {
|
|
1480
|
+
...this.receipt(established),
|
|
1481
|
+
childId,
|
|
1482
|
+
messageId
|
|
1483
|
+
};
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
releaseHold();
|
|
1486
|
+
throw error;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Start an external backend under activation ownership.
|
|
1491
|
+
* @param spec - task, provider, cancellation, and delivery policy.
|
|
1492
|
+
* @returns the accepted activation and its result/disposal capabilities.
|
|
1493
|
+
*/
|
|
1494
|
+
async startExternal(spec) {
|
|
1495
|
+
const parent = spec.request.parent;
|
|
1496
|
+
this.assertAdmitting(parent);
|
|
1497
|
+
const pendingId = brandString(randomUUID());
|
|
1498
|
+
const releaseHold = this.holdOwnership(parent, pendingId);
|
|
1499
|
+
let activation;
|
|
1500
|
+
try {
|
|
1501
|
+
const cwd = await this.resolveDirectory(spec.request, spec.signal);
|
|
1502
|
+
activation = await this.materialize({
|
|
1503
|
+
kind: "external",
|
|
1504
|
+
childId: pendingId,
|
|
1505
|
+
provider: spec.provider,
|
|
1506
|
+
parent,
|
|
1507
|
+
signal: spec.signal,
|
|
1508
|
+
delivery: spec.delivery,
|
|
1509
|
+
start: (signal) => this.host.startExternal(spec.provider, {
|
|
1510
|
+
...spec.request,
|
|
1511
|
+
cwd,
|
|
1512
|
+
label: spec.label,
|
|
1513
|
+
signal
|
|
1514
|
+
})
|
|
1515
|
+
});
|
|
1516
|
+
this.assertAdmitting(parent);
|
|
1517
|
+
this.assertLiveParent(parent, activation.childId);
|
|
1518
|
+
spec.signal.throwIfAborted();
|
|
1519
|
+
if (spec.delivery === "parent") establishExternalCatalogChild(parent.session, activation.childId, spec.label);
|
|
1520
|
+
this.announce(activation);
|
|
1521
|
+
return this.receipt(activation);
|
|
1522
|
+
} catch (error) {
|
|
1523
|
+
if (activation !== void 0) try {
|
|
1524
|
+
await this.dispose(activation);
|
|
1525
|
+
} catch (cleanupError) {
|
|
1526
|
+
this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`);
|
|
1527
|
+
}
|
|
1528
|
+
throw error;
|
|
1529
|
+
} finally {
|
|
1530
|
+
releaseHold();
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
/** Capture the explicit or inherited directory while the parent still owns startup. */
|
|
1534
|
+
async resolveDirectory(request, signal) {
|
|
1535
|
+
const cwd = request.cwd !== void 0 && isAbsolute(request.cwd) ? request.cwd : resolve(await this.ctx.workingDirectory.ensure(request.parent, signal), request.cwd ?? ".");
|
|
1536
|
+
signal.throwIfAborted();
|
|
1537
|
+
return cwd;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Deliver one model-authored message to a direct continuable child or to the
|
|
1541
|
+
* sender's direct parent. A missing direct child cold-resumes through the
|
|
1542
|
+
* ordinary continuation lifecycle.
|
|
1543
|
+
* @param sender - exact live Agent authorizing and originating the message.
|
|
1544
|
+
* @param targetId - durable direct-parent or direct-child session id.
|
|
1545
|
+
* @param content - model-authored content to deliver.
|
|
1546
|
+
* @param options - caller cancellation before acceptance.
|
|
1547
|
+
* @returns the accepted message's inbox id.
|
|
1548
|
+
*/
|
|
1549
|
+
async sendMessage(sender, targetId, content, options) {
|
|
1550
|
+
if (this.ctx.agents.get(sender.id) !== sender) throw new SubagentError("message delivery requires the exact live sender agent", "UNAUTHORIZED");
|
|
1551
|
+
this.assertAdmitting(sender);
|
|
1552
|
+
const senderActivation = this.resident.get(sender.id);
|
|
1553
|
+
if (senderActivation !== void 0 && senderActivation.kind === "local" && senderActivation.handle.agent === sender && senderActivation.parent.id === targetId) {
|
|
1554
|
+
options.signal.throwIfAborted();
|
|
1555
|
+
return this.sendToParent(senderActivation, sender, content);
|
|
1556
|
+
}
|
|
1557
|
+
if (sender.session.header.parentSession === targetId) throw new SubagentError(`agent "${sender.id}" is not a resident continuable child and cannot send to parent "${targetId}"`, "UNAUTHORIZED");
|
|
1558
|
+
return this.deliverToChild(sender, targetId, content, {
|
|
1559
|
+
signal: options.signal,
|
|
1560
|
+
delivery: "steer"
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Queue one human-authored prompt as a distinct direct-child turn.
|
|
1565
|
+
* @param parent - exact live direct parent authorizing delivery.
|
|
1566
|
+
* @param childId - durable direct-child session id.
|
|
1567
|
+
* @param content - model-visible prompt blocks.
|
|
1568
|
+
* @param source - durable attribution for the human prompt.
|
|
1569
|
+
* @param signal - caller cancellation before inbox acceptance.
|
|
1570
|
+
* @returns the accepted durable message id.
|
|
1571
|
+
*/
|
|
1572
|
+
async queuePrompt(parent, childId, content, source, signal) {
|
|
1573
|
+
return this.deliverToChild(parent, childId, content, {
|
|
1574
|
+
source,
|
|
1575
|
+
signal,
|
|
1576
|
+
delivery: "queue"
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Steer one host-authored prompt to a direct continuable child.
|
|
1581
|
+
* @param parent - exact live direct parent authorizing delivery.
|
|
1582
|
+
* @param childId - durable direct-child session id.
|
|
1583
|
+
* @param content - model-visible prompt blocks.
|
|
1584
|
+
* @param source - durable attribution for the host prompt.
|
|
1585
|
+
* @param signal - caller cancellation before inbox acceptance.
|
|
1586
|
+
* @returns the accepted durable message id.
|
|
1587
|
+
*/
|
|
1588
|
+
async steerPrompt(parent, childId, content, source, signal) {
|
|
1589
|
+
return this.deliverToChild(parent, childId, content, {
|
|
1590
|
+
source,
|
|
1591
|
+
signal,
|
|
1592
|
+
delivery: "steer"
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
/** Admit local input synchronously before any teardown can begin. */
|
|
1596
|
+
deliver(activation, message, delivery) {
|
|
1597
|
+
if (activation.closing !== void 0) throw new SubagentError("subagent activation is being disposed; the message was not accepted", "ACTIVATION_CLOSING");
|
|
1598
|
+
const local = requireLocalActivation(activation);
|
|
1599
|
+
if (local.structured?.acceptsInput() === false) throw new SubagentError("subagent is submitting or has submitted its structured result; the message was not accepted", "INPUT_CLOSED");
|
|
1600
|
+
if (delivery === "steer") local.handle.agent.steer(message);
|
|
1601
|
+
else local.handle.agent.followup(message);
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Reject one child identity already owned by a live Agent or Session.
|
|
1605
|
+
* @param childId - proposed durable child session id.
|
|
1606
|
+
*/
|
|
1607
|
+
assertChildIdAvailable(childId) {
|
|
1608
|
+
if (this.resident.has(childId) || this.ctx.agents.get(childId) !== void 0 || this.ctx.get("sessions")?.get(childId) !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Pre-register `childId` in a continuation-managed parent's owned set so the
|
|
1612
|
+
* parent cannot settle while a caller is still establishing or resuming that
|
|
1613
|
+
* child. Returns a releaser for the failure path; it removes only a hold
|
|
1614
|
+
* this call added, and leaves ownership in place once a live Activation for
|
|
1615
|
+
* the child exists.
|
|
1616
|
+
* @param parent - the live direct parent the operation is admitted under.
|
|
1617
|
+
* @param childId - the durable child the operation addresses.
|
|
1618
|
+
* @returns the failure-path releaser; a no-op when nothing was added.
|
|
1619
|
+
*/
|
|
1620
|
+
holdOwnership(parent, childId) {
|
|
1621
|
+
const parentActivation = this.resident.get(parent.id);
|
|
1622
|
+
if (parentActivation === void 0 || activationAgent(parentActivation) !== parent) return () => {};
|
|
1623
|
+
if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
|
|
1624
|
+
if (parentActivation.ownedChildren.has(childId)) return () => {};
|
|
1625
|
+
parentActivation.ownedChildren.add(childId);
|
|
1626
|
+
return () => {
|
|
1627
|
+
const live = this.resident.get(childId);
|
|
1628
|
+
/* v8 ignore next 4 -- reaching this arm needs another delivery to establish the child
|
|
1629
|
+
* between this operation's failure and its releaser running, which no test can schedule
|
|
1630
|
+
* deterministically: the ownership edge then belongs to that live Activation, so the
|
|
1631
|
+
* conservative keep leaves it for finishDisposal's releaseOwnership. */
|
|
1632
|
+
if (live !== void 0 && live.closing === void 0) return;
|
|
1633
|
+
if (parentActivation.ownedChildren.delete(childId)) this.wake(parentActivation);
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Apply activation admission to a resident parent before delivering input.
|
|
1638
|
+
* @param parent - exact live Agent receiving the message.
|
|
1639
|
+
* @param message - durable user message to deliver.
|
|
1640
|
+
* @param delivery - receiving inbox destination.
|
|
1641
|
+
*/
|
|
1642
|
+
sendWaking(parent, message, delivery) {
|
|
1643
|
+
const parentActivation = this.resident.get(parent.id);
|
|
1644
|
+
if (parentActivation !== void 0 && activationAgent(parentActivation) === parent) {
|
|
1645
|
+
try {
|
|
1646
|
+
this.deliver(parentActivation, message, delivery);
|
|
1647
|
+
} finally {
|
|
1648
|
+
this.wake(parentActivation);
|
|
1649
|
+
}
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
if (delivery === "steer") parent.steer(message);
|
|
1653
|
+
else parent.followup(message);
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Reject new admission once the manager or this exact parent tree began draining.
|
|
1657
|
+
* @param agent - exact live Agent whose lineage determines admission.
|
|
1658
|
+
*/
|
|
1659
|
+
assertAdmitting(agent) {
|
|
1660
|
+
const closing = this.closingTeardownFor(agent);
|
|
1661
|
+
if (closing === void 0) return;
|
|
1662
|
+
throw new SubagentError(closing === "manager" ? "subagents are draining; the operation was not admitted" : `subagents below parent "${closing.id}" are draining; the operation was not admitted`, "DRAINING");
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Authorize one operation against the durable direct-parent lineage.
|
|
1666
|
+
* @param parent - exact live Agent claiming direct-parent authority.
|
|
1667
|
+
* @param childId - durable child session id addressed by the operation.
|
|
1668
|
+
* @param parentSession - durable direct-parent id recorded by the child.
|
|
1669
|
+
*/
|
|
1670
|
+
authorizeLineage(parent, childId, parentSession) {
|
|
1671
|
+
this.assertLiveParent(parent, childId);
|
|
1672
|
+
if (parentSession !== parent.id) throw new SubagentError(`subagent "${childId}" belongs to another parent session`, "UNAUTHORIZED");
|
|
1673
|
+
}
|
|
1674
|
+
/** Reject parent authority after the live registry entry changes. */
|
|
1675
|
+
assertLiveParent(parent, childId) {
|
|
1676
|
+
if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError(`subagent "${childId}" delivery requires the exact live parent agent`, "UNAUTHORIZED");
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* Create or resume one child Agent and publish its Activation.
|
|
1680
|
+
* @param inputs - reconstruction and admission inputs for the residency epoch.
|
|
1681
|
+
* @returns the published process-local Activation.
|
|
1682
|
+
*/
|
|
1683
|
+
materialize(inputs) {
|
|
1684
|
+
this.assertAdmitting(inputs.parent);
|
|
1685
|
+
inputs.signal.throwIfAborted();
|
|
1686
|
+
const lineage = this.liveLineage(inputs.parent);
|
|
1687
|
+
const pool = this.resident.get(inputs.parent.id)?.pool ?? this.rootPool(inputs.parent);
|
|
1688
|
+
const releaseSlot = pool.reserve(this.maxActiveSubagents());
|
|
1689
|
+
const settled = Promise.withResolvers();
|
|
1690
|
+
const controller = new AbortController();
|
|
1691
|
+
const materialization = {
|
|
1692
|
+
lineage,
|
|
1693
|
+
settled: settled.promise,
|
|
1694
|
+
controller
|
|
1695
|
+
};
|
|
1696
|
+
this.materializations.add(materialization);
|
|
1697
|
+
return this.materializeTracked({
|
|
1698
|
+
...inputs,
|
|
1699
|
+
signal: AbortSignal.any([inputs.signal, controller.signal])
|
|
1700
|
+
}, lineage, pool, releaseSlot).catch((error) => {
|
|
1701
|
+
releaseSlot();
|
|
1702
|
+
if (error instanceof Error && error.name === "AbortError") this.assertAdmitting(inputs.parent);
|
|
1703
|
+
throw error;
|
|
1704
|
+
}).finally(() => {
|
|
1705
|
+
this.materializations.delete(materialization);
|
|
1706
|
+
settled.resolve();
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* Stop and release one Activation through its memoized close transaction.
|
|
1711
|
+
* @param activation - exact residency epoch to close.
|
|
1712
|
+
* @returns the shared close transaction.
|
|
1713
|
+
*/
|
|
1714
|
+
dispose(activation) {
|
|
1715
|
+
return this.close(activation, () => this.finishDisposal(activation, true));
|
|
1716
|
+
}
|
|
1717
|
+
/** Close admission synchronously and share one release, including startup rollback. */
|
|
1718
|
+
close(activation, release) {
|
|
1719
|
+
if (activation.closing !== void 0) return activation.closing;
|
|
1720
|
+
const completion = Promise.withResolvers();
|
|
1721
|
+
activation.closing = completion.promise;
|
|
1722
|
+
release().then(completion.resolve, completion.reject);
|
|
1723
|
+
return completion.promise;
|
|
1724
|
+
}
|
|
1725
|
+
/** Dispose independent roots and report every branch failure after all settle. */
|
|
1726
|
+
async disposeRoots(roots, failureSubject) {
|
|
1727
|
+
const reasons = (await Promise.all(roots.map(async (activation) => {
|
|
1728
|
+
try {
|
|
1729
|
+
await this.dispose(activation);
|
|
1730
|
+
return;
|
|
1731
|
+
} catch (error) {
|
|
1732
|
+
return error;
|
|
1733
|
+
}
|
|
1734
|
+
}))).filter((failure) => failure !== void 0);
|
|
1735
|
+
if (reasons.length > 0) throw new SubagentError(`subagent teardown failed for ${reasons.length} ${failureSubject}: ` + reasons.map((reason) => failureMessage(reason)).join("; "), "ACTIVATION_TEARDOWN_FAILED");
|
|
1736
|
+
}
|
|
1737
|
+
/** Return the retained member set for one exact scoped-teardown root. */
|
|
1738
|
+
closingMembers(root) {
|
|
1739
|
+
const existing = this.closingScopes.get(root);
|
|
1740
|
+
if (existing !== void 0) return existing;
|
|
1741
|
+
const members = /* @__PURE__ */ new Set();
|
|
1742
|
+
this.closingScopes.set(root, members);
|
|
1743
|
+
return members;
|
|
1744
|
+
}
|
|
1745
|
+
/** Return the exact currently resolvable ancestry from `agent` upward. */
|
|
1746
|
+
liveLineage(agent) {
|
|
1747
|
+
const lineage = [agent];
|
|
1748
|
+
const seen = new Set([agent.id]);
|
|
1749
|
+
let parentSession = agent.session.header.parentSession;
|
|
1750
|
+
while (parentSession !== void 0) {
|
|
1751
|
+
const parent = this.ctx.agents.get(parentSession);
|
|
1752
|
+
if (parent === void 0 || seen.has(parent.id)) break;
|
|
1753
|
+
lineage.push(parent);
|
|
1754
|
+
seen.add(parent.id);
|
|
1755
|
+
parentSession = parent.session.header.parentSession;
|
|
1756
|
+
}
|
|
1757
|
+
return lineage;
|
|
1758
|
+
}
|
|
1759
|
+
/** Return the teardown that closed continuable admission for this agent's lineage. */
|
|
1760
|
+
closingTeardownFor(agent) {
|
|
1761
|
+
if (this.draining) return "manager";
|
|
1762
|
+
const lineage = this.liveLineage(agent);
|
|
1763
|
+
for (const [root, members] of this.closingScopes) if (members.has(agent) || lineage.includes(root)) return root;
|
|
1764
|
+
}
|
|
1765
|
+
/** Resolve a root's pool once; descendants inherit their resident parent's pool directly. */
|
|
1766
|
+
rootPool(parent) {
|
|
1767
|
+
let pool = this.rootPools.get(parent);
|
|
1768
|
+
if (pool === void 0) {
|
|
1769
|
+
pool = new ActivationPool();
|
|
1770
|
+
this.rootPools.set(parent, pool);
|
|
1771
|
+
}
|
|
1772
|
+
return pool;
|
|
1773
|
+
}
|
|
1774
|
+
/** Perform one tracked materialization through publication or rollback. */
|
|
1775
|
+
async materializeTracked(inputs, parentLineage, pool, releaseSlot) {
|
|
1776
|
+
const { provider, parent } = inputs;
|
|
1777
|
+
let childId = inputs.childId;
|
|
1778
|
+
inputs.signal.throwIfAborted();
|
|
1779
|
+
let resource;
|
|
1780
|
+
if (inputs.kind === "external") {
|
|
1781
|
+
const controller = new AbortController();
|
|
1782
|
+
const cancelStartup = () => {
|
|
1783
|
+
controller.abort(inputs.signal.reason);
|
|
1784
|
+
};
|
|
1785
|
+
inputs.signal.addEventListener("abort", cancelStartup, { once: true });
|
|
1786
|
+
try {
|
|
1787
|
+
const run = await inputs.start(controller.signal);
|
|
1788
|
+
resource = {
|
|
1789
|
+
kind: "external",
|
|
1790
|
+
run,
|
|
1791
|
+
controller
|
|
1792
|
+
};
|
|
1793
|
+
run.result.catch(() => void 0);
|
|
1794
|
+
childId = run.id;
|
|
1795
|
+
try {
|
|
1796
|
+
this.assertChildIdAvailable(childId);
|
|
1797
|
+
} catch (error) {
|
|
1798
|
+
await run.dispose();
|
|
1799
|
+
throw error;
|
|
1800
|
+
}
|
|
1801
|
+
} finally {
|
|
1802
|
+
inputs.signal.removeEventListener("abort", cancelStartup);
|
|
1803
|
+
}
|
|
1804
|
+
} else {
|
|
1805
|
+
const { create } = inputs;
|
|
1806
|
+
let structured;
|
|
1807
|
+
const setup = async (childCtx, child) => {
|
|
1808
|
+
if (create !== void 0) {
|
|
1809
|
+
child.session.append("subagent/descriptor", create.descriptor);
|
|
1810
|
+
appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies);
|
|
1811
|
+
const workingDirectory = childCtx.get("workingDirectory");
|
|
1812
|
+
if (workingDirectory === void 0) throw new Error("local subagents require the working-directory service");
|
|
1813
|
+
await workingDirectory.set(child, create.cwd, inputs.signal);
|
|
1814
|
+
}
|
|
1815
|
+
applyChildComposition(childCtx, parent, inputs.composition);
|
|
1816
|
+
if (inputs.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => this.resident.get(childId)?.ownedChildren.size === 0 && child.inbox.nextStep.length === 0 && child.inbox.nextTurn.length === 0);
|
|
1817
|
+
};
|
|
1818
|
+
const handle = create === void 0 ? await this.ownerCtx.agents.resume({
|
|
1819
|
+
resumeSessionId: childId,
|
|
1820
|
+
parentAgent: parent,
|
|
1821
|
+
agentOptions: inputs.agentOptions,
|
|
1822
|
+
signal: inputs.signal,
|
|
1823
|
+
setup
|
|
1824
|
+
}) : await this.ownerCtx.agents.create({
|
|
1825
|
+
sessionId: childId,
|
|
1826
|
+
parentAgent: parent,
|
|
1827
|
+
meta: create.meta,
|
|
1828
|
+
...create.seed === void 0 ? {} : { seed: create.seed },
|
|
1829
|
+
inheritedEventCount: create.inheritedEventCount,
|
|
1830
|
+
agentOptions: inputs.agentOptions,
|
|
1831
|
+
signal: inputs.signal,
|
|
1832
|
+
setup
|
|
1833
|
+
});
|
|
1834
|
+
resource = {
|
|
1835
|
+
kind: "local",
|
|
1836
|
+
handle,
|
|
1837
|
+
outputStart: handle.agent.session.seq,
|
|
1838
|
+
structured,
|
|
1839
|
+
failureAt: void 0,
|
|
1840
|
+
poke: Promise.withResolvers()
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
const observer = this.host.observeActivation(provider, childId, parent);
|
|
1844
|
+
const activation = {
|
|
1845
|
+
pool,
|
|
1846
|
+
releaseSlot,
|
|
1847
|
+
childId,
|
|
1848
|
+
...resource,
|
|
1849
|
+
parent,
|
|
1850
|
+
delivery: inputs.delivery ?? "parent",
|
|
1851
|
+
result: Promise.withResolvers(),
|
|
1852
|
+
closing: void 0,
|
|
1853
|
+
ancestry: new WeakSet(resource.kind === "external" ? parentLineage : [resource.handle.agent, ...parentLineage]),
|
|
1854
|
+
ownedChildren: /* @__PURE__ */ new Set(),
|
|
1855
|
+
observer,
|
|
1856
|
+
announced: false
|
|
1857
|
+
};
|
|
1858
|
+
activation.result.promise.catch(() => void 0);
|
|
1859
|
+
this.resident.set(childId, activation);
|
|
1860
|
+
try {
|
|
1861
|
+
this.assertAdmitting(parent);
|
|
1862
|
+
inputs.signal.throwIfAborted();
|
|
1863
|
+
if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("subagent parent is no longer live", "UNAUTHORIZED");
|
|
1864
|
+
this.acquireOwnership(parent, childId);
|
|
1865
|
+
const wakeSettlement = () => {
|
|
1866
|
+
this.wake(activation);
|
|
1867
|
+
};
|
|
1868
|
+
if (activation.kind === "local") {
|
|
1869
|
+
observeLocalFailure(activation, wakeSettlement);
|
|
1870
|
+
activation.handle.agent.ctx.on("agent/inbox/inserted", wakeSettlement);
|
|
1871
|
+
activation.handle.agent.ctx.on("agent/inbox/claimed", wakeSettlement);
|
|
1872
|
+
activation.handle.agent.ctx.on("agent/inbox/discarded", wakeSettlement);
|
|
1873
|
+
}
|
|
1874
|
+
observer.start(activationAgent(activation));
|
|
1875
|
+
} catch (error) {
|
|
1876
|
+
/* v8 ignore next -- rollback failure must not mask the admission failure
|
|
1877
|
+
* that prevented this operation from returning an accepted message id. */
|
|
1878
|
+
await this.rollbackUnpublished(activation, error).catch(() => void 0);
|
|
1879
|
+
throw error;
|
|
1880
|
+
}
|
|
1881
|
+
return activation;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Begin settlement observation after initial acceptance is recorded.
|
|
1885
|
+
* @param activation - accepted activation to observe.
|
|
1886
|
+
*/
|
|
1887
|
+
announce(activation) {
|
|
1888
|
+
if (activation.announced) return;
|
|
1889
|
+
activation.announced = true;
|
|
1890
|
+
if (activation.kind === "local") this.watchLocalSettlement(activation);
|
|
1891
|
+
else {
|
|
1892
|
+
const finish = () => this.close(activation, () => this.finishDisposal(activation, false));
|
|
1893
|
+
activation.run.result.then(finish, finish).catch((error) => {
|
|
1894
|
+
this.reportTeardownFailure(activation, error);
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
/** Release an Activation whose start edge was not published. */
|
|
1899
|
+
rollbackUnpublished(activation, error) {
|
|
1900
|
+
return this.close(activation, async () => {
|
|
1901
|
+
try {
|
|
1902
|
+
await (activation.kind === "local" ? activation.handle.dispose() : activation.run.dispose());
|
|
1903
|
+
} finally {
|
|
1904
|
+
this.resident.delete(activation.childId);
|
|
1905
|
+
activation.releaseSlot();
|
|
1906
|
+
this.releaseOwnership(activation.childId);
|
|
1907
|
+
activation.result.reject(error);
|
|
1908
|
+
}
|
|
1909
|
+
});
|
|
1910
|
+
}
|
|
1911
|
+
/** Register the child in a continuation-managed parent's owned set. */
|
|
1912
|
+
acquireOwnership(parent, childId) {
|
|
1913
|
+
const parentActivation = this.resident.get(parent.id);
|
|
1914
|
+
if (parentActivation === void 0) return;
|
|
1915
|
+
if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
|
|
1916
|
+
parentActivation.ownedChildren.add(childId);
|
|
1917
|
+
this.wake(parentActivation);
|
|
1918
|
+
}
|
|
1919
|
+
/** Remove one child from its live owner's set and let that owner re-check settlement. */
|
|
1920
|
+
releaseOwnership(childId) {
|
|
1921
|
+
for (const candidate of this.resident.values()) if (candidate.ownedChildren.delete(childId)) this.wake(candidate);
|
|
1922
|
+
}
|
|
1923
|
+
/** Let a settlement watcher re-check residency after relevant state changes. */
|
|
1924
|
+
wake(activation) {
|
|
1925
|
+
if (activation.kind === "external") return;
|
|
1926
|
+
activation.poke.resolve();
|
|
1927
|
+
activation.poke = Promise.withResolvers();
|
|
1928
|
+
}
|
|
1929
|
+
/** Follow one Activation to natural settlement. */
|
|
1930
|
+
watchLocalSettlement(activation) {
|
|
1931
|
+
(async () => {
|
|
1932
|
+
while (true) {
|
|
1933
|
+
const idleObservation = activation.poke;
|
|
1934
|
+
await activation.handle.agent.whenIdle();
|
|
1935
|
+
if (activation.closing !== void 0) return;
|
|
1936
|
+
const readiness = await this.locks.run(activation.childId, () => Promise.resolve(this.settlementState(activation, idleObservation)));
|
|
1937
|
+
if (readiness === "closed") return;
|
|
1938
|
+
if (readiness === "retry") continue;
|
|
1939
|
+
if (readiness === "wait") {
|
|
1940
|
+
await idleObservation.promise;
|
|
1941
|
+
continue;
|
|
1942
|
+
}
|
|
1943
|
+
const finalSeq = activation.handle.agent.session.seq;
|
|
1944
|
+
await this.flushFinalState(activation);
|
|
1945
|
+
const attempt = await this.locks.run(activation.childId, () => {
|
|
1946
|
+
const state = this.settlementState(activation, idleObservation);
|
|
1947
|
+
if (state !== "ready") return Promise.resolve(state);
|
|
1948
|
+
if (activation.handle.agent.session.seq !== finalSeq) return Promise.resolve("retry");
|
|
1949
|
+
let done;
|
|
1950
|
+
try {
|
|
1951
|
+
activation.handle.agent.runMaintenance(() => {
|
|
1952
|
+
done = this.close(activation, () => this.finishDisposal(activation, false));
|
|
1953
|
+
return Promise.resolve();
|
|
1954
|
+
});
|
|
1955
|
+
} catch (_error) {
|
|
1956
|
+
return Promise.resolve("retry");
|
|
1957
|
+
}
|
|
1958
|
+
return Promise.resolve({ done });
|
|
1959
|
+
});
|
|
1960
|
+
if (typeof attempt === "string") {
|
|
1961
|
+
if (attempt === "closed") return;
|
|
1962
|
+
continue;
|
|
1963
|
+
}
|
|
1964
|
+
try {
|
|
1965
|
+
await attempt.done;
|
|
1966
|
+
} catch (error) {
|
|
1967
|
+
this.reportTeardownFailure(activation, error);
|
|
1968
|
+
}
|
|
1969
|
+
return;
|
|
1970
|
+
}
|
|
1971
|
+
})();
|
|
1972
|
+
}
|
|
1973
|
+
/** Report disposal failure once after the natural settlement observer finishes. */
|
|
1974
|
+
reportTeardownFailure(activation, error) {
|
|
1975
|
+
this.ctx.logger.warn(`subagent "${activation.childId}" activation teardown failed: ${failureMessage(error)}`);
|
|
1976
|
+
}
|
|
1977
|
+
/** Check pending input and owned children before closing admission. */
|
|
1978
|
+
settlementState(activation, observation) {
|
|
1979
|
+
if (activation.closing !== void 0) return "closed";
|
|
1980
|
+
if (activation.poke !== observation) return "retry";
|
|
1981
|
+
const inbox = activation.handle.agent.inbox;
|
|
1982
|
+
if (activation.ownedChildren.size > 0) return "wait";
|
|
1983
|
+
if (activation.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return "wait";
|
|
1984
|
+
return "ready";
|
|
1985
|
+
}
|
|
1986
|
+
/** Propagate stop synchronously and await descendant startup rollback before release. */
|
|
1987
|
+
async finishDisposal(activation, stop) {
|
|
1988
|
+
this.wake(activation);
|
|
1989
|
+
const { childId } = activation;
|
|
1990
|
+
const failures = [];
|
|
1991
|
+
let result = {
|
|
1992
|
+
output: [],
|
|
1993
|
+
stopReason: "error"
|
|
1994
|
+
};
|
|
1995
|
+
let resultFailure;
|
|
1996
|
+
let externalDisposal;
|
|
1997
|
+
const child = activationAgent(activation);
|
|
1998
|
+
const detail = (error) => child === void 0 ? failureMessage(error) : errorChain(error);
|
|
1999
|
+
try {
|
|
2000
|
+
if (activation.kind === "external") {
|
|
2001
|
+
if (stop) {
|
|
2002
|
+
activation.controller.abort({ kind: "parent" });
|
|
2003
|
+
externalDisposal = Promise.resolve().then(() => activation.run.dispose());
|
|
2004
|
+
externalDisposal.catch(() => void 0);
|
|
2005
|
+
}
|
|
2006
|
+
result = await activation.run.result;
|
|
2007
|
+
} else {
|
|
2008
|
+
if (stop) {
|
|
2009
|
+
activation.handle.agent.cancel({ kind: "parent" });
|
|
2010
|
+
const idle = activation.handle.agent.whenIdle();
|
|
2011
|
+
const children = [...activation.ownedChildren].map((child) => this.resident.get(child)).filter((child) => child !== void 0);
|
|
2012
|
+
const pending = [...this.materializations].filter((item) => item.lineage.includes(activation.handle.agent));
|
|
2013
|
+
const childDisposals = children.map((child) => this.dispose(child));
|
|
2014
|
+
for (const item of pending) item.controller.abort();
|
|
2015
|
+
childDisposals.push(...pending.map((item) => item.settled));
|
|
2016
|
+
const reasons = (await Promise.all(childDisposals.map(async (disposal) => {
|
|
2017
|
+
try {
|
|
2018
|
+
await disposal;
|
|
2019
|
+
return;
|
|
2020
|
+
} catch (error) {
|
|
2021
|
+
return error;
|
|
2022
|
+
}
|
|
2023
|
+
}))).filter((reason) => reason !== void 0);
|
|
2024
|
+
if (reasons.length > 0) failures.push(new SubagentError(`subagent "${childId}" child teardown failed: ${reasons.map((reason) => failureMessage(reason)).join("; ")}`, "ACTIVATION_TEARDOWN_FAILED"));
|
|
2025
|
+
await idle;
|
|
2026
|
+
await this.flushFinalState(activation);
|
|
2027
|
+
}
|
|
2028
|
+
result = captureLocalResult(activation);
|
|
2029
|
+
}
|
|
2030
|
+
} catch (error) {
|
|
2031
|
+
resultFailure = { error };
|
|
2032
|
+
failures.push(new SubagentError(`subagent "${childId}" activation teardown failed: ${detail(error)}`, "ACTIVATION_TEARDOWN_FAILED", { cause: error }));
|
|
2033
|
+
}
|
|
2034
|
+
try {
|
|
2035
|
+
if (activation.kind === "local") await activation.handle.dispose();
|
|
2036
|
+
else await (externalDisposal ?? activation.run.dispose());
|
|
2037
|
+
} catch (error) {
|
|
2038
|
+
failures.push(new SubagentError(`subagent "${childId}" activation handle disposal failed: ${detail(error)}`, "ACTIVATION_TEARDOWN_FAILED", { cause: error }));
|
|
2039
|
+
}
|
|
2040
|
+
let failure;
|
|
2041
|
+
if (failures.length === 1) failure = failures[0];
|
|
2042
|
+
else if (failures.length > 1) failure = new SubagentError(`subagent "${childId}" activation teardown failed at ${failures.length} boundaries: ` + failures.map((item) => detail(item)).join("; "), "ACTIVATION_TEARDOWN_FAILED", { cause: new AggregateError(failures) });
|
|
2043
|
+
this.resident.delete(childId);
|
|
2044
|
+
activation.releaseSlot();
|
|
2045
|
+
const terminal = failure === void 0 ? result : {
|
|
2046
|
+
output: [],
|
|
2047
|
+
stopReason: "error"
|
|
2048
|
+
};
|
|
2049
|
+
this.notifySettlement(activation, result);
|
|
2050
|
+
this.releaseOwnership(childId);
|
|
2051
|
+
activation.observer.settle(terminal);
|
|
2052
|
+
if (resultFailure === void 0) activation.result.resolve(result);
|
|
2053
|
+
else activation.result.reject(resultFailure.error);
|
|
2054
|
+
if (failure !== void 0) throw failure;
|
|
2055
|
+
}
|
|
2056
|
+
/** Deliver the captured execution result to the durable direct parent after cleanup. */
|
|
2057
|
+
notifySettlement(activation, terminal) {
|
|
2058
|
+
if (!activation.announced || activation.delivery === "caller") return;
|
|
2059
|
+
try {
|
|
2060
|
+
const parent = this.ctx.agents.get(activation.parent.id);
|
|
2061
|
+
if (parent !== activation.parent) return;
|
|
2062
|
+
const message = createSettlementMessage(activation.childId, terminal, activationAgent(activation) !== void 0);
|
|
2063
|
+
if (this.closingTeardownFor(parent) !== void 0) {
|
|
2064
|
+
parent.inject(message);
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
this.sendWaking(parent, message, parent.status === "idle" ? "queue" : "steer");
|
|
2068
|
+
} catch (error) {
|
|
2069
|
+
this.ctx.logger.warn(`subagent "${activation.childId}" settlement notice was not delivered to its parent: ` + errorChain(error));
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
/** Request a best-effort final session flush before closing natural-settlement admission. */
|
|
2073
|
+
async flushFinalState(activation) {
|
|
2074
|
+
try {
|
|
2075
|
+
await activation.handle.agent.ctx.sessions.flush(activation.handle.agent.session);
|
|
2076
|
+
} catch (error) {
|
|
2077
|
+
this.ctx.logger.warn(`subagent "${activation.childId}" best-effort final session flush failed; the persisted state may be unavailable or stale on resume: ${errorChain(error)}`);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
/** Return capabilities bound to an exact activation instead of a future same-id instance. */
|
|
2081
|
+
receipt(activation) {
|
|
2082
|
+
return {
|
|
2083
|
+
childId: activation.childId,
|
|
2084
|
+
result: activation.result.promise,
|
|
2085
|
+
dispose: () => this.dispose(activation)
|
|
2086
|
+
};
|
|
2087
|
+
}
|
|
2088
|
+
/** Route one parent-originated delivery through residency and cold resume. */
|
|
2089
|
+
async deliverToChild(parent, childId, content, options) {
|
|
2090
|
+
this.assertAdmitting(parent);
|
|
2091
|
+
const releaseHold = this.holdOwnership(parent, childId);
|
|
2092
|
+
try {
|
|
2093
|
+
return await this.deliverFollowup(parent, childId, content, options);
|
|
2094
|
+
} catch (error) {
|
|
2095
|
+
releaseHold();
|
|
2096
|
+
throw error;
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
/** The delivery loop behind {@link deliverToChild}, run under the parent hold. */
|
|
2100
|
+
async deliverFollowup(parent, childId, content, options) {
|
|
2101
|
+
while (true) {
|
|
2102
|
+
const live = await this.locks.run(childId, async () => {
|
|
2103
|
+
const activation = this.resident.get(childId);
|
|
2104
|
+
if (activation === void 0) return this.coldResume(parent, childId, content, options);
|
|
2105
|
+
requireLocalActivation(activation);
|
|
2106
|
+
const disposal = activation.closing;
|
|
2107
|
+
/* v8 ignore next 3 -- the send-versus-dispose cutoff needs a delivery to
|
|
2108
|
+
* observe the transaction inside the same critical section that opened it. */
|
|
2109
|
+
if (disposal !== void 0) return disposal.then(() => void 0, () => void 0);
|
|
2110
|
+
if (contentHasImage(content)) {
|
|
2111
|
+
await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
|
|
2112
|
+
if (activation.closing !== void 0) {
|
|
2113
|
+
await Promise.allSettled([activation.closing]);
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
const messageId = this.submitAdmitted(activation, content, options, parent);
|
|
2118
|
+
this.announce(activation);
|
|
2119
|
+
return messageId;
|
|
2120
|
+
});
|
|
2121
|
+
/* v8 ignore start -- only a delivery that lost the disposal cutoff retries. */
|
|
2122
|
+
if (live !== void 0) return live;
|
|
2123
|
+
this.assertAdmitting(parent);
|
|
2124
|
+
options.signal.throwIfAborted();
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
/** Deliver one resident continuable child's message to its live direct parent. */
|
|
2128
|
+
sendToParent(activation, sender, content) {
|
|
2129
|
+
/* v8 ignore next 6 -- only synchronous re-entrant teardown can open this
|
|
2130
|
+
* transaction between exact-agent authorization and this no-await span. */
|
|
2131
|
+
if (activation.closing !== void 0) throw new SubagentError(`subagent "${sender.id}" activation is being disposed; the message was not delivered`, "ACTIVATION_CLOSING");
|
|
2132
|
+
const parent = this.ctx.agents.get(activation.parent.id);
|
|
2133
|
+
if (parent !== activation.parent) throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE");
|
|
2134
|
+
const message = createAgentMessage(sender, content);
|
|
2135
|
+
this.sendAgentMessage(parent, message);
|
|
2136
|
+
return message.id;
|
|
2137
|
+
}
|
|
2138
|
+
/** Send one Agent message while translating only the target's own rejection. */
|
|
2139
|
+
sendAgentMessage(parent, message) {
|
|
2140
|
+
try {
|
|
2141
|
+
this.sendWaking(parent, message, "steer");
|
|
2142
|
+
} catch (error) {
|
|
2143
|
+
throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE", { cause: error });
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Cold-resume a persisted child and submit the waiting turn. The descriptor
|
|
2148
|
+
* supplies every reconstruction input; no subagent provider is dispatched.
|
|
2149
|
+
*/
|
|
2150
|
+
async coldResume(parent, childId, content, options) {
|
|
2151
|
+
const env_1 = {
|
|
2152
|
+
stack: [],
|
|
2153
|
+
error: void 0,
|
|
2154
|
+
hasError: false
|
|
2155
|
+
};
|
|
2156
|
+
try {
|
|
2157
|
+
const query = this.requireSessionQuery();
|
|
2158
|
+
let observation;
|
|
2159
|
+
try {
|
|
2160
|
+
observation = await query.observeSession(childId, { signal: options.signal });
|
|
2161
|
+
} catch (error) {
|
|
2162
|
+
options.signal.throwIfAborted();
|
|
2163
|
+
throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
|
|
2164
|
+
}
|
|
2165
|
+
const source = __addDisposableResource$2(env_1, observation, false);
|
|
2166
|
+
this.assertAdmitting(parent);
|
|
2167
|
+
this.authorizeLineage(parent, childId, source.header.parentSession);
|
|
2168
|
+
const descriptor = foldSubagentDescriptor(source.events.slice(source.inheritedEventCount));
|
|
2169
|
+
if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
|
|
2170
|
+
let activation;
|
|
2171
|
+
try {
|
|
2172
|
+
activation = await this.materialize({
|
|
2173
|
+
kind: "local",
|
|
2174
|
+
childId,
|
|
2175
|
+
provider: descriptor.provider,
|
|
2176
|
+
parent,
|
|
2177
|
+
agentOptions: {
|
|
2178
|
+
...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
|
|
2179
|
+
...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
|
|
2180
|
+
...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } : {}
|
|
2181
|
+
},
|
|
2182
|
+
composition: {
|
|
2183
|
+
persona: descriptor.persona,
|
|
2184
|
+
toolFilter: descriptor.toolFilter
|
|
2185
|
+
},
|
|
2186
|
+
signal: options.signal
|
|
2187
|
+
});
|
|
2188
|
+
} catch (error) {
|
|
2189
|
+
options.signal.throwIfAborted();
|
|
2190
|
+
if (error instanceof SubagentError) throw error;
|
|
2191
|
+
throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
|
|
2192
|
+
}
|
|
2193
|
+
return await this.submitMaterialized(activation, content, options, parent);
|
|
2194
|
+
} catch (e_1) {
|
|
2195
|
+
env_1.error = e_1;
|
|
2196
|
+
env_1.hasError = true;
|
|
2197
|
+
} finally {
|
|
2198
|
+
__disposeResources$2(env_1);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
/** Admit a materialized child, commit its creation fact, and release it on failure. */
|
|
2202
|
+
async submitMaterialized(activation, content, options, parent, commit) {
|
|
2203
|
+
try {
|
|
2204
|
+
if (contentHasImage(content)) {
|
|
2205
|
+
await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
|
|
2206
|
+
if (activation.closing !== void 0) throw new SubagentError(`subagent "${activation.childId}" is closing`, "ACTIVATION_CLOSING");
|
|
2207
|
+
}
|
|
2208
|
+
const messageId = this.submitAdmitted(activation, content, options, parent);
|
|
2209
|
+
commit?.();
|
|
2210
|
+
this.announce(activation);
|
|
2211
|
+
return messageId;
|
|
2212
|
+
} catch (error) {
|
|
2213
|
+
try {
|
|
2214
|
+
await this.dispose(activation);
|
|
2215
|
+
} catch (cleanupError) {
|
|
2216
|
+
this.ctx.logger.warn(`subagent continuation: disposal after admission or catalog append failure also failed: ${String(cleanupError)}`);
|
|
2217
|
+
}
|
|
2218
|
+
throw error;
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
/** Build and submit one message across the final synchronous admission cutoff. */
|
|
2222
|
+
submitAdmitted(activation, content, options, parent) {
|
|
2223
|
+
const message = options.source === void 0 ? createAgentMessage(parent, content) : createUserMessage({
|
|
2224
|
+
content,
|
|
2225
|
+
source: options.source
|
|
2226
|
+
});
|
|
2227
|
+
options.signal.throwIfAborted();
|
|
2228
|
+
this.assertAdmitting(parent);
|
|
2229
|
+
this.authorizeLineage(parent, activation.childId, activation.parent.id);
|
|
2230
|
+
this.acquireOwnership(parent, activation.childId);
|
|
2231
|
+
try {
|
|
2232
|
+
this.deliver(activation, message, options.delivery);
|
|
2233
|
+
} finally {
|
|
2234
|
+
this.wake(activation);
|
|
2235
|
+
}
|
|
2236
|
+
return message.id;
|
|
2237
|
+
}
|
|
2238
|
+
/** Refuse image content for a child whose fixed model accepts text only. */
|
|
2239
|
+
async assertImageCapable(agent, signal) {
|
|
2240
|
+
const { provider, model } = agent.options;
|
|
2241
|
+
if (provider === void 0 || model === void 0) return;
|
|
2242
|
+
const llm = this.ctx.get("llm");
|
|
2243
|
+
/* v8 ignore next -- without an LLM registry, delivery defers to projection. */
|
|
2244
|
+
if (llm === void 0) return;
|
|
2245
|
+
const info = await llm.resolveModelInfo(provider, model, signal);
|
|
2246
|
+
if (info.inputModalities !== void 0 && !info.inputModalities.includes("image")) throw new SubagentError(`Model "${model}" does not support image input.`, "MODEL_DOES_NOT_SUPPORT_IMAGES");
|
|
2247
|
+
}
|
|
2248
|
+
/** Resolve the persistence service continuable children require, or fail loud. */
|
|
2249
|
+
requirePersistence() {
|
|
2250
|
+
const persistence = this.ctx.get("sessionPersistence");
|
|
2251
|
+
if (persistence === void 0) throw new SubagentError("continuable subagents require session persistence (load a dsh-session-persistence backend)", "PERSISTENCE_UNAVAILABLE");
|
|
2252
|
+
return persistence;
|
|
2253
|
+
}
|
|
2254
|
+
/** Resolve the Session query service used for cold child observations. */
|
|
2255
|
+
requireSessionQuery() {
|
|
2256
|
+
const query = this.ctx.get("sessionQuery");
|
|
2257
|
+
if (query === void 0) throw new SubagentError("continuable subagents require session query (load @qlzt/dsh-session-query)", "CONTINUATION_UNAVAILABLE");
|
|
2258
|
+
return query;
|
|
2259
|
+
}
|
|
2260
|
+
};
|
|
2261
|
+
//#endregion
|
|
2262
|
+
//#region lib/types/list-children.js
|
|
2263
|
+
/**
|
|
2264
|
+
* Direct-child and recursive descendant discovery from parent-owned catalogs.
|
|
2265
|
+
* Each catalog read releases its Session observation before the next branch.
|
|
2266
|
+
* @module @qlzt/dsh-subagent
|
|
2267
|
+
*/
|
|
2268
|
+
var __addDisposableResource$1 = function(env, value, async) {
|
|
2269
|
+
if (value !== null && value !== void 0) {
|
|
2270
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
2271
|
+
var dispose, inner;
|
|
2272
|
+
if (async) {
|
|
2273
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
2274
|
+
dispose = value[Symbol.asyncDispose];
|
|
2275
|
+
}
|
|
2276
|
+
if (dispose === void 0) {
|
|
2277
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
2278
|
+
dispose = value[Symbol.dispose];
|
|
2279
|
+
if (async) inner = dispose;
|
|
2280
|
+
}
|
|
2281
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
2282
|
+
if (inner) dispose = function() {
|
|
2283
|
+
try {
|
|
2284
|
+
inner.call(this);
|
|
2285
|
+
} catch (e) {
|
|
2286
|
+
return Promise.reject(e);
|
|
2287
|
+
}
|
|
2288
|
+
};
|
|
2289
|
+
env.stack.push({
|
|
2290
|
+
value,
|
|
2291
|
+
dispose,
|
|
2292
|
+
async
|
|
2293
|
+
});
|
|
2294
|
+
} else if (async) env.stack.push({ async: true });
|
|
2295
|
+
return value;
|
|
2296
|
+
};
|
|
2297
|
+
var __disposeResources$1 = (function(SuppressedError) {
|
|
2298
|
+
return function(env) {
|
|
2299
|
+
function fail(e) {
|
|
2300
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
2301
|
+
env.hasError = true;
|
|
2302
|
+
}
|
|
2303
|
+
var r, s = 0;
|
|
2304
|
+
function next() {
|
|
2305
|
+
while (r = env.stack.pop()) try {
|
|
2306
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
2307
|
+
if (r.dispose) {
|
|
2308
|
+
var result = r.dispose.call(r.value);
|
|
2309
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
2310
|
+
fail(e);
|
|
2311
|
+
return next();
|
|
2312
|
+
});
|
|
2313
|
+
} else s |= 1;
|
|
2314
|
+
} catch (e) {
|
|
2315
|
+
fail(e);
|
|
2316
|
+
}
|
|
2317
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
2318
|
+
if (env.hasError) throw env.error;
|
|
2319
|
+
}
|
|
2320
|
+
return next();
|
|
2321
|
+
};
|
|
2322
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
2323
|
+
var e = new Error(message);
|
|
2324
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
2325
|
+
});
|
|
2326
|
+
/**
|
|
2327
|
+
* Read one parent's durable catalog through a live-preferred Session observation.
|
|
2328
|
+
* @param ctx - context carrying the Session query service.
|
|
2329
|
+
* @param parentSessionId - parent whose direct children are requested.
|
|
2330
|
+
* @param signal - cancellation forwarded to the Session observation.
|
|
2331
|
+
* @returns direct-child rows in parent catalog event order.
|
|
2332
|
+
* @throws {@link SubagentError} when query or catalog projection is unavailable.
|
|
2333
|
+
*/
|
|
2334
|
+
async function listChildren(ctx, parentSessionId, signal) {
|
|
2335
|
+
const env_1 = {
|
|
2336
|
+
stack: [],
|
|
2337
|
+
error: void 0,
|
|
2338
|
+
hasError: false
|
|
2339
|
+
};
|
|
2340
|
+
try {
|
|
2341
|
+
const query = ctx.get("sessionQuery");
|
|
2342
|
+
if (query === void 0) throw new SubagentError("listing subagents requires the sessionQuery service (load @qlzt/dsh-session-query)", "SUBAGENT_CONTROL_QUERY_UNAVAILABLE");
|
|
2343
|
+
const entries = __addDisposableResource$1(env_1, await query.observeSession(parentSessionId, { ...signal === void 0 ? {} : { signal } }), false).projections?.values.subagentCatalog;
|
|
2344
|
+
if (entries === void 0) throw new SubagentError("listing subagents requires the registered subagentCatalog projection", "SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE");
|
|
2345
|
+
return entries;
|
|
2346
|
+
} catch (e_1) {
|
|
2347
|
+
env_1.error = e_1;
|
|
2348
|
+
env_1.hasError = true;
|
|
2349
|
+
} finally {
|
|
2350
|
+
__disposeResources$1(env_1);
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
/**
|
|
2354
|
+
* Walk reachable parent catalogs in stable pre-order without loading Agents.
|
|
2355
|
+
* @see SubagentRuntime.listDescendants for failure and cancellation semantics.
|
|
2356
|
+
* @param ctx - context carrying the Session store and query service.
|
|
2357
|
+
* @param rootSessionId - parent whose catalog starts the traversal.
|
|
2358
|
+
* @param signal - cancellation checked around each catalog read.
|
|
2359
|
+
* @returns children and branch diagnostics with catalog parent and depth.
|
|
2360
|
+
*/
|
|
2361
|
+
async function listDescendants(ctx, rootSessionId, signal) {
|
|
2362
|
+
const sessions = ctx.get("sessions");
|
|
2363
|
+
if (sessions === void 0) throw new SubagentError("listing subagents requires the session store (load @qlzt/dsh-session)", "SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE");
|
|
2364
|
+
const readChildren = async (id) => {
|
|
2365
|
+
assertListingNotCancelled(signal);
|
|
2366
|
+
let children;
|
|
2367
|
+
try {
|
|
2368
|
+
children = await listChildren(ctx, id, signal);
|
|
2369
|
+
} catch (error) {
|
|
2370
|
+
assertListingNotCancelled(signal);
|
|
2371
|
+
throw error;
|
|
2372
|
+
}
|
|
2373
|
+
assertListingNotCancelled(signal);
|
|
2374
|
+
return children;
|
|
2375
|
+
};
|
|
2376
|
+
const stack = (await readChildren(rootSessionId)).map((entry) => ({
|
|
2377
|
+
entry,
|
|
2378
|
+
parentId: rootSessionId,
|
|
2379
|
+
depth: 1
|
|
2380
|
+
})).reverse();
|
|
2381
|
+
const visited = new Set([rootSessionId]);
|
|
2382
|
+
const result = [];
|
|
2383
|
+
for (let position = stack.pop(); position !== void 0; position = stack.pop()) {
|
|
2384
|
+
const { entry, parentId, depth } = position;
|
|
2385
|
+
if (visited.has(entry.id)) continue;
|
|
2386
|
+
visited.add(entry.id);
|
|
2387
|
+
let children;
|
|
2388
|
+
try {
|
|
2389
|
+
children = entry.mode === "external" ? [] : await readChildren(entry.id);
|
|
2390
|
+
} catch (error) {
|
|
2391
|
+
if (error instanceof SubagentError) throw error;
|
|
2392
|
+
const code = error instanceof Error && "code" in error ? error.code : void 0;
|
|
2393
|
+
result.push({
|
|
2394
|
+
kind: "diagnostic",
|
|
2395
|
+
id: entry.id,
|
|
2396
|
+
parentId,
|
|
2397
|
+
depth,
|
|
2398
|
+
reason: code === "SESSION_QUERY_CORRUPT_SESSION" || code === "SESSION_QUERY_SOURCE_CONFLICT" ? "corrupt" : "unavailable"
|
|
2399
|
+
});
|
|
2400
|
+
continue;
|
|
2401
|
+
}
|
|
2402
|
+
if (entry.mode === "unknown") result.push({
|
|
2403
|
+
kind: "diagnostic",
|
|
2404
|
+
id: entry.id,
|
|
2405
|
+
parentId,
|
|
2406
|
+
depth,
|
|
2407
|
+
reason: "unsupported"
|
|
2408
|
+
});
|
|
2409
|
+
else {
|
|
2410
|
+
const { createdAt: _createdAt, ...identity } = entry;
|
|
2411
|
+
result.push({
|
|
2412
|
+
...identity,
|
|
2413
|
+
kind: "child",
|
|
2414
|
+
parentId,
|
|
2415
|
+
depth,
|
|
2416
|
+
activity: sessions.get(entry.id) === void 0 ? "inactive" : "running",
|
|
2417
|
+
hasChildren: children.length > 0
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
for (const child of [...children].reverse()) stack.push({
|
|
2421
|
+
entry: child,
|
|
2422
|
+
parentId: entry.id,
|
|
2423
|
+
depth: depth + 1
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
return result;
|
|
2427
|
+
}
|
|
2428
|
+
/** Stop the complete traversal when its caller cancels. */
|
|
2429
|
+
function assertListingNotCancelled(signal) {
|
|
2430
|
+
if (signal?.aborted) throw new SubagentError("subagent listing was cancelled", "CANCELLED");
|
|
2431
|
+
}
|
|
2432
|
+
//#endregion
|
|
2433
|
+
//#region lib/types/archive-admission.js
|
|
2434
|
+
/**
|
|
2435
|
+
* The `subagent` family of the Workspace registry's archive admission: which
|
|
2436
|
+
* subagent descendants of a Session are still inside a turn, and how they
|
|
2437
|
+
* stop when the Session is archived with its work.
|
|
2438
|
+
*
|
|
2439
|
+
* @module @qlzt/dsh-subagent
|
|
2440
|
+
*/
|
|
2441
|
+
var __addDisposableResource = function(env, value, async) {
|
|
2442
|
+
if (value !== null && value !== void 0) {
|
|
2443
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
2444
|
+
var dispose, inner;
|
|
2445
|
+
if (async) {
|
|
2446
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
2447
|
+
dispose = value[Symbol.asyncDispose];
|
|
2448
|
+
}
|
|
2449
|
+
if (dispose === void 0) {
|
|
2450
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
2451
|
+
dispose = value[Symbol.dispose];
|
|
2452
|
+
if (async) inner = dispose;
|
|
2453
|
+
}
|
|
2454
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
2455
|
+
if (inner) dispose = function() {
|
|
2456
|
+
try {
|
|
2457
|
+
inner.call(this);
|
|
2458
|
+
} catch (e) {
|
|
2459
|
+
return Promise.reject(e);
|
|
2460
|
+
}
|
|
2461
|
+
};
|
|
2462
|
+
env.stack.push({
|
|
2463
|
+
value,
|
|
2464
|
+
dispose,
|
|
2465
|
+
async
|
|
2466
|
+
});
|
|
2467
|
+
} else if (async) env.stack.push({ async: true });
|
|
2468
|
+
return value;
|
|
2469
|
+
};
|
|
2470
|
+
var __disposeResources = (function(SuppressedError) {
|
|
2471
|
+
return function(env) {
|
|
2472
|
+
function fail(e) {
|
|
2473
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
2474
|
+
env.hasError = true;
|
|
2475
|
+
}
|
|
2476
|
+
var r, s = 0;
|
|
2477
|
+
function next() {
|
|
2478
|
+
while (r = env.stack.pop()) try {
|
|
2479
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
2480
|
+
if (r.dispose) {
|
|
2481
|
+
var result = r.dispose.call(r.value);
|
|
2482
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
2483
|
+
fail(e);
|
|
2484
|
+
return next();
|
|
2485
|
+
});
|
|
2486
|
+
} else s |= 1;
|
|
2487
|
+
} catch (e) {
|
|
2488
|
+
fail(e);
|
|
2489
|
+
}
|
|
2490
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
2491
|
+
if (env.hasError) throw env.error;
|
|
2492
|
+
}
|
|
2493
|
+
return next();
|
|
2494
|
+
};
|
|
2495
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
2496
|
+
var e = new Error(message);
|
|
2497
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
2498
|
+
});
|
|
2499
|
+
/**
|
|
2500
|
+
* Answer `workspace/session-activity` with the running subagent descendants of
|
|
2501
|
+
* the asked Session, and `workspace/session-stop` by cancelling each of them
|
|
2502
|
+
* as their parent would. Both listeners live as long as `ctx`'s fiber.
|
|
2503
|
+
* @param ctx - context carrying the Agent registry; the Session query service is optional and only supplies labels.
|
|
2504
|
+
*/
|
|
2505
|
+
function installSubagentArchiveAdmission(ctx) {
|
|
2506
|
+
ctx.on("workspace/session-activity", async ({ sessionId }, next) => {
|
|
2507
|
+
const running = runningDescendants(ctx, sessionId);
|
|
2508
|
+
const rest = await next();
|
|
2509
|
+
if (running.length === 0) return rest;
|
|
2510
|
+
return [{
|
|
2511
|
+
kind: "subagent",
|
|
2512
|
+
items: await Promise.all(running.map((child) => describe(ctx, child)))
|
|
2513
|
+
}, ...rest];
|
|
2514
|
+
});
|
|
2515
|
+
ctx.on("workspace/session-stop", ({ sessionId }) => {
|
|
2516
|
+
for (const child of runningDescendants(ctx, sessionId)) try {
|
|
2517
|
+
child.cancel({ kind: "parent" });
|
|
2518
|
+
} catch (error) {
|
|
2519
|
+
ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`);
|
|
2520
|
+
}
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* Live subagent descendants inside a turn, by durable lineage: a child whose
|
|
2525
|
+
* header names its parent and carries the subagent origin this package
|
|
2526
|
+
* records, at any depth. A fork shares the lineage field without the origin
|
|
2527
|
+
* and is an independent conversation, so it never holds its source. Lineage
|
|
2528
|
+
* is read as data, so a damaged header chain that loops is visited once.
|
|
2529
|
+
*/
|
|
2530
|
+
function runningDescendants(ctx, rootId) {
|
|
2531
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
2532
|
+
for (const agent of ctx.agents.list()) {
|
|
2533
|
+
const { parentSession, origin } = agent.session.header;
|
|
2534
|
+
if (parentSession === void 0 || origin !== "subagent") continue;
|
|
2535
|
+
const siblings = childrenOf.get(parentSession) ?? [];
|
|
2536
|
+
siblings.push(agent);
|
|
2537
|
+
childrenOf.set(parentSession, siblings);
|
|
2538
|
+
}
|
|
2539
|
+
const running = [];
|
|
2540
|
+
const pending = [rootId];
|
|
2541
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2542
|
+
while (pending.length > 0) {
|
|
2543
|
+
const parentId = pending.shift();
|
|
2544
|
+
if (visited.has(parentId)) continue;
|
|
2545
|
+
visited.add(parentId);
|
|
2546
|
+
for (const child of childrenOf.get(parentId) ?? []) {
|
|
2547
|
+
if (child.status === "running") running.push(child);
|
|
2548
|
+
pending.push(child.id);
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
return running;
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* The child's activity item: its id, plus the durable creation label its
|
|
2555
|
+
* descriptor carries, read through a live Session observation. Without the
|
|
2556
|
+
* Session query service, or with a descriptor that is absent or unreadable,
|
|
2557
|
+
* the item names the child by id alone.
|
|
2558
|
+
*/
|
|
2559
|
+
async function describe(ctx, child) {
|
|
2560
|
+
const query = ctx.get("sessionQuery");
|
|
2561
|
+
if (query === void 0) return { id: child.id };
|
|
2562
|
+
try {
|
|
2563
|
+
const env_1 = {
|
|
2564
|
+
stack: [],
|
|
2565
|
+
error: void 0,
|
|
2566
|
+
hasError: false
|
|
2567
|
+
};
|
|
2568
|
+
try {
|
|
2569
|
+
const observation = __addDisposableResource(env_1, await query.observeSession(child.id, { projectionMode: "none" }), false);
|
|
2570
|
+
const label = foldSubagentDescriptor(observation.events.slice(observation.inheritedEventCount))?.label;
|
|
2571
|
+
return label === void 0 ? { id: child.id } : {
|
|
2572
|
+
id: child.id,
|
|
2573
|
+
label
|
|
2574
|
+
};
|
|
2575
|
+
} catch (e_1) {
|
|
2576
|
+
env_1.error = e_1;
|
|
2577
|
+
env_1.hasError = true;
|
|
2578
|
+
} finally {
|
|
2579
|
+
__disposeResources(env_1);
|
|
2580
|
+
}
|
|
2581
|
+
} catch {
|
|
2582
|
+
return { id: child.id };
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
//#endregion
|
|
2586
|
+
//#region lib/types/projection.js
|
|
2587
|
+
/**
|
|
2588
|
+
* Pure session projections for subagent identity (mode/label) and active-turn
|
|
2589
|
+
* duration.
|
|
2590
|
+
*
|
|
2591
|
+
* @module @qlzt/dsh-subagent/projection
|
|
2592
|
+
*/
|
|
2593
|
+
const activeIntervalSchema = z$1.object({
|
|
2594
|
+
since: z$1.number().int().nonnegative(),
|
|
2595
|
+
through: z$1.number().int().nonnegative()
|
|
2596
|
+
}).strict();
|
|
2597
|
+
const projectionSchema = z$1.object({
|
|
2598
|
+
settledMs: z$1.number().int().nonnegative(),
|
|
2599
|
+
active: activeIntervalSchema.optional(),
|
|
2600
|
+
lastTurnCompleted: z$1.boolean().optional()
|
|
2601
|
+
}).strict().transform(({ settledMs, active, lastTurnCompleted }) => ({
|
|
2602
|
+
settledMs,
|
|
2603
|
+
...active === void 0 ? {} : { active },
|
|
2604
|
+
...lastTurnCompleted === void 0 ? {} : { lastTurnCompleted }
|
|
2605
|
+
}));
|
|
2606
|
+
/**
|
|
2607
|
+
* Fold turn boundaries around the child's own durable descriptor.
|
|
2608
|
+
*
|
|
2609
|
+
* A fork seed may contain an ancestor descriptor and completed turns. Every
|
|
2610
|
+
* descriptor therefore resets the accumulated state; the healthy catalog
|
|
2611
|
+
* admits only a child with exactly one descriptor in its own suffix, making
|
|
2612
|
+
* the final reset the child's authoritative timing origin.
|
|
2613
|
+
*/
|
|
2614
|
+
const subagentTimingProjectionDefinition = {
|
|
2615
|
+
key: "subagentTiming",
|
|
2616
|
+
stateSchema: z$1.object({
|
|
2617
|
+
settledMs: z$1.number().int().nonnegative(),
|
|
2618
|
+
active: activeIntervalSchema.optional(),
|
|
2619
|
+
pendingTurnStart: z$1.number().int().nonnegative().optional(),
|
|
2620
|
+
descriptorSeen: z$1.boolean(),
|
|
2621
|
+
lastTurnCompleted: z$1.boolean().optional()
|
|
2622
|
+
}).strict(),
|
|
2623
|
+
init: () => ({
|
|
2624
|
+
descriptorSeen: false,
|
|
2625
|
+
settledMs: 0
|
|
2626
|
+
}),
|
|
2627
|
+
apply: (state, event) => {
|
|
2628
|
+
if (event.type === "turn/start") {
|
|
2629
|
+
const { lastTurnCompleted: _closed, ...openState } = state;
|
|
2630
|
+
return state.descriptorSeen ? {
|
|
2631
|
+
...openState,
|
|
2632
|
+
active: {
|
|
2633
|
+
since: event.time,
|
|
2634
|
+
through: event.time
|
|
2635
|
+
}
|
|
2636
|
+
} : {
|
|
2637
|
+
...openState,
|
|
2638
|
+
pendingTurnStart: event.time
|
|
2639
|
+
};
|
|
2640
|
+
}
|
|
2641
|
+
if (event.type === "subagent/descriptor") {
|
|
2642
|
+
const activeSince = state.active?.since ?? state.pendingTurnStart;
|
|
2643
|
+
return {
|
|
2644
|
+
descriptorSeen: true,
|
|
2645
|
+
settledMs: 0,
|
|
2646
|
+
...activeSince === void 0 ? {} : { active: {
|
|
2647
|
+
since: activeSince,
|
|
2648
|
+
through: event.time
|
|
2649
|
+
} }
|
|
2650
|
+
};
|
|
2651
|
+
}
|
|
2652
|
+
if (event.type === "turn/end") {
|
|
2653
|
+
if (!state.descriptorSeen) {
|
|
2654
|
+
if (state.pendingTurnStart === void 0) return state;
|
|
2655
|
+
const { pendingTurnStart: _closed, ...next } = state;
|
|
2656
|
+
return next;
|
|
2657
|
+
}
|
|
2658
|
+
if (state.active === void 0) return state;
|
|
2659
|
+
const { active, ...rest } = state;
|
|
2660
|
+
return {
|
|
2661
|
+
...rest,
|
|
2662
|
+
settledMs: state.settledMs + Math.max(0, event.time - active.since),
|
|
2663
|
+
lastTurnCompleted: event.data.reason.kind === "completed"
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
if (state.active === void 0) return state;
|
|
2667
|
+
return {
|
|
2668
|
+
...state,
|
|
2669
|
+
active: {
|
|
2670
|
+
...state.active,
|
|
2671
|
+
through: event.time
|
|
2672
|
+
}
|
|
2673
|
+
};
|
|
2674
|
+
},
|
|
2675
|
+
wire: {
|
|
2676
|
+
viewSchema: projectionSchema,
|
|
2677
|
+
view: (state) => ({
|
|
2678
|
+
settledMs: state.settledMs,
|
|
2679
|
+
...state.active === void 0 ? {} : { active: state.active },
|
|
2680
|
+
...state.lastTurnCompleted === void 0 ? {} : { lastTurnCompleted: state.lastTurnCompleted }
|
|
2681
|
+
})
|
|
2682
|
+
},
|
|
2683
|
+
stateVersion: 3
|
|
2684
|
+
};
|
|
2685
|
+
const identityValueSchema = z$1.discriminatedUnion("mode", [z$1.object({
|
|
2686
|
+
mode: z$1.literal("one-shot"),
|
|
2687
|
+
label: z$1.string().optional(),
|
|
2688
|
+
seq: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
|
|
2689
|
+
}).strict(), z$1.object({
|
|
2690
|
+
mode: z$1.literal("continuable"),
|
|
2691
|
+
label: z$1.string(),
|
|
2692
|
+
seq: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
|
|
2693
|
+
}).strict()]);
|
|
2694
|
+
const identitySchema = identityValueSchema.nullable();
|
|
2695
|
+
const identityStateSchema = z$1.object({ identity: identityValueSchema.optional() }).strict();
|
|
2696
|
+
/** Interpret one `subagent/descriptor` event's identity; no value when the payload cannot be trusted. */
|
|
2697
|
+
function descriptorIdentity(event) {
|
|
2698
|
+
let descriptor;
|
|
2699
|
+
try {
|
|
2700
|
+
descriptor = foldSubagentDescriptor([event]);
|
|
2701
|
+
} catch {
|
|
2702
|
+
descriptor = void 0;
|
|
2703
|
+
}
|
|
2704
|
+
if (descriptor === void 0) return void 0;
|
|
2705
|
+
return descriptor.mode === "one-shot" ? {
|
|
2706
|
+
mode: "one-shot",
|
|
2707
|
+
...descriptor.label !== void 0 ? { label: descriptor.label } : {},
|
|
2708
|
+
seq: event.seq
|
|
2709
|
+
} : {
|
|
2710
|
+
mode: "continuable",
|
|
2711
|
+
label: descriptor.label,
|
|
2712
|
+
seq: event.seq
|
|
2713
|
+
};
|
|
2714
|
+
}
|
|
2715
|
+
/**
|
|
2716
|
+
* Fold the durable mode/label identity from `subagent/descriptor` events,
|
|
2717
|
+
* last-wins: a fork seed may replay an ancestor's descriptor, and the child's
|
|
2718
|
+
* own descriptor must override it — the same reset discipline as
|
|
2719
|
+
* {@link subagentTimingProjectionDefinition}. A malformed or unknown-version
|
|
2720
|
+
* payload resets to the `null` sentinel instead of throwing, so a fork of a
|
|
2721
|
+
* healthy ancestor never inherits an identity its own descriptor failed to
|
|
2722
|
+
* establish — and the reset survives every JSON push frame, so a consumer
|
|
2723
|
+
* holding the earlier identity replaces it instead of keeping it stale;
|
|
2724
|
+
* `null` ⟺ no valid descriptor, with the causes deliberately undistinguished.
|
|
2725
|
+
*/
|
|
2726
|
+
const subagentIdentityProjectionDefinition = {
|
|
2727
|
+
key: "subagent",
|
|
2728
|
+
stateSchema: identityStateSchema,
|
|
2729
|
+
init: () => ({}),
|
|
2730
|
+
apply: (state, event) => {
|
|
2731
|
+
if (event.type !== "subagent/descriptor") return state;
|
|
2732
|
+
const identity = descriptorIdentity(event);
|
|
2733
|
+
return identity === void 0 ? {} : { identity };
|
|
2734
|
+
},
|
|
2735
|
+
wire: {
|
|
2736
|
+
viewSchema: identitySchema,
|
|
2737
|
+
view: (state) => state.identity ?? null
|
|
2738
|
+
},
|
|
2739
|
+
stateVersion: 2
|
|
2740
|
+
};
|
|
2741
|
+
//#endregion
|
|
2742
|
+
//#region lib/types/out-of-process.js
|
|
2743
|
+
/**
|
|
2744
|
+
* Provider-side vocabulary for OUT-OF-PROCESS subagent backends — the pieces
|
|
2745
|
+
* that enforce this seam's own contracts around a child in another process:
|
|
2746
|
+
* the no-capabilities advertisement, timing-bound validation, child
|
|
2747
|
+
* working-directory validation, the never-reject result settlement, and the standard
|
|
2748
|
+
* run-handle publication. Backends compose these with their own wire drivers;
|
|
2749
|
+
* the process machinery itself (spawn, env scrub, managed-range teardown)
|
|
2750
|
+
* belongs to the `dsh-subprocess` seam.
|
|
2751
|
+
*
|
|
2752
|
+
* @module @qlzt/dsh-subagent/out-of-process
|
|
2753
|
+
*/
|
|
2754
|
+
/** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */
|
|
2755
|
+
const MAX_SUBAGENT_DIAGNOSTIC_BYTES = 4096;
|
|
2756
|
+
const DIAGNOSTIC_TRUNCATION_SUFFIX = "\n[diagnostic truncated]";
|
|
2757
|
+
const utf8Encoder = new TextEncoder();
|
|
2758
|
+
const utf8Decoder = new TextDecoder();
|
|
2759
|
+
/**
|
|
2760
|
+
* Limit provider-authored failure detail without splitting a UTF-8 sequence.
|
|
2761
|
+
* @param diagnostic - safe diagnostic text produced by the provider.
|
|
2762
|
+
* @returns the original text, or a visibly truncated value within the limit.
|
|
2763
|
+
*/
|
|
2764
|
+
function limitSubagentDiagnostic(diagnostic) {
|
|
2765
|
+
const bytes = utf8Encoder.encode(diagnostic);
|
|
2766
|
+
if (bytes.byteLength <= MAX_SUBAGENT_DIAGNOSTIC_BYTES) return diagnostic;
|
|
2767
|
+
let prefixBytes = MAX_SUBAGENT_DIAGNOSTIC_BYTES - utf8Encoder.encode(DIAGNOSTIC_TRUNCATION_SUFFIX).byteLength;
|
|
2768
|
+
while ((bytes[prefixBytes] & 192) === 128) prefixBytes -= 1;
|
|
2769
|
+
return utf8Decoder.decode(bytes.subarray(0, prefixBytes)) + DIAGNOSTIC_TRUNCATION_SUFFIX;
|
|
2770
|
+
}
|
|
2771
|
+
/** Enforce the byte limit on a provider-returned diagnostic. */
|
|
2772
|
+
function normalizeSubagentDiagnostic(result) {
|
|
2773
|
+
return result.diagnostic === void 0 ? result : {
|
|
2774
|
+
...result,
|
|
2775
|
+
diagnostic: limitSubagentDiagnostic(result.diagnostic)
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* The capability advertisement of an out-of-process backend: NONE. A child in
|
|
2780
|
+
* another process cannot honor parent-enforced start features
|
|
2781
|
+
* (`agentOptions`/`outputSchema`/`maxDepth`/`toolFilter`/`persona`), so the service rejects a
|
|
2782
|
+
* request needing any of them before `start` runs — never accepted-then-ignored.
|
|
2783
|
+
*/
|
|
2784
|
+
const NO_START_CAPABILITIES = Object.freeze({
|
|
2785
|
+
agentOptions: false,
|
|
2786
|
+
outputSchema: false,
|
|
2787
|
+
depthLimit: false,
|
|
2788
|
+
toolFilter: false,
|
|
2789
|
+
persona: false
|
|
2790
|
+
});
|
|
2791
|
+
/**
|
|
2792
|
+
* Assert a configured timing bound is a positive finite number (it bounds a
|
|
2793
|
+
* teardown or shutdown wait; zero, negative, or NaN would skip or wedge it).
|
|
2794
|
+
* @param prefix - the consuming plugin's diagnostic prefix (e.g. `subagent-acp`).
|
|
2795
|
+
* @param name - the config field name, for the diagnostic.
|
|
2796
|
+
* @param value - the configured value.
|
|
2797
|
+
*/
|
|
2798
|
+
function assertPositiveFinite(prefix, name, value) {
|
|
2799
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`${prefix}: ${name} must be a positive finite number`);
|
|
2800
|
+
}
|
|
2801
|
+
/**
|
|
2802
|
+
* Whether `path` names an existing directory the harness can ENTER. The
|
|
2803
|
+
* search-permission probe matters: `statSync().isDirectory()` is true for a
|
|
2804
|
+
* mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.
|
|
2805
|
+
*/
|
|
2806
|
+
function isEnterableDirectory(path) {
|
|
2807
|
+
try {
|
|
2808
|
+
if (!statSync(path).isDirectory()) return false;
|
|
2809
|
+
accessSync(path, constants.X_OK);
|
|
2810
|
+
return true;
|
|
2811
|
+
} catch {
|
|
2812
|
+
return false;
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
/**
|
|
2816
|
+
* Assert `cwd` can actually host the child: absolute (it doubles as the
|
|
2817
|
+
* child's workspace identity, and a relative path would be re-anchored to the
|
|
2818
|
+
* server process's launch directory) and an existing directory (fail here,
|
|
2819
|
+
* before the process boundary, instead of as an ambiguous spawn ENOENT).
|
|
2820
|
+
* @param prefix - the consuming plugin's diagnostic prefix.
|
|
2821
|
+
* @param label - which source supplied the value, for the diagnostic.
|
|
2822
|
+
* @param cwd - the candidate working directory.
|
|
2823
|
+
* @returns `cwd`, validated.
|
|
2824
|
+
*/
|
|
2825
|
+
function assertUsableCwd(prefix, label, cwd) {
|
|
2826
|
+
if (!isAbsolute(cwd)) throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`);
|
|
2827
|
+
if (!isEnterableDirectory(cwd)) throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`);
|
|
2828
|
+
return cwd;
|
|
2829
|
+
}
|
|
2830
|
+
/** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */
|
|
2831
|
+
function toError(value) {
|
|
2832
|
+
/* v8 ignore next */
|
|
2833
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2836
|
+
* Settle an out-of-process run result under the seam contract: `result` never
|
|
2837
|
+
* rejects after publication. A normally completed or rejected attempt resolves
|
|
2838
|
+
* as `aborted` when cancellation already settled locally; another rejection is
|
|
2839
|
+
* flattened to `stopReason: 'error'` through the contained diagnostic sink.
|
|
2840
|
+
* Provider-returned diagnostics use the same byte limit. The abort listener is
|
|
2841
|
+
* removed on every path.
|
|
2842
|
+
* @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring.
|
|
2843
|
+
* @returns the terminal result (never a rejection).
|
|
2844
|
+
*/
|
|
2845
|
+
async function settleRunResult(parts) {
|
|
2846
|
+
try {
|
|
2847
|
+
const result = await parts.attempt();
|
|
2848
|
+
return parts.cancelled() ? {
|
|
2849
|
+
output: parts.collectOutput(),
|
|
2850
|
+
stopReason: "aborted"
|
|
2851
|
+
} : normalizeSubagentDiagnostic(result);
|
|
2852
|
+
} catch (error) {
|
|
2853
|
+
if (parts.cancelled()) return {
|
|
2854
|
+
output: parts.collectOutput(),
|
|
2855
|
+
stopReason: "aborted"
|
|
2856
|
+
};
|
|
2857
|
+
try {
|
|
2858
|
+
parts.onError?.(toError(error), "error");
|
|
2859
|
+
} catch {}
|
|
2860
|
+
const collected = parts.collectDiagnostic?.();
|
|
2861
|
+
const diagnostic = collected === void 0 ? void 0 : limitSubagentDiagnostic(collected);
|
|
2862
|
+
return {
|
|
2863
|
+
output: parts.collectOutput(),
|
|
2864
|
+
...diagnostic === void 0 ? {} : { diagnostic },
|
|
2865
|
+
stopReason: "error"
|
|
2866
|
+
};
|
|
2867
|
+
} finally {
|
|
2868
|
+
parts.signal.removeEventListener("abort", parts.onAbort);
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* Publish the seam run handle for an out-of-process child. `dispose()` is
|
|
2873
|
+
* idempotent (one memoized teardown): it removes the abort listener, settles
|
|
2874
|
+
* local cancellation — there is no assumption the child cooperates — and then
|
|
2875
|
+
* awaits the backend's teardown to actual exit.
|
|
2876
|
+
* @param parts - the run identity, result, cancellation wiring, and teardown.
|
|
2877
|
+
* @returns the external run handle.
|
|
2878
|
+
*/
|
|
2879
|
+
function subprocessRunHandle(parts) {
|
|
2880
|
+
let disposal;
|
|
2881
|
+
return {
|
|
2882
|
+
id: parts.id,
|
|
2883
|
+
result: parts.result,
|
|
2884
|
+
dispose() {
|
|
2885
|
+
if (disposal !== void 0) return disposal;
|
|
2886
|
+
parts.signal.removeEventListener("abort", parts.onAbort);
|
|
2887
|
+
parts.requestCancel();
|
|
2888
|
+
disposal = parts.teardown();
|
|
2889
|
+
return disposal;
|
|
2890
|
+
}
|
|
2891
|
+
};
|
|
2892
|
+
}
|
|
2893
|
+
//#endregion
|
|
2894
|
+
//#region lib/types/index.js
|
|
2895
|
+
var __runInitializers = function(thisArg, initializers, value) {
|
|
2896
|
+
var useValue = arguments.length > 2;
|
|
2897
|
+
for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
2898
|
+
return useValue ? value : void 0;
|
|
2899
|
+
};
|
|
2900
|
+
var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
2901
|
+
function accept(f) {
|
|
2902
|
+
if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
|
|
2903
|
+
return f;
|
|
2904
|
+
}
|
|
2905
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
2906
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
2907
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
2908
|
+
var _, done = false;
|
|
2909
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
2910
|
+
var context = {};
|
|
2911
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
2912
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
2913
|
+
context.addInitializer = function(f) {
|
|
2914
|
+
if (done) throw new TypeError("Cannot add initializers after decoration has completed");
|
|
2915
|
+
extraInitializers.push(accept(f || null));
|
|
2916
|
+
};
|
|
2917
|
+
var result = (0, decorators[i])(kind === "accessor" ? {
|
|
2918
|
+
get: descriptor.get,
|
|
2919
|
+
set: descriptor.set
|
|
2920
|
+
} : descriptor[key], context);
|
|
2921
|
+
if (kind === "accessor") {
|
|
2922
|
+
if (result === void 0) continue;
|
|
2923
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
2924
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
2925
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
2926
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
2927
|
+
} else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
|
|
2928
|
+
else descriptor[key] = _;
|
|
2929
|
+
}
|
|
2930
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
2931
|
+
done = true;
|
|
2932
|
+
};
|
|
2933
|
+
/** Named provider registry with managed activations, durable discovery, and local child messaging. */
|
|
2934
|
+
let SubagentRuntime = (() => {
|
|
2935
|
+
let _classSuper = TypertRemoteService;
|
|
2936
|
+
let _instanceExtraInitializers = [];
|
|
2937
|
+
let _prompt_decorators;
|
|
2938
|
+
let _interruptByParent_decorators;
|
|
2939
|
+
return class SubagentRuntime extends _classSuper {
|
|
2940
|
+
static {
|
|
2941
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
2942
|
+
_prompt_decorators = [Remote("prompt")];
|
|
2943
|
+
_interruptByParent_decorators = [Remote("interruptByParent")];
|
|
2944
|
+
__esDecorate(this, null, _prompt_decorators, {
|
|
2945
|
+
kind: "method",
|
|
2946
|
+
name: "prompt",
|
|
2947
|
+
static: false,
|
|
2948
|
+
private: false,
|
|
2949
|
+
access: {
|
|
2950
|
+
has: (obj) => "prompt" in obj,
|
|
2951
|
+
get: (obj) => obj.prompt
|
|
2952
|
+
},
|
|
2953
|
+
metadata: _metadata
|
|
2954
|
+
}, null, _instanceExtraInitializers);
|
|
2955
|
+
__esDecorate(this, null, _interruptByParent_decorators, {
|
|
2956
|
+
kind: "method",
|
|
2957
|
+
name: "interruptByParent",
|
|
2958
|
+
static: false,
|
|
2959
|
+
private: false,
|
|
2960
|
+
access: {
|
|
2961
|
+
has: (obj) => "interruptByParent" in obj,
|
|
2962
|
+
get: (obj) => obj.interruptByParent
|
|
2963
|
+
},
|
|
2964
|
+
metadata: _metadata
|
|
2965
|
+
}, null, _instanceExtraInitializers);
|
|
2966
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, {
|
|
2967
|
+
enumerable: true,
|
|
2968
|
+
configurable: true,
|
|
2969
|
+
writable: true,
|
|
2970
|
+
value: _metadata
|
|
2971
|
+
});
|
|
2972
|
+
}
|
|
2973
|
+
config = __runInitializers(this, _instanceExtraInitializers);
|
|
2974
|
+
static Config = z.object({
|
|
2975
|
+
maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile(),
|
|
2976
|
+
maxActiveSubagents: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8).volatile()
|
|
2977
|
+
});
|
|
2978
|
+
static inject = ["workingDirectory"];
|
|
2979
|
+
providers = /* @__PURE__ */ new Map();
|
|
2980
|
+
manager;
|
|
2981
|
+
/**
|
|
2982
|
+
* The contained lifecycle-edge publisher. Built here because scoped dispatch
|
|
2983
|
+
* keys its carrier by this exact service instance, whose own context filter
|
|
2984
|
+
* composes into the carrier.
|
|
2985
|
+
*/
|
|
2986
|
+
emitLifecycle;
|
|
2987
|
+
constructor(ctx, config) {
|
|
2988
|
+
super(ctx, "subagents");
|
|
2989
|
+
this.config = config;
|
|
2990
|
+
this.emitLifecycle = createLifecycleEmitter(this.ctx, (parent) => scopeTarget(this, parent));
|
|
2991
|
+
ctx.inject(["agents"], (childCtx) => {
|
|
2992
|
+
const manager = new SubagentManager(childCtx, {
|
|
2993
|
+
startExternal: (name, request) => {
|
|
2994
|
+
return this.expectProvider(name).start(request);
|
|
2995
|
+
},
|
|
2996
|
+
prepareContinuable: (name, request) => this.prepareContinuable(name, request),
|
|
2997
|
+
observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent)
|
|
2998
|
+
}, () => this.config.maxActiveSubagents.get());
|
|
2999
|
+
this.manager = manager;
|
|
3000
|
+
childCtx.effect(() => () => {
|
|
3001
|
+
/* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
|
|
3002
|
+
if (this.manager === manager) this.manager = void 0;
|
|
3003
|
+
}, "subagents.managerBinding()");
|
|
3004
|
+
});
|
|
3005
|
+
ctx.inject(["sessionProjections"], (projectionCtx) => {
|
|
3006
|
+
projectionCtx.sessionProjections.register(subagentCatalogProjectionDefinition);
|
|
3007
|
+
projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
|
|
3008
|
+
projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
|
|
3009
|
+
});
|
|
3010
|
+
ctx.inject(["agents"], (agentsCtx) => {
|
|
3011
|
+
installSubagentArchiveAdmission(agentsCtx);
|
|
3012
|
+
});
|
|
3013
|
+
}
|
|
3014
|
+
/**
|
|
3015
|
+
* Resolve a delegation tool's depth policy against the current user setting.
|
|
3016
|
+
* @param configured - Explicit tool limit, or provider-managed for external delegation.
|
|
3017
|
+
* @returns The numeric limit, or undefined when the provider owns depth enforcement.
|
|
3018
|
+
*/
|
|
3019
|
+
resolveMaxDepth(configured) {
|
|
3020
|
+
if (configured === "provider-managed") return void 0;
|
|
3021
|
+
if (configured !== void 0) return configured;
|
|
3022
|
+
const depth = this.config.maxDepth.get();
|
|
3023
|
+
assertSubagentMaxDepth(depth);
|
|
3024
|
+
return depth;
|
|
3025
|
+
}
|
|
3026
|
+
/**
|
|
3027
|
+
* Establish a managed child with backend-specific execution capabilities.
|
|
3028
|
+
* @param spec - task, backend, and result recipient.
|
|
3029
|
+
* @returns identities, execution result, and exact-activation disposal. A reserved
|
|
3030
|
+
* childId requires a local backend and guarantees an accepted messageId.
|
|
3031
|
+
*/
|
|
3032
|
+
async startActivation(spec) {
|
|
3033
|
+
const provider = this.expectProvider(spec.provider);
|
|
3034
|
+
if (spec.childId !== void 0 && provider.prepareContinuable === void 0) throw new SubagentError("reserved child ids require a local backend", "UNSUPPORTED_CAPABILITY");
|
|
3035
|
+
assertSubagentMaxDepth(spec.request.maxDepth);
|
|
3036
|
+
this.assertCapabilities(provider, {
|
|
3037
|
+
...spec.request,
|
|
3038
|
+
signal: spec.signal
|
|
3039
|
+
});
|
|
3040
|
+
const manager = this.requireManager();
|
|
3041
|
+
if (this.ctx.get("agents")?.get(spec.request.parent.id) !== spec.request.parent) throw new SubagentError("subagent creation requires the exact live parent agent", "UNAUTHORIZED");
|
|
3042
|
+
if (spec.request.outputSchema !== void 0) assertObjectJsonSchema(spec.request.outputSchema);
|
|
3043
|
+
return provider.prepareContinuable === void 0 ? manager.startExternal(spec) : manager.startLocal(spec);
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Join progressing descendants without cancelling them. Idle descendants whose
|
|
3047
|
+
* inboxes require a later wake stay resident and do not delay host completion.
|
|
3048
|
+
* @param parent - the exact parent whose descendant work is observed.
|
|
3049
|
+
* @returns whether work was joined; hosts recheck parent idle after true.
|
|
3050
|
+
*/
|
|
3051
|
+
async waitForChildren(parent) {
|
|
3052
|
+
return this.manager?.waitForChildren(parent) ?? false;
|
|
3053
|
+
}
|
|
3054
|
+
/**
|
|
3055
|
+
* Steer one model-authored message to the sender's direct parent or direct
|
|
3056
|
+
* continuable child. A running target admits it at the nearest step boundary;
|
|
3057
|
+
* an idle target starts a turn, and an absent direct child cold-resumes from
|
|
3058
|
+
* persistence. The service derives durable sender attribution from the exact
|
|
3059
|
+
* live sender. Caller cancellation stops only pre-acceptance work.
|
|
3060
|
+
* @param sender - exact live Agent authorizing and originating the message.
|
|
3061
|
+
* @param targetId - durable direct-parent or direct-child session id.
|
|
3062
|
+
* @param content - model-authored content to deliver.
|
|
3063
|
+
* @param options - caller cancellation before inbox acceptance.
|
|
3064
|
+
* @returns the accepted message's inbox id.
|
|
3065
|
+
* @throws when continuation services are unavailable, adjacency is rejected,
|
|
3066
|
+
* or the message was not admitted.
|
|
3067
|
+
*/
|
|
3068
|
+
async sendMessage(sender, targetId, content, options) {
|
|
3069
|
+
return this.requireManager().sendMessage(sender, targetId, content, options);
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* Deliver one host-protocol message to a direct continuable child.
|
|
3073
|
+
* Symbol-keyed so host adapters can preserve their own source descriptors without
|
|
3074
|
+
* widening the public Service Definition or impersonating an Agent sender.
|
|
3075
|
+
* @param parent - exact live direct parent authorizing delivery.
|
|
3076
|
+
* @param childId - durable direct-child session id.
|
|
3077
|
+
* @param content - host-authored content to deliver.
|
|
3078
|
+
* @param source - durable host-protocol source descriptor.
|
|
3079
|
+
* @param signal - caller cancellation before inbox acceptance.
|
|
3080
|
+
* @param delivery - Queue as a distinct turn or Steer at the nearest step.
|
|
3081
|
+
* @returns the accepted message's inbox id.
|
|
3082
|
+
*/
|
|
3083
|
+
[deliverSubagentPrompt](parent, childId, content, source, signal, delivery) {
|
|
3084
|
+
return delivery === "steer" ? this.requireManager().steerPrompt(parent, childId, content, source, signal) : this.requireManager().queuePrompt(parent, childId, content, source, signal);
|
|
3085
|
+
}
|
|
3086
|
+
/**
|
|
3087
|
+
* Interrupt one live child's current execution under a human parent
|
|
3088
|
+
* address or an exact live ancestor Agent. Fire-and-return: the cancel
|
|
3089
|
+
* signal is issued before this returns, but the target may keep running
|
|
3090
|
+
* until it observes the signal. Unclaimed pending inbox work, the Activation,
|
|
3091
|
+
* and published descendants are preserved; claimed work is not requeued.
|
|
3092
|
+
* Once the interrupted Agent is idle, a waking send resumes the parked FIFO
|
|
3093
|
+
* queue. External backends stop their single execution. An absent target
|
|
3094
|
+
* is an accepted no-op, as is a manager-less composition, which cannot own a
|
|
3095
|
+
* live Activation.
|
|
3096
|
+
* @param targetSessionId - the durable child session id to interrupt.
|
|
3097
|
+
* @param authority - the human parent address or exact live ancestor Agent.
|
|
3098
|
+
* @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
|
|
3099
|
+
* live target.
|
|
3100
|
+
*/
|
|
3101
|
+
interrupt(targetSessionId, authority) {
|
|
3102
|
+
this.manager?.interrupt(targetSessionId, authority);
|
|
3103
|
+
}
|
|
3104
|
+
/**
|
|
3105
|
+
* Close subagent admission below exact live parent Agents, stop only their
|
|
3106
|
+
* visible descendant Activations synchronously, then await admitted scoped
|
|
3107
|
+
* materializations and release those forests child-first. The scoped cutoff
|
|
3108
|
+
* lasts until each exact parent leaves the registry; unrelated parent trees
|
|
3109
|
+
* remain live.
|
|
3110
|
+
* @param parents - exact host-owned parent Agents entering teardown.
|
|
3111
|
+
* @returns once every retained descendant activation released its execution handle.
|
|
3112
|
+
* @throws an aggregate error after all branches settle when any failed.
|
|
3113
|
+
*/
|
|
3114
|
+
async drainDescendants(parents) {
|
|
3115
|
+
const manager = this.manager;
|
|
3116
|
+
if (manager === void 0) return;
|
|
3117
|
+
await manager.drainDescendants(parents);
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Release selected resident direct children of one exact live
|
|
3121
|
+
* parent. Other children of the same parent remain admitted and resident.
|
|
3122
|
+
* Absent targets and a manager-less composition are accepted no-ops.
|
|
3123
|
+
* @param parent - exact live direct parent authorizing the selected release.
|
|
3124
|
+
* @param childIds - durable direct-child ids to release when resident.
|
|
3125
|
+
* @returns once every selected activation released its execution handle.
|
|
3126
|
+
* @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a
|
|
3127
|
+
* different parent or the supplied parent identity is stale.
|
|
3128
|
+
*/
|
|
3129
|
+
async drainChildren(parent, childIds) {
|
|
3130
|
+
const manager = this.manager;
|
|
3131
|
+
if (manager === void 0) return;
|
|
3132
|
+
await manager.drainChildren(parent, childIds);
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Read the parent's durable direct-child catalog without loading or resuming an Agent.
|
|
3136
|
+
* The service owns and releases the live-preferred Session observation.
|
|
3137
|
+
* @param parentSessionId - parent whose direct children are requested.
|
|
3138
|
+
* @param signal - cancellation forwarded to the Session query.
|
|
3139
|
+
* @returns catalog children in parent event order.
|
|
3140
|
+
* @throws {@link SubagentError} when query or catalog projection is unavailable.
|
|
3141
|
+
* @throws SessionQueryError when the parent cannot be read or the query is cancelled.
|
|
3142
|
+
*/
|
|
3143
|
+
listChildren(parentSessionId, signal) {
|
|
3144
|
+
return listChildren(this.ctx, parentSessionId, signal);
|
|
3145
|
+
}
|
|
3146
|
+
/**
|
|
3147
|
+
* Recursively list reachable parent catalogs in stable pre-order, preserving
|
|
3148
|
+
* each catalog's event order. Each row carries its catalog parent and depth;
|
|
3149
|
+
* external children are leaves; one-shot and unknown-mode children remain
|
|
3150
|
+
* traversal nodes. Unknown modes
|
|
3151
|
+
* produce unsupported diagnostics. Unreadable child catalogs produce corrupt
|
|
3152
|
+
* or unavailable diagnostics and stop only that branch. Root read failures,
|
|
3153
|
+
* missing services or projections, and cancellation reject the whole listing.
|
|
3154
|
+
* Each catalog is observed once and released before the next read. No Agent
|
|
3155
|
+
* is loaded or resumed; Sessions absent from reachable catalogs are omitted.
|
|
3156
|
+
* @param rootSessionId - session whose catalog starts descendant discovery.
|
|
3157
|
+
* @param signal - cancellation forwarded to and checked around each catalog read.
|
|
3158
|
+
* @returns children and branch diagnostics in parent-catalog pre-order.
|
|
3159
|
+
* @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.
|
|
3160
|
+
* @throws SessionQueryError when the root catalog cannot be read.
|
|
3161
|
+
*/
|
|
3162
|
+
listDescendants(rootSessionId, signal) {
|
|
3163
|
+
return listDescendants(this.ctx, rootSessionId, signal);
|
|
3164
|
+
}
|
|
3165
|
+
/**
|
|
3166
|
+
* Deliver one browser-authored message to a continuable child through the
|
|
3167
|
+
* exact live direct parent, retaining the caller-minted request identity and
|
|
3168
|
+
* validated browser zone on the accepted message. Success identifies the
|
|
3169
|
+
* message the child's inbox accepted; later execution is independent of this
|
|
3170
|
+
* call. Queue delivery targets a later turn; steer delivery targets the
|
|
3171
|
+
* nearest step and retains the Agent loop's best-effort fallback semantics.
|
|
3172
|
+
* Image parts are admitted and persisted through the attachment store
|
|
3173
|
+
* before delivery, and the child's model must accept image input.
|
|
3174
|
+
* Cold resume at capacity rejects with `subagent/delivery-unavailable`.
|
|
3175
|
+
* @param request - durable address, delivery, minted identity, content, and optional browser zone.
|
|
3176
|
+
* @param signal - carrier cancellation, owning the call until inbox acceptance.
|
|
3177
|
+
* @returns the accepted message's inbox identity.
|
|
3178
|
+
* @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
|
|
3179
|
+
* `subagent/invalid-time-zone`, `subagent/parent-unavailable`,
|
|
3180
|
+
* `subagent/not-resumable`, `subagent/unauthorized`,
|
|
3181
|
+
* `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
|
|
3182
|
+
*/
|
|
3183
|
+
async prompt(request, signal) {
|
|
3184
|
+
const { parentSessionId, childSessionId, clientTimeZone, delivery } = request;
|
|
3185
|
+
validateControlRequest("subagent.prompt", request);
|
|
3186
|
+
const canonicalTimeZone = clientTimeZone === void 0 ? void 0 : canonicalClientTimeZone(clientTimeZone);
|
|
3187
|
+
if (clientTimeZone !== void 0 && canonicalTimeZone === void 0) throw new RemoteError("subagent/invalid-time-zone", "clientTimeZone must be UTC or a valid IANA Area/Location name", { value: clientTimeZone });
|
|
3188
|
+
const parent = this.ctx.get("agents")?.get(parentSessionId);
|
|
3189
|
+
if (parent === void 0) throw new RemoteError("subagent/parent-unavailable", `parent session "${parentSessionId}" is not live`, { parentSessionId });
|
|
3190
|
+
const source = {
|
|
3191
|
+
kind: "user",
|
|
3192
|
+
rpcId: request.requestId,
|
|
3193
|
+
...canonicalTimeZone === void 0 ? {} : { clientTimeZone: canonicalTimeZone }
|
|
3194
|
+
};
|
|
3195
|
+
try {
|
|
3196
|
+
let content;
|
|
3197
|
+
if (request.content.every((part) => part.type === "text")) content = request.content.map((part) => ({
|
|
3198
|
+
type: "text",
|
|
3199
|
+
text: part.text
|
|
3200
|
+
}));
|
|
3201
|
+
else {
|
|
3202
|
+
const attachments = this.ctx.get("attachments");
|
|
3203
|
+
if (attachments === void 0) throw new Error("subagent image prompt requires an attachment store");
|
|
3204
|
+
content = await attachments.admitPromptContent(request.content);
|
|
3205
|
+
}
|
|
3206
|
+
return { messageId: await this[deliverSubagentPrompt](parent, childSessionId, content, source, signal, delivery) };
|
|
3207
|
+
} catch (error) {
|
|
3208
|
+
return rejectPrompt(error, childSessionId, signal);
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
/**
|
|
3212
|
+
* Remote face of {@link interrupt} under one durable parent address. No
|
|
3213
|
+
* catalog, history, persistence, or parent Agent lookup runs: the core
|
|
3214
|
+
* primitive alone authorizes the address against the live Activation, which
|
|
3215
|
+
* is what keeps a live child interruptible while its parent Agent is offline.
|
|
3216
|
+
* Absent, idle, and already-completed targets are accepted no-ops there.
|
|
3217
|
+
* @param childSessionId - durable child session id to interrupt.
|
|
3218
|
+
* @param parentSessionId - durable direct parent whose authority is claimed.
|
|
3219
|
+
* @param mode - required continuable-address discriminator.
|
|
3220
|
+
* @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
|
|
3221
|
+
* @throws {RemoteError} `gateway/bad-request` for an empty id,
|
|
3222
|
+
* `subagent/unauthorized` when the address does not own the live target,
|
|
3223
|
+
* otherwise `gateway/internal`.
|
|
3224
|
+
*/
|
|
3225
|
+
interruptByParent(childSessionId, parentSessionId, mode) {
|
|
3226
|
+
validateControlRequest("subagent.interrupt", {
|
|
3227
|
+
childSessionId,
|
|
3228
|
+
parentSessionId,
|
|
3229
|
+
mode
|
|
3230
|
+
});
|
|
3231
|
+
try {
|
|
3232
|
+
this.interrupt(childSessionId, {
|
|
3233
|
+
kind: "user",
|
|
3234
|
+
parentSessionId
|
|
3235
|
+
});
|
|
3236
|
+
} catch (error) {
|
|
3237
|
+
if (error instanceof SubagentError && error.code === "UNAUTHORIZED") throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
|
|
3238
|
+
throw new RemoteError("gateway/internal", "subagent interrupt failed", {}, { cause: error });
|
|
3239
|
+
}
|
|
3240
|
+
return { accepted: true };
|
|
3241
|
+
}
|
|
3242
|
+
/**
|
|
3243
|
+
* Register a provider under its name. Registration is effect-scoped and HMR
|
|
3244
|
+
* safe; removing a provider blocks new starts but does not revoke runs that
|
|
3245
|
+
* were already returned to their holders. Providers without either execution
|
|
3246
|
+
* method are rejected with UNSUPPORTED_CAPABILITY before registration.
|
|
3247
|
+
* @param provider - the trusted provider implementation.
|
|
3248
|
+
* @returns the exact Cordis effect disposer.
|
|
3249
|
+
*/
|
|
3250
|
+
registerProvider(provider) {
|
|
3251
|
+
const name = provider.name;
|
|
3252
|
+
if (provider.start === void 0 && provider.prepareContinuable === void 0) throw new SubagentError(`subagent provider "${name}" must implement start or prepareContinuable`, "UNSUPPORTED_CAPABILITY");
|
|
3253
|
+
return this.ctx.effect(function* () {
|
|
3254
|
+
if (this.providers.has(name)) throw new SubagentError(`a subagent provider named "${name}" is already registered`, "DUPLICATE_PROVIDER");
|
|
3255
|
+
this.providers.set(name, provider);
|
|
3256
|
+
yield () => {
|
|
3257
|
+
this.providers.delete(name);
|
|
3258
|
+
this.emitLifecycle("subagent/provider-removed", name);
|
|
3259
|
+
};
|
|
3260
|
+
this.ctx.emit("subagent/provider-added", provider);
|
|
3261
|
+
}.bind(this), "subagents.registerProvider()");
|
|
3262
|
+
}
|
|
3263
|
+
/**
|
|
3264
|
+
* Look up a provider by name.
|
|
3265
|
+
* @param name - the provider name.
|
|
3266
|
+
* @returns the provider, or undefined when absent.
|
|
3267
|
+
*/
|
|
3268
|
+
getProvider(name) {
|
|
3269
|
+
return this.providers.get(name);
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* List registered provider names in insertion order.
|
|
3273
|
+
* @returns the registered names.
|
|
3274
|
+
*/
|
|
3275
|
+
list() {
|
|
3276
|
+
return [...this.providers.keys()];
|
|
3277
|
+
}
|
|
3278
|
+
/**
|
|
3279
|
+
* Resolve one provider's detached continuable-creation contribution. Method
|
|
3280
|
+
* presence on the provider IS the capability, so a provider without it is
|
|
3281
|
+
* rejected before the manager reserves any child resources.
|
|
3282
|
+
*/
|
|
3283
|
+
async prepareContinuable(name, request) {
|
|
3284
|
+
return this.expectProvider(name).prepareContinuable(request);
|
|
3285
|
+
}
|
|
3286
|
+
/** Look up a provider for dispatch or fail loud. */
|
|
3287
|
+
expectProvider(name) {
|
|
3288
|
+
const provider = this.providers.get(name);
|
|
3289
|
+
if (provider === void 0) throw new SubagentError(`no subagent provider registered for "${name}"`, "NO_PROVIDER");
|
|
3290
|
+
return provider;
|
|
3291
|
+
}
|
|
3292
|
+
/** Resolve the subagent manager or fail loud. */
|
|
3293
|
+
requireManager() {
|
|
3294
|
+
if (this.manager === void 0) throw new SubagentError("continuable subagents require the agents service", "CONTINUATION_UNAVAILABLE");
|
|
3295
|
+
return this.manager;
|
|
3296
|
+
}
|
|
3297
|
+
/**
|
|
3298
|
+
* Build the lifecycle observer for one continuable Activation's residency
|
|
3299
|
+
* epoch, so the manager publishes its edges without owning event dispatch.
|
|
3300
|
+
*/
|
|
3301
|
+
observeActivation(provider, childId, parent) {
|
|
3302
|
+
return createActivationObserver(this.emitLifecycle, provider, childId, parent);
|
|
3303
|
+
}
|
|
3304
|
+
/** Reject the first requested capability that the provider lacks. */
|
|
3305
|
+
assertCapabilities(provider, request) {
|
|
3306
|
+
const needs = [
|
|
3307
|
+
{
|
|
3308
|
+
when: request.agentOptions !== void 0,
|
|
3309
|
+
cap: "agentOptions"
|
|
3310
|
+
},
|
|
3311
|
+
{
|
|
3312
|
+
when: request.outputSchema !== void 0,
|
|
3313
|
+
cap: "outputSchema"
|
|
3314
|
+
},
|
|
3315
|
+
{
|
|
3316
|
+
when: request.maxDepth !== void 0,
|
|
3317
|
+
cap: "depthLimit"
|
|
3318
|
+
},
|
|
3319
|
+
{
|
|
3320
|
+
when: request.toolFilter !== void 0,
|
|
3321
|
+
cap: "toolFilter"
|
|
3322
|
+
},
|
|
3323
|
+
{
|
|
3324
|
+
when: request.persona !== void 0,
|
|
3325
|
+
cap: "persona"
|
|
3326
|
+
}
|
|
3327
|
+
];
|
|
3328
|
+
for (const { when, cap } of needs) if (when && !provider.capabilities[cap]) throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`, "UNSUPPORTED_CAPABILITY");
|
|
3329
|
+
}
|
|
3330
|
+
};
|
|
3331
|
+
})();
|
|
3332
|
+
//#endregion
|
|
3333
|
+
export { AssistantOutputFold, NO_START_CAPABILITIES, STRUCTURED_OUTPUT_TOOL, SUBAGENT_DESCRIPTOR_VERSION, SubagentDepthError, SubagentError, SubagentRunId, SubagentRuntime, SubagentRuntime as default, appendDelegatedPolicyOverrides, applyChildComposition, assertPositiveFinite, assertSubagentMaxDepth, assertUsableCwd, captureDelegatedPolicyOverrides, childSessionMeta, delegationDepthOf, finalAssistantOutput, foldSubagentDescriptor, parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, settleRunResult, snapshotSubagentDescriptor, subprocessRunHandle };
|