@eum-agent/agent-delegation 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1153 -155
- package/package.json +4 -4
- package/ui/ui.js +234 -196
package/dist/index.js
CHANGED
|
@@ -8,19 +8,19 @@ const GUIDANCE = {
|
|
|
8
8
|
entries: [
|
|
9
9
|
{
|
|
10
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."
|
|
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
12
|
},
|
|
13
13
|
{
|
|
14
14
|
tools: ["subagent_get"],
|
|
15
|
-
text: "`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
16
|
},
|
|
17
17
|
{
|
|
18
18
|
tools: ["subagent_list"],
|
|
19
|
-
text: "`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
20
|
},
|
|
21
21
|
{
|
|
22
22
|
tools: ["subagent_send"],
|
|
23
|
-
text: "`subagent_send` sends a follow-up
|
|
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
24
|
},
|
|
25
25
|
{
|
|
26
26
|
tools: ["subagent_stop"],
|
|
@@ -105,24 +105,81 @@ function taskSchema(framework) {
|
|
|
105
105
|
}
|
|
106
106
|
/** Model-selected creation fields; ancestry always comes from the trusted caller. */
|
|
107
107
|
const SpawnSubagentSchema = z.object({
|
|
108
|
-
task: z.string().min(1),
|
|
108
|
+
task: z.string().min(1).describe("Self-contained task for an independent child context; include facts, paths and requested result."),
|
|
109
109
|
/** The agent to delegate to; the general-purpose agent when absent. */
|
|
110
|
-
agent: AgentIdSchema.optional(),
|
|
111
|
-
providerId: z.string().optional(),
|
|
112
|
-
model: z.string().optional(),
|
|
113
|
-
params: z.record(z.string(), z.unknown()).optional()
|
|
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
114
|
}).strict();
|
|
115
115
|
/** Native state announcements use the task codec supplied by the framework. */
|
|
116
116
|
function changedSchema(framework) {
|
|
117
117
|
return z.strictObject({
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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) });
|
|
125
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
|
+
});
|
|
126
183
|
//#endregion
|
|
127
184
|
//#region src/storage/catalog.ts
|
|
128
185
|
/** Opens native delegation tables without owning or closing the connection. */
|
|
@@ -168,7 +225,20 @@ function createSubagentCatalogOn(storage, framework) {
|
|
|
168
225
|
createdAt: row.created_at
|
|
169
226
|
});
|
|
170
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`;
|
|
171
240
|
return {
|
|
241
|
+
connectionIdentity: storage.connectionIdentity,
|
|
172
242
|
transaction(write) {
|
|
173
243
|
if (db.isTransaction) return write();
|
|
174
244
|
db.exec("BEGIN");
|
|
@@ -188,15 +258,88 @@ function createSubagentCatalogOn(storage, framework) {
|
|
|
188
258
|
const row = db.prepare(`SELECT ${relationColumns} FROM subagent_session WHERE child_session_id = ?`).get(child);
|
|
189
259
|
return row ? decode(row) : void 0;
|
|
190
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
|
+
},
|
|
191
268
|
addRelation(input) {
|
|
269
|
+
membership++;
|
|
192
270
|
const row = SubagentRelationSchema.parse(input);
|
|
193
271
|
db.prepare(`INSERT INTO subagent_session (${relationColumns}) VALUES (?, ?, ?, ?, ?, ?)`).run(row.childSessionId, row.parentSessionId, row.rootSessionId, row.depth, JSON.stringify(row.definition), row.createdAt);
|
|
194
272
|
},
|
|
195
273
|
tasks(child) {
|
|
196
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))));
|
|
197
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
|
+
},
|
|
198
340
|
saveTask(input) {
|
|
199
341
|
const task = SubagentTaskSchema.parse(input);
|
|
342
|
+
if (!db.prepare("SELECT task_id FROM subagent_task WHERE task_id=?").get(task.taskId)) membership++;
|
|
200
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));
|
|
201
344
|
}
|
|
202
345
|
};
|
|
@@ -205,6 +348,14 @@ function createSubagentCatalogOn(storage, framework) {
|
|
|
205
348
|
//#region src/runtime/manager.ts
|
|
206
349
|
const DEFAULT_AGENT_ID = "general-purpose";
|
|
207
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
|
+
}
|
|
208
359
|
/** Builds the native coordinator over the existing session loop. */
|
|
209
360
|
function createSubagentManager(deps) {
|
|
210
361
|
const { sessions, catalog, runs } = deps;
|
|
@@ -214,6 +365,21 @@ function createSubagentManager(deps) {
|
|
|
214
365
|
const blocked = /* @__PURE__ */ new Set();
|
|
215
366
|
let closed = false;
|
|
216
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
|
+
}
|
|
217
383
|
function session(id) {
|
|
218
384
|
const value = sessions.listSessions().find((row) => row.sessionId === id);
|
|
219
385
|
if (!value) throw new Error("not-found: session does not exist");
|
|
@@ -253,15 +419,15 @@ function createSubagentManager(deps) {
|
|
|
253
419
|
return catalog.tasks(child).map(projected);
|
|
254
420
|
}
|
|
255
421
|
function announce(task) {
|
|
422
|
+
if (batchedTaskIds.has(task.taskId) || stoppingNotifications.has(task.taskId)) return;
|
|
256
423
|
queueMicrotask(() => {
|
|
257
424
|
if (deps.signal.aborted) return;
|
|
258
425
|
const current = tasks(task.childSessionId).find((row) => row.taskId === task.taskId);
|
|
259
426
|
if (!current || current.revision !== task.revision) return;
|
|
260
|
-
|
|
261
|
-
deps.changed(current, [.../* @__PURE__ */ new Set([relation.rootSessionId, relation.parentSessionId])]);
|
|
427
|
+
publishTasks([current]);
|
|
262
428
|
});
|
|
263
429
|
}
|
|
264
|
-
function acceptTask(caller, child, input, message) {
|
|
430
|
+
function acceptTask(caller, child, input, message, scope) {
|
|
265
431
|
deps.signal.throwIfAborted();
|
|
266
432
|
if (recovering) throw new Error("recovering");
|
|
267
433
|
if (closed || stopping.has(child) || stopping.has(caller.sessionId)) throw new Error("stopping");
|
|
@@ -304,14 +470,32 @@ function createSubagentManager(deps) {
|
|
|
304
470
|
updatedAt: now,
|
|
305
471
|
revision: 0
|
|
306
472
|
};
|
|
307
|
-
|
|
473
|
+
const write = (joined) => {
|
|
474
|
+
if (catalog.connectionIdentity !== joined.connectionIdentity) throw new Error("Native task storage must share the host connection");
|
|
308
475
|
catalog.saveTask(task);
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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);
|
|
315
499
|
return task;
|
|
316
500
|
}
|
|
317
501
|
function plan(task) {
|
|
@@ -390,7 +574,7 @@ function createSubagentManager(deps) {
|
|
|
390
574
|
unsubscribe();
|
|
391
575
|
blocked.clear();
|
|
392
576
|
}, { once: true });
|
|
393
|
-
|
|
577
|
+
const manager = {
|
|
394
578
|
async drain() {
|
|
395
579
|
await Promise.resolve();
|
|
396
580
|
},
|
|
@@ -405,7 +589,7 @@ function createSubagentManager(deps) {
|
|
|
405
589
|
if (!task) throw new Error("not-found: task does not exist");
|
|
406
590
|
if (task.state === "finished") return;
|
|
407
591
|
if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
|
|
408
|
-
else await sessions.
|
|
592
|
+
else if ((await sessions.cancelMany([child])).results.some((item) => !item.ok)) throw new Error("cleanup-failed: native task cleanup did not complete");
|
|
409
593
|
return;
|
|
410
594
|
}
|
|
411
595
|
const ids = /* @__PURE__ */ new Set([child]);
|
|
@@ -420,11 +604,70 @@ function createSubagentManager(deps) {
|
|
|
420
604
|
for (const id of ids) stopping.add(id);
|
|
421
605
|
try {
|
|
422
606
|
for (const id of ids) for (const task of tasks(id)) if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
|
|
423
|
-
await
|
|
607
|
+
if ((await sessions.cancelMany([...ids])).results.some((item) => !item.ok)) throw new Error("cleanup-failed: native subtree cleanup did not complete");
|
|
424
608
|
} finally {
|
|
425
609
|
for (const id of ids) stopping.delete(id);
|
|
426
610
|
}
|
|
427
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
|
+
},
|
|
428
671
|
async recover() {
|
|
429
672
|
recovering = true;
|
|
430
673
|
try {
|
|
@@ -437,7 +680,7 @@ function createSubagentManager(deps) {
|
|
|
437
680
|
deps.signal.throwIfAborted();
|
|
438
681
|
if (recovering) throw new Error("recovering");
|
|
439
682
|
if (closed || stopping.has(caller.sessionId)) throw new Error("stopping");
|
|
440
|
-
const fingerprint =
|
|
683
|
+
const fingerprint = memberDigest(input);
|
|
441
684
|
const parent = session(caller.sessionId);
|
|
442
685
|
const existing = tasks().find((row) => row.callerSessionId === caller.sessionId && row.requestKey === caller.requestKey);
|
|
443
686
|
if (existing) {
|
|
@@ -457,7 +700,7 @@ function createSubagentManager(deps) {
|
|
|
457
700
|
agent: agentId,
|
|
458
701
|
...narrowed === void 0 ? {} : { tools: narrowed }
|
|
459
702
|
};
|
|
460
|
-
const { chosen, candidate } = childModel({
|
|
703
|
+
const { chosen, candidate, baseParams } = childModel({
|
|
461
704
|
input,
|
|
462
705
|
agentId,
|
|
463
706
|
delegate,
|
|
@@ -465,11 +708,12 @@ function createSubagentManager(deps) {
|
|
|
465
708
|
...deps.available ? { available: deps.available } : {},
|
|
466
709
|
...deps.instantiate ? { instantiate: deps.instantiate } : {}
|
|
467
710
|
});
|
|
468
|
-
if (!chosen && deps.requireModel) throw new Error("no model is configured");
|
|
469
|
-
const prepared = chosen ? deps.prepareModel?.(agentId, chosen, candidate, Object.keys(input.params ?? {})) : void 0;
|
|
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;
|
|
470
713
|
const params = prepared?.effectiveParams ?? candidate;
|
|
471
|
-
return
|
|
472
|
-
|
|
714
|
+
return deps.unitOfWork.run((scope) => {
|
|
715
|
+
let result;
|
|
716
|
+
sessions.createSession({
|
|
473
717
|
agentId: parent.agentId,
|
|
474
718
|
workspaceId: parent.workspaceId,
|
|
475
719
|
title: input.task.slice(0, 60),
|
|
@@ -477,42 +721,154 @@ function createSubagentManager(deps) {
|
|
|
477
721
|
model: chosen,
|
|
478
722
|
params
|
|
479
723
|
},
|
|
480
|
-
deferLoad: true
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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
|
+
}
|
|
489
755
|
});
|
|
490
|
-
|
|
491
|
-
...acceptTask(caller, child.sessionId, input.task),
|
|
492
|
-
requestFingerprint: fingerprint,
|
|
493
|
-
...prepared ? { modelValidation: {
|
|
494
|
-
validation: prepared.validation,
|
|
495
|
-
changes: [...prepared.changes],
|
|
496
|
-
unknownKeys: [...prepared.unknownKeys]
|
|
497
|
-
} } : {}
|
|
498
|
-
};
|
|
499
|
-
catalog.saveTask(result);
|
|
756
|
+
if (!result) throw new Error("Native child initialization did not produce an accepted task");
|
|
500
757
|
return result;
|
|
501
758
|
});
|
|
502
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
|
+
},
|
|
503
808
|
send(caller, child, task) {
|
|
504
809
|
authorized(caller.sessionId, child);
|
|
505
810
|
return acceptTask(caller, child, task);
|
|
506
811
|
},
|
|
507
812
|
list(caller) {
|
|
508
|
-
return
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
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);
|
|
515
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);
|
|
516
872
|
},
|
|
517
873
|
accept(child, trigger) {
|
|
518
874
|
const relation = catalog.relation(child);
|
|
@@ -525,6 +881,7 @@ function createSubagentManager(deps) {
|
|
|
525
881
|
return true;
|
|
526
882
|
}
|
|
527
883
|
};
|
|
884
|
+
return manager;
|
|
528
885
|
}
|
|
529
886
|
/** The narrowing chain a child's snapshot stores: every earlier delegate's
|
|
530
887
|
* whitelist, then the new delegate's. `undefined` narrows nothing and `[]`
|
|
@@ -535,29 +892,90 @@ function narrowTools(chain, delegate) {
|
|
|
535
892
|
if (chain === void 0) return [...delegate];
|
|
536
893
|
return chain.filter((name) => delegate.includes(name));
|
|
537
894
|
}
|
|
538
|
-
/**
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
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
|
+
*/
|
|
543
901
|
function childModel(options) {
|
|
544
902
|
const { input, delegate, parent } = options;
|
|
545
|
-
|
|
546
|
-
|
|
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 ? {
|
|
547
907
|
providerId: input.providerId,
|
|
548
908
|
model: input.model
|
|
549
909
|
} : void 0;
|
|
550
|
-
|
|
551
|
-
|
|
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);
|
|
552
925
|
return {
|
|
553
|
-
chosen,
|
|
926
|
+
chosen: chosen ? { ...chosen } : null,
|
|
927
|
+
baseParams,
|
|
554
928
|
candidate: {
|
|
555
|
-
...
|
|
556
|
-
...input.params
|
|
929
|
+
...structuredClone(baseParams),
|
|
930
|
+
...structuredClone(input.params ?? {})
|
|
557
931
|
}
|
|
558
932
|
};
|
|
559
933
|
}
|
|
560
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
|
|
561
979
|
//#region src/runtime/settings.ts
|
|
562
980
|
/** Reads limits at admission and replaces the full settings row atomically. */
|
|
563
981
|
function subagentSettings(storage) {
|
|
@@ -593,6 +1011,7 @@ function createSubagentCapability(ctx) {
|
|
|
593
1011
|
const modelPolicy = ctx.services.get("model-dispatch-policy");
|
|
594
1012
|
const models = () => modelPolicy;
|
|
595
1013
|
const manager = createSubagentManager({
|
|
1014
|
+
unitOfWork: ctx.services.get("unit-of-work"),
|
|
596
1015
|
sessions,
|
|
597
1016
|
runs,
|
|
598
1017
|
catalog,
|
|
@@ -607,40 +1026,93 @@ function createSubagentCapability(ctx) {
|
|
|
607
1026
|
};
|
|
608
1027
|
},
|
|
609
1028
|
available: (ref) => models()?.available(ref) ?? false,
|
|
610
|
-
instantiate: (id, ref) => models()
|
|
611
|
-
prepareModel: (
|
|
1029
|
+
instantiate: (id, ref) => models().instantiate(id, ref),
|
|
1030
|
+
prepareModel: (_agent, ref, params, explicit, defaults) => models()?.prepareParams({
|
|
612
1031
|
providerId: ref.providerId,
|
|
613
1032
|
model: ref.model,
|
|
614
1033
|
params,
|
|
615
1034
|
explicitKeys: explicit,
|
|
616
|
-
defaults
|
|
1035
|
+
defaults
|
|
617
1036
|
}) ?? {
|
|
618
1037
|
effectiveParams: params,
|
|
619
1038
|
changes: [],
|
|
620
1039
|
unknownKeys: [...explicit],
|
|
621
1040
|
validation: "unknown"
|
|
622
1041
|
},
|
|
623
|
-
changed(
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
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
|
+
}
|
|
633
1071
|
}
|
|
634
1072
|
});
|
|
635
1073
|
ctx.services.provide("session-delegation-observer", {
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
return manager.
|
|
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
|
+
}) };
|
|
639
1100
|
},
|
|
640
1101
|
project(frame) {
|
|
641
1102
|
ctx.signal.throwIfAborted();
|
|
642
1103
|
if (frame.kind !== changed.kind || !("payload" in frame)) return void 0;
|
|
643
|
-
|
|
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
|
+
};
|
|
644
1116
|
}
|
|
645
1117
|
});
|
|
646
1118
|
return {
|
|
@@ -697,10 +1169,10 @@ function registerSubagentMethods(ctx, manager, framework, settings) {
|
|
|
697
1169
|
}, childSessionId, task)
|
|
698
1170
|
});
|
|
699
1171
|
ctx.client.registerMethod({
|
|
700
|
-
name: "
|
|
701
|
-
params:
|
|
702
|
-
result:
|
|
703
|
-
handle: (
|
|
1172
|
+
name: "listByParents",
|
|
1173
|
+
params: ListByParentsParams,
|
|
1174
|
+
result: listByParentsResult(framework),
|
|
1175
|
+
handle: (input) => readParents(manager, input, ctx.signal)
|
|
704
1176
|
});
|
|
705
1177
|
ctx.client.registerMethod({
|
|
706
1178
|
name: "get",
|
|
@@ -711,7 +1183,10 @@ function registerSubagentMethods(ctx, manager, framework, settings) {
|
|
|
711
1183
|
}),
|
|
712
1184
|
result: Task,
|
|
713
1185
|
handle({ parentSessionId, childSessionId, taskId }) {
|
|
714
|
-
const task = manager.
|
|
1186
|
+
const task = manager.read(parentSessionId, {
|
|
1187
|
+
childSessionId,
|
|
1188
|
+
taskId
|
|
1189
|
+
}, 8388608)[0];
|
|
715
1190
|
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
716
1191
|
return task;
|
|
717
1192
|
}
|
|
@@ -740,34 +1215,80 @@ function subagentService(ctx, manager) {
|
|
|
740
1215
|
call.signal.throwIfAborted();
|
|
741
1216
|
return {
|
|
742
1217
|
sessionId: call.sessionId,
|
|
1218
|
+
execution: call,
|
|
743
1219
|
owner: ctx.pluginName,
|
|
744
1220
|
requestKey: `${call.turn}:${call.toolCallId}`
|
|
745
1221
|
};
|
|
746
1222
|
};
|
|
747
1223
|
return {
|
|
748
1224
|
spawn: (call, input) => manager.spawn(caller(call), input),
|
|
1225
|
+
spawnMany: (call, inputs) => manager.spawnMany(caller(call), inputs),
|
|
749
1226
|
send: (call, child, task) => manager.send(caller(call), child, task),
|
|
750
1227
|
list: (call) => {
|
|
751
1228
|
caller(call);
|
|
752
1229
|
return manager.list(call.sessionId);
|
|
753
1230
|
},
|
|
754
|
-
get(call, child, taskId) {
|
|
1231
|
+
get(call, child, taskId, maxBytes = 262144) {
|
|
755
1232
|
caller(call);
|
|
756
|
-
const task = manager.
|
|
1233
|
+
const task = manager.read(call.sessionId, {
|
|
1234
|
+
childSessionId: child,
|
|
1235
|
+
taskId
|
|
1236
|
+
}, maxBytes)[0];
|
|
757
1237
|
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
758
1238
|
return task;
|
|
759
1239
|
},
|
|
760
|
-
async wait(call, taskId, timeoutMs) {
|
|
1240
|
+
async wait(call, taskId, timeoutMs, maxBytes = 262144) {
|
|
761
1241
|
caller(call);
|
|
762
|
-
const until =
|
|
1242
|
+
const until = performance.now() + Math.min(6e4, Math.max(0, timeoutMs));
|
|
763
1243
|
for (;;) {
|
|
764
1244
|
ctx.signal.throwIfAborted();
|
|
765
|
-
const task = manager.
|
|
1245
|
+
const task = manager.read(call.sessionId, { taskId }, maxBytes)[0];
|
|
766
1246
|
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
767
|
-
if (task.state === "finished" ||
|
|
768
|
-
await new Promise((resolve) => setTimeout(resolve, Math.min(50, until -
|
|
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())));
|
|
769
1249
|
}
|
|
770
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
|
+
},
|
|
771
1292
|
stop: (call, child, scope, taskId) => {
|
|
772
1293
|
caller(call);
|
|
773
1294
|
return manager.stop(call.sessionId, child, scope, taskId);
|
|
@@ -775,80 +1296,555 @@ function subagentService(ctx, manager) {
|
|
|
775
1296
|
};
|
|
776
1297
|
}
|
|
777
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
|
|
778
1727
|
//#region src/subagents/index.ts
|
|
779
1728
|
/** Registers five independent controls over the host's native task service. */
|
|
780
1729
|
function registerSubagentTools(ctx, register, service = ctx.services.get("subagents")) {
|
|
781
1730
|
register({
|
|
782
1731
|
name: "subagent_spawn",
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
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",
|
|
791
1754
|
async execute(input, call) {
|
|
792
|
-
|
|
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
|
+
};
|
|
793
1773
|
}
|
|
794
1774
|
});
|
|
795
1775
|
register({
|
|
796
1776
|
name: "subagent_send",
|
|
1777
|
+
preload: false,
|
|
797
1778
|
description: "Append a task to an existing descendant. Busy children queue FIFO; an idle child must reacquire capacity.",
|
|
798
1779
|
inputSchema: z.object({
|
|
799
|
-
childSessionId: z.string(),
|
|
800
|
-
task: z.string().min(1)
|
|
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.")
|
|
801
1782
|
}).strict(),
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
}
|
|
805
|
-
});
|
|
806
|
-
register({
|
|
807
|
-
name: "subagent_get",
|
|
808
|
-
description: "Read a descendant task status, outcome and bounded result. With `taskId` and `waitMs`, wait up to that long (at most 60 seconds) for the task to finish first; without `waitMs` it answers at once. A timeout or cancelled wait does not stop the child.",
|
|
809
|
-
inputSchema: z.object({
|
|
1783
|
+
outputSchema: z.strictObject({
|
|
1784
|
+
taskId: z.string(),
|
|
810
1785
|
childSessionId: z.string(),
|
|
811
|
-
|
|
812
|
-
waitMs: z.number().int().min(0).max(6e4).optional()
|
|
813
|
-
}).strict().superRefine((input, issues) => {
|
|
814
|
-
if (input.waitMs !== void 0 && input.taskId === void 0) issues.addIssue({
|
|
815
|
-
code: "custom",
|
|
816
|
-
path: ["taskId"],
|
|
817
|
-
message: "waitMs needs the taskId to wait for"
|
|
818
|
-
});
|
|
1786
|
+
state: z.string()
|
|
819
1787
|
}),
|
|
1788
|
+
deliveryKind: "receipt",
|
|
820
1789
|
async execute(input, call) {
|
|
821
|
-
const task = service.
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
const tasks = service.list(call);
|
|
835
|
-
return { content: JSON.stringify({
|
|
836
|
-
tasks: tasks.slice(input.offset, input.offset + input.limit),
|
|
837
|
-
nextOffset: tasks.length > input.offset + input.limit ? input.offset + input.limit : null
|
|
838
|
-
}) };
|
|
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
|
+
};
|
|
839
1803
|
}
|
|
840
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);
|
|
841
1809
|
register({
|
|
842
1810
|
name: "subagent_stop",
|
|
1811
|
+
preload: false,
|
|
843
1812
|
description: "Stop one named task, leaving its children running, or stop the entire native subtree. Existing file edits are not undone.",
|
|
844
|
-
inputSchema:
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
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",
|
|
849
1837
|
async execute(input, call) {
|
|
850
|
-
await service.
|
|
851
|
-
return {
|
|
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
|
+
};
|
|
852
1848
|
}
|
|
853
1849
|
});
|
|
854
1850
|
}
|
|
@@ -877,10 +1873,12 @@ const subagentPlugin = {
|
|
|
877
1873
|
name: "@eum-agent/agent-delegation",
|
|
878
1874
|
requires: [
|
|
879
1875
|
"agent-runs",
|
|
1876
|
+
"unit-of-work",
|
|
880
1877
|
"agent-execution",
|
|
881
1878
|
"agent-sessions",
|
|
882
1879
|
"agent-data-schemas",
|
|
883
|
-
"model-dispatch-policy"
|
|
1880
|
+
"model-dispatch-policy",
|
|
1881
|
+
"query-resources"
|
|
884
1882
|
],
|
|
885
1883
|
provides: [
|
|
886
1884
|
"subagents",
|