@eum-agent/agent-delegation 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +1153 -155
  2. package/package.json +4 -4
  3. package/ui/ui.js +234 -196
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "en-US": "Subagent Delegation",
5
5
  "zh-CN": "子智能体协作"
6
6
  },
7
- "version": "1.0.0",
7
+ "version": "1.0.1",
8
8
  "type": "module",
9
9
  "description": "Delegated agent execution and subagent management",
10
10
  "license": "MIT",
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "devDependencies": {
24
24
  "@eum-agent/container": "1.0.0",
25
- "@eum-agent/plugin": "1.0.0",
25
+ "@eum-agent/plugin": "1.0.1",
26
26
  "@types/react": "^19.2.18",
27
27
  "@types/react-dom": "^19.2.5",
28
28
  "vite": "^8.2.2",
@@ -38,11 +38,11 @@
38
38
  "zh-CN": "委派智能体执行任务与子智能体管理"
39
39
  },
40
40
  "dependencies": {
41
- "@eum-agent/llm-management": "1.0.0"
41
+ "@eum-agent/llm-management": "1.0.1"
42
42
  },
43
43
  "kind": "extension",
44
44
  "foundationDependencies": {
45
- "@eum-agent/storage-sqlite": "1.0.0"
45
+ "@eum-agent/storage-sqlite": "1.0.1"
46
46
  }
47
47
  },
