dsh-multigameassistant 2.2.1 → 2.2.3

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.
@@ -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-OFVGRKTD.js";
4
+ } from "./chunk-6NJSSOB6.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-F7ZQE7BT.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 : []);
@@ -136,6 +136,9 @@ function pastBetween(all, a, b, name) {
136
136
  var MAX_THREAD_MESSAGES = 10;
137
137
  var MAX_HOPS = 3;
138
138
  var MAX_CHAIN_MESSAGES = 30;
139
+ function failedReply(error) {
140
+ return { blocks: [], outcome: "failed", ended: error instanceof Error ? error.message : String(error) };
141
+ }
139
142
  function createHandOffDesk(deps) {
140
143
  const now = deps.now ?? Date.now;
141
144
  const live = /* @__PURE__ */ new Map();
@@ -149,9 +152,18 @@ function createHandOffDesk(deps) {
149
152
  chainTop(thread).said++;
150
153
  await save(thread, { ...patch, messages: [...thread.item.messages ?? [], { from, kind, text, at: now() }] });
151
154
  };
152
- const toWorker = (thread, message2) => {
153
- thread.turns.push(deps.converse(thread.item.toSession, message2, thread.signal, [], { insert: true }));
155
+ const deliver = (session, message2, signal, parentSessionId) => {
156
+ const receipt = Promise.withResolvers();
157
+ const reply = deps.converse(session, message2, signal, [], { insert: true, parentSessionId, onAccepted: receipt.resolve });
158
+ void reply.then(() => receipt.resolve(), receipt.reject);
159
+ return { accepted: receipt.promise, reply };
160
+ };
161
+ const toWorker = (thread, message2, record) => {
162
+ const { accepted, reply } = deliver(thread.item.toSession, message2, thread.signal, thread.item.ownerSession);
163
+ const recorded = accepted.then(record);
164
+ thread.turns.push(recorded.then(() => reply, () => ({ blocks: [] })).catch(failedReply));
154
165
  thread.wake();
166
+ return recorded;
155
167
  };
156
168
  const askerKind = (agent) => agent === void 0 || agent === MAIN ? "main" : "lead";
157
169
  const late = async ({ thread: id, fromSession, from, kind, text }) => {
@@ -161,36 +173,48 @@ function createHandOffDesk(deps) {
161
173
  if ((item.messages ?? []).length >= MAX_THREAD_MESSAGES)
162
174
  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
175
  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);
176
+ const keepAsker = workingOn(item.fromSession) !== void 0 || item.isolated && !item.ownerSession;
177
+ const askerNow = keepAsker || askerAgent === void 0 ? item.fromSession : await deps.home(askerAgent);
178
+ const workerNow = item.ownerSession ?? (item.isolated ? item.toSession : await deps.home(item.to));
166
179
  const worker = fromSession === item.toSession || fromSession === workerNow;
167
180
  if (!worker && fromSession !== item.fromSession && fromSession !== askerNow)
168
181
  throw new Error(`\u7EBF\u7D22 ${id} \u4E0D\u662F\u4F60\u548C\u5BF9\u65B9\u4E4B\u95F4\u7684`);
169
182
  if (worker && askerNow === "")
170
183
  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
- 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(() => {
175
- });
184
+ const said = kind === "done" && (!worker || item.state !== "failed") ? "update" : kind;
185
+ 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 });
186
+ const recipient = worker ? askerNow : workerNow;
187
+ await deliver(recipient, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS), workingOn(recipient)?.item.ownerSession).accepted;
188
+ const latest = deps.threads?.().find((h) => h.id === id) ?? item;
189
+ await deps.record({ ...latest, messages: [...latest.messages ?? [], { from, kind: said, text, at: now() }] });
176
190
  return "\u5DF2\u7ECF\u9001\u5230\u5BF9\u65B9\u90A3\u91CC\u4E86\u3002";
177
191
  };
