dsh-multigameassistant 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-multigameassistant 2.2.0
1
+ # dsh-multigameassistant 2.2.2
2
2
  # dsh-multigameassistant: the app's plugins (packages/bundle/cordis.patch.yml, each @adg/<plugin> as dsh-multigameassistant/<plugin>)
3
3
  # sharing the dsh with the person's other chats, and the app's agent preset (dsh's standard one with the app's
4
4
  # tools and prompts, and compaction as 设置 → 对话压缩 says). No row of dsh is restated.
package/lib/analyzer.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  discoverMcp,
4
4
  discoverSkills,
5
5
  mcpEndpoints
6
- } from "./chunk-J4QJC6UZ.js";
6
+ } from "./chunk-CCYE6H2F.js";
7
7
  import {
8
8
  probeProject
9
9
  } from "./chunk-B4UT4NYH.js";
@@ -15,16 +15,16 @@ import {
15
15
  parseManifest,
16
16
  require_dist,
17
17
  stripJsonc
18
- } from "./chunk-26JIEF6M.js";
19
- import "./chunk-I4NHWXKH.js";
20
- import "./chunk-KTOQFJ7R.js";
21
- import "./chunk-ICJLH3DP.js";
18
+ } from "./chunk-RGEGJH6R.js";
19
+ import "./chunk-6YPSKAQ5.js";
20
+ import "./chunk-DSWWQWQH.js";
21
+ import "./chunk-KMVQK5CI.js";
22
22
  import "./chunk-RESS7WVY.js";
23
23
  import {
24
24
  BUILTIN_PACK_VERSION,
25
25
  PACKS_CAPABILITY,
26
26
  ScriptId
27
- } from "./chunk-NEUZQ7TI.js";
27
+ } from "./chunk-LXHF6AKU.js";
28
28
  import {
29
29
  external_exports
30
30
  } from "./chunk-6DSSLS7I.js";
package/lib/browser.js CHANGED
@@ -189,11 +189,15 @@ ${v.url}
189
189
  },
190
190
  render: (_args, value) => {
191
191
  const v = value;
192
+ const media = v.images?.length ? `
193
+
194
+ \u9875\u9762\u914D\u56FE\u5019\u9009\uFF08\u4F9D\u6B21\u4E3A\u5206\u4EAB\u56FE\u3001\u6B63\u6587\u56FE\uFF09\uFF1A
195
+ ${v.images.join("\n")}` : "";
192
196
  return [{ type: "text", text: `\u6807\u7B7E\u9875 ${v.tab}\uFF1A${v.title}
193
197
  ${v.url}
194
198
 
195
199
  ${v.text}${v.truncated === void 0 ? "" : `
196
- \u2026\uFF08\u8FD8\u6709 ${v.truncated} \u5B57\uFF0C\u52A0\u5927 max_chars \u770B\u66F4\u591A\uFF09`}` }];
200
+ \u2026\uFF08\u8FD8\u6709 ${v.truncated} \u5B57\uFF0C\u52A0\u5927 max_chars \u770B\u66F4\u591A\uFF09`}${media}` }];
197
201
  }
198
202
  }),
199
203
  tool({
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __adgCreateRequire } from 'node:module'; import { dirname as __adgDirname } from 'node:path'; import { fileURLToPath as __adgFileURLToPath } from 'node:url'; const require = __adgCreateRequire(import.meta.url); const __filename = __adgFileURLToPath(import.meta.url); const __dirname = __adgDirname(__filename);
2
2
  import {
3
3
  convertRecord
4
- } from "./chunk-KTOQFJ7R.js";
4
+ } from "./chunk-DSWWQWQH.js";
5
5
  import {
6
6
  writeFileAtomic
7
7
  } from "./chunk-RESS7WVY.js";
@@ -20,7 +20,7 @@ import {
20
20
  threadMessage,
21
21
  threadReminder,
22
22
  threadsBetween
23
- } from "./chunk-NEUZQ7TI.js";
23
+ } from "./chunk-LXHF6AKU.js";
24
24
  import {
25
25
  external_exports
26
26
  } from "./chunk-6DSSLS7I.js";