48
48
  "scripts": {
package/ui/ui.js CHANGED
@@ -1,6 +1,140 @@
1
1
  import { Button, Field, FormFailure, InputNumber, ReadFailure, agentNamed, i18next, localeLeaves, pendingOf, useAgents, useGatewayAction, useInbox, useSessions, useToast, useTranslation } from "@eum-agent/host/framework";
2
2
  import React, { useEffect, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ //#region ui-src/components/settings/subagents.tsx
5
+ /** Delegation limits edited and saved independently inside global running settings. */
6
+ function DelegationSettingsSection({ ctx, registerGuard }) {
7
+ const { t } = useTranslation();
8
+ const toast = useToast();
9
+ const [online, setOnline] = useState(ctx.gateway.connection.status === "online");
10
+ useEffect(() => ctx.gateway.watchConnection((state) => setOnline(state.status === "online")), [ctx]);
11
+ const [data, setData] = useState(null);
12
+ const [error, setError] = useState(null);
13
+ const [pending, setPending] = useState(true);
14
+ const reading = useRef(false);
15
+ const reload = () => {
16
+ if (reading.current) return;
17
+ reading.current = true;
18
+ setPending(true);
19
+ setError(null);
20
+ ctx.invoke("getSettings", {}).then(setData).catch((error) => setError(error instanceof Error ? error.message : String(error))).finally(() => {
21
+ reading.current = false;
22
+ setPending(false);
23
+ });
24
+ };
25
+ useEffect(reload, [ctx]);
26
+ const read = {
27
+ data,
28
+ error,
29
+ reload
30
+ };
31
+ const save = useGatewayAction();
32
+ const [draft, setDraft] = useState(null);
33
+ const settings = draft ?? read.data;
34
+ const guardState = useRef({
35
+ dirty: false,
36
+ pending: false
37
+ });
38
+ guardState.current = {
39
+ dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(read.data),
40
+ pending: save.pending
41
+ };
42
+ useEffect(() => {
43
+ registerGuard(() => guardState.current);
44
+ return () => registerGuard(null);
45
+ }, [registerGuard]);
46
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ReadFailure, {
47
+ reason: read.error,
48
+ pending,
49
+ onRetry: read.reload
50
+ }), settings && /* @__PURE__ */ jsxs("form", {
51
+ className: "flex flex-col gap-6",
52
+ onSubmit: (event) => {
53
+ event.preventDefault();
54
+ if (save.pending) return;
55
+ save.run(() => ctx.invoke("setSettings", settings)).then((done) => {
56
+ if (!done.ok) return;
57
+ toast.add({
58
+ tone: "success",
59
+ title: t("delegation.saved")
60
+ });
61
+ setData(settings);
62
+ setDraft(null);
63
+ });
64
+ },
65
+ children: [
66
+ /* @__PURE__ */ jsx("p", {
67
+ className: "text-xs text-muted-foreground",
68
+ children: t("delegation.limitsHelp")
69
+ }),
70
+ ["maxConcurrent", "maxDepth"].map((key) => /* @__PURE__ */ jsx(Field, {
71
+ label: t(key === "maxConcurrent" ? "delegation.concurrency" : "delegation.depth"),
72
+ help: t(key === "maxConcurrent" ? "delegation.concurrencyHelp" : "delegation.depthHelp"),
73
+ required: true,
74
+ inline: true,
75
+ className: "delegation-limit-field",
76
+ children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
77
+ ...binding,
78
+ label: t(key === "maxConcurrent" ? "delegation.concurrency" : "delegation.depth"),
79
+ incrementLabel: t("common.increase"),
80
+ decrementLabel: t("common.decrease"),
81
+ min: 1,
82
+ step: 1,
83
+ required: true,
84
+ disabled: save.pending,
85
+ value: settings[key] || null,
86
+ onValueChange: (value) => setDraft({
87
+ ...settings,
88
+ [key]: value ?? 0
89
+ })
90
+ })
91
+ }, key)),
92
+ /* @__PURE__ */ jsx(FormFailure, { reason: save.error }),
93
+ /* @__PURE__ */ jsx("div", {
94
+ className: "flex justify-end gap-2",
95
+ children: /* @__PURE__ */ jsx(Button, {
96
+ variant: "primary",
97
+ type: "submit",
98
+ loading: save.pending,
99
+ disabled: pending || !Number.isSafeInteger(settings.maxConcurrent) || settings.maxConcurrent < 1 || !Number.isSafeInteger(settings.maxDepth) || settings.maxDepth < 1 || !online,
100
+ children: t("common.save")
101
+ })
102
+ })
103
+ ]
104
+ })] });
105
+ }
106
+ //#endregion
107
+ //#region ui-src/lib/subagents/task.ts
108
+ /** The two tools whose answer is the task they handed a child. */
109
+ var DISPATCHING = /* @__PURE__ */ new Set(["subagent_spawn", "subagent_send"]);
110
+ /** Accepted children started by this call, preserving successful collection order. */
111
+ function dispatchedBy(name, output) {
112
+ if (!DISPATCHING.has(name) || output === void 0) return [];
113
+ try {
114
+ const parsed = JSON.parse(output);
115
+ if (!parsed || typeof parsed !== "object") return [];
116
+ return (name === "subagent_spawn" ? "results" in parsed && Array.isArray(parsed.results) ? parsed.results.flatMap((item) => item && typeof item === "object" && "ok" in item && item.ok === true && "value" in item ? [item.value] : []) : [] : [parsed]).flatMap((value) => value && typeof value === "object" && "taskId" in value && typeof value.taskId === "string" && "childSessionId" in value && typeof value.childSessionId === "string" ? [{
117
+ taskId: value.taskId,
118
+ childSessionId: value.childSessionId
119
+ }] : []);
120
+ } catch {
121
+ return [];
122
+ }
123
+ }
124
+ /** A task's STATE column: at work, waiting for a person, or how it ended. */
125
+ function taskLineState(task) {
126
+ if (task.state === "awaiting-human") return "waiting";
127
+ if (task.state !== "finished") return "running";
128
+ if (task.outcome?.kind === "failed") return "failed";
129
+ return task.outcome?.kind === "interrupted" ? "stopped" : "success";
130
+ }
131
+ /** The catalogue key naming where a task stands. */
132
+ function taskStateKey(task) {
133
+ if (task.state !== "finished") return `delegation.${task.state}`;
134
+ if (task.outcome?.kind === "failed") return "sessionState.failed";
135
+ return task.outcome?.kind === "interrupted" ? "sessionState.halted" : "sessionState.done";
136
+ }
137
+ //#endregion
4
138
  //#region ui-src/locales/en-US.ts
5
139
  /** Text owned by this browser capability. */
6
140
  var catalogue$1 = { delegation: {
@@ -149,140 +283,6 @@ function registerMetadata(ctx) {
149
283
  });
150
284
  }
151
285
  //#endregion
