@eum-agent/agent-delegation 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +927 -0
- package/package.json +50 -3
- package/ui/ui.js +478 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,927 @@
|
|
|
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."
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
tools: ["subagent_get"],
|
|
15
|
+
text: "`subagent_get` reads one subagent's state and result; with `taskId` and `waitMs` it waits for that task to finish first, for when you cannot continue without the result."
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
tools: ["subagent_list"],
|
|
19
|
+
text: "`subagent_list` lists this session's subagents."
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
tools: ["subagent_send"],
|
|
23
|
+
text: "`subagent_send` sends a follow-up message to a subagent."
|
|
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),
|
|
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()
|
|
114
|
+
}).strict();
|
|
115
|
+
/** Native state announcements use the task codec supplied by the framework. */
|
|
116
|
+
function changedSchema(framework) {
|
|
117
|
+
return z.strictObject({
|
|
118
|
+
rootSessionId: z.string(),
|
|
119
|
+
parentSessionId: z.string(),
|
|
120
|
+
childSessionId: z.string(),
|
|
121
|
+
taskId: z.string(),
|
|
122
|
+
revision: z.number().int(),
|
|
123
|
+
task: taskSchema(framework)
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region src/storage/catalog.ts
|
|
128
|
+
/** Opens native delegation tables without owning or closing the connection. */
|
|
129
|
+
function createSubagentCatalogOn(storage, framework) {
|
|
130
|
+
const SubagentTaskSchema = taskSchema(framework);
|
|
131
|
+
const mapped = new Map([
|
|
132
|
+
"subagent_session",
|
|
133
|
+
"subagent_task",
|
|
134
|
+
"subagent_by_parent",
|
|
135
|
+
"subagent_by_root",
|
|
136
|
+
"subagent_task_by_state"
|
|
137
|
+
].map((name) => [name, storage.tableName(name)]));
|
|
138
|
+
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));
|
|
139
|
+
const db = {
|
|
140
|
+
prepare: (text) => storage.db.prepare(sql(text)),
|
|
141
|
+
exec: (text) => storage.db.exec(sql(text)),
|
|
142
|
+
get isTransaction() {
|
|
143
|
+
return storage.db.isTransaction;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
db.exec(`CREATE TABLE IF NOT EXISTS subagent_session (
|
|
147
|
+
child_session_id TEXT NOT NULL PRIMARY KEY, parent_session_id TEXT NOT NULL,
|
|
148
|
+
root_session_id TEXT NOT NULL, depth INTEGER NOT NULL CHECK(depth > 0),
|
|
149
|
+
definition_json TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
150
|
+
) STRICT;
|
|
151
|
+
CREATE INDEX IF NOT EXISTS subagent_by_parent ON subagent_session(parent_session_id, child_session_id);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS subagent_by_root ON subagent_session(root_session_id, child_session_id);
|
|
153
|
+
CREATE TABLE IF NOT EXISTS subagent_task (
|
|
154
|
+
task_id TEXT NOT NULL PRIMARY KEY, child_session_id TEXT NOT NULL,
|
|
155
|
+
caller_session_id TEXT NOT NULL, request_key TEXT NOT NULL, ordinal INTEGER NOT NULL,
|
|
156
|
+
task_state TEXT NOT NULL, payload TEXT NOT NULL,
|
|
157
|
+
UNIQUE(caller_session_id, request_key), UNIQUE(child_session_id, ordinal)
|
|
158
|
+
) STRICT;
|
|
159
|
+
CREATE INDEX IF NOT EXISTS subagent_task_by_state ON subagent_task(task_state, child_session_id);`);
|
|
160
|
+
const relationColumns = "child_session_id, parent_session_id, root_session_id, depth, definition_json, created_at";
|
|
161
|
+
function decode(row) {
|
|
162
|
+
return SubagentRelationSchema.parse({
|
|
163
|
+
childSessionId: row.child_session_id,
|
|
164
|
+
parentSessionId: row.parent_session_id,
|
|
165
|
+
rootSessionId: row.root_session_id,
|
|
166
|
+
depth: row.depth,
|
|
167
|
+
definition: JSON.parse(String(row.definition_json)),
|
|
168
|
+
createdAt: row.created_at
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
transaction(write) {
|
|
173
|
+
if (db.isTransaction) return write();
|
|
174
|
+
db.exec("BEGIN");
|
|
175
|
+
try {
|
|
176
|
+
const result = write();
|
|
177
|
+
db.exec("COMMIT");
|
|
178
|
+
return result;
|
|
179
|
+
} catch (error) {
|
|
180
|
+
db.exec("ROLLBACK");
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
relations(root) {
|
|
185
|
+
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);
|
|
186
|
+
},
|
|
187
|
+
relation(child) {
|
|
188
|
+
const row = db.prepare(`SELECT ${relationColumns} FROM subagent_session WHERE child_session_id = ?`).get(child);
|
|
189
|
+
return row ? decode(row) : void 0;
|
|
190
|
+
},
|
|
191
|
+
addRelation(input) {
|
|
192
|
+
const row = SubagentRelationSchema.parse(input);
|
|
193
|
+
db.prepare(`INSERT INTO subagent_session (${relationColumns}) VALUES (?, ?, ?, ?, ?, ?)`).run(row.childSessionId, row.parentSessionId, row.rootSessionId, row.depth, JSON.stringify(row.definition), row.createdAt);
|
|
194
|
+
},
|
|
195
|
+
tasks(child) {
|
|
196
|
+
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
|
+
},
|
|
198
|
+
saveTask(input) {
|
|
199
|
+
const task = SubagentTaskSchema.parse(input);
|
|
200
|
+
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
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region src/runtime/manager.ts
|
|
206
|
+
const DEFAULT_AGENT_ID = "general-purpose";
|
|
207
|
+
const agentRemovedMessage = (agentId) => `the agent of this session was deleted: ${agentId}. The session can be read but not continued`;
|
|
208
|
+
/** Builds the native coordinator over the existing session loop. */
|
|
209
|
+
function createSubagentManager(deps) {
|
|
210
|
+
const { sessions, catalog, runs } = deps;
|
|
211
|
+
const stopping = /* @__PURE__ */ new Set();
|
|
212
|
+
/** Children whose next queued task met a full root; retried when a task
|
|
213
|
+
* of any child finishes. */
|
|
214
|
+
const blocked = /* @__PURE__ */ new Set();
|
|
215
|
+
let closed = false;
|
|
216
|
+
let recovering = false;
|
|
217
|
+
function session(id) {
|
|
218
|
+
const value = sessions.listSessions().find((row) => row.sessionId === id);
|
|
219
|
+
if (!value) throw new Error("not-found: session does not exist");
|
|
220
|
+
return value;
|
|
221
|
+
}
|
|
222
|
+
function authorized(caller, child) {
|
|
223
|
+
session(caller);
|
|
224
|
+
let relation = catalog.relation(child);
|
|
225
|
+
while (relation) {
|
|
226
|
+
if (relation.parentSessionId === caller) return;
|
|
227
|
+
relation = catalog.relation(relation.parentSessionId);
|
|
228
|
+
}
|
|
229
|
+
throw new Error("forbidden: only descendants may be controlled");
|
|
230
|
+
}
|
|
231
|
+
/** Whether every task slot of `root` is taken: a task holds one from
|
|
232
|
+
* leaving the queue until it finishes. */
|
|
233
|
+
function full(root) {
|
|
234
|
+
const children = new Set(catalog.relations(root).map((row) => row.childSessionId));
|
|
235
|
+
return tasks().filter((task) => children.has(task.childSessionId) && task.state !== "finished" && task.state !== "queued").length >= deps.settings().maxConcurrent;
|
|
236
|
+
}
|
|
237
|
+
function capacity(root) {
|
|
238
|
+
if (full(root)) throw new Error("capacity-exceeded: native task limit reached");
|
|
239
|
+
}
|
|
240
|
+
function projected(task) {
|
|
241
|
+
const run = runs.get(task.taskId);
|
|
242
|
+
return run ? {
|
|
243
|
+
...task,
|
|
244
|
+
state: run.state === "pending" ? task.state : run.state,
|
|
245
|
+
triggerSeq: run.triggerSeq,
|
|
246
|
+
outcome: run.outcome,
|
|
247
|
+
result: run.result,
|
|
248
|
+
updatedAt: run.updatedAt,
|
|
249
|
+
revision: task.revision + run.revision
|
|
250
|
+
} : task;
|
|
251
|
+
}
|
|
252
|
+
function tasks(child) {
|
|
253
|
+
return catalog.tasks(child).map(projected);
|
|
254
|
+
}
|
|
255
|
+
function announce(task) {
|
|
256
|
+
queueMicrotask(() => {
|
|
257
|
+
if (deps.signal.aborted) return;
|
|
258
|
+
const current = tasks(task.childSessionId).find((row) => row.taskId === task.taskId);
|
|
259
|
+
if (!current || current.revision !== task.revision) return;
|
|
260
|
+
const relation = catalog.relation(task.childSessionId);
|
|
261
|
+
deps.changed(current, [.../* @__PURE__ */ new Set([relation.rootSessionId, relation.parentSessionId])]);
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
function acceptTask(caller, child, input, message) {
|
|
265
|
+
deps.signal.throwIfAborted();
|
|
266
|
+
if (recovering) throw new Error("recovering");
|
|
267
|
+
if (closed || stopping.has(child) || stopping.has(caller.sessionId)) throw new Error("stopping");
|
|
268
|
+
const previous = tasks().find((row) => row.callerSessionId === caller.sessionId && row.requestKey === caller.requestKey);
|
|
269
|
+
if (previous) {
|
|
270
|
+
if (previous.input !== input || previous.childSessionId !== child || previous.sourceOwner !== caller.owner) throw new Error("request-key-conflict");
|
|
271
|
+
return previous;
|
|
272
|
+
}
|
|
273
|
+
const relation = catalog.relation(child);
|
|
274
|
+
if (!relation) throw new Error("not-found: child does not exist");
|
|
275
|
+
for (const agentId of [relation.definition.agent, session(child).agentId]) if (!deps.agent(agentId)) throw new Error(agentRemovedMessage(agentId));
|
|
276
|
+
const childTasks = tasks(child);
|
|
277
|
+
const busy = childTasks.some((task) => task.state !== "finished");
|
|
278
|
+
if (!busy) capacity(relation.rootSessionId);
|
|
279
|
+
if (childTasks.filter((task) => task.state === "queued").length >= 32) throw new Error("queue-full");
|
|
280
|
+
const now = Date.now();
|
|
281
|
+
const task = {
|
|
282
|
+
taskId: message?.source?.taskId ?? randomUUID(),
|
|
283
|
+
childSessionId: child,
|
|
284
|
+
callerSessionId: caller.sessionId,
|
|
285
|
+
targetGeneration: session(relation.parentSessionId).historyGeneration,
|
|
286
|
+
sourceOwner: caller.owner,
|
|
287
|
+
requestKey: caller.requestKey,
|
|
288
|
+
agent: relation.definition.agent,
|
|
289
|
+
input,
|
|
290
|
+
message: message ?? {
|
|
291
|
+
id: randomUUID(),
|
|
292
|
+
role: "user",
|
|
293
|
+
content: [{
|
|
294
|
+
type: "text",
|
|
295
|
+
text: input
|
|
296
|
+
}]
|
|
297
|
+
},
|
|
298
|
+
ordinal: (childTasks.at(-1)?.ordinal ?? 0) + 1,
|
|
299
|
+
state: busy ? "queued" : "starting",
|
|
300
|
+
triggerSeq: null,
|
|
301
|
+
outcome: null,
|
|
302
|
+
result: null,
|
|
303
|
+
createdAt: now,
|
|
304
|
+
updatedAt: now,
|
|
305
|
+
revision: 0
|
|
306
|
+
};
|
|
307
|
+
catalog.transaction(() => {
|
|
308
|
+
catalog.saveTask(task);
|
|
309
|
+
runs.prepare(plan(task));
|
|
310
|
+
});
|
|
311
|
+
announce(task);
|
|
312
|
+
queueMicrotask(() => {
|
|
313
|
+
run(child);
|
|
314
|
+
});
|
|
315
|
+
return task;
|
|
316
|
+
}
|
|
317
|
+
function plan(task) {
|
|
318
|
+
const relation = catalog.relation(task.childSessionId);
|
|
319
|
+
return {
|
|
320
|
+
runId: task.taskId,
|
|
321
|
+
sessionId: task.childSessionId,
|
|
322
|
+
definition: relation.definition,
|
|
323
|
+
trigger: {
|
|
324
|
+
source: "plugin",
|
|
325
|
+
sourceId: "@eum-agent/agent-delegation",
|
|
326
|
+
message: task.message?.source !== void 0 ? task.message : {
|
|
327
|
+
...task.message ?? {
|
|
328
|
+
id: randomUUID(),
|
|
329
|
+
role: "user",
|
|
330
|
+
content: [{
|
|
331
|
+
type: "text",
|
|
332
|
+
text: task.input
|
|
333
|
+
}]
|
|
334
|
+
},
|
|
335
|
+
source: {
|
|
336
|
+
kind: "delegation-task",
|
|
337
|
+
owner: task.sourceOwner,
|
|
338
|
+
taskId: task.taskId
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
completion: {
|
|
343
|
+
owner: "@eum-agent/agent-delegation",
|
|
344
|
+
targetSessionId: relation.parentSessionId,
|
|
345
|
+
targetGeneration: task.targetGeneration,
|
|
346
|
+
idempotencyKey: task.taskId,
|
|
347
|
+
textPrefix: `Subagent ${task.childSessionId}, task ${task.taskId}: `,
|
|
348
|
+
includeOutcome: true,
|
|
349
|
+
separator: "\n",
|
|
350
|
+
maxResultBytes: 65536,
|
|
351
|
+
truncationSuffix: "\n[Truncated; open child transcript.]"
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function finish(task, outcome) {
|
|
356
|
+
const admitted = runs.get(task.taskId);
|
|
357
|
+
if (admitted && admitted.state !== "pending" && admitted.state !== "finished") {
|
|
358
|
+
runs.stop(task.taskId);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (admitted?.state === "finished") return;
|
|
362
|
+
runs.settle(plan(task), outcome);
|
|
363
|
+
}
|
|
364
|
+
function run(child) {
|
|
365
|
+
if (closed || deps.signal.aborted || stopping.has(child)) return Promise.resolve();
|
|
366
|
+
const task = tasks(child).find((row) => row.state !== "finished");
|
|
367
|
+
if (!task || task.state === "awaiting-human" || runs.get(task.taskId)?.state !== "pending" && runs.get(task.taskId)) return Promise.resolve();
|
|
368
|
+
const relation = catalog.relation(child);
|
|
369
|
+
if (task.state === "queued" && full(relation.rootSessionId)) {
|
|
370
|
+
blocked.add(child);
|
|
371
|
+
return Promise.resolve();
|
|
372
|
+
}
|
|
373
|
+
runs.start(plan(task));
|
|
374
|
+
return Promise.resolve();
|
|
375
|
+
}
|
|
376
|
+
const unsubscribe = runs.subscribe((runState) => {
|
|
377
|
+
if (deps.signal.aborted || closed) return;
|
|
378
|
+
const task = tasks(runState.sessionId).find((one) => one.taskId === runState.runId);
|
|
379
|
+
if (task) announce(task);
|
|
380
|
+
if (runState.state !== "finished") return;
|
|
381
|
+
for (const child of /* @__PURE__ */ new Set([runState.sessionId, ...blocked])) {
|
|
382
|
+
blocked.delete(child);
|
|
383
|
+
queueMicrotask(() => {
|
|
384
|
+
run(child);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
deps.signal.addEventListener("abort", () => {
|
|
389
|
+
closed = true;
|
|
390
|
+
unsubscribe();
|
|
391
|
+
blocked.clear();
|
|
392
|
+
}, { once: true });
|
|
393
|
+
return {
|
|
394
|
+
async drain() {
|
|
395
|
+
await Promise.resolve();
|
|
396
|
+
},
|
|
397
|
+
shutdown() {
|
|
398
|
+
closed = true;
|
|
399
|
+
unsubscribe();
|
|
400
|
+
},
|
|
401
|
+
async stop(caller, child, scope, taskId) {
|
|
402
|
+
authorized(caller, child);
|
|
403
|
+
if (scope === "task") {
|
|
404
|
+
const task = tasks(child).find((row) => row.taskId === taskId);
|
|
405
|
+
if (!task) throw new Error("not-found: task does not exist");
|
|
406
|
+
if (task.state === "finished") return;
|
|
407
|
+
if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
|
|
408
|
+
else await sessions.cancel(child);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const ids = /* @__PURE__ */ new Set([child]);
|
|
412
|
+
let added = true;
|
|
413
|
+
while (added) {
|
|
414
|
+
added = false;
|
|
415
|
+
for (const relation of catalog.relations()) if (ids.has(relation.parentSessionId) && !ids.has(relation.childSessionId)) {
|
|
416
|
+
ids.add(relation.childSessionId);
|
|
417
|
+
added = true;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
for (const id of ids) stopping.add(id);
|
|
421
|
+
try {
|
|
422
|
+
for (const id of ids) for (const task of tasks(id)) if (task.state === "queued" || task.state === "starting") finish(task, { kind: "interrupted" });
|
|
423
|
+
await Promise.all([...ids].map((id) => sessions.cancel(id)));
|
|
424
|
+
} finally {
|
|
425
|
+
for (const id of ids) stopping.delete(id);
|
|
426
|
+
}
|
|
427
|
+
},
|
|
428
|
+
async recover() {
|
|
429
|
+
recovering = true;
|
|
430
|
+
try {
|
|
431
|
+
for (const task of tasks()) if (!runs.get(task.taskId) && task.state !== "finished") finish(task, { kind: "interrupted" });
|
|
432
|
+
} finally {
|
|
433
|
+
recovering = false;
|
|
434
|
+
}
|
|
435
|
+
},
|
|
436
|
+
async spawn(caller, input) {
|
|
437
|
+
deps.signal.throwIfAborted();
|
|
438
|
+
if (recovering) throw new Error("recovering");
|
|
439
|
+
if (closed || stopping.has(caller.sessionId)) throw new Error("stopping");
|
|
440
|
+
const fingerprint = createHash("sha256").update(JSON.stringify(input)).digest("hex");
|
|
441
|
+
const parent = session(caller.sessionId);
|
|
442
|
+
const existing = tasks().find((row) => row.callerSessionId === caller.sessionId && row.requestKey === caller.requestKey);
|
|
443
|
+
if (existing) {
|
|
444
|
+
if (existing.input !== input.task || existing.sourceOwner !== caller.owner || existing.requestFingerprint !== fingerprint) throw new Error("request-key-conflict");
|
|
445
|
+
return existing;
|
|
446
|
+
}
|
|
447
|
+
const ancestry = catalog.relation(parent.sessionId);
|
|
448
|
+
const root = ancestry?.rootSessionId ?? parent.sessionId;
|
|
449
|
+
const depth = (ancestry?.depth ?? 0) + 1;
|
|
450
|
+
if (depth > deps.settings().maxDepth) throw new Error("depth-exceeded");
|
|
451
|
+
capacity(root);
|
|
452
|
+
const agentId = input.agent ?? DEFAULT_AGENT_ID;
|
|
453
|
+
const delegate = deps.agent(agentId);
|
|
454
|
+
if (!delegate) throw new Error(`agent-not-found: ${agentId}`);
|
|
455
|
+
const narrowed = narrowTools(ancestry?.definition.tools, delegate.tools);
|
|
456
|
+
const definition = {
|
|
457
|
+
agent: agentId,
|
|
458
|
+
...narrowed === void 0 ? {} : { tools: narrowed }
|
|
459
|
+
};
|
|
460
|
+
const { chosen, candidate } = childModel({
|
|
461
|
+
input,
|
|
462
|
+
agentId,
|
|
463
|
+
delegate,
|
|
464
|
+
parent,
|
|
465
|
+
...deps.available ? { available: deps.available } : {},
|
|
466
|
+
...deps.instantiate ? { instantiate: deps.instantiate } : {}
|
|
467
|
+
});
|
|
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;
|
|
470
|
+
const params = prepared?.effectiveParams ?? candidate;
|
|
471
|
+
return catalog.transaction(() => {
|
|
472
|
+
const child = sessions.createSession({
|
|
473
|
+
agentId: parent.agentId,
|
|
474
|
+
workspaceId: parent.workspaceId,
|
|
475
|
+
title: input.task.slice(0, 60),
|
|
476
|
+
snapshot: {
|
|
477
|
+
model: chosen,
|
|
478
|
+
params
|
|
479
|
+
},
|
|
480
|
+
deferLoad: true
|
|
481
|
+
});
|
|
482
|
+
catalog.addRelation({
|
|
483
|
+
childSessionId: child.sessionId,
|
|
484
|
+
parentSessionId: parent.sessionId,
|
|
485
|
+
rootSessionId: root,
|
|
486
|
+
depth,
|
|
487
|
+
definition,
|
|
488
|
+
createdAt: Date.now()
|
|
489
|
+
});
|
|
490
|
+
const result = {
|
|
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);
|
|
500
|
+
return result;
|
|
501
|
+
});
|
|
502
|
+
},
|
|
503
|
+
send(caller, child, task) {
|
|
504
|
+
authorized(caller.sessionId, child);
|
|
505
|
+
return acceptTask(caller, child, task);
|
|
506
|
+
},
|
|
507
|
+
list(caller) {
|
|
508
|
+
return tasks().filter((task) => {
|
|
509
|
+
try {
|
|
510
|
+
authorized(caller, task.childSessionId);
|
|
511
|
+
return true;
|
|
512
|
+
} catch {
|
|
513
|
+
return false;
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
},
|
|
517
|
+
accept(child, trigger) {
|
|
518
|
+
const relation = catalog.relation(child);
|
|
519
|
+
if (!relation) return false;
|
|
520
|
+
acceptTask({
|
|
521
|
+
sessionId: relation.parentSessionId,
|
|
522
|
+
owner: trigger.sourceId ?? "user",
|
|
523
|
+
requestKey: randomUUID()
|
|
524
|
+
}, child, trigger.message.content.filter((part) => part.type === "text").map((part) => part.text).join(""), trigger.message);
|
|
525
|
+
return true;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/** The narrowing chain a child's snapshot stores: every earlier delegate's
|
|
530
|
+
* whitelist, then the new delegate's. `undefined` narrows nothing and `[]`
|
|
531
|
+
* leaves no tools. The address agent's own whitelist is applied live by the
|
|
532
|
+
* session tool source, so it is never copied in here. */
|
|
533
|
+
function narrowTools(chain, delegate) {
|
|
534
|
+
if (delegate === null) return chain === void 0 ? void 0 : [...chain];
|
|
535
|
+
if (chain === void 0) return [...delegate];
|
|
536
|
+
return chain.filter((name) => delegate.includes(name));
|
|
537
|
+
}
|
|
538
|
+
/** The pair a child runs on and the parameters it starts from. The pair is
|
|
539
|
+
* the explicit one, else the delegate's default while its endpoint is there,
|
|
540
|
+
* else the parent's. Parameters are the delegate's templates for that pair
|
|
541
|
+
* under the explicit ones; the parent's session parameters are carried only
|
|
542
|
+
* when no catalogue can instantiate. */
|
|
543
|
+
function childModel(options) {
|
|
544
|
+
const { input, delegate, parent } = options;
|
|
545
|
+
if (input.providerId === void 0 !== (input.model === void 0)) throw new Error("invalid-model: provider and model must resolve together");
|
|
546
|
+
const explicitPair = input.providerId !== void 0 && input.model !== void 0 ? {
|
|
547
|
+
providerId: input.providerId,
|
|
548
|
+
model: input.model
|
|
549
|
+
} : void 0;
|
|
550
|
+
const delegateDefault = delegate.defaultModel && (options.available?.(delegate.defaultModel) ?? true) ? delegate.defaultModel : void 0;
|
|
551
|
+
const chosen = explicitPair ?? delegateDefault ?? parent.model ?? null;
|
|
552
|
+
return {
|
|
553
|
+
chosen,
|
|
554
|
+
candidate: {
|
|
555
|
+
...chosen ? options.instantiate?.(options.agentId, chosen) ?? parent.params : parent.params,
|
|
556
|
+
...input.params
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
//#endregion
|
|
561
|
+
//#region src/runtime/settings.ts
|
|
562
|
+
/** Reads limits at admission and replaces the full settings row atomically. */
|
|
563
|
+
function subagentSettings(storage) {
|
|
564
|
+
const table = storage.tableName("settings");
|
|
565
|
+
storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton = 0), value TEXT NOT NULL) STRICT`);
|
|
566
|
+
const readRow = storage.db.prepare(`SELECT value FROM ${table} WHERE singleton = 0`);
|
|
567
|
+
const writeRow = storage.db.prepare(`INSERT INTO ${table} (singleton,value) VALUES (0,?) ON CONFLICT(singleton) DO UPDATE SET value=excluded.value`);
|
|
568
|
+
return {
|
|
569
|
+
read: () => SubagentSettingsSchema.parse(JSON.parse(String(readRow.get()?.value ?? "{}"))),
|
|
570
|
+
write(value) {
|
|
571
|
+
const next = SubagentSettingsSchema.parse(value);
|
|
572
|
+
writeRow.run(JSON.stringify(next));
|
|
573
|
+
return next;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
//#endregion
|
|
578
|
+
//#region src/runtime/factory.ts
|
|
579
|
+
/** Creates one activation's policy, owned data and settings. */
|
|
580
|
+
function createSubagentCapability(ctx) {
|
|
581
|
+
const execution = ctx.services.get("agent-execution");
|
|
582
|
+
const sessions = ctx.services.get("agent-sessions");
|
|
583
|
+
const runs = ctx.services.get("agent-runs");
|
|
584
|
+
const framework = ctx.services.get("agent-data-schemas");
|
|
585
|
+
const storage = ctx.storage.open();
|
|
586
|
+
const catalog = createSubagentCatalogOn(storage, framework);
|
|
587
|
+
const settings = subagentSettings(storage);
|
|
588
|
+
const changed = ctx.client.registerFrame({
|
|
589
|
+
name: "changed",
|
|
590
|
+
delivery: "session",
|
|
591
|
+
payload: changedSchema(framework)
|
|
592
|
+
});
|
|
593
|
+
const modelPolicy = ctx.services.get("model-dispatch-policy");
|
|
594
|
+
const models = () => modelPolicy;
|
|
595
|
+
const manager = createSubagentManager({
|
|
596
|
+
sessions,
|
|
597
|
+
runs,
|
|
598
|
+
catalog,
|
|
599
|
+
signal: ctx.signal,
|
|
600
|
+
settings: settings.read,
|
|
601
|
+
agent(id) {
|
|
602
|
+
const agent = execution.agent(id);
|
|
603
|
+
if (!agent) return void 0;
|
|
604
|
+
return {
|
|
605
|
+
tools: agent.tools,
|
|
606
|
+
defaultModel: models().agentDefault(id)
|
|
607
|
+
};
|
|
608
|
+
},
|
|
609
|
+
available: (ref) => models()?.available(ref) ?? false,
|
|
610
|
+
instantiate: (id, ref) => models()?.instantiate(id, ref).params ?? {},
|
|
611
|
+
prepareModel: (agent, ref, params, explicit) => models()?.prepareParams({
|
|
612
|
+
providerId: ref.providerId,
|
|
613
|
+
model: ref.model,
|
|
614
|
+
params,
|
|
615
|
+
explicitKeys: explicit,
|
|
616
|
+
defaults: models()?.instantiate(agent, ref).params ?? {}
|
|
617
|
+
}) ?? {
|
|
618
|
+
effectiveParams: params,
|
|
619
|
+
changes: [],
|
|
620
|
+
unknownKeys: [...explicit],
|
|
621
|
+
validation: "unknown"
|
|
622
|
+
},
|
|
623
|
+
changed(task, targets) {
|
|
624
|
+
const relation = catalog.relation(task.childSessionId);
|
|
625
|
+
for (const target of targets) changed.emit(target, {
|
|
626
|
+
rootSessionId: relation.rootSessionId,
|
|
627
|
+
parentSessionId: relation.parentSessionId,
|
|
628
|
+
childSessionId: task.childSessionId,
|
|
629
|
+
taskId: task.taskId,
|
|
630
|
+
revision: task.revision,
|
|
631
|
+
task
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
ctx.services.provide("session-delegation-observer", {
|
|
636
|
+
list(parentSessionId) {
|
|
637
|
+
ctx.signal.throwIfAborted();
|
|
638
|
+
return manager.list(parentSessionId);
|
|
639
|
+
},
|
|
640
|
+
project(frame) {
|
|
641
|
+
ctx.signal.throwIfAborted();
|
|
642
|
+
if (frame.kind !== changed.kind || !("payload" in frame)) return void 0;
|
|
643
|
+
return changedSchema(framework).parse(frame.payload);
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
return {
|
|
647
|
+
execution,
|
|
648
|
+
framework,
|
|
649
|
+
catalog,
|
|
650
|
+
settings,
|
|
651
|
+
manager
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
//#endregion
|
|
655
|
+
//#region src/runtime/methods.ts
|
|
656
|
+
/** Registers native management and the session-scoped task state frame. */
|
|
657
|
+
function registerSubagentMethods(ctx, manager, framework, settings) {
|
|
658
|
+
const Task = taskSchema(framework);
|
|
659
|
+
ctx.client.registerMethod({
|
|
660
|
+
name: "getSettings",
|
|
661
|
+
params: z.strictObject({}),
|
|
662
|
+
result: SubagentSettingsSchema,
|
|
663
|
+
handle: () => settings.read()
|
|
664
|
+
});
|
|
665
|
+
ctx.client.registerMethod({
|
|
666
|
+
name: "setSettings",
|
|
667
|
+
params: SubagentSettingsSchema,
|
|
668
|
+
result: SubagentSettingsSchema,
|
|
669
|
+
handle: (input) => settings.write(input)
|
|
670
|
+
});
|
|
671
|
+
ctx.client.registerMethod({
|
|
672
|
+
name: "spawn",
|
|
673
|
+
params: SpawnSubagentSchema.extend({
|
|
674
|
+
parentSessionId: z.string(),
|
|
675
|
+
requestKey: z.string().min(1)
|
|
676
|
+
}),
|
|
677
|
+
result: Task,
|
|
678
|
+
handle: ({ parentSessionId, requestKey, ...input }) => manager.spawn({
|
|
679
|
+
sessionId: parentSessionId,
|
|
680
|
+
requestKey,
|
|
681
|
+
owner: "user"
|
|
682
|
+
}, input)
|
|
683
|
+
});
|
|
684
|
+
ctx.client.registerMethod({
|
|
685
|
+
name: "send",
|
|
686
|
+
params: z.strictObject({
|
|
687
|
+
parentSessionId: z.string(),
|
|
688
|
+
childSessionId: z.string(),
|
|
689
|
+
task: z.string().min(1),
|
|
690
|
+
requestKey: z.string().min(1)
|
|
691
|
+
}),
|
|
692
|
+
result: Task,
|
|
693
|
+
handle: ({ parentSessionId, childSessionId, task, requestKey }) => manager.send({
|
|
694
|
+
sessionId: parentSessionId,
|
|
695
|
+
requestKey,
|
|
696
|
+
owner: "user"
|
|
697
|
+
}, childSessionId, task)
|
|
698
|
+
});
|
|
699
|
+
ctx.client.registerMethod({
|
|
700
|
+
name: "list",
|
|
701
|
+
params: z.strictObject({ parentSessionId: z.string() }),
|
|
702
|
+
result: z.array(Task),
|
|
703
|
+
handle: ({ parentSessionId }) => [...manager.list(parentSessionId)]
|
|
704
|
+
});
|
|
705
|
+
ctx.client.registerMethod({
|
|
706
|
+
name: "get",
|
|
707
|
+
params: z.strictObject({
|
|
708
|
+
parentSessionId: z.string(),
|
|
709
|
+
childSessionId: z.string(),
|
|
710
|
+
taskId: z.string().optional()
|
|
711
|
+
}),
|
|
712
|
+
result: Task,
|
|
713
|
+
handle({ parentSessionId, childSessionId, taskId }) {
|
|
714
|
+
const task = manager.list(parentSessionId).filter((one) => one.childSessionId === childSessionId && (taskId === void 0 || one.taskId === taskId)).at(-1);
|
|
715
|
+
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
716
|
+
return task;
|
|
717
|
+
}
|
|
718
|
+
});
|
|
719
|
+
ctx.client.registerMethod({
|
|
720
|
+
name: "stop",
|
|
721
|
+
params: z.strictObject({
|
|
722
|
+
parentSessionId: z.string(),
|
|
723
|
+
childSessionId: z.string(),
|
|
724
|
+
scope: z.enum(["task", "subtree"]),
|
|
725
|
+
taskId: z.string().optional()
|
|
726
|
+
}),
|
|
727
|
+
result: z.strictObject({}),
|
|
728
|
+
async handle({ parentSessionId, childSessionId, scope, taskId }) {
|
|
729
|
+
await manager.stop(parentSessionId, childSessionId, scope, taskId);
|
|
730
|
+
return {};
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
//#endregion
|
|
735
|
+
//#region src/runtime/service.ts
|
|
736
|
+
/** Binds trusted tool identities and preserves bounded wait semantics. */
|
|
737
|
+
function subagentService(ctx, manager) {
|
|
738
|
+
const caller = (call) => {
|
|
739
|
+
ctx.signal.throwIfAborted();
|
|
740
|
+
call.signal.throwIfAborted();
|
|
741
|
+
return {
|
|
742
|
+
sessionId: call.sessionId,
|
|
743
|
+
owner: ctx.pluginName,
|
|
744
|
+
requestKey: `${call.turn}:${call.toolCallId}`
|
|
745
|
+
};
|
|
746
|
+
};
|
|
747
|
+
return {
|
|
748
|
+
spawn: (call, input) => manager.spawn(caller(call), input),
|
|
749
|
+
send: (call, child, task) => manager.send(caller(call), child, task),
|
|
750
|
+
list: (call) => {
|
|
751
|
+
caller(call);
|
|
752
|
+
return manager.list(call.sessionId);
|
|
753
|
+
},
|
|
754
|
+
get(call, child, taskId) {
|
|
755
|
+
caller(call);
|
|
756
|
+
const task = manager.list(call.sessionId).filter((row) => row.childSessionId === child && (taskId === void 0 || row.taskId === taskId)).at(-1);
|
|
757
|
+
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
758
|
+
return task;
|
|
759
|
+
},
|
|
760
|
+
async wait(call, taskId, timeoutMs) {
|
|
761
|
+
caller(call);
|
|
762
|
+
const until = Date.now() + Math.min(6e4, Math.max(0, timeoutMs));
|
|
763
|
+
for (;;) {
|
|
764
|
+
ctx.signal.throwIfAborted();
|
|
765
|
+
const task = manager.list(call.sessionId).find((row) => row.taskId === taskId);
|
|
766
|
+
if (!task) throw new Error("not-found: task is absent or inaccessible");
|
|
767
|
+
if (task.state === "finished" || Date.now() >= until || call.signal.aborted) return task;
|
|
768
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(50, until - Date.now())));
|
|
769
|
+
}
|
|
770
|
+
},
|
|
771
|
+
stop: (call, child, scope, taskId) => {
|
|
772
|
+
caller(call);
|
|
773
|
+
return manager.stop(call.sessionId, child, scope, taskId);
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
//#endregion
|
|
778
|
+
//#region src/subagents/index.ts
|
|
779
|
+
/** Registers five independent controls over the host's native task service. */
|
|
780
|
+
function registerSubagentTools(ctx, register, service = ctx.services.get("subagents")) {
|
|
781
|
+
register({
|
|
782
|
+
name: "subagent_spawn",
|
|
783
|
+
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); providerId, model and params override its default model. Returns immediately; the child does not see this conversation.",
|
|
784
|
+
inputSchema: z.object({
|
|
785
|
+
task: z.string().min(1),
|
|
786
|
+
agent: z.string().optional(),
|
|
787
|
+
providerId: z.string().optional(),
|
|
788
|
+
model: z.string().optional(),
|
|
789
|
+
params: z.record(z.string(), z.unknown()).optional()
|
|
790
|
+
}).strict(),
|
|
791
|
+
async execute(input, call) {
|
|
792
|
+
return { content: JSON.stringify(await service.spawn(call, input)) };
|
|
793
|
+
}
|
|
794
|
+
});
|
|
795
|
+
register({
|
|
796
|
+
name: "subagent_send",
|
|
797
|
+
description: "Append a task to an existing descendant. Busy children queue FIFO; an idle child must reacquire capacity.",
|
|
798
|
+
inputSchema: z.object({
|
|
799
|
+
childSessionId: z.string(),
|
|
800
|
+
task: z.string().min(1)
|
|
801
|
+
}).strict(),
|
|
802
|
+
async execute(input, call) {
|
|
803
|
+
return { content: JSON.stringify(service.send(call, input.childSessionId, input.task)) };
|
|
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({
|
|
810
|
+
childSessionId: z.string(),
|
|
811
|
+
taskId: z.string().optional(),
|
|
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
|
+
});
|
|
819
|
+
}),
|
|
820
|
+
async execute(input, call) {
|
|
821
|
+
const task = service.get(call, input.childSessionId, input.taskId);
|
|
822
|
+
if (!input.waitMs || input.taskId === void 0 || task.state === "finished") return { content: JSON.stringify(task) };
|
|
823
|
+
return { content: JSON.stringify(await service.wait(call, input.taskId, input.waitMs)) };
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
register({
|
|
827
|
+
name: "subagent_list",
|
|
828
|
+
description: "List descendant tasks. Results do not include unrelated sessions.",
|
|
829
|
+
inputSchema: z.object({
|
|
830
|
+
offset: z.number().int().nonnegative().default(0),
|
|
831
|
+
limit: z.number().int().min(1).max(200).default(50)
|
|
832
|
+
}).strict(),
|
|
833
|
+
async execute(input, call) {
|
|
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
|
+
}) };
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
register({
|
|
842
|
+
name: "subagent_stop",
|
|
843
|
+
description: "Stop one named task, leaving its children running, or stop the entire native subtree. Existing file edits are not undone.",
|
|
844
|
+
inputSchema: z.object({
|
|
845
|
+
childSessionId: z.string(),
|
|
846
|
+
scope: z.enum(["task", "subtree"]),
|
|
847
|
+
taskId: z.string().optional()
|
|
848
|
+
}).strict(),
|
|
849
|
+
async execute(input, call) {
|
|
850
|
+
await service.stop(call, input.childSessionId, input.scope, input.taskId);
|
|
851
|
+
return { content: "Stopped requested native work." };
|
|
852
|
+
}
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/tool-names.ts
|
|
857
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
858
|
+
const TOOL_NAMES = [
|
|
859
|
+
"subagent_spawn",
|
|
860
|
+
"subagent_send",
|
|
861
|
+
"subagent_get",
|
|
862
|
+
"subagent_list",
|
|
863
|
+
"subagent_stop"
|
|
864
|
+
];
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/index.ts
|
|
867
|
+
/**
|
|
868
|
+
* This plugin's slice of `config.json`.
|
|
869
|
+
*
|
|
870
|
+
* `disabled` turns one tool off while the rest of the package stays on —
|
|
871
|
+
* `enabled: false` on the declaration turns off every one of them. Strict and
|
|
872
|
+
* enumerated: a misspelled tool name is a load failure naming the field, not
|
|
873
|
+
* a line that quietly does nothing.
|
|
874
|
+
*/
|
|
875
|
+
const SubagentConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
|
|
876
|
+
const subagentPlugin = {
|
|
877
|
+
name: "@eum-agent/agent-delegation",
|
|
878
|
+
requires: [
|
|
879
|
+
"agent-runs",
|
|
880
|
+
"agent-execution",
|
|
881
|
+
"agent-sessions",
|
|
882
|
+
"agent-data-schemas",
|
|
883
|
+
"model-dispatch-policy"
|
|
884
|
+
],
|
|
885
|
+
provides: [
|
|
886
|
+
"subagents",
|
|
887
|
+
"session-admission",
|
|
888
|
+
"session-delegation-observer"
|
|
889
|
+
],
|
|
890
|
+
configSchema: SubagentConfig,
|
|
891
|
+
apply(ctx, config) {
|
|
892
|
+
const { execution, framework, catalog, settings, manager } = createSubagentCapability(ctx);
|
|
893
|
+
const service = subagentService(ctx, manager);
|
|
894
|
+
ctx.services.provide("subagents", service);
|
|
895
|
+
ctx.services.provide("session-admission", {
|
|
896
|
+
accept: manager.accept,
|
|
897
|
+
relation: catalog.relation
|
|
898
|
+
});
|
|
899
|
+
ctx.onDispose(() => manager.shutdown());
|
|
900
|
+
registerSubagentMethods(ctx, manager, framework, settings);
|
|
901
|
+
ctx.context.contribute({
|
|
902
|
+
id: "subagent-catalog",
|
|
903
|
+
slot: "system",
|
|
904
|
+
placement: {
|
|
905
|
+
chapter: "capabilities",
|
|
906
|
+
order: 10,
|
|
907
|
+
category: "agents",
|
|
908
|
+
requires: ["subagent_spawn"]
|
|
909
|
+
},
|
|
910
|
+
async contribute() {
|
|
911
|
+
const agents = execution.agents();
|
|
912
|
+
return agents.length ? { system: ["Agents you can delegate to (subagent_spawn with agent):\n" + agents.map((agent) => {
|
|
913
|
+
const line = agent.description.replace(/\s+/g, " ").trim();
|
|
914
|
+
return `- ${agent.agentId} — ${agent.name}: ${line || "no description"}`;
|
|
915
|
+
}).join("\n")] } : {};
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
const disabled = new Set(config.disabled);
|
|
919
|
+
const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
|
|
920
|
+
registerSubagentTools(ctx, register, service);
|
|
921
|
+
ctx.tools.guide(GUIDANCE);
|
|
922
|
+
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
923
|
+
if (existsSync(ui)) ctx.client.registerUi({ module: ui });
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
//#endregion
|
|
927
|
+
export { SubagentConfig, TOOL_NAMES, subagentPlugin as default, subagentPlugin, registerSubagentTools };
|