@@ -109,7 +109,7 @@ function replyPlain(reply) {
109
109
  }
110
110
  function render(reply) {
111
111
  const summary = finalText(reply).trim() || "\uFF08agent \u6CA1\u6709\u56DE\u590D\u6587\u5B57\uFF09";
112
- return [reply.note, summary, reply.ended, tally(reply)].filter((p) => p !== void 0 && p !== "").join("\n\n");
112
+ return [reply.note, summary, reply.ended === summary ? void 0 : reply.ended, tally(reply)].filter((p) => p !== void 0 && p !== "").join("\n\n");
113
113
  }
114
114
  function tally(reply) {
115
115
  const steps = reply.blocks.flatMap((b) => b.kind === "steps" ? b.steps : []);
@@ -161,17 +161,19 @@ function createHandOffDesk(deps) {
161
161
  if ((item.messages ?? []).length >= MAX_THREAD_MESSAGES)
162
162
  throw new Error(`\u8FD9\u6761\u7EBF\u7D22\u7684\u6765\u56DE\u5DF2\u7ECF\u591F\u591A\u4E86\uFF08${MAX_THREAD_MESSAGES} \u6761\uFF09\uFF1A\u8FD8\u6709\u4E8B\u5C31\u91CD\u65B0\u4EA4\u4E00\u6B21`);
163
163
  const askerAgent = item.chain?.at(-2);
164
- const askerNow = askerAgent === void 0 ? item.fromSession : await deps.home(askerAgent);
165
- const workerNow = await deps.home(item.to);
164
+ const keepAsker = workingOn(item.fromSession) !== void 0 || item.isolated && !item.ownerSession;
165
+ const askerNow = keepAsker || askerAgent === void 0 ? item.fromSession : await deps.home(askerAgent);
166
+ const workerNow = item.ownerSession ?? (item.isolated ? item.toSession : await deps.home(item.to));
166
167
  const worker = fromSession === item.toSession || fromSession === workerNow;
167
168
  if (!worker && fromSession !== item.fromSession && fromSession !== askerNow)
168
169
  throw new Error(`\u7EBF\u7D22 ${id} \u4E0D\u662F\u4F60\u548C\u5BF9\u65B9\u4E4B\u95F4\u7684`);
169
170
  if (worker && askerNow === "")
170
171
  throw new Error(`\u8FD9\u4EF6\u4E8B\u662F${item.by}\u4EA4\u7684\uFF0C\u6CA1\u6709\u4EBA\u5728\u7B49\u6D88\u606F\uFF1A\u8981\u544A\u8BC9\u8C01\u5C31\u91CD\u65B0\u4EA4\u7ED9\u5B83`);
171
- const said = kind === "done" ? "update" : kind;
172
+ const said = kind === "done" && (!worker || item.state !== "failed") ? "update" : kind;
172
173
  await deps.record({ ...item, messages: [...item.messages ?? [], { from, kind: said, text, at: now() }] });
173
- const message2 = threadMessage({ from, kind: said, thread: id, title: item.title, text, reader: worker ? askerKind(askerAgent) : "worker", closed: true });
174
- void deps.converse(worker ? askerNow : workerNow, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS), [], { insert: true }).catch(() => {
174
+ const message2 = threadMessage({ from, kind: said === "done" ? "update" : said, thread: id, title: item.title, text: said === "done" ? `\u8865\u4EA4\u7ED3\u8BBA\uFF1A${text}` : text, reader: worker ? askerKind(askerAgent) : "worker", closed: true });
175
+ const recipient = worker ? askerNow : workerNow;
176
+ void deps.converse(recipient, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS), [], { insert: true }).catch(() => {
175
177
  });
176
178
  return "\u5DF2\u7ECF\u9001\u5230\u5BF9\u65B9\u90A3\u91CC\u4E86\u3002";
177
179
  };
@@ -284,15 +286,29 @@ function createHandOffDesk(deps) {
284
286
  parent.open++;
285
287
  parent.consulted.add(input.to.name);
286
288
  }
287
- const toSession = await deps.home(input.to.id, input.focus === void 0 ? {} : { focus: input.focus });
288
289
  const relay = input.relay === true;
289
- const fromSession = input.from?.sessionId ?? (relay ? await deps.home(MAIN) : "");
290
+ let work;
291
+ let toSession;
292
+ let fromSession;
293
+ try {
294
+ work = await deps.prepareWorker?.(input);
295
+ toSession = work?.id ?? await deps.home(input.to.id, input.focus === void 0 ? {} : { focus: input.focus });
296
+ input.onWorker?.(toSession);
297
+ fromSession = input.from?.sessionId ?? (relay ? await deps.home(MAIN) : "");
298
+ } catch (error) {
299
+ if (parent) {
300
+ parent.open--;
301
+ parent.wake();
302
+ }
303
+ throw error;
304
+ }
290
305
  const id = input.from?.callId ?? `h-${randomUUID2().slice(0, 8)}`;
291
306
  const chain = [...parent?.item.chain ?? (input.from?.agent === void 0 ? [] : [input.from.agent]), input.to.id];
292
307
  const item = {
293
308
  id,
294
309
  fromSession,
295
310
  ...input.from?.callId === void 0 ? {} : { callId: input.from.callId },
311
+ ...work ? { isolated: true, ownerSession: work.owner } : {},
296
312
  by: input.by,
297
313
  to: input.to.id,
298
314
  toSession,
@@ -335,65 +351,70 @@ function createHandOffDesk(deps) {
335
351
  });
336
352
  stopped.catch(() => {
337
353
  });
338
- await deps.record(item);
339
- const asker = input.from?.agent;
340
- const past = asker === void 0 || deps.threads === void 0 ? [] : pastBetween(deps.threads(), asker, input.to.id, (agent) => agent === input.to.id ? input.to.name : input.by);
341
- thread.turns.push(deps.converse(toSession, taskMessage(input.by, input.title, body, relay, id, { who: `\u300C${input.by}\u300D`, lines: past }), signal, input.images));
342
- let reply;
343
- let failure;
344
- let thrown;
345
354
  try {
346
- for (; ; ) {
347
- while (thread.turns.length > 0) {
348
- const turn = await thread.turns.shift();
349
- if (reply === void 0 || finalText(turn) !== "" || turn.ended !== void 0)
350
- reply = turn;
355
+ await deps.record(item);
356
+ const asker = input.from?.agent;
357
+ const past = asker === void 0 || deps.threads === void 0 ? [] : pastBetween(deps.threads(), asker, input.to.id, (agent) => agent === input.to.id ? input.to.name : input.by);
358
+ const instruction = taskMessage(input.by, input.title, body, relay, id, { who: `\u300C${input.by}\u300D`, lines: past });
359
+ thread.turns.push(work ? work.run(instruction, signal, input.images).then((text2) => ({ blocks: [{ kind: "text", text: text2 }], outcome: "completed" })) : deps.converse(toSession, instruction, signal, input.images));
360
+ let reply;
361
+ let failure;
362
+ let thrown;
363
+ try {
364
+ for (; ; ) {
365
+ while (thread.turns.length > 0) {
366
+ const turn = await thread.turns.shift();
367
+ if (reply === void 0 || finalText(turn) !== "" || turn.ended !== void 0)
368
+ reply = turn;
369
+ }
370
+ if (thread.conclusion !== void 0 && thread.open === 0)
371
+ break;
372
+ if (!thread.awaiting && thread.open === 0)
373
+ break;
374
+ await Promise.race([new Promise((resolve) => {
375
+ wake = resolve;
376
+ }), stopped]);
377
+ }
378
+ const said = finalText(reply);
379
+ if (thread.conclusion === void 0) {
380
+ if (reply.ended !== void 0)
381
+ failure = `${reply.ended.replace(/^(|)$/g, "")}${said === "" ? "" : `\u3002\u5B83\u6700\u540E\u8BF4\uFF1A${said}`}`;
382
+ else if (said === "")
383
+ failure = "\u5B83\u6CA1\u6709\u7559\u4E0B\u56DE\u590D";
351
384
  }
352
- if (thread.conclusion !== void 0 && thread.open === 0)
353
- break;
354
- if (!thread.awaiting && thread.open === 0)
355
- break;
356
- await Promise.race([new Promise((resolve) => {
357
- wake = resolve;
358
- }), stopped]);
385
+ } catch (error) {
386
+ thrown = error;
387
+ failure = error instanceof Error ? error.message : String(error);
359
388
  }
360
- const said = finalText(reply);
361
- if (thread.conclusion === void 0) {
362
- if (reply.ended !== void 0)
363
- failure = `${reply.ended.replace(/^(|)$/g, "")}${said === "" ? "" : `\u3002\u5B83\u6700\u540E\u8BF4\uFF1A${said}`}`;
364
- else if (said === "")
365
- failure = "\u5B83\u6CA1\u6709\u7559\u4E0B\u56DE\u590D";
389
+ live.delete(id);
390
+ const text = failure ?? thread.conclusion ?? finalText(reply);
391
+ await save(thread, { state: failure === void 0 ? "done" : "failed", reply: text, endedAt: now() });
392
+ if (relay && fromSession !== "") {
393
+ const message2 = relayMessage({
394
+ agent: input.to.name,
395
+ asker: input.by === input.from?.asker ? "\u4F60" : input.by,
396
+ title: input.title,
397
+ ok: failure === void 0,
398
+ reply: text,
399
+ ...thread.consulted.size === 0 ? {} : { consulted: [...thread.consulted] },
400
+ ...input.from?.agent === void 0 || input.from.agent === MAIN ? {} : { toLead: true }
401
+ });
402
+ const back = deps.converse(fromSession, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS));
403
+ if (parent !== void 0 && live.has(parent.item.id))
404
+ parent.turns.push(back.catch(() => ({ blocks: [] })));
405
+ void back.then((answer) => input.relayed?.(answer), () => {
406
+ });
407
+ }
408
+ if (thrown !== void 0)
409
+ throw thrown;
410
+ return reply;
411
+ } finally {
412
+ live.delete(id);
413
+ if (parent !== void 0) {
414
+ parent.open--;
415
+ parent.wake();
366
416
  }
367
- } catch (error) {
368
- thrown = error;
369
- failure = error instanceof Error ? error.message : String(error);
370
- }
371
- live.delete(id);
372
- const text = failure ?? thread.conclusion ?? finalText(reply);
373
- await save(thread, { state: failure === void 0 ? "done" : "failed", reply: text, endedAt: now() });
374
- if (relay && fromSession !== "") {
375
- const message2 = relayMessage({
376
- agent: input.to.name,
377
- asker: input.by === input.from?.asker ? "\u4F60" : input.by,
378
- title: input.title,
379
- ok: failure === void 0,
380
- reply: text,
381
- ...thread.consulted.size === 0 ? {} : { consulted: [...thread.consulted] },
382
- ...input.from?.agent === void 0 || input.from.agent === MAIN ? {} : { toLead: true }
383
- });
384
- const back = deps.converse(fromSession, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS));
385
- if (parent !== void 0 && live.has(parent.item.id))
386
- parent.turns.push(back.catch(() => ({ blocks: [] })));
387
- void back.then((answer) => input.relayed?.(answer), () => {
388
- });
389
- }
390
- if (parent !== void 0) {
391
- parent.open--;
392
- parent.wake();
393
417
  }
394
- if (thrown !== void 0)
395
- throw thrown;
396
- return reply;
397
418
  }
398
419
  };