178
192
  const toAsker = (thread, message2, asked) => {
179
- void deps.converse(thread.item.fromSession, message2, AbortSignal.any([thread.signal, AbortSignal.timeout(RELAY_TIMEOUT_MS)]), [], { insert: true }).then((answer) => {
193
+ const session = thread.item.fromSession;
194
+ const { reply, accepted } = deliver(session, message2, AbortSignal.any([thread.signal, AbortSignal.timeout(RELAY_TIMEOUT_MS)]), workingOn(session)?.item.ownerSession);
195
+ void reply.then((answer) => {
180
196
  if (!asked || !thread.awaiting || thread.deferred || !live.has(thread.item.id))
181
197
  return;
182
198
  const said = finalText(answer).trim();
183
- void answered(thread, thread.item.by, said === "" || isQuiet(said) ? "\uFF08\u5B83\u6CA1\u6709\u56DE\u7B54\uFF1A\u6309\u4F60\u81EA\u5DF1\u7684\u5224\u65AD\u63A5\u7740\u505A\u3002\uFF09" : said);
199
+ return answered(thread, thread.item.by, said === "" || isQuiet(said) ? "\uFF08\u5B83\u6CA1\u6709\u56DE\u7B54\uFF1A\u6309\u4F60\u81EA\u5DF1\u7684\u5224\u65AD\u63A5\u7740\u505A\u3002\uFF09" : said);
184
200
  }, () => {
185
201
  if (asked && thread.awaiting && live.has(thread.item.id))
186
- void answered(thread, thread.item.by, "\uFF08\u6CA1\u6709\u7B49\u5230\u56DE\u7B54\uFF1A\u6309\u4F60\u81EA\u5DF1\u7684\u5224\u65AD\u63A5\u7740\u505A\u3002\uFF09");
202
+ return answered(thread, thread.item.by, "\uFF08\u6CA1\u6709\u7B49\u5230\u56DE\u7B54\uFF1A\u6309\u4F60\u81EA\u5DF1\u7684\u5224\u65AD\u63A5\u7740\u505A\u3002\uFF09");
203
+ }).catch((error) => {
204
+ if (!thread.awaiting || !live.has(thread.item.id))
205
+ return;
206
+ thread.awaiting = false;
207
+ thread.turns.push(Promise.resolve(failedReply(error)));
208
+ thread.wake();
187
209
  });
210
+ return accepted;
188
211
  };
189
212
  const answered = async (thread, from, text) => {
190
- thread.awaiting = false;
191
- thread.deferred = false;
192
- toWorker(thread, threadMessage({ from, kind: "answer", thread: thread.item.id, title: thread.item.title, text }));
193
- await say(thread, from, "answer", text, { state: "running" });
213
+ await toWorker(thread, threadMessage({ from, kind: "answer", thread: thread.item.id, title: thread.item.title, text }), () => {
214
+ thread.awaiting = false;
215
+ thread.deferred = false;
216
+ return say(thread, from, "answer", text, { state: "running" });
217
+ });
194
218
  };
195
219
  return {
196
220
  refusal(fromSession, to, fromAgent, toName = to) {
@@ -246,15 +270,16 @@ function createHandOffDesk(deps) {
246
270
  return "\u7ED3\u8BBA\u5DF2\u7ECF\u4EA4\u56DE\u53BB\u4E86\u3002\u8FD9\u4E00\u8F6E\u53EF\u4EE5\u7ED3\u675F\u4E86\u3002";
247
271
  case "update":
248
272
  if (!worker) {
249
- thread.deferred = true;
250
- await say(thread, from, "update", text);
251
- toWorker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }));
273
+ await toWorker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }), () => {
274
+ thread.deferred = true;
275
+ return say(thread, from, "update", text);
276
+ });
252
277
  return "\u5DF2\u7ECF\u544A\u8BC9\u5B83\u4E86\u3002\u6709\u7ED3\u679C\u8981\u56DE\u7B54\u5B83\u7684\u8BDD\uFF0C\u7528 kind: answer\u3002";