152
- //#region ui-src/components/settings/subagents.tsx
153
- /** Delegation limits edited and saved independently inside global running settings. */
154
- function DelegationSettingsSection({ ctx, registerGuard }) {
155
- const { t } = useTranslation();
156
- const toast = useToast();
157
- const [online, setOnline] = useState(ctx.gateway.connection.status === "online");
158
- useEffect(() => ctx.gateway.watchConnection((state) => setOnline(state.status === "online")), [ctx]);
159
- const [data, setData] = useState(null);
160
- const [error, setError] = useState(null);
161
- const [pending, setPending] = useState(true);
162
- const reading = useRef(false);
163
- const reload = () => {
164
- if (reading.current) return;
165
- reading.current = true;
166
- setPending(true);
167
- setError(null);
168
- ctx.invoke("getSettings", {}).then(setData).catch((error) => setError(error instanceof Error ? error.message : String(error))).finally(() => {
169
- reading.current = false;
170
- setPending(false);
171
- });
172
- };
173
- useEffect(reload, [ctx]);
174
- const read = {
175
- data,
176
- error,
177
- reload
178
- };
179
- const save = useGatewayAction();
180
- const [draft, setDraft] = useState(null);
181
- const settings = draft ?? read.data;
182
- const guardState = useRef({
183
- dirty: false,
184
- pending: false
185
- });
186
- guardState.current = {
187
- dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(read.data),
188
- pending: save.pending
189
- };
190
- useEffect(() => {
191
- registerGuard(() => guardState.current);
192
- return () => registerGuard(null);
193
- }, [registerGuard]);
194
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ReadFailure, {
195
- reason: read.error,
196
- pending,
197
- onRetry: read.reload
198
- }), settings && /* @__PURE__ */ jsxs("form", {
199
- className: "flex flex-col gap-6",
200
- onSubmit: (event) => {
201
- event.preventDefault();
202
- if (save.pending) return;
203
- save.run(() => ctx.invoke("setSettings", settings)).then((done) => {
204
- if (!done.ok) return;
205
- toast.add({
206
- tone: "success",
207
- title: t("delegation.saved")
208
- });
209
- setData(settings);
210
- setDraft(null);
211
- });
212
- },
213
- children: [
214
- /* @__PURE__ */ jsx("p", {
215
- className: "text-xs text-muted-foreground",
216
- children: t("delegation.limitsHelp")
217
- }),
218
- ["maxConcurrent", "maxDepth"].map((key) => /* @__PURE__ */ jsx(Field, {
219
- label: t(key === "maxConcurrent" ? "delegation.concurrency" : "delegation.depth"),
220
- help: t(key === "maxConcurrent" ? "delegation.concurrencyHelp" : "delegation.depthHelp"),
221
- required: true,
222
- inline: true,
223
- className: "delegation-limit-field",
224
- children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
225
- ...binding,
226
- label: t(key === "maxConcurrent" ? "delegation.concurrency" : "delegation.depth"),
227
- incrementLabel: t("common.increase"),
228
- decrementLabel: t("common.decrease"),
229
- min: 1,
230
- step: 1,
231
- required: true,
232
- disabled: save.pending,
233
- value: settings[key] || null,
234
- onValueChange: (value) => setDraft({
235
- ...settings,
236
- [key]: value ?? 0
237
- })
238
- })
239
- }, key)),
240
- /* @__PURE__ */ jsx(FormFailure, { reason: save.error }),
241
- /* @__PURE__ */ jsx("div", {
242
- className: "flex justify-end gap-2",
243
- children: /* @__PURE__ */ jsx(Button, {
244
- variant: "primary",
245
- type: "submit",
246
- loading: save.pending,
247
- disabled: pending || !Number.isSafeInteger(settings.maxConcurrent) || settings.maxConcurrent < 1 || !Number.isSafeInteger(settings.maxDepth) || settings.maxDepth < 1 || !online,
248
- children: t("common.save")
249
- })
250
- })
251
- ]
252
- })] });
253
- }
254
- //#endregion
255
- //#region ui-src/lib/subagents/task.ts
256
- /** The two tools whose answer is the task they handed a child. */
257
- var DISPATCHING = /* @__PURE__ */ new Set(["subagent_spawn", "subagent_send"]);
258
- /** The task a finished call started: `subagent_spawn` and `subagent_send`
259
- * answer with the accepted task as JSON. Anything else starts none. */
260
- function dispatchedBy(name, output) {
261
- if (!DISPATCHING.has(name) || output === void 0) return null;
262
- try {
263
- const task = JSON.parse(output);
264
- return typeof task.taskId === "string" && typeof task.childSessionId === "string" ? {
265
- taskId: task.taskId,
266
- childSessionId: task.childSessionId
267
- } : null;
268
- } catch {
269
- return null;
270
- }
271
- }
272
- /** A task's STATE column: at work, waiting for a person, or how it ended. */
273
- function taskLineState(task) {
274
- if (task.state === "awaiting-human") return "waiting";
275
- if (task.state !== "finished") return "running";
276
- if (task.outcome?.kind === "failed") return "failed";
277
- return task.outcome?.kind === "interrupted" ? "stopped" : "success";
278
- }
279
- /** The catalogue key naming where a task stands. */
280
- function taskStateKey(task) {
281
- if (task.state !== "finished") return `delegation.${task.state}`;
282
- if (task.outcome?.kind === "failed") return "sessionState.failed";
283
- return task.outcome?.kind === "interrupted" ? "sessionState.halted" : "sessionState.done";
284
- }
285
- //#endregion
286
286
  //#region ../../../node_modules/.pnpm/zustand@5.0.15_@types+react@19.2.18_react@19.2.8_use-sync-external-store@1.7.0_react@19.2.8_/node_modules/zustand/esm/vanilla.mjs
