@eum-agent/agent-delegation 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.js +1925 -0
  2. package/package.json +50 -3
  3. package/ui/ui.js +516 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,1925 @@
1
+ import { existsSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { z } from "zod";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ //#region src/guidance.ts
6
+ const GUIDANCE = {
7
+ title: "Subagents",
8
+ entries: [
9
+ {
10
+ tools: ["subagent_spawn"],
11
+ text: "`subagent_spawn` delegates a self-contained part of the task to another agent, the listed one that fits it best, or the general-purpose one when none does. It starts with none of this conversation: give it the goal, the relevant paths and facts, and what to hand back. Its result reaches you as a message beginning `Subagent <id>, task <id>:` — that message is from the subagent, not from the person. Check the result before you rely on it. Query model_list before choosing an explicit pair. Without an explicit pair, a usable Agent default wins, then the current session model and parameters, then the system default; explicit params overrides the selected base."
12
+ },
13
+ {
14
+ tools: ["subagent_get"],
15
+ text: "`subagent_get` accepts items of descendant targets and defaults to status summaries without task input or output bodies. Use view=result with taskId for original final text. A positive waitMs also requires taskId for every target and shares one deadline of at most 60000 milliseconds; cancelling a wait leaves children running. Pages default to 50 members, reject limits above 100, and may contain fewer members or partial original text when allowance is small. Copy next.arguments unchanged. outputTokens requests an allowance; effective reports the actual allocation."
16
+ },
17
+ {
18
+ tools: ["subagent_list"],
19
+ text: "`subagent_list` pages descendant task summaries without input or result bodies. Default limit 50, hard maximum 100; copy next.arguments unchanged and restart when source_changed is reported."
20
+ },
21
+ {
22
+ tools: ["subagent_send"],
23
+ text: "`subagent_send` sends a follow-up task and returns a short acceptance receipt. Keep the task ID and query status; never resend accepted work merely because its receipt was shortened."
24
+ },
25
+ {
26
+ tools: ["subagent_stop"],
27
+ text: "`subagent_stop` stops a subagent you no longer need."
28
+ }
29
+ ]
30
+ };
31
+ //#endregion
32
+ //#region src/schema.ts
33
+ /** Installation-wide defaults, applied independently to each root session. */
34
+ const SubagentSettingsSchema = z.object({
35
+ maxConcurrent: z.number().int().positive().default(8),
36
+ maxDepth: z.number().int().positive().default(3)
37
+ }).strict();
38
+ /** An agent identifier: also a directory name under the work root, so it is
39
+ * checked before it is ever joined into a path. */
40
+ const AgentIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]*$/).max(80);
41
+ /** What a child session keeps from the moment it was delegated: which agent it
42
+ * works as, and the narrowing of tools the delegation chain applied. Its
43
+ * prompt is not kept here — it is read from that agent on every step. */
44
+ const SubagentDefinitionSchema = z.object({
45
+ agent: AgentIdSchema,
46
+ tools: z.array(z.string()).optional()
47
+ }).strict();
48
+ /** A retained child session and its immutable ancestry. */
49
+ const SubagentRelationSchema = z.object({
50
+ childSessionId: z.string(),
51
+ parentSessionId: z.string(),
52
+ rootSessionId: z.string(),
53
+ depth: z.number().int().positive(),
54
+ definition: SubagentDefinitionSchema,
55
+ createdAt: z.number()
56
+ }).strict();
57
+ /** One accepted task; a retained session can have many sequential tasks. */
58
+ /** Validates native task fields with the framework's shared vocabulary codecs. */
59
+ function taskSchema(framework) {
60
+ return z.object({
61
+ taskId: z.string(),
62
+ childSessionId: z.string(),
63
+ callerSessionId: z.string(),
64
+ /** Parent history generation captured when this task was accepted. */
65
+ targetGeneration: z.number().int().nonnegative(),
66
+ sourceOwner: z.string(),
67
+ requestKey: z.string(),
68
+ /** The agent the task was delegated to. */
69
+ agent: AgentIdSchema,
70
+ ordinal: z.number().int(),
71
+ modelValidation: z.object({
72
+ validation: z.enum([
73
+ "known",
74
+ "partial",
75
+ "unknown"
76
+ ]),
77
+ changes: z.array(z.object({
78
+ field: z.string(),
79
+ reason: z.string(),
80
+ value: z.unknown().optional()
81
+ })),
82
+ unknownKeys: z.array(z.string())
83
+ }).optional(),
84
+ requestFingerprint: z.string().optional(),
85
+ input: z.string(),
86
+ message: framework.message.optional(),
87
+ state: z.enum([
88
+ "queued",
89
+ "starting",
90
+ "running",
91
+ "awaiting-human",
92
+ "stopping",
93
+ "finished"
94
+ ]),
95
+ triggerSeq: z.number().int().nullable(),
96
+ outcome: framework.outcome.nullable(),
97
+ result: z.object({
98
+ text: z.string(),
99
+ truncated: z.boolean()
100
+ }).nullable(),
101
+ createdAt: z.number(),
102
+ updatedAt: z.number(),
103
+ revision: z.number().int()
104
+ }).strict();
105
+ }
106
+ /** Model-selected creation fields; ancestry always comes from the trusted caller. */
107
+ const SpawnSubagentSchema = z.object({
108
+ task: z.string().min(1).describe("Self-contained task for an independent child context; include facts, paths and requested result."),
109
+ /** The agent to delegate to; the general-purpose agent when absent. */
110
+ agent: AgentIdSchema.optional().describe("Agent identity to delegate to; omit for the general-purpose agent."),
111
+ providerId: z.string().optional().describe("Configured provider identity; requires model when specified."),
112
+ model: z.string().optional().describe("Configured chat model paired with providerId; omit both to use the delegation default."),
113
+ params: z.record(z.string(), z.unknown()).optional().describe("Model parameter overrides applied to the selected source template.")
114
+ }).strict();
115
+ /** Native state announcements use the task codec supplied by the framework. */
116
+ function changedSchema(framework) {
117
+ return z.strictObject({
118
+ entries: z.array(z.strictObject({
119
+ rootSessionId: z.string(),
120
+ parentSessionId: z.string(),
121
+ childSessionId: z.string(),
122
+ taskId: z.string(),
123
+ revision: z.number().int(),
124
+ task: taskSchema(framework)
125
+ })).max(64),
126
+ invalidated: z.boolean().optional()
127
+ }).refine((input) => input.entries.length > 0 || input.invalidated === true, "Empty changes must explicitly invalidate the retained task view");
128
+ }
129
+ /** Bounded independent child-creation collection; duplicates need distinct task input. */
130
+ const SpawnSubagentsInput = z.strictObject({ tasks: z.array(SpawnSubagentSchema).min(1).max(64).describe("One to 64 independent native child tasks; each accepted member receives a distinct task ID.") }).refine((input) => Buffer.byteLength(JSON.stringify(input)) <= 8388608, "Input exceeds 8 MiB");
131
+ /** One native task or subtree owned by an ancestor session. */
132
+ const StopSubagentInput = z.strictObject({
133
+ childSessionId: z.string().min(1).max(512).describe("Descendant child session identity to control."),
134
+ scope: z.enum(["task", "subtree"]).describe("task stops the named or current task; subtree stops this child and all its native descendants."),
135
+ taskId: z.string().min(1).max(512).optional().describe("Task identity for task scope; omit to stop the current task.")
136
+ });
137
+ /** Native stop collection; duplicate resources settle once. */
138
+ const StopSubagentsInput = z.strictObject({ items: z.array(StopSubagentInput).min(1).max(64).describe("One to 64 ordered descendant stop targets; duplicate resources settle once.") }).refine((input) => Buffer.byteLength(JSON.stringify(input)) <= 8388608, "Input exceeds 8 MiB");
139
+ /** Browser management reads enforce byte bounds independently of model summary pages. */
140
+ const ListByParentsParams = z.strictObject({
141
+ parentSessionIds: z.array(z.string().min(1).max(512)).min(1).max(64),
142
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
143
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
144
+ }).refine((input) => input.parentSessionIds.length * input.maxItemBytes + 8192 <= input.maxTotalBytes, "batch-limit: declared member budgets exceed total").refine((input) => Buffer.byteLength(JSON.stringify(input)) <= 8388608, "Input exceeds 8 MiB");
145
+ /** Ordered parent query outcomes retain each member's original identity. */
146
+ function listByParentsResult(framework) {
147
+ const target = z.string().min(1).max(512);
148
+ return z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
149
+ index: z.number().int().nonnegative(),
150
+ target,
151
+ ok: z.literal(true),
152
+ value: z.array(taskSchema(framework))
153
+ }), z.strictObject({
154
+ index: z.number().int().nonnegative(),
155
+ target,
156
+ ok: z.literal(false),
157
+ error: z.strictObject({
158
+ code: z.string(),
159
+ message: z.string()
160
+ })
161
+ })])).max(64) });
162
+ }
163
+ /** Bounded task metadata; accepted inputs and output bodies are never included. */
164
+ const NativeTaskSummarySchema = z.strictObject({
165
+ taskId: z.string(),
166
+ childSessionId: z.string(),
167
+ state: z.enum([
168
+ "queued",
169
+ "starting",
170
+ "running",
171
+ "awaiting-human",
172
+ "stopping",
173
+ "finished"
174
+ ]),
175
+ outcome: z.unknown().nullable(),
176
+ title: z.string().max(1024),
177
+ resultAvailable: z.boolean(),
178
+ revision: z.number().int().nonnegative(),
179
+ agent: z.string().optional(),
180
+ createdAt: z.number().optional(),
181
+ updatedAt: z.number().optional()
182
+ });
183
+ //#endregion
184
+ //#region src/storage/catalog.ts
185
+ /** Opens native delegation tables without owning or closing the connection. */
186
+ function createSubagentCatalogOn(storage, framework) {
187
+ const SubagentTaskSchema = taskSchema(framework);
188
+ const mapped = new Map([
189
+ "subagent_session",
190
+ "subagent_task",
191
+ "subagent_by_parent",
192
+ "subagent_by_root",
193
+ "subagent_task_by_state"
194
+ ].map((name) => [name, storage.tableName(name)]));
195
+ const sql = (text) => text.replace(/\b(subagent_session|subagent_task|subagent_by_parent|subagent_by_root|subagent_task_by_state)\b/g, (name) => mapped.get(name));
196
+ const db = {
197
+ prepare: (text) => storage.db.prepare(sql(text)),
198
+ exec: (text) => storage.db.exec(sql(text)),
199
+ get isTransaction() {
200
+ return storage.db.isTransaction;
201
+ }
202
+ };
203
+ db.exec(`CREATE TABLE IF NOT EXISTS subagent_session (
204
+ child_session_id TEXT NOT NULL PRIMARY KEY, parent_session_id TEXT NOT NULL,
205
+ root_session_id TEXT NOT NULL, depth INTEGER NOT NULL CHECK(depth > 0),
206
+ definition_json TEXT NOT NULL, created_at INTEGER NOT NULL
207
+ ) STRICT;
208
+ CREATE INDEX IF NOT EXISTS subagent_by_parent ON subagent_session(parent_session_id, child_session_id);
209
+ CREATE INDEX IF NOT EXISTS subagent_by_root ON subagent_session(root_session_id, child_session_id);
210
+ CREATE TABLE IF NOT EXISTS subagent_task (
211
+ task_id TEXT NOT NULL PRIMARY KEY, child_session_id TEXT NOT NULL,
212
+ caller_session_id TEXT NOT NULL, request_key TEXT NOT NULL, ordinal INTEGER NOT NULL,
213
+ task_state TEXT NOT NULL, payload TEXT NOT NULL,
214
+ UNIQUE(caller_session_id, request_key), UNIQUE(child_session_id, ordinal)
215
+ ) STRICT;
216
+ CREATE INDEX IF NOT EXISTS subagent_task_by_state ON subagent_task(task_state, child_session_id);`);
217
+ const relationColumns = "child_session_id, parent_session_id, root_session_id, depth, definition_json, created_at";
218
+ function decode(row) {
219
+ return SubagentRelationSchema.parse({
220
+ childSessionId: row.child_session_id,
221
+ parentSessionId: row.parent_session_id,
222
+ rootSessionId: row.root_session_id,
223
+ depth: row.depth,
224
+ definition: JSON.parse(String(row.definition_json)),
225
+ createdAt: row.created_at
226
+ });
227
+ }
228
+ let membership = 0;
229
+ const descendants = `WITH RECURSIVE descendants(child_session_id) AS (
230
+ SELECT child_session_id FROM subagent_session WHERE parent_session_id = ?
231
+ UNION SELECT child.child_session_id FROM subagent_session child
232
+ JOIN descendants ancestor ON child.parent_session_id = ancestor.child_session_id
233
+ )`;
234
+ const summary = `json_object('taskId',task_id,'childSessionId',child_session_id,
235
+ 'state',task_state,'outcome',json_extract(payload,'$.outcome'),
236
+ 'title',substr(json_extract(payload,'$.input'),1,256),
237
+ 'resultAvailable',CASE WHEN json_type(payload,'$.result')='object' THEN json('true') ELSE json('false') END,
238
+ 'revision',json_extract(payload,'$.revision'),'agent',json_extract(payload,'$.agent'),
239
+ 'createdAt',json_extract(payload,'$.createdAt'),'updatedAt',json_extract(payload,'$.updatedAt')) AS summary`;
240
+ return {
241
+ connectionIdentity: storage.connectionIdentity,
242
+ transaction(write) {
243
+ if (db.isTransaction) return write();
244
+ db.exec("BEGIN");
245
+ try {
246
+ const result = write();
247
+ db.exec("COMMIT");
248
+ return result;
249
+ } catch (error) {
250
+ db.exec("ROLLBACK");
251
+ throw error;
252
+ }
253
+ },
254
+ relations(root) {
255
+ return (root === void 0 ? db.prepare(`SELECT ${relationColumns} FROM subagent_session`).all() : db.prepare(`SELECT ${relationColumns} FROM subagent_session WHERE root_session_id = ?`).all(root)).map(decode);
256
+ },
257
+ relation(child) {
258
+ const row = db.prepare(`SELECT ${relationColumns} FROM subagent_session WHERE child_session_id = ?`).get(child);
259
+ return row ? decode(row) : void 0;
260
+ },
261
+ ancestry(child) {
262
+ const row = db.prepare("SELECT parent_session_id, root_session_id FROM subagent_session WHERE child_session_id = ?").get(child);
263
+ return row ? {
264
+ parentSessionId: String(row.parent_session_id),
265
+ rootSessionId: String(row.root_session_id)
266
+ } : void 0;
267
+ },
268
+ addRelation(input) {
269
+ membership++;
270
+ const row = SubagentRelationSchema.parse(input);
271
+ db.prepare(`INSERT INTO subagent_session (${relationColumns}) VALUES (?, ?, ?, ?, ?, ?)`).run(row.childSessionId, row.parentSessionId, row.rootSessionId, row.depth, JSON.stringify(row.definition), row.createdAt);
272
+ },
273
+ tasks(child) {
274
+ return (child === void 0 ? db.prepare("SELECT payload FROM subagent_task ORDER BY child_session_id, ordinal").all() : db.prepare("SELECT payload FROM subagent_task WHERE child_session_id = ? ORDER BY ordinal").all(child)).map((row) => SubagentTaskSchema.parse(JSON.parse(String(row.payload))));
275
+ },
276
+ measureTasks(parent, query, maxBytes) {
277
+ const descendants = `WITH RECURSIVE descendants(child_session_id) AS (
278
+ SELECT child_session_id FROM subagent_session WHERE parent_session_id = ?
279
+ UNION SELECT child.child_session_id FROM subagent_session child
280
+ JOIN descendants ancestor ON child.parent_session_id = ancestor.child_session_id
281
+ )`;
282
+ const conditions = ["child_session_id IN (SELECT child_session_id FROM descendants)"];
283
+ const values = [parent];
284
+ if (query.childSessionId !== void 0) {
285
+ conditions.push("child_session_id = ?");
286
+ values.push(query.childSessionId);
287
+ }
288
+ if (query.taskId !== void 0) {
289
+ conditions.push("task_id = ?");
290
+ values.push(query.taskId);
291
+ }
292
+ const selected = `SELECT task_id, payload FROM subagent_task WHERE ${conditions.join(" AND ")}
293
+ ORDER BY child_session_id, ordinal${query.childSessionId !== void 0 && query.taskId === void 0 ? " DESC LIMIT 1" : ""}`;
294
+ const total = db.prepare(`${descendants} SELECT COALESCE(SUM(length(CAST(payload AS BLOB))), 0) AS bytes FROM (${selected})`).get(...values);
295
+ const bytes = Number(total?.bytes ?? 0);
296
+ if (bytes > maxBytes) return {
297
+ bytes,
298
+ taskIds: []
299
+ };
300
+ return {
301
+ bytes,
302
+ taskIds: db.prepare(`${descendants} SELECT task_id FROM (${selected})`).all(...values).map((row) => String(row.task_id))
303
+ };
304
+ },
305
+ summary(parent, query) {
306
+ const conditions = ["child_session_id IN (SELECT child_session_id FROM descendants)"];
307
+ const values = [parent];
308
+ if (query.childSessionId !== void 0) {
309
+ conditions.push("child_session_id=?");
310
+ values.push(query.childSessionId);
311
+ }
312
+ if (query.taskId !== void 0) {
313
+ conditions.push("task_id=?");
314
+ values.push(query.taskId);
315
+ }
316
+ const row = db.prepare(`${descendants} SELECT ${summary} FROM subagent_task WHERE ${conditions.join(" AND ")} ORDER BY ordinal DESC LIMIT 1`).get(...values);
317
+ return row ? NativeTaskSummarySchema.parse(JSON.parse(String(row.summary))) : void 0;
318
+ },
319
+ summaryPage(parent, query) {
320
+ if (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 100) throw new Error("Invalid summary page limit");
321
+ const observed = db.prepare(`${descendants} SELECT COUNT(*) AS count,COALESCE(MAX(rowid),0) AS upper FROM subagent_task WHERE child_session_id IN (SELECT child_session_id FROM descendants)`).get(parent);
322
+ const source = `${membership}:${observed.count}:${observed.upper}`;
323
+ if (query.source !== void 0 && query.source !== source) throw new Error("source_changed: native task membership changed");
324
+ const upper = query.upper ?? Number(observed.upper);
325
+ const rows = db.prepare(`${descendants} SELECT rowid AS task_key,${summary} FROM subagent_task WHERE child_session_id IN (SELECT child_session_id FROM descendants) AND rowid>? AND rowid<=? ORDER BY rowid LIMIT ?`).all(parent, query.after ?? 0, upper, query.limit + 1);
326
+ return {
327
+ items: rows.slice(0, query.limit).map((row) => ({
328
+ key: Number(row.task_key),
329
+ value: NativeTaskSummarySchema.parse(JSON.parse(String(row.summary)))
330
+ })),
331
+ source,
332
+ upper,
333
+ complete: rows.length <= query.limit
334
+ };
335
+ },
336
+ readTask(taskId) {
337
+ const row = db.prepare("SELECT payload FROM subagent_task WHERE task_id = ?").get(taskId);
338
+ return row ? SubagentTaskSchema.parse(JSON.parse(String(row.payload))) : void 0;
339
+ },
340
+ saveTask(input) {
341
+ const task = SubagentTaskSchema.parse(input);
342
+ if (!db.prepare("SELECT task_id FROM subagent_task WHERE task_id=?").get(task.taskId)) membership++;
343
+ db.prepare(`INSERT INTO subagent_task (task_id, child_session_id, caller_session_id, request_key, ordinal, task_state, payload) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id) DO UPDATE SET task_state = excluded.task_state, payload = excluded.payload`).run(task.taskId, task.childSessionId, task.callerSessionId, task.requestKey, task.ordinal, task.state, JSON.stringify(task));
344
+ }
345
+ };
346
+ }
347
+ //#endregion
348
+ //#region src/runtime/manager.ts
349
+ const DEFAULT_AGENT_ID = "general-purpose";
350
+ const agentRemovedMessage = (agentId) => `the agent of this session was deleted: ${agentId}. The session can be read but not continued`;
351
+ /** Hashes one complete normalized member independently of array order or neighbours. */
352
+ function memberDigest(input) {
353
+ const canonical = JSON.stringify(input, (_key, value) => {
354
+ if (value && typeof value === "object" && !Array.isArray(value)) return Object.fromEntries(Object.keys(value).sort().map((key) => [key, value[key]]));
355
+ return value;
356
+ });
357
+ return createHash("sha256").update(canonical).digest("hex");
358
+ }
359
+ /** Builds the native coordinator over the existing session loop. */
360
+ function createSubagentManager(deps) {
361
+ const { sessions, catalog, runs } = deps;
362
+ const stopping = /* @__PURE__ */ new Set();
363
+ /** Children whose next queued task met a full root; retried when a task
364
+ * of any child finishes. */
365
+ const blocked = /* @__PURE__ */ new Set();
366
+ let closed = false;
367
+ let recovering = false;
368
+ const batchedTaskIds = /* @__PURE__ */ new Set();
369
+ const stoppingNotifications = /* @__PURE__ */ new Map();
370
+ const admissionBatches = /* @__PURE__ */ new WeakMap();
371
+ function publishTasks(values) {
372
+ if (deps.signal.aborted || values.length === 0) return;
373
+ const targets = /* @__PURE__ */ new Set();
374
+ for (const task of values) {
375
+ const relation = catalog.relation(task.childSessionId);
376
+ if (relation) {
377
+ targets.add(relation.rootSessionId);
378
+ targets.add(relation.parentSessionId);
379
+ }
380
+ }
381
+ deps.changed(values, [...targets]);
382
+ }
383
+ function session(id) {
384
+ const value = sessions.listSessions().find((row) => row.sessionId === id);
385
+ if (!value) throw new Error("not-found: session does not exist");
386
+ return value;
387
+ }
388
+ function authorized(caller, child) {
389
+ session(caller);
390
+ let relation = catalog.relation(child);
391
+ while (relation) {
392
+ if (relation.parentSessionId === caller) return;
393
+ relation = catalog.relation(relation.parentSessionId);
394
+ }
395
+ throw new Error("forbidden: only descendants may be controlled");
396
+ }
397
+ /** Whether every task slot of `root` is taken: a task holds one from
398
+ * leaving the queue until it finishes. */
399
+ function full(root) {
400
+ const children = new Set(catalog.relations(root).map((row) => row.childSessionId));
401
+ return tasks().filter((task) => children.has(task.childSessionId) && task.state !== "finished" && task.state !== "queued").length >= deps.settings().maxConcurrent;
402
+ }
403
+ function capacity(root) {
404
+ if (full(root)) throw new Error("capacity-exceeded: native task limit reached");
405
+ }
406
+ function projected(task) {
407
+ const run = runs.get(task.taskId);
408
+ return run ? {
409
+ ...task,
410
+ state: run.state === "pending" ? task.state : run.state,
411
+ triggerSeq: run.triggerSeq,
412
+ outcome: run.outcome,
413
+ result: run.result,
414
+ updatedAt: run.updatedAt,
415
+ revision: task.revision + run.revision
416
+ } : task;
417
+ }
418
+ function tasks(child) {
419
+ return catalog.tasks(child).map(projected);
420
+ }
421
+ function announce(task) {
422
+ if (batchedTaskIds.has(task.taskId) || stoppingNotifications.has(task.taskId)) return;
423
+ queueMicrotask(() => {
424
+ if (deps.signal.aborted) return;
425
+ const current = tasks(task.childSessionId).find((row) => row.taskId === task.taskId);
426
+ if (!current || current.revision !== task.revision) return;
427
+ publishTasks([current]);
428
+ });
429
+ }
430
+ function acceptTask(caller, child, input, message, scope) {
431
+ deps.signal.throwIfAborted();
432
+ if (recovering) throw new Error("recovering");
433
+ if (closed || stopping.has(child) || stopping.has(caller.sessionId)) throw new Error("stopping");
434
+ const previous = tasks().find((row) => row.callerSessionId === caller.sessionId && row.requestKey === caller.requestKey);
435
+ if (previous) {
436
+ if (previous.input !== input || previous.childSessionId !== child || previous.sourceOwner !== caller.owner) throw new Error("request-key-conflict");
437
+ return previous;
438
+ }
439
+ const relation = catalog.relation(child);
440
+ if (!relation) throw new Error("not-found: child does not exist");
441
+ for (const agentId of [relation.definition.agent, session(child).agentId]) if (!deps.agent(agentId)) throw new Error(agentRemovedMessage(agentId));
442
+ const childTasks = tasks(child);
443
+ const busy = childTasks.some((task) => task.state !== "finished");
444
+ if (!busy) capacity(relation.rootSessionId);
445
+ if (childTasks.filter((task) => task.state === "queued").length >= 32) throw new Error("queue-full");
446
+ const now = Date.now();
447
+ const task = {
448
+ taskId: message?.source?.taskId ?? randomUUID(),
449
+ childSessionId: child,
450
+ callerSessionId: caller.sessionId,
451
+ targetGeneration: session(relation.parentSessionId).historyGeneration,
452
+ sourceOwner: caller.owner,
453
+ requestKey: caller.requestKey,
454
+ agent: relation.definition.agent,
455
+ input,
456
+ message: message ?? {
457
+ id: randomUUID(),
458
+ role: "user",
459
+ content: [{
460
+ type: "text",
461
+ text: input
462
+ }]
463
+ },
464
+ ordinal: (childTasks.at(-1)?.ordinal ?? 0) + 1,
465
+ state: busy ? "queued" : "starting",
466
+ triggerSeq: null,
467
+ outcome: null,
468
+ result: null,
469
+ createdAt: now,
470
+ updatedAt: now,
471
+ revision: 0
472
+ };
473
+ const write = (joined) => {
474
+ if (catalog.connectionIdentity !== joined.connectionIdentity) throw new Error("Native task storage must share the host connection");
475
+ catalog.saveTask(task);
476
+ if (admissionBatches.has(caller)) {
477
+ batchedTaskIds.add(task.taskId);
478
+ joined.afterRollback(() => batchedTaskIds.delete(task.taskId));
479
+ }
480
+ runs.prepare(plan(task), joined);
481
+ joined.afterCommit(() => {
482
+ const batch = admissionBatches.get(caller);
483
+ if (batch) {
484
+ const committed = tasks(child).find((row) => row.taskId === task.taskId);
485
+ if (committed) batch.tasks.push(committed);
486
+ batch.starts.push(() => {
487
+ run(child);
488
+ });
489
+ } else {
490
+ announce(task);
491
+ queueMicrotask(() => {
492
+ run(child);
493
+ });
494
+ }
495
+ });
496
+ };
497
+ if (scope) deps.unitOfWork.join(scope, write);
498
+ else deps.unitOfWork.run(write);
499
+ return task;
500
+ }
501
+ function plan(task) {
502
+ const relation = catalog.relation(task.childSessionId);
503
+ return {
504
+ runId: task.taskId,
505
+ sessionId: task.childSessionId,
506
+ definition: relation.definition,
507
+ trigger: {
508
+ source: "plugin",
509
+ sourceId: "@eum-agent/agent-delegation",
510
+ message: task.message?.source !== void 0 ? task.message : {
511
+ ...task.message ?? {
512
+ id: randomUUID(),
513
+ role: "user",
514
+ content: [{
515
+ type: "text",
516
+ text: task.input
517
+ }]
518
+ },
519
+ source: {
520
+ kind: "delegation-task",
521
+ owner: task.sourceOwner,
522
+ taskId: task.taskId
523
+ }
524
+ }
525
+ },
526
+ completion: {
527
+ owner: "@eum-agent/agent-delegation",
528
+ targetSessionId: relation.parentSessionId,
529
+ targetGeneration: task.targetGeneration,
530
+ idempotencyKey: task.taskId,
531
+ textPrefix: `Subagent ${task.childSessionId}, task ${task.taskId}: `,
532
+ includeOutcome: true,
533
+ separator: "\n",
534
+ maxResultBytes: 65536,
535
+ truncationSuffix: "\n[Truncated; open child transcript.]"
536
+ }
537
+ };
538
+ }
539
+ function finish(task, outcome) {
540
+ const admitted = runs.get(task.taskId);
541
+ if (admitted && admitted.state !== "pending" && admitted.state !== "finished") {
542
+ runs.stop(task.taskId);
543
+ return;
544
+ }
545
+ if (admitted?.state === "finished") return;
546
+ runs.settle(plan(task), outcome);
547
+ }
548
+ function run(child) {
549
+ if (closed || deps.signal.aborted || stopping.has(child)) return Promise.resolve();
550
+ const task = tasks(child).find((row) => row.state !== "finished");
551
+ if (!task || task.state === "awaiting-human" || runs.get(task.taskId)?.state !== "pending" && runs.get(task.taskId)) return Promise.resolve();
552
+ const relation = catalog.relation(child);
553
+ if (task.state === "queued" && full(relation.rootSessionId)) {
554
+ blocked.add(child);
555
+ return Promise.resolve();
556
+ }
557
+ runs.start(plan(task));
558
+ return Promise.resolve();
559
+ }
560
+ const unsubscribe = runs.subscribe((runState) => {
561
+ if (deps.signal.aborted || closed) return;
562
+ const task = tasks(runState.sessionId).find((one) => one.taskId === runState.runId);
563
+ if (task) announce(task);
564
+ if (runState.state !== "finished") return;
565
+ for (const child of /* @__PURE__ */ new Set([runState.sessionId, ...blocked])) {
566
+ blocked.delete(child);
567
+ queueMicrotask(() => {
568
+ run(child);
569
+ });
570
+ }
571
+ });
572
+ deps.signal.addEventListener("abort", () => {
573
+ closed = true;
574
+ unsubscribe();
575
+ blocked.clear();
576
+ }, { once: true });
577
+ const manager = {
578
+ async drain() {
579
+ await Promise.resolve();
580
+ },
581
+ shutdown() {
582
+ closed = true;
583
+ unsubscribe();
584
+ },
585
+ async stop(caller, child, scope, taskId) {
586
+ authorized(caller, child);
587
+ if (scope === "task") {
588
+ const task = tasks(child).find((row) => row.taskId === taskId);
589
+ if (!task) throw new Error("not-found: task does not exist");
590
+ if (task.state === "finished") return;
591
+ if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
592
+ else if ((await sessions.cancelMany([child])).results.some((item) => !item.ok)) throw new Error("cleanup-failed: native task cleanup did not complete");
593
+ return;
594
+ }
595
+ const ids = /* @__PURE__ */ new Set([child]);
596
+ let added = true;
597
+ while (added) {
598
+ added = false;
599
+ for (const relation of catalog.relations()) if (ids.has(relation.parentSessionId) && !ids.has(relation.childSessionId)) {
600
+ ids.add(relation.childSessionId);
601
+ added = true;
602
+ }
603
+ }
604
+ for (const id of ids) stopping.add(id);
605
+ try {
606
+ for (const id of ids) for (const task of tasks(id)) if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
607
+ if ((await sessions.cancelMany([...ids])).results.some((item) => !item.ok)) throw new Error("cleanup-failed: native subtree cleanup did not complete");
608
+ } finally {
609
+ for (const id of ids) stopping.delete(id);
610
+ }
611
+ },
612
+ async stopMany(caller, inputs) {
613
+ if (inputs.length < 1 || inputs.length > 64 || Buffer.byteLength(JSON.stringify(inputs)) > 8388608) throw new Error("batch-limit: native stop requires 1..64 bounded members");
614
+ const outcomes = /* @__PURE__ */ new Map();
615
+ const held = /* @__PURE__ */ new Map();
616
+ for (const target of inputs) try {
617
+ authorized(caller, target.childSessionId);
618
+ for (const task of tasks()) {
619
+ let included = task.childSessionId === target.childSessionId;
620
+ if (!included && target.scope === "subtree") try {
621
+ authorized(target.childSessionId, task.childSessionId);
622
+ included = true;
623
+ } catch {}
624
+ if (included && (target.scope === "subtree" || task.taskId === target.taskId)) held.set(task.taskId, task);
625
+ }
626
+ } catch {}
627
+ for (const id of held.keys()) stoppingNotifications.set(id, (stoppingNotifications.get(id) ?? 0) + 1);
628
+ const results = [];
629
+ try {
630
+ for (const [index, target] of inputs.entries()) {
631
+ const key = `${target.childSessionId}:${target.scope}:${target.scope === "task" ? target.taskId ?? "" : ""}`;
632
+ let pending = outcomes.get(key);
633
+ if (!pending) {
634
+ pending = manager.stop(caller, target.childSessionId, target.scope, target.taskId).then(() => ({ stopped: true }));
635
+ outcomes.set(key, pending);
636
+ }
637
+ try {
638
+ results.push({
639
+ index,
640
+ target,
641
+ ok: true,
642
+ value: await pending
643
+ });
644
+ } catch (error) {
645
+ const message = error instanceof Error ? error.message : "Native task stop failed";
646
+ results.push({
647
+ index,
648
+ target,
649
+ ok: false,
650
+ error: {
651
+ code: message.split(":")[0].slice(0, 64),
652
+ message: message.slice(0, 512)
653
+ }
654
+ });
655
+ }
656
+ }
657
+ } finally {
658
+ const changed = [...held.values()].flatMap((old) => {
659
+ const current = tasks(old.childSessionId).find((task) => task.taskId === old.taskId);
660
+ return current && current.revision !== old.revision ? [current] : [];
661
+ });
662
+ for (const id of held.keys()) {
663
+ const remaining = (stoppingNotifications.get(id) ?? 1) - 1;
664
+ if (remaining === 0) stoppingNotifications.delete(id);
665
+ else stoppingNotifications.set(id, remaining);
666
+ }
667
+ publishTasks(changed);
668
+ }
669
+ return { results };
670
+ },
671
+ async recover() {
672
+ recovering = true;
673
+ try {
674
+ for (const task of tasks()) if (!runs.get(task.taskId) && task.state !== "finished") finish(task, { kind: "interrupted" });
675
+ } finally {
676
+ recovering = false;
677
+ }
678
+ },
679
+ async spawn(caller, input) {
680
+ deps.signal.throwIfAborted();
681
+ if (recovering) throw new Error("recovering");
682
+ if (closed || stopping.has(caller.sessionId)) throw new Error("stopping");
683
+ const fingerprint = memberDigest(input);
684
+ const parent = session(caller.sessionId);
685
+ const existing = tasks().find((row) => row.callerSessionId === caller.sessionId && row.requestKey === caller.requestKey);
686
+ if (existing) {
687
+ if (existing.input !== input.task || existing.sourceOwner !== caller.owner || existing.requestFingerprint !== fingerprint) throw new Error("request-key-conflict");
688
+ return existing;
689
+ }
690
+ const ancestry = catalog.relation(parent.sessionId);
691
+ const root = ancestry?.rootSessionId ?? parent.sessionId;
692
+ const depth = (ancestry?.depth ?? 0) + 1;
693
+ if (depth > deps.settings().maxDepth) throw new Error("depth-exceeded");
694
+ capacity(root);
695
+ const agentId = input.agent ?? DEFAULT_AGENT_ID;
696
+ const delegate = deps.agent(agentId);
697
+ if (!delegate) throw new Error(`agent-not-found: ${agentId}`);
698
+ const narrowed = narrowTools(ancestry?.definition.tools, delegate.tools);
699
+ const definition = {
700
+ agent: agentId,
701
+ ...narrowed === void 0 ? {} : { tools: narrowed }
702
+ };
703
+ const { chosen, candidate, baseParams } = childModel({
704
+ input,
705
+ agentId,
706
+ delegate,
707
+ parent,
708
+ ...deps.available ? { available: deps.available } : {},
709
+ ...deps.instantiate ? { instantiate: deps.instantiate } : {}
710
+ });
711
+ if (!chosen && deps.requireModel) throw new Error("no model is configured. Use model_list to find available providerId/model pairs.");
712
+ const prepared = chosen ? deps.prepareModel?.(agentId, chosen, candidate, Object.keys(input.params ?? {}), baseParams) : void 0;
713
+ const params = prepared?.effectiveParams ?? candidate;
714
+ return deps.unitOfWork.run((scope) => {
715
+ let result;
716
+ sessions.createSession({
717
+ agentId: parent.agentId,
718
+ workspaceId: parent.workspaceId,
719
+ title: input.task.slice(0, 60),
720
+ snapshot: {
721
+ model: chosen,
722
+ params
723
+ },
724
+ deferLoad: true,
725
+ inheritFrom: caller.execution,
726
+ ancestry: {
727
+ parentSessionId: parent.sessionId,
728
+ rootSessionId: root,
729
+ depth
730
+ },
731
+ scope,
732
+ initialize: {
733
+ connectionIdentity: catalog.connectionIdentity,
734
+ write(childSessionId, joined) {
735
+ catalog.addRelation({
736
+ childSessionId,
737
+ parentSessionId: parent.sessionId,
738
+ rootSessionId: root,
739
+ depth,
740
+ definition,
741
+ createdAt: Date.now()
742
+ });
743
+ result = {
744
+ ...acceptTask(caller, childSessionId, input.task, void 0, joined),
745
+ requestFingerprint: fingerprint,
746
+ ...prepared ? { modelValidation: {
747
+ validation: prepared.validation,
748
+ changes: [...prepared.changes],
749
+ unknownKeys: [...prepared.unknownKeys]
750
+ } } : {}
751
+ };
752
+ catalog.saveTask(result);
753
+ }
754
+ }
755
+ });
756
+ if (!result) throw new Error("Native child initialization did not produce an accepted task");
757
+ return result;
758
+ });
759
+ },
760
+ async spawnMany(caller, inputs) {
761
+ if (inputs.length < 1 || inputs.length > 64 || Buffer.byteLength(JSON.stringify(inputs)) > 8388608) throw new Error("batch-limit: native spawn requires 1..64 bounded members");
762
+ const digests = inputs.map(memberDigest);
763
+ if (new Set(digests).size !== digests.length) throw new Error("duplicate-member: identical native tasks must be given distinct input before admission");
764
+ const batch = {
765
+ tasks: [],
766
+ starts: []
767
+ };
768
+ const results = [];
769
+ try {
770
+ for (const [index, target] of inputs.entries()) {
771
+ deps.signal.throwIfAborted();
772
+ const member = {
773
+ ...caller,
774
+ requestKey: `${caller.requestKey}:${memberDigest(target)}`
775
+ };
776
+ admissionBatches.set(member, batch);
777
+ try {
778
+ results.push({
779
+ index,
780
+ target,
781
+ ok: true,
782
+ value: await manager.spawn(member, target)
783
+ });
784
+ } catch (error) {
785
+ deps.signal.throwIfAborted();
786
+ const message = error instanceof Error ? error.message : "Native delegation failed";
787
+ const code = message.split(":")[0].slice(0, 64);
788
+ results.push({
789
+ index,
790
+ target,
791
+ ok: false,
792
+ error: {
793
+ code,
794
+ message: message.slice(0, 512)
795
+ }
796
+ });
797
+ } finally {
798
+ admissionBatches.delete(member);
799
+ }
800
+ }
801
+ } finally {
802
+ publishTasks(batch.tasks);
803
+ for (const task of batch.tasks) batchedTaskIds.delete(task.taskId);
804
+ for (const start of batch.starts) queueMicrotask(start);
805
+ }
806
+ return { results };
807
+ },
808
+ send(caller, child, task) {
809
+ authorized(caller.sessionId, child);
810
+ return acceptTask(caller, child, task);
811
+ },
812
+ list(caller) {
813
+ return manager.read(caller, {}, 8388608);
814
+ },
815
+ read(caller, query, maxBytes) {
816
+ deps.signal.throwIfAborted();
817
+ session(caller);
818
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 8388608) throw new Error("batch-limit: invalid task byte budget");
819
+ const observed = catalog.measureTasks(caller, query, maxBytes);
820
+ if (observed.bytes > maxBytes) throw new Error("read-limit: stored task bodies exceed budget");
821
+ if ((query.childSessionId !== void 0 || query.taskId !== void 0) && observed.taskIds.length === 0) throw new Error("not-found: task is absent or inaccessible");
822
+ let upper = observed.bytes + 512 * observed.taskIds.length;
823
+ for (let offset = 0; offset < observed.taskIds.length; offset += 64) {
824
+ const measured = runs.measure(observed.taskIds.slice(offset, offset + 64));
825
+ upper += measured.reduce((sum, row) => sum + row.bytes, 0);
826
+ if (upper > maxBytes) throw new Error("read-limit: projected task bodies exceed budget");
827
+ }
828
+ const rows = observed.taskIds.map((id) => {
829
+ const task = catalog.readTask(id);
830
+ if (!task) throw new Error("not-found: task disappeared after observation");
831
+ return projected(task);
832
+ });
833
+ if (Buffer.byteLength(JSON.stringify(rows)) > maxBytes) throw new Error("read-limit: task response exceeds budget");
834
+ return rows;
835
+ },
836
+ summary(caller, query) {
837
+ deps.signal.throwIfAborted();
838
+ session(caller);
839
+ const summary = catalog.summary(caller, query);
840
+ if (!summary) throw new Error("not-found: task is absent or inaccessible");
841
+ const run = runs.status(summary.taskId);
842
+ return run ? {
843
+ ...summary,
844
+ state: run.state === "pending" ? summary.state : run.state,
845
+ outcome: run.outcome,
846
+ resultAvailable: run.resultAvailable,
847
+ updatedAt: run.updatedAt,
848
+ revision: summary.revision + run.revision
849
+ } : summary;
850
+ },
851
+ summaryPage(caller, query) {
852
+ deps.signal.throwIfAborted();
853
+ session(caller);
854
+ const page = catalog.summaryPage(caller, query);
855
+ return {
856
+ ...page,
857
+ items: page.items.map((item) => ({
858
+ ...item,
859
+ value: manager.summary(caller, {
860
+ childSessionId: item.value.childSessionId,
861
+ taskId: item.value.taskId
862
+ })
863
+ }))
864
+ };
865
+ },
866
+ result(caller, child, taskId, input) {
867
+ manager.summary(caller, {
868
+ childSessionId: child,
869
+ taskId
870
+ });
871
+ return runs.readResult(taskId, input);
872
+ },
873
+ accept(child, trigger) {
874
+ const relation = catalog.relation(child);
875
+ if (!relation) return false;
876
+ acceptTask({
877
+ sessionId: relation.parentSessionId,
878
+ owner: trigger.sourceId ?? "user",
879
+ requestKey: randomUUID()
880
+ }, child, trigger.message.content.filter((part) => part.type === "text").map((part) => part.text).join(""), trigger.message);
881
+ return true;
882
+ }
883
+ };
884
+ return manager;
885
+ }
886
+ /** The narrowing chain a child's snapshot stores: every earlier delegate's
887
+ * whitelist, then the new delegate's. `undefined` narrows nothing and `[]`
888
+ * leaves no tools. The address agent's own whitelist is applied live by the
889
+ * session tool source, so it is never copied in here. */
890
+ function narrowTools(chain, delegate) {
891
+ if (delegate === null) return chain === void 0 ? void 0 : [...chain];
892
+ if (chain === void 0) return [...delegate];
893
+ return chain.filter((name) => delegate.includes(name));
894
+ }
895
+ /**
896
+ * Selects a model and its parameters together, then overlays explicit parameters.
897
+ * Explicit pairs and available Agent defaults use their templates; a usable parent
898
+ * pair inherits the parent's parameters, otherwise the system template is selected.
899
+ * Returned parameters are independent deep copies. An unavailable explicit pair is refused.
900
+ */
901
+ function childModel(options) {
902
+ const { input, delegate, parent } = options;
903
+ const invalid = "invalid-model: use model_list to find available providerId/model pairs";
904
+ if (input.providerId === void 0 !== (input.model === void 0)) throw new Error(invalid);
905
+ const usable = (pair) => options.available?.(pair) ?? true;
906
+ const explicit = input.providerId !== void 0 && input.model !== void 0 ? {
907
+ providerId: input.providerId,
908
+ model: input.model
909
+ } : void 0;
910
+ if (explicit && !usable(explicit)) throw new Error(invalid);
911
+ let chosen;
912
+ let base;
913
+ if (explicit || delegate.defaultModel && usable(delegate.defaultModel)) {
914
+ chosen = explicit ?? delegate.defaultModel;
915
+ base = options.instantiate?.(options.agentId, chosen)?.params ?? {};
916
+ } else if (parent.model && usable(parent.model)) {
917
+ chosen = parent.model;
918
+ base = parent.params;
919
+ } else {
920
+ const system = options.instantiate?.(null);
921
+ chosen = system?.model && usable(system.model) ? system.model : null;
922
+ base = chosen ? system.params : {};
923
+ }
924
+ const baseParams = structuredClone(base);
925
+ return {
926
+ chosen: chosen ? { ...chosen } : null,
927
+ baseParams,
928
+ candidate: {
929
+ ...structuredClone(baseParams),
930
+ ...structuredClone(input.params ?? {})
931
+ }
932
+ };
933
+ }
934
+ //#endregion
935
+ //#region src/runtime/reads.ts
936
+ /** Returns independent parent outcomes without exposing unrelated task bodies. */
937
+ function readParents(manager, input, signal) {
938
+ signal.throwIfAborted();
939
+ for (const [index, target] of input.parentSessionIds.entries()) if (Buffer.byteLength(JSON.stringify({
940
+ index,
941
+ target,
942
+ ok: false,
943
+ error: {
944
+ code: "read-limit",
945
+ message: "Native tasks exceed their member byte budget"
946
+ }
947
+ })) > input.maxItemBytes) throw new Error("batch-limit: parent metadata exceeds member byte budget");
948
+ return { results: input.parentSessionIds.map((target, index) => {
949
+ const error = (code, message) => ({
950
+ index,
951
+ target,
952
+ ok: false,
953
+ error: {
954
+ code,
955
+ message
956
+ }
957
+ });
958
+ try {
959
+ const overhead = Buffer.byteLength(JSON.stringify({
960
+ index,
961
+ target,
962
+ ok: true,
963
+ value: []
964
+ }));
965
+ const result = {
966
+ index,
967
+ target,
968
+ ok: true,
969
+ value: [...manager.read(target, {}, input.maxItemBytes - overhead)]
970
+ };
971
+ return Buffer.byteLength(JSON.stringify(result)) <= input.maxItemBytes ? result : error("read-limit", "Native tasks exceed their member byte budget");
972
+ } catch (cause) {
973
+ signal.throwIfAborted();
974
+ return cause instanceof Error && cause.message.startsWith("read-limit:") ? error("read-limit", "Native tasks exceed their member byte budget") : error("not-found", "Parent session is absent or inaccessible");
975
+ }
976
+ }) };
977
+ }
978
+ //#endregion
979
+ //#region src/runtime/settings.ts
980
+ /** Reads limits at admission and replaces the full settings row atomically. */
981
+ function subagentSettings(storage) {
982
+ const table = storage.tableName("settings");
983
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton = 0), value TEXT NOT NULL) STRICT`);
984
+ const readRow = storage.db.prepare(`SELECT value FROM ${table} WHERE singleton = 0`);
985
+ const writeRow = storage.db.prepare(`INSERT INTO ${table} (singleton,value) VALUES (0,?) ON CONFLICT(singleton) DO UPDATE SET value=excluded.value`);
986
+ return {
987
+ read: () => SubagentSettingsSchema.parse(JSON.parse(String(readRow.get()?.value ?? "{}"))),
988
+ write(value) {
989
+ const next = SubagentSettingsSchema.parse(value);
990
+ writeRow.run(JSON.stringify(next));
991
+ return next;
992
+ }
993
+ };
994
+ }
995
+ //#endregion
996
+ //#region src/runtime/factory.ts
997
+ /** Creates one activation's policy, owned data and settings. */
998
+ function createSubagentCapability(ctx) {
999
+ const execution = ctx.services.get("agent-execution");
1000
+ const sessions = ctx.services.get("agent-sessions");
1001
+ const runs = ctx.services.get("agent-runs");
1002
+ const framework = ctx.services.get("agent-data-schemas");
1003
+ const storage = ctx.storage.open();
1004
+ const catalog = createSubagentCatalogOn(storage, framework);
1005
+ const settings = subagentSettings(storage);
1006
+ const changed = ctx.client.registerFrame({
1007
+ name: "changed",
1008
+ delivery: "session",
1009
+ payload: changedSchema(framework)
1010
+ });
1011
+ const modelPolicy = ctx.services.get("model-dispatch-policy");
1012
+ const models = () => modelPolicy;
1013
+ const manager = createSubagentManager({
1014
+ unitOfWork: ctx.services.get("unit-of-work"),
1015
+ sessions,
1016
+ runs,
1017
+ catalog,
1018
+ signal: ctx.signal,
1019
+ settings: settings.read,
1020
+ agent(id) {
1021
+ const agent = execution.agent(id);
1022
+ if (!agent) return void 0;
1023
+ return {
1024
+ tools: agent.tools,
1025
+ defaultModel: models().agentDefault(id)
1026
+ };
1027
+ },
1028
+ available: (ref) => models()?.available(ref) ?? false,
1029
+ instantiate: (id, ref) => models().instantiate(id, ref),
1030
+ prepareModel: (_agent, ref, params, explicit, defaults) => models()?.prepareParams({
1031
+ providerId: ref.providerId,
1032
+ model: ref.model,
1033
+ params,
1034
+ explicitKeys: explicit,
1035
+ defaults
1036
+ }) ?? {
1037
+ effectiveParams: params,
1038
+ changes: [],
1039
+ unknownKeys: [...explicit],
1040
+ validation: "unknown"
1041
+ },
1042
+ changed(tasks, targets) {
1043
+ for (const target of targets) {
1044
+ const entries = tasks.flatMap((task) => {
1045
+ const relation = catalog.relation(task.childSessionId);
1046
+ if (!relation || target !== relation.rootSessionId && target !== relation.parentSessionId) return [];
1047
+ return [{
1048
+ rootSessionId: relation.rootSessionId,
1049
+ parentSessionId: relation.parentSessionId,
1050
+ childSessionId: task.childSessionId,
1051
+ taskId: task.taskId,
1052
+ revision: task.revision,
1053
+ task
1054
+ }];
1055
+ });
1056
+ if (entries.length) {
1057
+ let bytes = 8192;
1058
+ const bounded = [];
1059
+ for (const entry of entries) {
1060
+ const length = Buffer.byteLength(JSON.stringify(entry)) + 1;
1061
+ if (bounded.length === 64 || bytes + length > 8388608) break;
1062
+ bounded.push(entry);
1063
+ bytes += length;
1064
+ }
1065
+ changed.emit(target, {
1066
+ entries: bounded,
1067
+ ...bounded.length < entries.length ? { invalidated: true } : {}
1068
+ });
1069
+ }
1070
+ }
1071
+ }
1072
+ });
1073
+ ctx.services.provide("session-delegation-observer", {
1074
+ listByParents(input) {
1075
+ const parsed = ListByParentsParams.parse(input);
1076
+ return { results: readParents(manager, parsed, ctx.signal).results.map((item) => {
1077
+ if (!item.ok) return item;
1078
+ const value = item.value.map((task) => {
1079
+ const ancestry = catalog.ancestry(task.childSessionId);
1080
+ if (!ancestry) throw new Error("Native task relation is absent");
1081
+ return {
1082
+ ...task,
1083
+ ...ancestry
1084
+ };
1085
+ });
1086
+ const projected = {
1087
+ ...item,
1088
+ value
1089
+ };
1090
+ return Buffer.byteLength(JSON.stringify(projected)) <= parsed.maxItemBytes ? projected : {
1091
+ index: item.index,
1092
+ target: item.target,
1093
+ ok: false,
1094
+ error: {
1095
+ code: "read-limit",
1096
+ message: "Native observer projection exceeds its member budget"
1097
+ }
1098
+ };
1099
+ }) };
1100
+ },
1101
+ project(frame) {
1102
+ ctx.signal.throwIfAborted();
1103
+ if (frame.kind !== changed.kind || !("payload" in frame)) return void 0;
1104
+ const payload = changedSchema(framework).parse(frame.payload);
1105
+ return {
1106
+ entries: payload.entries.map((entry) => ({
1107
+ ...entry,
1108
+ task: {
1109
+ ...entry.task,
1110
+ parentSessionId: entry.parentSessionId,
1111
+ rootSessionId: entry.rootSessionId
1112
+ }
1113
+ })),
1114
+ invalidated: payload.invalidated === true
1115
+ };
1116
+ }
1117
+ });
1118
+ return {
1119
+ execution,
1120
+ framework,
1121
+ catalog,
1122
+ settings,
1123
+ manager
1124
+ };
1125
+ }
1126
+ //#endregion
1127
+ //#region src/runtime/methods.ts
1128
+ /** Registers native management and the session-scoped task state frame. */
1129
+ function registerSubagentMethods(ctx, manager, framework, settings) {
1130
+ const Task = taskSchema(framework);
1131
+ ctx.client.registerMethod({
1132
+ name: "getSettings",
1133
+ params: z.strictObject({}),
1134
+ result: SubagentSettingsSchema,
1135
+ handle: () => settings.read()
1136
+ });
1137
+ ctx.client.registerMethod({
1138
+ name: "setSettings",
1139
+ params: SubagentSettingsSchema,
1140
+ result: SubagentSettingsSchema,
1141
+ handle: (input) => settings.write(input)
1142
+ });
1143
+ ctx.client.registerMethod({
1144
+ name: "spawn",
1145
+ params: SpawnSubagentSchema.extend({
1146
+ parentSessionId: z.string(),
1147
+ requestKey: z.string().min(1)
1148
+ }),
1149
+ result: Task,
1150
+ handle: ({ parentSessionId, requestKey, ...input }) => manager.spawn({
1151
+ sessionId: parentSessionId,
1152
+ requestKey,
1153
+ owner: "user"
1154
+ }, input)
1155
+ });
1156
+ ctx.client.registerMethod({
1157
+ name: "send",
1158
+ params: z.strictObject({
1159
+ parentSessionId: z.string(),
1160
+ childSessionId: z.string(),
1161
+ task: z.string().min(1),
1162
+ requestKey: z.string().min(1)
1163
+ }),
1164
+ result: Task,
1165
+ handle: ({ parentSessionId, childSessionId, task, requestKey }) => manager.send({
1166
+ sessionId: parentSessionId,
1167
+ requestKey,
1168
+ owner: "user"
1169
+ }, childSessionId, task)
1170
+ });
1171
+ ctx.client.registerMethod({
1172
+ name: "listByParents",
1173
+ params: ListByParentsParams,
1174
+ result: listByParentsResult(framework),
1175
+ handle: (input) => readParents(manager, input, ctx.signal)
1176
+ });
1177
+ ctx.client.registerMethod({
1178
+ name: "get",
1179
+ params: z.strictObject({
1180
+ parentSessionId: z.string(),
1181
+ childSessionId: z.string(),
1182
+ taskId: z.string().optional()
1183
+ }),
1184
+ result: Task,
1185
+ handle({ parentSessionId, childSessionId, taskId }) {
1186
+ const task = manager.read(parentSessionId, {
1187
+ childSessionId,
1188
+ taskId
1189
+ }, 8388608)[0];
1190
+ if (!task) throw new Error("not-found: task is absent or inaccessible");
1191
+ return task;
1192
+ }
1193
+ });
1194
+ ctx.client.registerMethod({
1195
+ name: "stop",
1196
+ params: z.strictObject({
1197
+ parentSessionId: z.string(),
1198
+ childSessionId: z.string(),
1199
+ scope: z.enum(["task", "subtree"]),
1200
+ taskId: z.string().optional()
1201
+ }),
1202
+ result: z.strictObject({}),
1203
+ async handle({ parentSessionId, childSessionId, scope, taskId }) {
1204
+ await manager.stop(parentSessionId, childSessionId, scope, taskId);
1205
+ return {};
1206
+ }
1207
+ });
1208
+ }
1209
+ //#endregion
1210
+ //#region src/runtime/service.ts
1211
+ /** Binds trusted tool identities and preserves bounded wait semantics. */
1212
+ function subagentService(ctx, manager) {
1213
+ const caller = (call) => {
1214
+ ctx.signal.throwIfAborted();
1215
+ call.signal.throwIfAborted();
1216
+ return {
1217
+ sessionId: call.sessionId,
1218
+ execution: call,
1219
+ owner: ctx.pluginName,
1220
+ requestKey: `${call.turn}:${call.toolCallId}`
1221
+ };
1222
+ };
1223
+ return {
1224
+ spawn: (call, input) => manager.spawn(caller(call), input),
1225
+ spawnMany: (call, inputs) => manager.spawnMany(caller(call), inputs),
1226
+ send: (call, child, task) => manager.send(caller(call), child, task),
1227
+ list: (call) => {
1228
+ caller(call);
1229
+ return manager.list(call.sessionId);
1230
+ },
1231
+ get(call, child, taskId, maxBytes = 262144) {
1232
+ caller(call);
1233
+ const task = manager.read(call.sessionId, {
1234
+ childSessionId: child,
1235
+ taskId
1236
+ }, maxBytes)[0];
1237
+ if (!task) throw new Error("not-found: task is absent or inaccessible");
1238
+ return task;
1239
+ },
1240
+ async wait(call, taskId, timeoutMs, maxBytes = 262144) {
1241
+ caller(call);
1242
+ const until = performance.now() + Math.min(6e4, Math.max(0, timeoutMs));
1243
+ for (;;) {
1244
+ ctx.signal.throwIfAborted();
1245
+ const task = manager.read(call.sessionId, { taskId }, maxBytes)[0];
1246
+ if (!task) throw new Error("not-found: task is absent or inaccessible");
1247
+ if (task.state === "finished" || performance.now() >= until || call.signal.aborted) return task;
1248
+ await new Promise((resolve) => setTimeout(resolve, Math.min(50, until - performance.now())));
1249
+ }
1250
+ },
1251
+ status(call, child, taskId) {
1252
+ caller(call);
1253
+ return manager.summary(call.sessionId, {
1254
+ childSessionId: child,
1255
+ taskId
1256
+ });
1257
+ },
1258
+ page(call, input) {
1259
+ caller(call);
1260
+ return manager.summaryPage(call.sessionId, input);
1261
+ },
1262
+ result(call, child, taskId, input) {
1263
+ caller(call);
1264
+ return manager.result(call.sessionId, child, taskId, input);
1265
+ },
1266
+ async waitStatus(call, child, taskId, timeoutMs) {
1267
+ caller(call);
1268
+ const until = performance.now() + Math.min(6e4, Math.max(0, timeoutMs));
1269
+ for (;;) {
1270
+ ctx.signal.throwIfAborted();
1271
+ call.signal.throwIfAborted();
1272
+ const status = manager.summary(call.sessionId, {
1273
+ childSessionId: child,
1274
+ taskId
1275
+ });
1276
+ if (status.state === "finished" || performance.now() >= until) return status;
1277
+ await new Promise((resolve) => {
1278
+ const complete = () => {
1279
+ clearTimeout(timer);
1280
+ call.signal.removeEventListener("abort", complete);
1281
+ resolve();
1282
+ };
1283
+ const timer = setTimeout(complete, Math.min(50, Math.max(0, until - performance.now())));
1284
+ call.signal.addEventListener("abort", complete, { once: true });
1285
+ });
1286
+ }
1287
+ },
1288
+ stopMany: (call, inputs) => {
1289
+ caller(call);
1290
+ return manager.stopMany(call.sessionId, inputs);
1291
+ },
1292
+ stop: (call, child, scope, taskId) => {
1293
+ caller(call);
1294
+ return manager.stop(call.sessionId, child, scope, taskId);
1295
+ }
1296
+ };
1297
+ }
1298
+ //#endregion
1299
+ //#region src/subagents/pages.ts
1300
+ /** Native task discovery and original results use owner-scoped exact pages. */
1301
+ const tokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less.");
1302
+ const limit = z.number().int().min(1).max(100).default(50).describe("Maximum whole members per page; default 50, hard maximum 100.");
1303
+ const target = z.strictObject({
1304
+ childSessionId: z.string().min(1).max(512).describe("Descendant child session ID."),
1305
+ taskId: z.string().min(1).max(512).optional().describe("Named child task; omit for its current or most recent task.")
1306
+ });
1307
+ const getInitial = z.strictObject({
1308
+ items: z.array(target).min(1).max(64).describe("One to 64 ordered task targets; a positive wait or result view requires taskId for every member."),
1309
+ view: z.enum(["status", "result"]).default("status").describe("status returns metadata without input/output bodies; result reads original final text."),
1310
+ waitMs: z.number().int().min(0).max(6e4).optional().describe("One shared deadline in milliseconds; positive waits require taskId for every member and leave children running."),
1311
+ limit,
1312
+ outputTokens: tokens
1313
+ }).superRefine((value, issues) => {
1314
+ if (((value.waitMs ?? 0) > 0 || value.view === "result") && value.items.some((item) => !item.taskId)) issues.addIssue({
1315
+ code: "custom",
1316
+ path: ["items"],
1317
+ message: "taskId is required for every result or positive wait target"
1318
+ });
1319
+ });
1320
+ const listInitial = z.strictObject({
1321
+ limit,
1322
+ outputTokens: tokens
1323
+ });
1324
+ const continuation = z.strictObject({
1325
+ cursor: z.string().min(1).max(512).describe("Opaque cursor copied unchanged from next.arguments."),
1326
+ outputTokens: tokens
1327
+ });
1328
+ const readValue = z.strictObject({
1329
+ taskId: z.string(),
1330
+ childSessionId: z.string(),
1331
+ text: z.string(),
1332
+ offset: z.number(),
1333
+ end: z.number(),
1334
+ total: z.number(),
1335
+ unit: z.literal("code-points"),
1336
+ source: z.unknown(),
1337
+ revision: z.number()
1338
+ });
1339
+ const member = z.strictObject({
1340
+ index: z.number().int().nonnegative(),
1341
+ target,
1342
+ value: z.union([NativeTaskSummarySchema, readValue]).optional(),
1343
+ error: z.object({
1344
+ code: z.string(),
1345
+ message: z.string()
1346
+ }).optional()
1347
+ });
1348
+ const errorBody = z.strictObject({
1349
+ ok: z.literal(false),
1350
+ error: z.object({
1351
+ code: z.string(),
1352
+ message: z.string(),
1353
+ retryable: z.boolean()
1354
+ }),
1355
+ next: z.unknown()
1356
+ });
1357
+ const output = z.union([z.strictObject({
1358
+ ok: z.literal(true),
1359
+ complete: z.boolean(),
1360
+ items: z.array(member),
1361
+ next: z.unknown(),
1362
+ effective: z.object({
1363
+ limit: z.number(),
1364
+ outputTokens: z.number()
1365
+ })
1366
+ }), errorBody]);
1367
+ /** Registers finite query state; authority is rechecked on each returned page. */
1368
+ function nativeReadTools(service, signal, resources) {
1369
+ const cursors = /* @__PURE__ */ new Map();
1370
+ let queue = Promise.resolve();
1371
+ const cleanupQuery = (query) => {
1372
+ if (query.closed) return;
1373
+ query.closed = true;
1374
+ query.resultSources.clear();
1375
+ query.summaries = void 0;
1376
+ for (const [id, cursor] of cursors) if (cursor.query === query) {
1377
+ cursor.result = void 0;
1378
+ cursors.delete(id);
1379
+ }
1380
+ };
1381
+ const closeQuery = (query) => query.lease.close("completed");
1382
+ const error = (code, message, next = null) => ({
1383
+ content: JSON.stringify({
1384
+ ok: false,
1385
+ error: {
1386
+ code,
1387
+ message: [...message].slice(0, 256).join(""),
1388
+ retryable: next !== null
1389
+ },
1390
+ next
1391
+ }),
1392
+ isError: true
1393
+ });
1394
+ const tool = (kind) => ({
1395
+ name: kind,
1396
+ preload: false,
1397
+ description: kind === "subagent_get" ? "Read descendant status summaries by default, without accepted input or result bodies. view=result pages original final text; every result or positive wait requires taskId. Waits share one deadline of at most 60000 milliseconds and do not stop the child. Follow next.arguments unchanged; hard member limit 100." : "List descendant task summaries in admission-key order without reading full task inputs or results. Default 50, hard maximum 100 members per page. Follow next.arguments unchanged; changed query membership requires a restart.",
1398
+ inputSchema: z.union([kind === "subagent_get" ? getInitial : listInitial, continuation]),
1399
+ outputSchema: output,
1400
+ deliveryKind: "exact-page",
1401
+ async execute(raw, ctx) {
1402
+ ctx.signal.throwIfAborted();
1403
+ signal.throwIfAborted();
1404
+ const input = z.union([kind === "subagent_get" ? getInitial : listInitial, continuation]).parse(raw), now = performance.now();
1405
+ let selected, id;
1406
+ if ("cursor" in input) {
1407
+ id = input.cursor;
1408
+ const found = cursors.get(id);
1409
+ if (!found || found.query.kind !== kind || found.query.session !== ctx.sessionId || found.query.address !== JSON.stringify(ctx.address) || found.query.generation !== ctx.historyGeneration) return error("cursor_invalid", "Cursor is unavailable for this session and history.");
1410
+ selected = found;
1411
+ if (now - found.query.touched > 6e5 || now - found.query.created > 36e5) {
1412
+ closeQuery(found.query);
1413
+ return error("cursor_expired", "Restart this expired native task query.", {
1414
+ tool: kind,
1415
+ arguments: found.query.input
1416
+ });
1417
+ }
1418
+ } else {
1419
+ for (const query of new Set([...cursors.values()].map((cursor) => cursor.query))) if (now - query.touched > 6e5 || now - query.created > 36e5 || query.session === ctx.sessionId && query.generation !== ctx.historyGeneration) closeQuery(query);
1420
+ id = randomUUID();
1421
+ const query = {
1422
+ kind,
1423
+ session: ctx.sessionId,
1424
+ address: JSON.stringify(ctx.address),
1425
+ generation: ctx.historyGeneration,
1426
+ created: now,
1427
+ touched: now,
1428
+ input,
1429
+ resultSources: /* @__PURE__ */ new Map(),
1430
+ lease: await resources.reserve(ctx, {
1431
+ bytes: Buffer.byteLength(JSON.stringify(input)) + 512,
1432
+ scratchBytes: 0,
1433
+ cleanup: async () => {
1434
+ cleanupQuery(query);
1435
+ return { status: "complete" };
1436
+ }
1437
+ }),
1438
+ bytes: Buffer.byteLength(JSON.stringify(input)) + 512
1439
+ };
1440
+ selected = {
1441
+ query,
1442
+ member: 0,
1443
+ offset: 0,
1444
+ after: 0
1445
+ };
1446
+ cursors.set(id, selected);
1447
+ if ("items" in input && (input.view === "status" || (input.waitMs ?? 0) > 0)) await query.lease.withUse(ctx, async () => {
1448
+ const deadline = performance.now() + (input.waitMs ?? 0);
1449
+ query.summaries = [];
1450
+ for (const item of input.items) try {
1451
+ let status = service.status(ctx, item.childSessionId, item.taskId);
1452
+ if ((input.waitMs ?? 0) > 0 && item.taskId && status.state !== "finished") status = await service.waitStatus(ctx, item.childSessionId, item.taskId, Math.max(0, Math.floor(deadline - performance.now())));
1453
+ query.summaries.push(status);
1454
+ } catch (cause) {
1455
+ ctx.signal.throwIfAborted();
1456
+ query.summaries.push({ error: {
1457
+ code: "not-descendant",
1458
+ message: cause instanceof Error ? cause.message.slice(0, 256) : "Task is absent or inaccessible"
1459
+ } });
1460
+ }
1461
+ const growth = Buffer.byteLength(JSON.stringify(query.summaries));
1462
+ try {
1463
+ await query.lease.grow(ctx, {
1464
+ bytes: growth,
1465
+ scratchBytes: 0
1466
+ });
1467
+ query.bytes += growth;
1468
+ } catch (failure) {
1469
+ if (resources.isAdmissionFailure(failure)) throw failure;
1470
+ closeQuery(query);
1471
+ return error("query_capacity_exceeded", "Native metadata exceeds temporary capacity.");
1472
+ }
1473
+ });
1474
+ }
1475
+ const query = selected.query;
1476
+ try {
1477
+ return await query.lease.withUse(ctx, async () => {
1478
+ query.touched = now;
1479
+ const inputQuery = query.input;
1480
+ const restart = (message) => {
1481
+ closeQuery(query);
1482
+ return error("source_changed", message, {
1483
+ tool: kind,
1484
+ arguments: inputQuery
1485
+ });
1486
+ };
1487
+ if (selected.result) {
1488
+ try {
1489
+ if ("items" in inputQuery && inputQuery.view === "result") {
1490
+ const cached = output.parse(JSON.parse(selected.result.content));
1491
+ if (cached.ok) for (const member of cached.items) {
1492
+ if (!member.value || !("text" in member.value)) continue;
1493
+ const original = service.result(ctx, member.target.childSessionId, member.target.taskId, {
1494
+ offset: member.value.offset,
1495
+ limit: 1
1496
+ });
1497
+ if (!original.ok || JSON.stringify({
1498
+ source: original.source,
1499
+ revision: original.revision
1500
+ }) !== query.resultSources.get(member.index)) return restart("Native original result changed; restart the query.");
1501
+ }
1502
+ }
1503
+ } catch (cause) {
1504
+ return restart(cause instanceof Error ? cause.message : "Native original source unavailable");
1505
+ }
1506
+ try {
1507
+ if ("items" in inputQuery) for (const item of inputQuery.items) service.status(ctx, item.childSessionId, item.taskId);
1508
+ else service.page(ctx, {
1509
+ after: selected.after,
1510
+ upper: query.upper,
1511
+ source: query.source,
1512
+ limit: 1
1513
+ });
1514
+ } catch (cause) {
1515
+ return restart(cause instanceof Error ? cause.message : "Native source unavailable");
1516
+ }
1517
+ const needed = ctx.output.measure(selected.result);
1518
+ if (needed > ctx.output.outputTokens) return error("page_too_small", "The fixed native page requires more allowance.", needed <= ctx.output.maximumTokens ? {
1519
+ tool: kind,
1520
+ arguments: {
1521
+ cursor: id,
1522
+ outputTokens: needed
1523
+ }
1524
+ } : null);
1525
+ ctx.output.acceptExact(selected.result);
1526
+ return selected.result;
1527
+ }
1528
+ const nextId = randomUUID(), items = [];
1529
+ let at = selected.member, offset = selected.offset, after = selected.after, complete = false;
1530
+ const page = () => ({ content: JSON.stringify({
1531
+ ok: true,
1532
+ complete,
1533
+ items,
1534
+ next: complete ? null : {
1535
+ tool: kind,
1536
+ arguments: { cursor: nextId }
1537
+ },
1538
+ effective: {
1539
+ limit: inputQuery.limit,
1540
+ outputTokens: ctx.output.outputTokens
1541
+ }
1542
+ }) });
1543
+ if ("items" in inputQuery) {
1544
+ while (at < inputQuery.items.length && items.length < inputQuery.limit) {
1545
+ const item = inputQuery.items[at];
1546
+ let row;
1547
+ try {
1548
+ if ("cursor" in input || inputQuery.view === "result") service.status(ctx, item.childSessionId, item.taskId);
1549
+ if (inputQuery.view === "status") {
1550
+ const status = query.summaries[at];
1551
+ row = "error" in status ? {
1552
+ index: at,
1553
+ target: item,
1554
+ error: status.error
1555
+ } : {
1556
+ index: at,
1557
+ target: item,
1558
+ value: status
1559
+ };
1560
+ } else {
1561
+ const result = service.result(ctx, item.childSessionId, item.taskId, {
1562
+ offset,
1563
+ limit: 4096
1564
+ });
1565
+ const prior = query.resultSources.get(at);
1566
+ if (!result.ok && prior !== void 0) return restart("Native original result is unavailable; restart the query.");
1567
+ if (result.ok) {
1568
+ const identity = JSON.stringify({
1569
+ source: result.source,
1570
+ revision: result.revision
1571
+ });
1572
+ if (prior !== void 0 && prior !== identity) return restart("Native original result changed; restart the query.");
1573
+ query.resultSources.set(at, identity);
1574
+ }
1575
+ if (!result.ok) row = {
1576
+ index: at,
1577
+ target: item,
1578
+ error: {
1579
+ code: result.code,
1580
+ message: result.message
1581
+ }
1582
+ };
1583
+ else {
1584
+ let points = [...result.text];
1585
+ const value = () => ({
1586
+ taskId: item.taskId,
1587
+ childSessionId: item.childSessionId,
1588
+ text: points.join(""),
1589
+ offset: result.offset,
1590
+ end: result.offset + points.length,
1591
+ total: result.total,
1592
+ unit: "code-points",
1593
+ source: result.source,
1594
+ revision: result.revision
1595
+ });
1596
+ row = {
1597
+ index: at,
1598
+ target: item,
1599
+ value: value()
1600
+ };
1601
+ items.push(row);
1602
+ while (points.length && ctx.output.measure(page()) > ctx.output.outputTokens) {
1603
+ points = points.slice(0, Math.floor(points.length / 2));
1604
+ row.value = value();
1605
+ }
1606
+ items.pop();
1607
+ if (result.text.length && !points.length) break;
1608
+ }
1609
+ }
1610
+ } catch (cause) {
1611
+ ctx.signal.throwIfAborted();
1612
+ row = {
1613
+ index: at,
1614
+ target: item,
1615
+ error: {
1616
+ code: "not-descendant",
1617
+ message: cause instanceof Error ? cause.message.slice(0, 256) : "Task is absent or inaccessible"
1618
+ }
1619
+ };
1620
+ }
1621
+ items.push(row);
1622
+ if (ctx.output.measure(page()) > ctx.output.outputTokens) {
1623
+ items.pop();
1624
+ break;
1625
+ }
1626
+ if (row.value && "text" in row.value && row.value.end < row.value.total) {
1627
+ offset = row.value.end;
1628
+ break;
1629
+ }
1630
+ at++;
1631
+ offset = 0;
1632
+ }
1633
+ complete = at === inputQuery.items.length;
1634
+ } else {
1635
+ let fetched;
1636
+ try {
1637
+ fetched = service.page(ctx, {
1638
+ after,
1639
+ upper: query.upper,
1640
+ source: query.source,
1641
+ limit: inputQuery.limit
1642
+ });
1643
+ } catch (cause) {
1644
+ return restart(cause instanceof Error ? cause.message : "Native source unavailable");
1645
+ }
1646
+ query.source = fetched.source;
1647
+ query.upper = fetched.upper;
1648
+ for (const item of fetched.items) {
1649
+ const row = {
1650
+ index: at++,
1651
+ target: {
1652
+ childSessionId: item.value.childSessionId,
1653
+ taskId: item.value.taskId
1654
+ },
1655
+ value: item.value
1656
+ };
1657
+ items.push(row);
1658
+ if (ctx.output.measure(page()) > ctx.output.outputTokens) {
1659
+ items.pop();
1660
+ at--;
1661
+ break;
1662
+ }
1663
+ after = item.key;
1664
+ }
1665
+ complete = fetched.complete && items.length === fetched.items.length;
1666
+ }
1667
+ if (!items.length && !complete || ctx.output.measure(page()) > ctx.output.outputTokens) return error("page_too_small", "No complete native member fits this allowance.", ctx.output.outputTokens < ctx.output.maximumTokens ? {
1668
+ tool: kind,
1669
+ arguments: {
1670
+ cursor: id,
1671
+ outputTokens: ctx.output.maximumTokens
1672
+ }
1673
+ } : null);
1674
+ const result = page();
1675
+ const growth = Buffer.byteLength(result.content) + 512;
1676
+ try {
1677
+ await query.lease.grow(ctx, {
1678
+ bytes: growth,
1679
+ scratchBytes: 0
1680
+ });
1681
+ query.bytes += growth;
1682
+ } catch (failure) {
1683
+ if (resources.isAdmissionFailure(failure)) throw failure;
1684
+ closeQuery(query);
1685
+ return error("query_capacity_exceeded", "Native cursor cache exceeds temporary capacity.");
1686
+ }
1687
+ ctx.output.acceptExact(result);
1688
+ query.lease.retain({
1689
+ reason: "public-cursor",
1690
+ idleMs: 6e5,
1691
+ maxAgeMs: 36e5
1692
+ });
1693
+ selected.result = result;
1694
+ if (!complete) cursors.set(nextId, {
1695
+ query,
1696
+ member: at,
1697
+ offset,
1698
+ after
1699
+ });
1700
+ return result;
1701
+ });
1702
+ } catch (cause) {
1703
+ await query.lease.close("failed");
1704
+ throw cause;
1705
+ }
1706
+ }
1707
+ });
1708
+ const wrap = (definition) => ({
1709
+ ...definition,
1710
+ execute(input, ctx) {
1711
+ const pending = queue.then(() => definition.execute(input, ctx));
1712
+ queue = pending.catch(() => {});
1713
+ return pending;
1714
+ }
1715
+ });
1716
+ return {
1717
+ get: wrap(tool("subagent_get")),
1718
+ list: wrap(tool("subagent_list")),
1719
+ async close() {
1720
+ await queue;
1721
+ for (const query of new Set([...cursors.values()].map((cursor) => cursor.query))) await closeQuery(query);
1722
+ cursors.clear();
1723
+ }
1724
+ };
1725
+ }
1726
+ //#endregion
1727
+ //#region src/subagents/index.ts
1728
+ /** Registers five independent controls over the host's native task service. */
1729
+ function registerSubagentTools(ctx, register, service = ctx.services.get("subagents")) {
1730
+ register({
1731
+ name: "subagent_spawn",
1732
+ preload: false,
1733
+ description: "Delegate a task to another agent, which works in its own session with your permissions. `agent` names one of the listed agents (the general-purpose one when omitted); Use model_list to find available providerId/model pairs. Explicit providerId/model uses the selected pair template; otherwise a usable Agent default, current session pair and parameters, then system default are selected together. params overlays that source. Returns immediately; the child does not see this conversation.",
1734
+ inputSchema: SpawnSubagentsInput,
1735
+ outputSchema: z.strictObject({ results: z.array(z.union([z.object({
1736
+ index: z.number(),
1737
+ target: z.object({ agent: z.string().optional() }),
1738
+ ok: z.literal(true),
1739
+ value: z.object({
1740
+ taskId: z.string(),
1741
+ childSessionId: z.string(),
1742
+ state: z.string()
1743
+ })
1744
+ }), z.object({
1745
+ index: z.number(),
1746
+ target: z.object({ agent: z.string().optional() }),
1747
+ ok: z.literal(false),
1748
+ error: z.object({
1749
+ code: z.string(),
1750
+ message: z.string()
1751
+ })
1752
+ })])) }),
1753
+ deliveryKind: "receipt",
1754
+ async execute(input, call) {
1755
+ const result = await service.spawnMany(call, input.tasks);
1756
+ return {
1757
+ content: JSON.stringify({ results: result.results.map((item) => ({
1758
+ ...item,
1759
+ target: { ...item.target.agent ? { agent: item.target.agent } : {} },
1760
+ ...item.ok ? { value: {
1761
+ taskId: item.value.taskId,
1762
+ childSessionId: item.value.childSessionId,
1763
+ state: item.value.state
1764
+ } } : {}
1765
+ })) }),
1766
+ delivery: {
1767
+ kind: "receipt",
1768
+ outputTokens: call.output.outputTokens,
1769
+ execution: result.results.some((item) => item.ok) ? "committed" : "not-started"
1770
+ },
1771
+ ...result.results.some((item) => !item.ok) ? { isError: true } : {}
1772
+ };
1773
+ }
1774
+ });
1775
+ register({
1776
+ name: "subagent_send",
1777
+ preload: false,
1778
+ description: "Append a task to an existing descendant. Busy children queue FIFO; an idle child must reacquire capacity.",
1779
+ inputSchema: z.object({
1780
+ childSessionId: z.string().min(1).max(512).describe("Descendant session ID."),
1781
+ task: z.string().min(1).describe("Follow-up task; its text is not repeated in the receipt.")
1782
+ }).strict(),
1783
+ outputSchema: z.strictObject({
1784
+ taskId: z.string(),
1785
+ childSessionId: z.string(),
1786
+ state: z.string()
1787
+ }),
1788
+ deliveryKind: "receipt",
1789
+ async execute(input, call) {
1790
+ const task = service.send(call, input.childSessionId, input.task);
1791
+ return {
1792
+ content: JSON.stringify({
1793
+ taskId: task.taskId,
1794
+ childSessionId: task.childSessionId,
1795
+ state: task.state
1796
+ }),
1797
+ delivery: {
1798
+ kind: "receipt",
1799
+ outputTokens: call.output.outputTokens,
1800
+ execution: "committed"
1801
+ }
1802
+ };
1803
+ }
1804
+ });
1805
+ const reads = nativeReadTools(service, ctx.signal, ctx.services.get("query-resources"));
1806
+ ctx.onDispose(() => reads.close());
1807
+ register(reads.get);
1808
+ register(reads.list);
1809
+ register({
1810
+ name: "subagent_stop",
1811
+ preload: false,
1812
+ description: "Stop one named task, leaving its children running, or stop the entire native subtree. Existing file edits are not undone.",
1813
+ inputSchema: StopSubagentsInput,
1814
+ outputSchema: z.strictObject({ results: z.array(z.union([z.object({
1815
+ index: z.number(),
1816
+ target: z.object({
1817
+ childSessionId: z.string(),
1818
+ scope: z.enum(["task", "subtree"]),
1819
+ taskId: z.string().optional()
1820
+ }),
1821
+ ok: z.literal(true),
1822
+ value: z.object({ stopped: z.boolean() })
1823
+ }), z.object({
1824
+ index: z.number(),
1825
+ target: z.object({
1826
+ childSessionId: z.string(),
1827
+ scope: z.enum(["task", "subtree"]),
1828
+ taskId: z.string().optional()
1829
+ }),
1830
+ ok: z.literal(false),
1831
+ error: z.object({
1832
+ code: z.string(),
1833
+ message: z.string()
1834
+ })
1835
+ })])) }),
1836
+ deliveryKind: "receipt",
1837
+ async execute(input, call) {
1838
+ const result = await service.stopMany(call, input.items);
1839
+ return {
1840
+ content: JSON.stringify(result),
1841
+ delivery: {
1842
+ kind: "receipt",
1843
+ outputTokens: call.output.outputTokens,
1844
+ execution: result.results.some((item) => item.ok) ? "committed" : "unknown"
1845
+ },
1846
+ ...result.results.some((item) => !item.ok) ? { isError: true } : {}
1847
+ };
1848
+ }
1849
+ });
1850
+ }
1851
+ //#endregion
1852
+ //#region src/tool-names.ts
1853
+ /** Canonical names shared by tool registration and browser presentation. */
1854
+ const TOOL_NAMES = [
1855
+ "subagent_spawn",
1856
+ "subagent_send",
1857
+ "subagent_get",
1858
+ "subagent_list",
1859
+ "subagent_stop"
1860
+ ];
1861
+ //#endregion
1862
+ //#region src/index.ts
1863
+ /**
1864
+ * This plugin's slice of `config.json`.
1865
+ *
1866
+ * `disabled` turns one tool off while the rest of the package stays on —
1867
+ * `enabled: false` on the declaration turns off every one of them. Strict and
1868
+ * enumerated: a misspelled tool name is a load failure naming the field, not
1869
+ * a line that quietly does nothing.
1870
+ */
1871
+ const SubagentConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
1872
+ const subagentPlugin = {
1873
+ name: "@eum-agent/agent-delegation",
1874
+ requires: [
1875
+ "agent-runs",
1876
+ "unit-of-work",
1877
+ "agent-execution",
1878
+ "agent-sessions",
1879
+ "agent-data-schemas",
1880
+ "model-dispatch-policy",
1881
+ "query-resources"
1882
+ ],
1883
+ provides: [
1884
+ "subagents",
1885
+ "session-admission",
1886
+ "session-delegation-observer"
1887
+ ],
1888
+ configSchema: SubagentConfig,
1889
+ apply(ctx, config) {
1890
+ const { execution, framework, catalog, settings, manager } = createSubagentCapability(ctx);
1891
+ const service = subagentService(ctx, manager);
1892
+ ctx.services.provide("subagents", service);
1893
+ ctx.services.provide("session-admission", {
1894
+ accept: manager.accept,
1895
+ relation: catalog.relation
1896
+ });
1897
+ ctx.onDispose(() => manager.shutdown());
1898
+ registerSubagentMethods(ctx, manager, framework, settings);
1899
+ ctx.context.contribute({
1900
+ id: "subagent-catalog",
1901
+ slot: "system",
1902
+ placement: {
1903
+ chapter: "capabilities",
1904
+ order: 10,
1905
+ category: "agents",
1906
+ requires: ["subagent_spawn"]
1907
+ },
1908
+ async contribute() {
1909
+ const agents = execution.agents();
1910
+ return agents.length ? { system: ["Agents you can delegate to (subagent_spawn with agent):\n" + agents.map((agent) => {
1911
+ const line = agent.description.replace(/\s+/g, " ").trim();
1912
+ return `- ${agent.agentId} — ${agent.name}: ${line || "no description"}`;
1913
+ }).join("\n")] } : {};
1914
+ }
1915
+ });
1916
+ const disabled = new Set(config.disabled);
1917
+ const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
1918
+ registerSubagentTools(ctx, register, service);
1919
+ ctx.tools.guide(GUIDANCE);
1920
+ const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1921
+ if (existsSync(ui)) ctx.client.registerUi({ module: ui });
1922
+ }
1923
+ };
1924
+ //#endregion
1925
+ export { SubagentConfig, TOOL_NAMES, subagentPlugin as default, subagentPlugin, registerSubagentTools };