253
278
  }
254
279
  await say(thread, from, "update", text);
255
280
  if (thread.item.fromSession === "")
256
281
  return "\u8BB0\u4E0B\u4E86\u3002\u63A5\u7740\u505A\u3002";
257
- toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text, reader: askerKind(thread.input.from?.agent) }), false);
282
+ await toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text, reader: askerKind(thread.input.from?.agent) }), false);
258
283
  return "\u5DF2\u7ECF\u9001\u5230\u5BF9\u65B9\u90A3\u91CC\u4E86\u3002\u63A5\u7740\u505A\u3002";
259
284
  case "question":
260
285
  if (worker) {
@@ -262,11 +287,10 @@ function createHandOffDesk(deps) {
262
287
  throw new Error(`\u8FD9\u4EF6\u4E8B\u662F${asker}\u4EA4\u7684\uFF0C\u6CA1\u6709\u4EBA\u7B49\u7740\u56DE\u7B54\uFF1A\u6309\u4F60\u81EA\u5DF1\u7684\u5224\u65AD\u505A\uFF0C\u628A\u8981\u95EE\u7684\u5199\u8FDB\u7ED3\u8BBA`);
263
288
  thread.awaiting = true;
264
289
  await say(thread, from, "question", text, { state: "waiting" });
265
- toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }), true);
290
+ await toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }), true);
266
291
  return `\u5DF2\u7ECF\u95EE\u4E86${asker}\u3002\u5B83\u56DE\u7B54\u540E\u4F1A\u4F5C\u4E3A\u4E00\u6761\u65B0\u6D88\u606F\u53D1\u5230\u8FD9\u91CC\uFF1A\u73B0\u5728\u7ED3\u675F\u8FD9\u4E00\u8F6E\uFF0C\u4E0D\u8981\u66FF\u5B83\u56DE\u7B54\u3002`;
267
292
  }
268
- toWorker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }));
269
- await say(thread, from, "question", text);
293
+ await toWorker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text }), () => say(thread, from, "question", text));
270
294
  return `\u5DF2\u7ECF\u95EE\u4E86\u300C${thread.item.to}\u300D\u3002\u5B83\u56DE\u7B54\u540E\u4F1A\u4F5C\u4E3A\u4E00\u6761\u65B0\u6D88\u606F\u53D1\u5230\u8FD9\u91CC\uFF1A\u73B0\u5728\u7ED3\u675F\u8FD9\u4E00\u8F6E\u3002`;
271
295
  case "answer":
272
296
  if (!worker) {
@@ -274,7 +298,7 @@ function createHandOffDesk(deps) {
274
298
  return "\u5DF2\u7ECF\u56DE\u7B54\u4E86\u3002\u73B0\u5728\u7ED3\u675F\u8FD9\u4E00\u8F6E\u3002";
275
299
  }
276
300
  await say(thread, from, "answer", text);
277
- toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text, reader: askerKind(thread.input.from?.agent) }), false);
301
+ await toAsker(thread, threadMessage({ from, kind, thread: id, title: thread.item.title, text, reader: askerKind(thread.input.from?.agent) }), false);
278
302
  return "\u5DF2\u7ECF\u56DE\u7B54\u4E86\u3002\u63A5\u7740\u505A\u3002";
279
303
  }
280
304
  },
@@ -284,15 +308,29 @@ function createHandOffDesk(deps) {
284
308
  parent.open++;
285
309
  parent.consulted.add(input.to.name);
286
310
  }
287
- const toSession = await deps.home(input.to.id, input.focus === void 0 ? {} : { focus: input.focus });
288
311
  const relay = input.relay === true;