399
420
  }
@@ -401,17 +422,24 @@ function createHandOffDesk(deps) {
401
422
  // packages/notify/lib/conversations.js
402
423
  var SUB_AGENT_TOOLS = /* @__PURE__ */ new Set(["subagent", "subagent_fork"]);
403
424
  var QUIET_MS = 250;
404
- function sessionConversations(sessions, cwd = () => void 0, focus, app) {
425
+ function sessionConversations(sessions, _cwd = () => void 0, focus, app) {
405
426
  const converse = async (sessionId, text, signal, images = [], options = {}) => {
427
+ signal.throwIfAborted();
406
428
  const controller = new AbortController();
407
429
  const requestId = `notify-${crypto.randomUUID()}`;
408
430
  const turn = { started: false };
431
+ let stopping;
409
432
  const abort = () => {
410
433
  controller.abort(signal.reason);
411
- void Promise.resolve().then(async () => {
412
- if (turn.started) {
413
- sessions.cancel?.({ sessionId });
414
- app?.()?.stopSubAgents?.(sessionId);
434
+ stopping = Promise.resolve().then(async () => {
435
+ if (turn.started || options.isolated) {
436
+ try {
437
+ await sessions.cancel?.({ sessionId });
438
+ } finally {
439
+ app?.()?.stopSubAgents?.(sessionId);
440
+ }
441
+ if (!turn.started)
442
+ await unqueue(sessions, sessionId, requestId);
415
443
  } else
416
444
  await unqueue(sessions, sessionId, requestId);
417
445
  }).catch(() => {
@@ -431,10 +459,11 @@ function sessionConversations(sessions, cwd = () => void 0, focus, app) {
431
459
  clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
432
460
  }, controller.signal);
433
461
  const settled = app?.()?.settled;
434
- return await workReply(iterator, requestId, text, turn, settled === void 0 ? void 0 : () => settled.call(app(), sessionId, controller.signal));
462
+ return await workReply(iterator, requestId, text, turn, settled === void 0 ? void 0 : () => settled.call(app(), sessionId, controller.signal), options.onWorkerReport);
435
463
  } finally {
436
464
  signal.removeEventListener("abort", abort);
437
465
  controller.abort();
466
+ await stopping;
438
467
  }
439
468
  };
440
469
  const gateway = () => {
@@ -449,10 +478,23 @@ function sessionConversations(sessions, cwd = () => void 0, focus, app) {
449
478
  await focus?.(sessionId, options.focus);
450
479
  return sessionId;
451
480
  };
481
+ const prepareTask = async (role, title, scope) => {
482
+ const owner = await gateway().home(role);
483
+ const id = crypto.randomUUID();
484
+ if (scope)
485
+ await focus?.(id, scope);
486
+ return { owner, id, run: (instruction, signal, images) => gateway().runChild(owner, id, title, instruction, signal, images) };
487
+ };
452
488
  let own;
453
489
  const desk = () => {
454
490
  const found = app?.();
455
- const make = () => createHandOffDesk({ home, converse, record: (item) => gateway().handOffs.put(item), threads: () => gateway().handOffs.all() });
491
+ const make = () => createHandOffDesk({
492
+ home,
493
+ converse,
494
+ prepareWorker: (input) => prepareTask(input.to.id, input.title, input.focus),
495
+ record: (item) => gateway().handOffs.put(item),
496
+ threads: () => gateway().handOffs.all()
497
+ });
456
498
  if (found === void 0)
457
499
  return own ??= make();
458
500
  return found.handOffDesk ??= make();
@@ -465,32 +507,20 @@ function sessionConversations(sessions, cwd = () => void 0, focus, app) {
465
507
  handOff: (input) => desk().handOff(input),
466
508
  handOffRefusal: (fromSession, to, fromAgent, toName) => desk().refusal(fromSession, to, fromAgent, toName),
467
509
  askRefusal: (sessionId) => desk().askRefusal(sessionId),
468
- async create(title, options = {}) {
469
- const chosen = options.role === void 0 ? void 0 : app?.()?.agentModel(options.role);
470
- const agentModel = chosen === void 0 ? void 0 : { provider: chosen.provider, model: chosen.model, ...chosen.reasoningEffort === void 0 ? {} : { reasoningEffort: chosen.reasoningEffort } };
471
- const model = agentModel ?? (options.defaultModel === true ? void 0 : await recentModel(sessions).catch(() => void 0));
472
- const dir = cwd();
473
- const created = await sessions.create({ ...dir === void 0 ? {} : { cwd: dir }, ...app?.()?.sessionPreset() });
474
- await app?.()?.adopt(created.sessionId);
475
- if (options.role !== void 0)
476
- await app?.()?.tagSession(created.sessionId, options.role, options.by);
477
- await sessions.rename({ sessionId: created.sessionId, title }).catch(() => {
478
- });
479
- if (model !== void 0) {
480
- const gateway2 = app?.();
481
- await (gateway2?.selectSessionModel !== void 0 ? gateway2.selectSessionModel(created.sessionId, model) : sessions.selectModel({ sessionId: created.sessionId, ...model })).catch(() => {
482
- });
483
- }
484
- if (options.focus !== void 0)
485
- await focus?.(created.sessionId, options.focus);
486
- return created.sessionId;
487
- },
510
+ prepareTask,
488
511
  async lastActive(sessionId) {
489
512
  const { items } = await sessions.list({}, AbortSignal.timeout(1e4));
490
513
  return items.find((s) => s.sessionId === sessionId)?.updatedAt;
491
514
  },
492
515
  async ask(sessionId, text, signal, images) {
493
- return finalText(await converse(sessionId, text, signal, images)) || "\uFF08agent \u6CA1\u6709\u56DE\u590D\u6587\u5B57\uFF09";
516
+ const reply = await converse(sessionId, text, signal, images);
517
+ signal.throwIfAborted();
518
+ if (reply.ended !== void 0)
519
+ throw new Error(reply.ended);
520
+ const answer = finalText(reply);
521
+ if (!answer.trim())
522
+ throw new Error("\u4EFB\u52A1\u7ED3\u675F\u65F6\u6CA1\u6709\u8FD4\u56DE\u7ED3\u8BBA");
523
+ return answer;
494
524
  },
495
525
  converse
496
526
  };
@@ -532,31 +562,11 @@ function endReason(reason) {
532
562
  return BY[message2] ?? message2;
533
563
  return KIND[reason.kind] ?? reason.kind;
534
564
  }
535
- async function recentModel(sessions) {
536
- const { items } = await sessions.list({}, AbortSignal.timeout(1e4));
537
- const recent = [...items].sort((a, b) => b.updatedAt - a.updatedAt).filter((s) => !/^(飞书|feishu):/.test(String(s.projections?.values?.["title"] ?? ""))).slice(0, 5);
538
- for (const summary of recent) {
539
- const values = summary.projections?.values ?? (await sessions.projections({ sessionId: summary.sessionId }, AbortSignal.timeout(1e4)))?.values;
540
- const selection = pick(values?.["modelSelection"]);
541
- if (selection !== void 0)
542
- return selection;
543
- }
544
- return void 0;
545
- }
546
- function pick(value) {
547
- const v = value ?? {};
548
- for (const candidate of [v.next, v.lastUsed]) {
549
- const c = candidate;
550
- if (typeof c?.provider === "string" && typeof c.model === "string") {
551
- return { provider: c.provider, model: c.model, ...typeof c.reasoningEffort === "string" ? { reasoningEffort: c.reasoningEffort } : {} };
552
- }
553
- }
554
- return void 0;
555
- }
556
565
  var TurnReply = class {
557
566
  #blocks = [];
558
567
  /** Where each call's step is: its group in `blocks` and its place there. */
559
568
  #where = /* @__PURE__ */ new Map();
569
+ #outcome;
560
570
  #ended;
561
571
  /** @returns true once the turn has ended. */
562
572
  add(event) {
@@ -578,34 +588,61 @@ var TurnReply = class {
578
588
  steps(at.block)[at.index] = { ...steps(at.block)[at.index], status: event.isError ? "error" : "ok" };
579
589
  } else if (event.type === "turn/end") {
580
590
  if (event.reason.kind !== "completed" && event.reason.kind !== "stop") {
591
+ this.#outcome = ["aborted", "interrupted"].includes(event.reason.kind) ? "cancelled" : "failed";
581
592
  const why = `\uFF08\u8FD9\u4E00\u8F6E\u6CA1\u6709\u5B8C\u6210\uFF1A${endReason(event.reason)}\uFF09`;
582
593
  if (finalText({ blocks }) === "")
583
594
  blocks.push({ kind: "text", text: why });
584
- else
585
- this.#ended = why;
586
- }
595
+ this.#ended = why;
596
+ } else
597
+ this.#outcome = "completed";
587
598
  return true;
588
599
  }
589
600
  return false;
590
601
  }
591
602
  get reply() {
592
- return this.#ended === void 0 ? { blocks: [...this.#blocks] } : { blocks: [...this.#blocks], ended: this.#ended };
603
+ return { blocks: [...this.#blocks], ...this.#outcome === void 0 ? {} : { outcome: this.#outcome }, ...this.#ended === void 0 ? {} : { ended: this.#ended } };
593
604
  }
594
605
  };
595
- async function workReply(iterator, requestId, text, turn, settled) {
606
+ async function workReply(iterator, requestId, text, turn, settled, onWorkerReport) {
607
+ const inbox = {};
608
+ let cancelled = false;
596
609
  let mine = false;
597
610
  let other = false;
598
611
  let opened = false;
599
612
  let cut = false;
600
613
  const turns = [];
601
614
  let reply = new TurnReply();
615
+ let switched = false;
602
616
  const take = (frame) => {
603
617
  if (frame.type !== "event")
604
618
  return false;
619
+ if (!mine) {
620
+ const record = frame.event;
621
+ const splice = record.data;
622
+ if (record.type === "agent/inbox/spliced" && splice?.target && typeof splice.start === "number") {
623
+ const items = inbox[splice.target] ??= [];
624
+ if (items.length < splice.start)
625
+ items.length = splice.start;
626
+ const removed = items.splice(splice.start, splice.removedCount ?? 0, ...(splice.inserted ?? []).map((m) => m.source?.rpcId));
627
+ if (splice.outcome === "canceled" && removed.includes(requestId)) {
628
+ cancelled = true;
629
+ return true;
630
+ }
631
+ }
632
+ }
605
633
  const event = convertRecord(frame);
606
634
  if (event === null)
607
635
  return false;
636
+ const afterSwitch = switched;
637
+ switched = event.type === "unknown" && event.upstreamType === "model/selection";
608
638
  if (event.type === "user/message") {
639
+ if (mine && !other && onWorkerReport) {
640
+ const raw = frame.event;
641
+ const source = raw.data?.source;
642
+ if (source?.kind === "subagent-settled" && source.stopReason === "completed") {
643
+ onWorkerReport(event.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n"));
644
+ }
645
+ }
609
646
  const body = event.content.map((p) => p.type === "text" ? p.text : "").join("");
610
647
  if (event.requestId === requestId || event.requestId === void 0 && !mine && body.trim() === text.trim())
611
648
  mine = turn.started = true;
@@ -620,6 +657,11 @@ async function workReply(iterator, requestId, text, turn, settled) {
620
657
  }
621
658
  if (event.type === "tool/call" && SUB_AGENT_TOOLS.has(event.name))
622
659
  opened = true;
660
+ if (event.type === "turn/end" && event.reason.kind === "error" && afterSwitch) {
661
+ turns.push(reply.reply);
662
+ reply = new TurnReply();
663
+ return false;
664
+ }
623
665
  if (event.type === "turn/end" && event.reason.kind !== "completed" && event.reason.kind !== "stop")
624
666
  cut = true;
625
667
  if (!reply.add(event))
@@ -631,10 +673,12 @@ async function workReply(iterator, requestId, text, turn, settled) {
631
673
  for (; ; ) {
632
674
  const next = await iterator.next();
633
675
  if (next.done === true)
634
- return joined(turns, reply);
676
+ return { ...joined(turns, reply), outcome: "failed", ended: mine ? "\u4F1A\u8BDD\u5728\u4EFB\u52A1\u7ED3\u675F\u524D\u65AD\u5F00" : "\u8BF7\u6C42\u5C1A\u672A\u8FD0\u884C\uFF0C\u4F1A\u8BDD\u5DF2\u7ED3\u675F" };
635
677
  if (take(next.value))
636
678
  break;
637
679
  }
680
+ if (cancelled)
681
+ return { blocks: [], outcome: "cancelled", ended: "\u6392\u961F\u8BF7\u6C42\u5DF2\u53D6\u6D88" };
638
682
  if (!opened || settled === void 0 || cut)
639
683
  return joined(turns, reply);
640
684
  let done = false;
@@ -659,8 +703,9 @@ async function workReply(iterator, requestId, text, turn, settled) {
659
703
  function joined(turns, unfinished) {
660
704
  const open = unfinished.reply;
661
705
  const all = open.blocks.length > 0 ? [...turns, open] : turns;
706
+ const outcome = all.at(-1)?.outcome;
662
707
  const ended = all.at(-1)?.ended;
663
- return { blocks: all.flatMap((r) => r.blocks), ...ended === void 0 ? {} : { ended } };
708
+ return { blocks: all.flatMap((r) => r.blocks), ...outcome === void 0 ? {} : { outcome }, ...ended === void 0 ? {} : { ended } };
664
709
  }
665
710
 
666
711
  // packages/notify/lib/delegate.js
@@ -711,7 +756,7 @@ function delegateTool(deps) {
711
756
  if (parent === void 0)
712
757
  throw new Error("\u53EA\u80FD\u5728\u4F1A\u8BDD\u91CC\u4EA4\u51FA\u53BB");
713
758
  const caller = deps.agentOf?.(parent);
714
- const agents = deps.agents().filter((a) => a.id !== caller?.id);
759
+ const agents = deps.agents();
715
760
  const agent = agents.find((a) => a.name === wanted || a.id === wanted);
716
761
  if (agent === void 0)
717
762
  throw new Error(`\u6CA1\u6709\u53EB\u300C${wanted}\u300D\u7684 agent\u3002\u53EF\u4EE5\u4EA4\u7ED9\uFF1A${agents.map((a) => a.name).join("\u3001") || "\uFF08\u6CA1\u6709\uFF09"}`);
@@ -720,7 +765,8 @@ function delegateTool(deps) {
720
765
  throw new Error("agent \u670D\u52A1\u8FD8\u6CA1\u6709\u51C6\u5907\u597D");
721
766
  if ((out.get(parent) ?? 0) >= MAX_OUT)
722
767
  throw new Error(`\u8FD9\u4E2A\u5BF9\u8BDD\u5DF2\u7ECF\u6709 ${MAX_OUT} \u4EF6\u4E8B\u5728\u522B\u7684 agent \u90A3\u91CC\uFF0C\u7B49\u5176\u4E2D\u4E00\u4EF6\u56DE\u6765\u518D\u4EA4`);
723
- const refusal = conversations.handOffRefusal?.(parent, agent.id, caller?.id ?? "", agent.name);
768
+ const self = agent.id === caller?.id;
769
+ const refusal = self ? void 0 : conversations.handOffRefusal?.(parent, agent.id, caller?.id ?? "", agent.name);
724
770
  if (refusal !== void 0)
725
771
  throw new Error(refusal);
726
772
  out.set(parent, (out.get(parent) ?? 0) + 1);
@@ -736,7 +782,7 @@ function delegateTool(deps) {
736
782
  ...expecting ? { expecting } : {},
737
783
  signal: AbortSignal.timeout(TIMEOUT_MS),
738
784
  from: { sessionId: parent, callId, asker: by, ...caller === void 0 ? {} : { agent: caller.id } },
739
- relay: true,
785
+ relay: !self,
740
786
  ...relayed === void 0 ? {} : { relayed }
741
787
  }).catch(() => {
742
788
  }).finally(() => settle(parent));