287
287
  var createStoreImpl = (createState) => {
288
288
  let state;
@@ -352,32 +352,68 @@ var useSubagents = create()((set) => ({
352
352
  }));
353
353
  /** Reads each observed parent once and refreshes its retained view after reconnect. */
354
354
  function nativeTaskReader(ctx) {
355
- const reading = /* @__PURE__ */ new Set();
356
355
  const observed = /* @__PURE__ */ new Set();
357
- const read = (sessionId) => {
358
- if (reading.has(sessionId) || ctx.signal.aborted) return;
359
- reading.add(sessionId);
360
- ctx.invoke("list", { parentSessionId: sessionId }).then((rows) => {
361
- if (!ctx.signal.aborted) useSubagents.getState().merge(sessionId, rows);
362
- }).catch(() => {}).finally(() => reading.delete(sessionId));
356
+ const pending = /* @__PURE__ */ new Set();
357
+ const reading = /* @__PURE__ */ new Map();
358
+ let generation = 0;
359
+ let scheduled = false;
360
+ let online = ctx.host.get().connection === "online";
361
+ const flush = () => {
362
+ scheduled = false;
363
+ if (ctx.signal.aborted || !online) return;
364
+ const available = [...pending].filter((id) => !reading.has(id));
365
+ for (let offset = 0; offset < available.length; offset += 31) {
366
+ const parentSessionIds = available.slice(offset, offset + 31);
367
+ const token = Symbol();
368
+ const at = generation;
369
+ for (const id of parentSessionIds) {
370
+ pending.delete(id);
371
+ reading.set(id, token);
372
+ }
373
+ ctx.invoke("listByParents", { parentSessionIds }).then(({ results }) => {
374
+ if (ctx.signal.aborted || generation !== at || results.length !== parentSessionIds.length) return;
375
+ for (const [index, item] of results.entries()) if (item.index !== index || item.target !== parentSessionIds[index]) return;
376
+ for (const item of results) if (item.ok) useSubagents.getState().merge(item.target, item.value);
377
+ }).catch(() => {}).finally(() => {
378
+ for (const id of parentSessionIds) if (reading.get(id) === token) reading.delete(id);
379
+ if (pending.size) schedule();
380
+ });
381
+ }
382
+ };
383
+ const schedule = () => {
384
+ if (scheduled || ctx.signal.aborted) return;
385
+ scheduled = true;
386
+ queueMicrotask(flush);
387
+ };
388
+ const refresh = () => {
389
+ for (const id of observed) pending.add(id);
390
+ schedule();
363
391
  };
364
392
  ctx.on("changed", ({ sessionId, payload }) => {
365
- if (sessionId !== void 0) useSubagents.getState().merge(sessionId, [payload.task]);
393
+ if (ctx.signal.aborted || sessionId === void 0 || !observed.has(sessionId)) return;
394
+ const changed = payload;
395
+ if (changed.invalidated) refresh();
396
+ else useSubagents.getState().merge(sessionId, changed.entries.map((entry) => entry.task));
366
397
  });
367
- let online = ctx.host.get().connection === "online";
368
398
  const off = ctx.host.subscribe(() => {
369
399
  const next = ctx.host.get().connection === "online";
370
- if (next && !online) for (const sessionId of observed) read(sessionId);
400
+ if (next !== online) {
401
+ generation++;
402
+ reading.clear();
403
+ }
404
+ if (next && !online) refresh();
371
405
  online = next;
372
406
  });
373
407
  ctx.signal.addEventListener("abort", () => {
374
408
  off();
409
+ generation++;
375
410
  useSubagents.getState().clear();
376
411
  }, { once: true });
377
412
  return (sessionId) => {
378
413
  if (observed.has(sessionId)) return;
379
414
  observed.add(sessionId);
380
- queueMicrotask(() => read(sessionId));
415
+ pending.add(sessionId);
416
+ schedule();
381
417
  };
382
418
  }
383
419
  //#endregion
@@ -418,59 +454,61 @@ var register = (ctx) => {
418
454
  subscribe,
419
455
  describe: ({ call, result, sessionId, openRelated }) => {
420
456
  if (sessionId === void 0 || openRelated === void 0) return void 0;
421
- const ref = dispatchedBy(call.name, result?.content);
422
- if (!ref) return void 0;
457
+ const refs = dispatchedBy(call.name, result?.content);
458
+ if (refs.length === 0) return void 0;
423
459
  observe(sessionId);
424
- const task = useSubagents.getState().bySession[sessionId]?.[ref.taskId];
425
- if (!task) return void 0;
426
- const agent = agentNamed(useAgents.getState(), task.agent) ?? task.agent;
427
- const child = {
428
- childSessionId: task.childSessionId,
429
- parentSessionId: sessionId,
430
- agent,
431
- task: task.input
432
- };
433
- const sessions = useSessions.getState().sessions;
434
- const under = (id) => {
435
- const seen = /* @__PURE__ */ new Set();
436
- let at = id;
437
- while (at !== void 0 && !seen.has(at)) {
438
- if (at === task.childSessionId) return true;
439
- seen.add(at);
440
- at = sessions.find((one) => one.sessionId === at)?.parentSessionId;
441
- }
442
- return false;
443
- };
444
- const pending = pendingOf(useInbox.getState().items).filter((one) => under(one.sessionId));
445
- const request = ctx.services.get("chat:pending-request");
446
- const state = taskLineState(task);
447
- return { relatedSession: {
448
- taskId: task.taskId,
449
- agent,
450
- title: task.input.replace(/\s+/g, " ").slice(0, 80),
451
- groupLabel: i18next.t("transcript.run.subagents"),
452
- state,
453
- stateLabel: i18next.t(taskStateKey(task)),
454
- onOpen: () => openRelated(child),
455
- ops: [...task.state === "finished" ? [] : [{
456
- icon: "stop",
457
- label: i18next.t("delegation.stopTask"),
458
- disabled: task.state === "stopping" || ctx.host.get().connection !== "online",
459
- onClick: async () => {
460
- await ctx.invoke("stop", {
461
- parentSessionId: sessionId,
462
- childSessionId: task.childSessionId,
463
- scope: "task",
464
- taskId: task.taskId
465
- });
460
+ return { relatedSessions: refs.flatMap((ref) => {
461
+ const task = useSubagents.getState().bySession[sessionId]?.[ref.taskId];
462
+ if (!task) return [];
463
+ const agent = agentNamed(useAgents.getState(), task.agent) ?? task.agent;
464
+ const child = {
465
+ childSessionId: task.childSessionId,
466
+ parentSessionId: sessionId,
467
+ agent,
468
+ task: task.input
469
+ };
470
+ const sessions = useSessions.getState().sessions;
471
+ const under = (id) => {
472
+ const seen = /* @__PURE__ */ new Set();
473
+ let at = id;
474
+ while (at !== void 0 && !seen.has(at)) {
475
+ if (at === task.childSessionId) return true;
476
+ seen.add(at);
477
+ at = sessions.find((one) => one.sessionId === at)?.parentSessionId;
466
478
  }
467
- }], {
468
- icon: "open",
469
- label: i18next.t("delegation.viewSession"),
470
- onClick: () => openRelated(child)
471
- }],
472
- ...request === void 0 || pending.length === 0 ? {} : { requests: pending.map((one) => /* @__PURE__ */ jsx(request.component, { pending: one }, one.request.requestId)) }
473
- } };
479
+ return false;
480
+ };
481
+ const pending = pendingOf(useInbox.getState().items).filter((one) => under(one.sessionId));
482
+ const request = ctx.services.get("chat:pending-request");
483
+ const state = taskLineState(task);
484
+ return [{
485
+ taskId: task.taskId,
486
+ agent,
487
+ title: task.input.replace(/\s+/g, " ").slice(0, 80),
488
+ groupLabel: i18next.t("transcript.run.subagents"),
489
+ state,
490
+ stateLabel: i18next.t(taskStateKey(task)),
491
+ onOpen: () => openRelated(child),
492
+ ops: [...task.state === "finished" ? [] : [{
493
+ icon: "stop",
494
+ label: i18next.t("delegation.stopTask"),
495
+ disabled: task.state === "stopping" || ctx.host.get().connection !== "online",
496
+ onClick: async () => {
497
+ await ctx.invoke("stop", {
498
+ parentSessionId: sessionId,
499
+ childSessionId: task.childSessionId,
500
+ scope: "task",
501
+ taskId: task.taskId
502
+ });
503
+ }
504
+ }], {
505
+ icon: "open",
506
+ label: i18next.t("delegation.viewSession"),
507
+ onClick: () => openRelated(child)
508
+ }],
509
+ ...request === void 0 || pending.length === 0 ? {} : { requests: pending.map((one) => /* @__PURE__ */ jsx(request.component, { pending: one }, one.request.requestId)) }
510
+ }];
511
+ }) };
474
512
  }
475
513
  });
476
514
  };