289
- const fromSession = input.from?.sessionId ?? (relay ? await deps.home(MAIN) : "");
312
+ let work;
313
+ let toSession;
314
+ let fromSession;
315
+ try {
316
+ work = await deps.prepareWorker?.(input);
317
+ toSession = work?.id ?? await deps.home(input.to.id, input.focus === void 0 ? {} : { focus: input.focus });
318
+ input.onWorker?.(toSession);
319
+ fromSession = input.from?.sessionId ?? (relay ? await deps.home(MAIN) : "");
320
+ } catch (error) {
321
+ if (parent) {
322
+ parent.open--;
323
+ parent.wake();
324
+ }
325
+ throw error;
326
+ }
290
327
  const id = input.from?.callId ?? `h-${randomUUID2().slice(0, 8)}`;
291
328
  const chain = [...parent?.item.chain ?? (input.from?.agent === void 0 ? [] : [input.from.agent]), input.to.id];
292
329
  const item = {
293
330
  id,
294
331
  fromSession,
295
332
  ...input.from?.callId === void 0 ? {} : { callId: input.from.callId },
333
+ ...work ? { isolated: true, ownerSession: work.owner } : {},
296
334
  by: input.by,
297
335
  to: input.to.id,
298
336
  toSession,
@@ -335,65 +373,70 @@ function createHandOffDesk(deps) {
335
373
  });
336
374
  stopped.catch(() => {
337
375
  });
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
376
  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;
377
+ await deps.record(item);
378
+ const asker = input.from?.agent;
379
+ 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);
380
+ const instruction = taskMessage(input.by, input.title, body, relay, id, { who: `\u300C${input.by}\u300D`, lines: past });
381
+ 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));
382
+ let reply;
383
+ let failure;
384
+ let thrown;
385
+ try {
386
+ for (; ; ) {
387
+ while (thread.turns.length > 0) {
388
+ const turn = await thread.turns.shift();
389
+ if (reply === void 0 || finalText(turn) !== "" || turn.ended !== void 0)
390
+ reply = turn;
391
+ }
392
+ if (thread.conclusion !== void 0 && thread.open === 0)
393
+ break;
394
+ if (!thread.awaiting && thread.open === 0)
395
+ break;
396
+ await Promise.race([new Promise((resolve) => {
397
+ wake = resolve;
398
+ }), stopped]);
351
399
  }
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]);
400
+ const said = finalText(reply);
401
+ if (thread.conclusion === void 0) {
402
+ if (reply.ended !== void 0)
403
+ failure = `${reply.ended.replace(/^(|)$/g, "")}${said === "" ? "" : `\u3002\u5B83\u6700\u540E\u8BF4\uFF1A${said}`}`;
404
+ else if (said === "")
405
+ failure = "\u5B83\u6CA1\u6709\u7559\u4E0B\u56DE\u590D";
406
+ }
407
+ } catch (error) {
408
+ thrown = error;
409
+ failure = error instanceof Error ? error.message : String(error);
359
410
  }
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";
411
+ live.delete(id);
412
+ const text = failure ?? thread.conclusion ?? finalText(reply);
413
+ await save(thread, { state: failure === void 0 ? "done" : "failed", reply: text, endedAt: now() });
414
+ if (relay && fromSession !== "") {
415
+ const message2 = relayMessage({
416
+ agent: input.to.name,
417
+ asker: input.by === input.from?.asker ? "\u4F60" : input.by,
418
+ title: input.title,
419
+ ok: failure === void 0,
420
+ reply: text,
421
+ ...thread.consulted.size === 0 ? {} : { consulted: [...thread.consulted] },
422
+ ...input.from?.agent === void 0 || input.from.agent === MAIN ? {} : { toLead: true }
423
+ });
424
+ const back = deps.converse(fromSession, message2, AbortSignal.timeout(RELAY_TIMEOUT_MS), [], { parentSessionId: parent?.item.ownerSession });
425
+ if (parent !== void 0 && live.has(parent.item.id))
426
+ parent.turns.push(back.catch(() => ({ blocks: [] })));
427
+ void back.then((answer) => input.relayed?.(answer), () => {
428
+ });
429
+ }
430
+ if (thrown !== void 0)
431
+ throw thrown;
432
+ return reply;
433
+ } finally {
434
+ live.delete(id);
435
+ if (parent !== void 0) {
436
+ parent.open--;
437
+ parent.wake();
366
438
  }
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
439
  }
394
- if (thrown !== void 0)
395
- throw thrown;
396
- return reply;
397
440
  }
398
441
  };
399
442
  }
@@ -401,40 +444,69 @@ function createHandOffDesk(deps) {
401
444
  // packages/notify/lib/conversations.js
402
445
  var SUB_AGENT_TOOLS = /* @__PURE__ */ new Set(["subagent", "subagent_fork"]);
403
446
  var QUIET_MS = 250;
404
- function sessionConversations(sessions, cwd = () => void 0, focus, app) {
447
+ function sessionConversations(sessions, _cwd = () => void 0, focus, app) {
405
448
  const converse = async (sessionId, text, signal, images = [], options = {}) => {
449
+ signal.throwIfAborted();
406
450
  const controller = new AbortController();
451
+ const observing = AbortSignal.any([signal, controller.signal]);
407
452
  const requestId = `notify-${crypto.randomUUID()}`;
408
453
  const turn = { started: false };
409
- const abort = () => {
410
- controller.abort(signal.reason);
411
- void Promise.resolve().then(async () => {
412
- if (turn.started) {
413
- sessions.cancel?.({ sessionId });
454
+ let parent = options.parentSessionId;
455
+ let childMessageId;
456
+ let iterator;
457
+ const cancel = async () => {
458
+ if (parent !== void 0) {
459
+ if (turn.started || options.isolated)
460
+ app?.()?.stopSubAgent(sessionId);
461
+ else if (childMessageId !== void 0) {
462
+ await sessions.updateQueue?.({ sessionId, itemId: childMessageId, action: { kind: "remove" } });
463
+ }
464
+ return;
465
+ }
466
+ if (turn.started || options.isolated) {
467
+ try {
468
+ await sessions.cancel?.({ sessionId });
469
+ } finally {
414
470
  app?.()?.stopSubAgents?.(sessionId);
415
- } else
416
- await unqueue(sessions, sessionId, requestId);
417
- }).catch(() => {
418
- });
471
+ }
472
+ }
473
+ if (!turn.started)
474
+ await unqueue(sessions, sessionId, requestId);
419
475
  };
420
- signal.addEventListener("abort", abort, { once: true });
421
476
  try {
422
- const iterator = sessions.follow({ address: { kind: "session", sessionId }, assistantStream: true, maxMessages: 1 }, controller.signal)[Symbol.asyncIterator]();
477
+ const summary = parent === void 0 ? (await sessions.list({}, observing)).items.find((s) => s.sessionId === sessionId) : void 0;
478
+ if (summary?.origin === "subagent") {
479
+ parent = summary.parentSessionId;
480
+ if (parent === void 0)
481
+ throw new Error("\u5B50\u4EFB\u52A1\u7F3A\u5C11\u6240\u5C5E\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u6295\u9012\u6D88\u606F");
482
+ }
483
+ const id = sessionId;
484
+ const address = parent === void 0 ? { kind: "session", sessionId: id } : { kind: "subagent", parentSessionId: parent, childSessionId: id, mode: "unknown" };
485
+ iterator = sessions.follow({ address, assistantStream: true, maxMessages: 1 }, observing)[Symbol.asyncIterator]();
423
486
  const first = await iterator.next();
424
487
  if (first.done === true)
425
488
  throw new Error("\u4F1A\u8BDD\u6CA1\u6709\u6253\u5F00");
426
- await sessions.prompt({
489
+ const prompt = {
427
490
  requestId,
428
- sessionId,
429
- mode: options.insert === true && await running(sessions, sessionId, controller.signal) ? "steer" : "queue",
430
491
  content: [{ type: "text", text }, ...images.map((png) => ({ type: "image", mediaType: "image/png", data: png.toString("base64") }))],
431
492
  clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
432
- }, controller.signal);
493
+ };
494
+ if (parent !== void 0) {
495
+ const receipt = await gateway().promptChild({ ...prompt, childSessionId: id, delivery: options.insert ? "steer" : "queue" }, observing);
496
+ childMessageId = receipt.messageId;
497
+ } else {
498
+ await sessions.prompt({ ...prompt, sessionId: id, mode: options.insert && summary?.running ? "steer" : "queue" }, observing);
499
+ }
500
+ signal.throwIfAborted();
501
+ options.onAccepted?.();
433
502
  const settled = app?.()?.settled;
434
- return await workReply(iterator, requestId, text, turn, settled === void 0 ? void 0 : () => settled.call(app(), sessionId, controller.signal));
503
+ return await workReply(iterator, requestId, text, turn, settled === void 0 ? void 0 : () => settled.call(app(), sessionId, observing), options.onWorkerReport);
435
504
  } finally {
436
- signal.removeEventListener("abort", abort);
437
505
  controller.abort();
506
+ if (signal.aborted && iterator !== void 0)
507
+ await cancel().catch(() => {
508
+ });
509
+ await iterator?.return?.();
438
510
  }
439
511
  };
440
512
  const gateway = () => {
@@ -449,10 +521,23 @@ function sessionConversations(sessions, cwd = () => void 0, focus, app) {
449
521
  await focus?.(sessionId, options.focus);
450
522
  return sessionId;
451
523
  };
524
+ const prepareTask = async (role, title, scope) => {
525
+ const owner = await gateway().home(role);
526
+ const id = crypto.randomUUID();
527
+ if (scope)
528
+ await focus?.(id, scope);
529
+ return { owner, id, run: (instruction, signal, images) => gateway().runChild(owner, id, title, instruction, signal, images) };
530
+ };
452
531
  let own;
453
532
  const desk = () => {
454
533
  const found = app?.();
455
- const make = () => createHandOffDesk({ home, converse, record: (item) => gateway().handOffs.put(item), threads: () => gateway().handOffs.all() });
534
+ const make = () => createHandOffDesk({
535
+ home,
536
+ converse,
537
+ prepareWorker: (input) => prepareTask(input.to.id, input.title, input.focus),
538
+ record: (item) => gateway().handOffs.put(item),
539
+ threads: () => gateway().handOffs.all()
540
+ });
456
541
  if (found === void 0)
457
542
  return own ??= make();
458
543
  return found.handOffDesk ??= make();
@@ -465,40 +550,24 @@ function sessionConversations(sessions, cwd = () => void 0, focus, app) {
465
550
  handOff: (input) => desk().handOff(input),
466
551
  handOffRefusal: (fromSession, to, fromAgent, toName) => desk().refusal(fromSession, to, fromAgent, toName),
467
552
  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
- },
553
+ prepareTask,
488
554
  async lastActive(sessionId) {
489
555
  const { items } = await sessions.list({}, AbortSignal.timeout(1e4));
490
556
  return items.find((s) => s.sessionId === sessionId)?.updatedAt;
491
557
  },
492
558
  async ask(sessionId, text, signal, images) {
493
- return finalText(await converse(sessionId, text, signal, images)) || "\uFF08agent \u6CA1\u6709\u56DE\u590D\u6587\u5B57\uFF09";
559
+ const reply = await converse(sessionId, text, signal, images);
560
+ signal.throwIfAborted();
561
+ if (reply.ended !== void 0)
562
+ throw new Error(reply.ended);
563
+ const answer = finalText(reply);
564
+ if (!answer.trim())
565
+ throw new Error("\u4EFB\u52A1\u7ED3\u675F\u65F6\u6CA1\u6709\u8FD4\u56DE\u7ED3\u8BBA");
566
+ return answer;
494
567
  },
495
568
  converse
496
569
  };
497
570
  }
498
- async function running(sessions, sessionId, signal) {
499
- const { items } = await sessions.list({}, signal);
500
- return items.find((s) => s.sessionId === sessionId)?.running === true;
501
- }
502
571
  async function unqueue(sessions, sessionId, requestId) {
503
572
  if (sessions.updateQueue === void 0)
504
573
  return;
@@ -532,31 +601,11 @@ function endReason(reason) {
532
601
  return BY[message2] ?? message2;
533
602
  return KIND[reason.kind] ?? reason.kind;
534
603
  }
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
604
  var TurnReply = class {
557
605
  #blocks = [];
558
606
  /** Where each call's step is: its group in `blocks` and its place there. */
559
607
  #where = /* @__PURE__ */ new Map();
608
+ #outcome;
560
609
  #ended;
561
610
  /** @returns true once the turn has ended. */
562
611
  add(event) {
@@ -578,21 +627,24 @@ var TurnReply = class {
578
627
  steps(at.block)[at.index] = { ...steps(at.block)[at.index], status: event.isError ? "error" : "ok" };
579
628
  } else if (event.type === "turn/end") {
580
629
  if (event.reason.kind !== "completed" && event.reason.kind !== "stop") {
630
+ this.#outcome = ["aborted", "interrupted"].includes(event.reason.kind) ? "cancelled" : "failed";
581
631
  const why = `\uFF08\u8FD9\u4E00\u8F6E\u6CA1\u6709\u5B8C\u6210\uFF1A${endReason(event.reason)}\uFF09`;
582
632
  if (finalText({ blocks }) === "")
583
633
  blocks.push({ kind: "text", text: why });
584
- else
585
- this.#ended = why;
586
- }
634
+ this.#ended = why;
635
+ } else
636
+ this.#outcome = "completed";
587
637
  return true;
588
638
  }
589
639
  return false;
590
640
  }
591
641
  get reply() {
592
- return this.#ended === void 0 ? { blocks: [...this.#blocks] } : { blocks: [...this.#blocks], ended: this.#ended };
642
+ return { blocks: [...this.#blocks], ...this.#outcome === void 0 ? {} : { outcome: this.#outcome }, ...this.#ended === void 0 ? {} : { ended: this.#ended } };
593
643
  }
594
644
  };
595
- async function workReply(iterator, requestId, text, turn, settled) {
645
+ async function workReply(iterator, requestId, text, turn, settled, onWorkerReport) {
646
+ const inbox = {};
647
+ let cancelled = false;
596
648
  let mine = false;
597
649
  let other = false;
598
650
  let opened = false;
@@ -603,12 +655,33 @@ async function workReply(iterator, requestId, text, turn, settled) {
603
655
  const take = (frame) => {
604
656
  if (frame.type !== "event")
605
657
  return false;
658
+ if (!mine) {
659
+ const record = frame.event;
660
+ const splice = record.data;
661
+ if (record.type === "agent/inbox/spliced" && splice?.target && typeof splice.start === "number") {
662
+ const items = inbox[splice.target] ??= [];
663
+ if (items.length < splice.start)
664
+ items.length = splice.start;
665
+ const removed = items.splice(splice.start, splice.removedCount ?? 0, ...(splice.inserted ?? []).map((m) => m.source?.rpcId));
666
+ if (splice.outcome === "canceled" && removed.includes(requestId)) {
667
+ cancelled = true;
668
+ return true;
669
+ }
670
+ }
671
+ }
606
672
  const event = convertRecord(frame);
607
673
  if (event === null)
608
674
  return false;
609
675
  const afterSwitch = switched;
610
676
  switched = event.type === "unknown" && event.upstreamType === "model/selection";
611
677
  if (event.type === "user/message") {
678
+ if (mine && !other && onWorkerReport) {
679
+ const raw = frame.event;
680
+ const source = raw.data?.source;
681
+ if (source?.kind === "subagent-settled" && source.stopReason === "completed") {
682
+ onWorkerReport(event.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n"));
683
+ }
684
+ }
612
685
  const body = event.content.map((p) => p.type === "text" ? p.text : "").join("");
613
686
  if (event.requestId === requestId || event.requestId === void 0 && !mine && body.trim() === text.trim())
614
687
  mine = turn.started = true;
@@ -639,10 +712,12 @@ async function workReply(iterator, requestId, text, turn, settled) {
639
712
  for (; ; ) {
640
713
  const next = await iterator.next();
641
714
  if (next.done === true)
642
- return joined(turns, reply);
715
+ 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" };
643
716
  if (take(next.value))
644
717
  break;
645
718
  }
719
+ if (cancelled)
720
+ return { blocks: [], outcome: "cancelled", ended: "\u6392\u961F\u8BF7\u6C42\u5DF2\u53D6\u6D88" };
646
721
  if (!opened || settled === void 0 || cut)
647
722
  return joined(turns, reply);
648
723
  let done = false;
@@ -667,8 +742,9 @@ async function workReply(iterator, requestId, text, turn, settled) {
667
742
  function joined(turns, unfinished) {
668
743
  const open = unfinished.reply;
669
744
  const all = open.blocks.length > 0 ? [...turns, open] : turns;
745
+ const outcome = all.at(-1)?.outcome;
670
746
  const ended = all.at(-1)?.ended;
671
- return { blocks: all.flatMap((r) => r.blocks), ...ended === void 0 ? {} : { ended } };
747
+ return { blocks: all.flatMap((r) => r.blocks), ...outcome === void 0 ? {} : { outcome }, ...ended === void 0 ? {} : { ended } };
672
748
  }
673
749
 
674
750
  // packages/notify/lib/delegate.js
@@ -719,7 +795,7 @@ function delegateTool(deps) {
719
795
  if (parent === void 0)
720
796
  throw new Error("\u53EA\u80FD\u5728\u4F1A\u8BDD\u91CC\u4EA4\u51FA\u53BB");
721
797
  const caller = deps.agentOf?.(parent);
722
- const agents = deps.agents().filter((a) => a.id !== caller?.id);
798
+ const agents = deps.agents();
723
799
  const agent = agents.find((a) => a.name === wanted || a.id === wanted);
724
800
  if (agent === void 0)
725
801
  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"}`);
@@ -728,7 +804,8 @@ function delegateTool(deps) {
728
804
  throw new Error("agent \u670D\u52A1\u8FD8\u6CA1\u6709\u51C6\u5907\u597D");
729
805
  if ((out.get(parent) ?? 0) >= MAX_OUT)
730
806
  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`);
731
- const refusal = conversations.handOffRefusal?.(parent, agent.id, caller?.id ?? "", agent.name);
807
+ const self = agent.id === caller?.id;
808
+ const refusal = self ? void 0 : conversations.handOffRefusal?.(parent, agent.id, caller?.id ?? "", agent.name);
732
809
  if (refusal !== void 0)
733
810
  throw new Error(refusal);
734
811
  out.set(parent, (out.get(parent) ?? 0) + 1);
@@ -744,7 +821,7 @@ function delegateTool(deps) {
744
821
  ...expecting ? { expecting } : {},
745
822
  signal: AbortSignal.timeout(TIMEOUT_MS),
746
823
  from: { sessionId: parent, callId, asker: by, ...caller === void 0 ? {} : { agent: caller.id } },
747
- relay: true,
824
+ relay: !self,
748
825
  ...relayed === void 0 ? {} : { relayed }
749
826
  }).catch(() => {
750
827
  }).finally(() => settle(parent));
@@ -4,7 +4,7 @@ import {
4
4
  LOW_CONTEXT_WINDOW_MS,
5
5
  MAX_ARCHIVE_DAYS,
6
6
  MIN_ARCHIVE_DAYS
7
- } from "./chunk-F7ZQE7BT.js";
7
+ } from "./chunk-LXHF6AKU.js";
8
8
 
9
9
  // packages/gateway/lib/low-context.js
10
10
  import { appendFile, mkdir, readFile, stat } from "node:fs/promises";