dsh-multigameassistant 2.1.1 → 2.2.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 (45) hide show
  1. package/cordis.patch.yml +16 -1
  2. package/lib/analyzer.js +37 -81
  3. package/lib/browser.js +1 -1
  4. package/lib/{chunk-FBDVN6Q2.js → chunk-52LYI7WP.js} +1 -1
  5. package/lib/{chunk-SHTX4AGU.js → chunk-6DSSLS7I.js} +26 -0
  6. package/lib/{chunk-VOTN4IHB.js → chunk-EOZKHLHK.js} +3 -3
  7. package/lib/{chunk-NM6H6WCQ.js → chunk-F7ZQE7BT.js} +291 -18
  8. package/lib/{chunk-5PDYWE24.js → chunk-IBPJC6DX.js} +153 -5
  9. package/lib/chunk-NOZCFSQP.js +22944 -0
  10. package/lib/chunk-NOZCFSQP.js.LEGAL.txt +8 -0
  11. package/lib/{chunk-MQG5FLOG.js → chunk-OFVGRKTD.js} +667 -39
  12. package/lib/{chunk-UQLHGLMP.js → chunk-YSTZL6HE.js} +11 -3
  13. package/lib/emulator.js +2 -2
  14. package/lib/feishu.js +5 -5
  15. package/lib/game-intel.js +531 -67
  16. package/lib/gateway.js +14 -6
  17. package/lib/guard.js +2 -2
  18. package/lib/intervene.js +8 -6
  19. package/lib/low-context.js +3 -3
  20. package/lib/monitor.js +4 -4
  21. package/lib/notify.js +5 -5
  22. package/lib/orchestrator.js +8 -8
  23. package/lib/qqbot.js +5 -5
  24. package/lib/runner.js +4 -4
  25. package/lib/scheduler.js +2 -2
  26. package/lib/script-registry.js +33 -3705
  27. package/lib/webapi-GDSF5EWP.js +2481 -0
  28. package/package.json +1 -1
  29. package/skills/game-intel.md +12 -3
  30. package/skills/script-analysis.md +30 -3
  31. package/skills/web-reading.md +52 -15
  32. package/web/assets/index-BBPTH2CM.css +1 -0
  33. package/web/assets/index-DRxvDcu6.js +245 -0
  34. package/web/assets/index-DRxvDcu6.js.map +1 -0
  35. package/web/index.html +2 -2
  36. package/lib/chunk-RFCFA5P5.js +0 -11
  37. package/lib/games/arknights/game.yaml +0 -36
  38. package/lib/games/endfield/game.yaml +0 -25
  39. package/lib/games/starrail/game.yaml +0 -33
  40. package/lib/packs/maa/adg.script.yaml +0 -220
  41. package/lib/packs/maaend/adg.script.yaml +0 -160
  42. package/lib/packs/march7th/adg.script.yaml +0 -216
  43. package/web/assets/index-CL3SeTW9.css +0 -1
  44. package/web/assets/index-GYwpGP3f.js +0 -244
  45. package/web/assets/index-GYwpGP3f.js.map +0 -1
@@ -2,7 +2,7 @@ import { createRequire as __adgCreateRequire } from 'node:module'; import { dirn
2
2
  import {
3
3
  SUMMARIES_FILE,
4
4
  summariesReader
5
- } from "./chunk-FBDVN6Q2.js";
5
+ } from "./chunk-52LYI7WP.js";
6
6
  import {
7
7
  writeFileAtomic
8
8
  } from "./chunk-RESS7WVY.js";
@@ -21,8 +21,10 @@ import {
21
21
  MAX_MEMORY_TEXT,
22
22
  MAX_SKILL_NAME,
23
23
  MEMORY_CAPABILITY,
24
+ MODEL_FALLBACK_SOURCE,
24
25
  MemoryEntry,
25
26
  MemoryKind,
27
+ ModelFallbackNotice,
26
28
  PERMISSIONS_CAPABILITY,
27
29
  PERSONA_CAPABILITY,
28
30
  Persona,
@@ -34,15 +36,17 @@ import {
34
36
  SHARED_MEMORY,
35
37
  SKILLS_CAPABILITY,
36
38
  SKILL_NAME,
39
+ SUMMARY_MAX_TOKENS,
37
40
  areaOf,
38
41
  classify,
39
42
  personaOf,
40
43
  personaPrompt,
41
- threadsBetween
42
- } from "./chunk-NM6H6WCQ.js";
44
+ threadsBetween,
45
+ timetableText
46
+ } from "./chunk-F7ZQE7BT.js";
43
47
  import {
44
48
  external_exports
45
- } from "./chunk-SHTX4AGU.js";
49
+ } from "./chunk-6DSSLS7I.js";
46
50
  import {
47
51
  __commonJS,
48
52
  __require,
@@ -3767,6 +3771,14 @@ function routesOf(value) {
3767
3771
  const providers = value?.providers;
3768
3772
  return typeof providers === "object" && providers !== null ? providers : {};
3769
3773
  }
3774
+ function declaredMaxTokens(settings, namespace, provider, model) {
3775
+ const descriptor = settings.describe({ redactSecrets: true }).find((d) => d.ns === namespace);
3776
+ if (descriptor === void 0)
3777
+ return void 0;
3778
+ const profile = routesOf(descriptor.value)[provider] ?? routesOf(descriptor.user)[provider];
3779
+ const models = Array.isArray(profile?.models) ? profile.models : [];
3780
+ return models.map(toProviderModel).find((m) => m?.id === model)?.maxTokens;
3781
+ }
3770
3782
  function toProviderModel(entry) {
3771
3783
  if (typeof entry !== "object" || entry === null)
3772
3784
  return void 0;
@@ -4348,6 +4360,93 @@ ${content.trim()}
4348
4360
  await deps.saved?.(name);
4349
4361
  return { saved: file, replaced: existing !== void 0 };
4350
4362
  }
4363
+ var IMPORTED = ".imported.json";
4364
+ var SKIPPED = /^(node_modules|__pycache__|\.git)$/;
4365
+ async function importedSkills(dir) {
4366
+ const saved = await readFile2(join(dir, IMPORTED), "utf8").then((text) => JSON.parse(text), () => []);
4367
+ if (!Array.isArray(saved))
4368
+ return [];
4369
+ const out = [];
4370
+ for (const item of saved) {
4371
+ if (typeof item?.name !== "string" || !SKILL_NAME.test(item.name) || typeof item.origin?.kind !== "string")
4372
+ continue;
4373
+ if (await readFile2(join(dir, item.name, "SKILL.md"), "utf8").then(() => true, () => false))
4374
+ out.push(item);
4375
+ }
4376
+ return out;
4377
+ }
4378
+ async function importSkill(deps, input) {
4379
+ const { cp, mkdir: mkdirp, rm: remove } = await import("node:fs/promises");
4380
+ const imported = await importedSkills(deps.dir);
4381
+ const sameOrigin = (item) => JSON.stringify([item.origin.kind, item.origin["script"], item.origin["path"]]) === JSON.stringify([input.origin.kind, input.origin["script"], input.origin["path"]]);
4382
+ const taken = await deps.taken();
4383
+ const usable = async (name2) => {
4384
+ if (!SKILL_NAME.test(name2) || name2.length > MAX_SKILL_NAME || taken.includes(name2))
4385
+ return false;
4386
+ const exists = await readFile2(join(deps.dir, name2, "SKILL.md"), "utf8").then(() => true, () => false);
4387
+ return !exists || imported.some((item) => item.name === name2 && sameOrigin(item));
4388
+ };
4389
+ const previous = imported.find(sameOrigin);
4390
+ const candidates = [...previous === void 0 ? [] : [previous.name], input.name, ...input.fallbackName === void 0 ? [] : [input.fallbackName]];
4391
+ let name;
4392
+ for (const candidate2 of candidates)
4393
+ if (await usable(candidate2)) {
4394
+ name = candidate2;
4395
+ break;
4396
+ }
4397
+ if (name === void 0)
4398
+ throw new Error(`\u6280\u80FD\u540D\u300C${input.name}\u300D\u5DF2\u7ECF\u88AB\u522B\u7684\u6280\u80FD\u7528\u4E86`);
4399
+ const folder = join(deps.dir, name);
4400
+ const replaced = await readFile2(join(folder, "SKILL.md"), "utf8").then(() => true, () => false);
4401
+ const text = await readFile2(input.single === true ? input.from : join(input.from, "SKILL.md"), "utf8");
4402
+ const body = /^?---\r?\n[\s\S]*?\r?\n---\r?\n?([\s\S]*)$/.exec(text)?.[1] ?? text;
4403
+ await remove(folder, { recursive: true, force: true });
4404
+ await mkdirp(folder, { recursive: true });
4405
+ if (input.single !== true)
4406
+ await cp(input.from, folder, { recursive: true, filter: (source) => !SKIPPED.test(source.split(/[\\/]/).pop() ?? "") });
4407
+ const owner = [
4408
+ ...input.scripts === void 0 || input.scripts.length === 0 ? [] : [`scripts: ${JSON.stringify(input.scripts)}
4409
+ `],
4410
+ ...input.games === void 0 || input.games.length === 0 ? [] : [`games: ${JSON.stringify(input.games)}
4411
+ `]
4412
+ ].join("");
4413
+ await writeFile(join(folder, "SKILL.md"), `---
4414
+ name: ${name}
4415
+ description: ${JSON.stringify(input.description.replace(/\s+/g, " ").trim())}
4416
+ ${owner}---
4417
+
4418
+ ${body.trim()}
4419
+ `);
4420
+ const record = { name, origin: input.origin, copyHash: await copyHash(folder), at: Date.now() };
4421
+ const rest = imported.filter((item) => item.name !== name && !sameOrigin(item));
4422
+ await writeFile(join(deps.dir, IMPORTED), `${JSON.stringify([...rest, record], null, 1)}
4423
+ `);
4424
+ await deps.saved?.(name);
4425
+ return { name, saved: join(folder, "SKILL.md"), replaced };
4426
+ }
4427
+ async function importUnchanged(dir, item) {
4428
+ return await copyHash(join(dir, item.name)).catch(() => "") === item.copyHash;
4429
+ }
4430
+ async function copyHash(folder) {
4431
+ const { createHash } = await import("node:crypto");
4432
+ const { readdir: readdir2 } = await import("node:fs/promises");
4433
+ const files = [];
4434
+ const walk = async (sub) => {
4435
+ for (const entry of await readdir2(join(folder, sub), { withFileTypes: true })) {
4436
+ const rel = sub === "" ? entry.name : `${sub}/${entry.name}`;
4437
+ if (entry.isDirectory()) {
4438
+ if (!SKIPPED.test(entry.name))
4439
+ await walk(rel);
4440
+ } else if (entry.isFile())
4441
+ files.push(rel);
4442
+ }
4443
+ };
4444
+ await walk("");
4445
+ const digest = createHash("sha256");
4446
+ for (const rel of files.sort())
4447
+ digest.update(rel).update("\0").update(await readFile2(join(folder, ...rel.split("/")))).update("\0");
4448
+ return digest.digest("hex").slice(0, 16);
4449
+ }
4351
4450
  async function removeSkill(dir, name) {
4352
4451
  if (!SKILL_NAME.test(name))
4353
4452
  return false;
@@ -4365,6 +4464,7 @@ function skillSaveTool(deps) {
4365
4464
  "content \u5199\u6D53\u7F29\u540E\u7684\u505A\u6CD5\uFF1A\u4EC0\u4E48\u65F6\u5019\u7528\uFF1B\u4E00\u6B65\u4E00\u6B65\u7684\u64CD\u4F5C\uFF08\u7528\u5230\u7684\u5DE5\u5177\u3001\u547D\u4EE4\u3001\u8DEF\u5F84\u3001\u53C2\u6570\u7167\u5B9E\u5199\uFF09\uFF1B\u5224\u65AD\u6210\u529F\u7684\u65B9\u6CD5\uFF1B\u8E29\u8FC7\u7684\u5751\u548C\u6CE8\u610F\u4E8B\u9879\u3002\u4E0D\u5199\u8FD9\u6B21\u5BF9\u8BDD\u7684\u95F2\u804A\u548C\u5931\u8D25\u7684\u5C1D\u8BD5\u8FC7\u7A0B\uFF0C\u53EA\u5199\u6700\u540E\u8D70\u901A\u7684\u8DEF\u3002",
4366
4465
  "description \u4E00\u4E24\u53E5\u8BDD\u5199\u6E05\u695A\u300C\u505A\u4EC0\u4E48\u3001\u7528\u6237\u8BF4\u4EC0\u4E48\u65F6\u7528\u300D\uFF0Cagent \u9760\u5B83\u51B3\u5B9A\u4EC0\u4E48\u65F6\u5019\u8C03\u7528\u3002\u5DF2\u6709\u540C\u540D\u6280\u80FD\u65F6\u5148\u7528 replace=true \u624D\u4F1A\u8986\u76D6\u3002",
4367
4466
  "\u6280\u80FD\u53EA\u5199\u300C\u600E\u4E48\u505A\u300D\uFF1A\u7528\u6237\u7684\u504F\u597D\u3001\u79F0\u547C\u3001\u7EA6\u5B9A\uFF0C\u548C\u8FD9\u6B21\u505A\u4E86\u4EC0\u4E48\u3001\u5B9A\u4E86\u4EC0\u4E48\uFF0C\u4E0D\u5199\u6210\u6280\u80FD\uFF0C\u7528 memory_save \u8BB0\u8FDB\u957F\u671F\u8BB0\u5FC6\u3002",
4467
+ "\u6280\u80FD\u53EA\u7528\u8FD9\u4E2A\u5DE5\u5177\u4FDD\u5B58\uFF08\u5B58\u5728\u672C\u8F6F\u4EF6\u81EA\u5DF1\u7684\u6570\u636E\u76EE\u5F55\u91CC\uFF0C\u53EA\u7ED9\u672C\u8F6F\u4EF6\u7684 agent \u7528\uFF09\uFF1B\u4E0D\u8981\u81EA\u5DF1\u5F80 ~/.agents/skills\u3001~/.dsh/skills \u6216\u5DE5\u4F5C\u76EE\u5F55\u7684 .agents/skills \u5199 SKILL.md\uFF0C\u90A3\u4E9B\u662F\u522B\u7684 agent \u4E5F\u8BFB\u7684\u6587\u4EF6\u5939\uFF0C\u672C\u8F6F\u4EF6\u7684 agent \u4E0D\u8BFB\u3002",
4368
4468
  "\u4E00\u5B9A\u8981\u5206\u5230\u5BF9\u5E94\u7684\u6E38\u620F\u548C\u811A\u672C\uFF1A\u53EA\u6709\u7528\u67D0\u4E2A\u811A\u672C\u65F6\u624D\u7528\u5F97\u4E0A\u7684\uFF08\u5B83\u7684\u914D\u7F6E\u3001\u62A5\u9519\u3001\u65E5\u5FD7\uFF09\u586B scripts\uFF08\u811A\u672C id\uFF09\uFF1B\u548C\u6E38\u620F\u672C\u8EAB\u6709\u5173\u3001\u6362\u4E2A\u811A\u672C\u4E5F\u7528\u5F97\u4E0A\u7684\uFF08\u6E38\u620F\u91CC\u7684\u64CD\u4F5C\u3001\u754C\u9762\u3001\u6D3B\u52A8\u3001\u673A\u5236\uFF09\u586B games\uFF08\u6E38\u620F id\uFF0Cgame_list \u53EF\u67E5\uFF09\uFF0C\u4E0D\u586B scripts\u3002\u8FD9\u6837\u5B83\u53EA\u5728\u5904\u7406\u8FD9\u4E2A\u811A\u672C\u6216\u6E38\u620F\u65F6\u51FA\u73B0\uFF0C\u4E0D\u4F1A\u88AB\u62FF\u53BB\u7528\u5728\u522B\u7684\u811A\u672C\u3001\u522B\u7684\u6E38\u620F\u4E0A\uFF0C\u300C\u6280\u80FD\u300D\u9875\u4E5F\u6309\u6E38\u620F\u5F52\u597D\u7C7B\u3002\u548C\u54EA\u4E2A\u6E38\u620F\u90FD\u65E0\u5173\u7684\u901A\u7528\u505A\u6CD5\u4E24\u4E2A\u90FD\u4E0D\u586B\u3002"
4369
4469
  ].join(""),
4370
4470
  parameters: {
@@ -4514,6 +4614,13 @@ var SkillScope = class {
4514
4614
  ownerOf(name) {
4515
4615
  return this.#skills.get(name)?.owner;
4516
4616
  }
4617
+ kindOf(name) {
4618
+ return this.#skills.get(name)?.kind;
4619
+ }
4620
+ packOf(name) {
4621
+ const skill = this.#skills.get(name);
4622
+ return { ...skill?.pack === void 0 ? {} : { pack: skill.pack }, ...skill?.ownPack === true ? { ownPack: true } : {} };
4623
+ }
4517
4624
  /** A session's focus; undefined: no session (everything shows). A session never focused shows the general skills only. */
4518
4625
  focusOf(sessionId) {
4519
4626
  if (sessionId === void 0)
@@ -4538,8 +4645,18 @@ var SkillScope = class {
4538
4645
  this.#focus.delete(this.#focus.keys().next().value);
4539
4646
  this.#invalidate();
4540
4647
  this.#save();
4648
+ for (const listener of this.#focusListeners)
4649
+ listener(sessionId, merged);
4541
4650
  return merged;
4542
4651
  }
4652
+ #focusListeners = /* @__PURE__ */ new Set();
4653
+ /** Run `listener` after a session's focus is set (the page offers its games' packs). @returns the disposer. */
4654
+ onFocus(listener) {
4655
+ this.#focusListeners.add(listener);
4656
+ return () => {
4657
+ this.#focusListeners.delete(listener);
4658
+ };
4659
+ }
4543
4660
  /** The skills a focus shows (general ones included). */
4544
4661
  skillsFor(focus) {
4545
4662
  return [...this.#skills.values()].filter((skill) => this.visible(skill.owner, focus));
@@ -4899,7 +5016,7 @@ import { readFileSync as readFileSync2 } from "node:fs";
4899
5016
  import { mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
4900
5017
  import { join as join4 } from "node:path";
4901
5018
  var COMPACTION_FILE = "compaction.json";
4902
- var DEFAULT_COMPACTION = { auto: true, threshold: DEFAULT_COMPACTION_THRESHOLD, lowContext: false, archiveDays: null, ptcSubagents: true };
5019
+ var DEFAULT_COMPACTION = { auto: true, threshold: DEFAULT_COMPACTION_THRESHOLD, lowContext: false, archiveDays: null, ptcSubagents: true, summarizer: null };
4903
5020
  var CompactionStore = class {
4904
5021
  #file;
4905
5022
  /** As read at start: what dsh runs with. */
@@ -4913,8 +5030,13 @@ var CompactionStore = class {
4913
5030
  state() {
4914
5031
  return { settings: this.#current, applied: { ...this.applied, lowContext: this.#current.lowContext, archiveDays: this.#current.archiveDays } };
4915
5032
  }
4916
- async set(settings) {
4917
- const clean4 = CompactionSettings.parse(settings);
5033
+ /**
5034
+ * @param outputLimit - the chosen summarizer's own output limit, if its route declares one: a summary is asked
5035
+ * to fit in that (when below dsh's default), not in more than the model can write.
5036
+ */
5037
+ async set(settings, outputLimit) {
5038
+ const parsed = CompactionSettings.parse(settings);
5039
+ const clean4 = { ...parsed, summarizer: withLimit(parsed.summarizer, outputLimit) };
4918
5040
  await mkdir3(join4(this.#file, ".."), { recursive: true });
4919
5041
  await writeFile3(`${this.#file}.tmp`, `${JSON.stringify(clean4, null, 2)}
4920
5042
  `);
@@ -4923,6 +5045,12 @@ var CompactionStore = class {
4923
5045
  return this.state();
4924
5046
  }
4925
5047
  };
5048
+ function withLimit(summarizer, outputLimit) {
5049
+ if (summarizer === null)
5050
+ return null;
5051
+ const limit = outputLimit?.(summarizer.provider, summarizer.model);
5052
+ return { provider: summarizer.provider, model: summarizer.model, ...limit === void 0 || limit >= SUMMARY_MAX_TOKENS ? {} : { maxTokens: limit } };
5053
+ }
4926
5054
  function readSettings(file) {
4927
5055
  try {
4928
5056
  const raw = JSON.parse(readFileSync2(file, "utf8"));
@@ -6355,6 +6483,10 @@ var RecallLog = class {
6355
6483
  };
6356
6484
 
6357
6485
  // packages/gateway/lib/convert.js
6486
+ function fallbackOf(value) {
6487
+ const parsed = ModelFallbackNotice.safeParse(value);
6488
+ return parsed.success ? parsed.data : void 0;
6489
+ }
6358
6490
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6359
6491
  var str2 = (v) => typeof v === "string" ? v : void 0;
6360
6492
  var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
@@ -6516,7 +6648,8 @@ function convertEvent(event) {
6516
6648
  origin: {
6517
6649
  kind,
6518
6650
  human: HUMAN_SOURCES.has(kind),
6519
- ...opt("summary", source.form === "notice" ? str2(source.summary) : void 0)
6651
+ ...opt("summary", source.form === "notice" ? str2(source.summary) : void 0),
6652
+ ...opt("fallback", kind === MODEL_FALLBACK_SOURCE ? fallbackOf(source.fallback) : void 0)
6520
6653
  },
6521
6654
  ...opt("requestId", str2(source.rpcId)),
6522
6655
  ...replaces ? { replacesHistory: true } : {}
@@ -6876,6 +7009,118 @@ function safely2(fn, fallback) {
6876
7009
  }
6877
7010
  }
6878
7011
 
7012
+ // packages/gateway/lib/queue.js
7013
+ var HUMAN = /* @__PURE__ */ new Set(["user", "user-rpc"]);
7014
+ function isHuman(message) {
7015
+ return typeof message.id === "string" && typeof message.source?.kind === "string" && HUMAN.has(message.source.kind);
7016
+ }
7017
+ function queuedPrompt(message, placement) {
7018
+ if (!isHuman(message))
7019
+ return void 0;
7020
+ const content = Array.isArray(message.content) ? message.content : [];
7021
+ const text = content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
7022
+ const images = content.filter((c) => c.type === "image").length;
7023
+ return {
7024
+ id: message.id,
7025
+ ...typeof message.source?.rpcId === "string" ? { requestId: message.source.rpcId } : {},
7026
+ text,
7027
+ ...images === 0 ? {} : { images },
7028
+ placement
7029
+ };
7030
+ }
7031
+ function toQueue(inbox, taken = []) {
7032
+ const items = [];
7033
+ for (const placement of ["next-step", "next-turn"]) {
7034
+ const list = inbox?.[placement];
7035
+ if (!Array.isArray(list))
7036
+ continue;
7037
+ for (const message of list) {
7038
+ const item = queuedPrompt(message, placement);
7039
+ if (item !== void 0)
7040
+ items.push(item);
7041
+ }
7042
+ }
7043
+ const waiting = new Set(items.map((item) => item.id));
7044
+ return [...taken.filter((item) => !waiting.has(item.id)), ...items];
7045
+ }
7046
+ var TakenInput = class {
7047
+ #taken = /* @__PURE__ */ new Map();
7048
+ /** Messages already handed back once (`lost`): a step that keeps failing before it logs them does not loop. */
7049
+ #handedBack = /* @__PURE__ */ new Set();
7050
+ #changed;
7051
+ /** @param changed - called when a session's taken messages change (to send its queue again). */
7052
+ constructor(changed) {
7053
+ this.#changed = changed;
7054
+ }
7055
+ /** dsh took `message` from the inbox for a step. */
7056
+ take(sessionId, message) {
7057
+ const item = queuedPrompt(message, "taken");
7058
+ if (item === void 0)
7059
+ return;
7060
+ let taken = this.#taken.get(sessionId);
7061
+ if (taken === void 0)
7062
+ this.#taken.set(sessionId, taken = /* @__PURE__ */ new Map());
7063
+ taken.set(item.id, { message, item });
7064
+ this.#changed(sessionId);
7065
+ }
7066
+ /** A message was written to the log: it is in the conversation now. */
7067
+ logged(sessionId, messageId) {
7068
+ this.#handedBack.delete(messageId);
7069
+ const taken = this.#taken.get(sessionId);
7070
+ if (taken === void 0 || !taken.delete(messageId))
7071
+ return;
7072
+ if (taken.size === 0)
7073
+ this.#taken.delete(sessionId);
7074
+ this.#changed(sessionId);
7075
+ }
7076
+ /**
7077
+ * The agent stopped with taken messages it never logged (its step failed
7078
+ * before it got that far): they are no longer taken.
7079
+ * @returns the ones to hand back to the agent, each at most once.
7080
+ */
7081
+ lost(sessionId) {
7082
+ const taken = this.#taken.get(sessionId);
7083
+ if (taken === void 0)
7084
+ return [];
7085
+ this.#taken.delete(sessionId);
7086
+ this.#changed(sessionId);
7087
+ const back = [];
7088
+ for (const [id, { message }] of taken) {
7089
+ if (this.#handedBack.has(id)) {
7090
+ this.#handedBack.delete(id);
7091
+ continue;
7092
+ }
7093
+ this.#handedBack.add(id);
7094
+ back.push(message);
7095
+ }
7096
+ return back;
7097
+ }
7098
+ /** The agent stopped: nothing it took is still on its way to the log. */
7099
+ clear(sessionId) {
7100
+ if (this.#taken.delete(sessionId))
7101
+ this.#changed(sessionId);
7102
+ }
7103
+ /** A session's taken messages as queue items, in the order taken. */
7104
+ items(sessionId) {
7105
+ return [...this.#taken.get(sessionId)?.values() ?? []].map(({ item }) => item);
7106
+ }
7107
+ };
7108
+ function resumeAfterError(agent, taken) {
7109
+ if (agent.status !== "idle" || agent.lifetimeSignal?.aborted === true)
7110
+ return 0;
7111
+ const lost = taken.lost(agent.session.id);
7112
+ for (const message of lost)
7113
+ agent.followup(message);
7114
+ const stuck = agent.inbox.nextStep.filter(isHuman);
7115
+ if (lost.length > 0)
7116
+ return lost.length + stuck.length;
7117
+ const last = stuck.at(-1);
7118
+ if (last === void 0 || !agent.inbox.remove(last.id))
7119
+ return 0;
7120
+ agent.steer(last);
7121
+ return stuck.length;
7122
+ }
7123
+
6879
7124
  // packages/gateway/lib/builtin.js
6880
7125
  function handlers(map) {
6881
7126
  return map;
@@ -6897,29 +7142,6 @@ function toContext(pressure, breakdown) {
6897
7142
  ...system === void 0 || tools === void 0 || messages === void 0 ? {} : { breakdown: { systemTokens: system, toolsTokens: tools, messageTokens: messages } }
6898
7143
  };
6899
7144
  }
6900
- function toQueue(inbox) {
6901
- const items = [];
6902
- for (const placement of ["next-step", "next-turn"]) {
6903
- const list = inbox?.[placement];
6904
- if (!Array.isArray(list))
6905
- continue;
6906
- for (const message of list) {
6907
- if (typeof message.id !== "string" || message.source?.kind !== "user")
6908
- continue;
6909
- const content = Array.isArray(message.content) ? message.content : [];
6910
- const text = content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
6911
- const images = content.filter((c) => c.type === "image").length;
6912
- items.push({
6913
- id: message.id,
6914
- ...typeof message.source.rpcId === "string" ? { requestId: message.source.rpcId } : {},
6915
- text,
6916
- ...images === 0 ? {} : { images },
6917
- placement
6918
- });
6919
- }
6920
- }
6921
- return items;
6922
- }
6923
7145
  function titleOf(values) {
6924
7146
  const title = values?.title;
6925
7147
  return typeof title === "string" ? title : null;
@@ -7053,7 +7275,7 @@ function builtinCapabilities(deps) {
7053
7275
  hasMore: snapshot.hasMore,
7054
7276
  title: titleOf(snapshot.projections.values),
7055
7277
  live: convertLiveBaseline(snapshot.assistantStream),
7056
- queue: toQueue(snapshot.projections.values.inbox),
7278
+ queue: toQueue(snapshot.projections.values.inbox, deps.takenOf?.(params.sessionId)),
7057
7279
  ...contextOf(snapshot.projections.values)
7058
7280
  };
7059
7281
  },
@@ -7651,7 +7873,7 @@ import { readFile as readFile9 } from "node:fs/promises";
7651
7873
  import { mkdirSync as mkdirSync3 } from "node:fs";
7652
7874
  import { dirname as dirname4 } from "node:path";
7653
7875
  var LEGACY_ROLES = ["intervene", "games", "scripts", "pipelines"];
7654
- var EMPTY = { agents: {}, subAgents: null, subAgentsOf: {} };
7876
+ var EMPTY = { agents: {}, subAgents: null, subAgentsOf: {}, fallbacks: { agents: [], subAgents: [] } };
7655
7877
  var AgentModels = class {
7656
7878
  #file;
7657
7879
  #legacyFile;
@@ -7674,6 +7896,17 @@ var AgentModels = class {
7674
7896
  subOf(agentId) {
7675
7897
  return this.#state.subAgentsOf[agentId] ?? this.#state.subAgents ?? void 0;
7676
7898
  }
7899
+ /** The fallback list for the agents' own conversations (`sub` false) or for sub-agents. */
7900
+ fallbacksOf(sub) {
7901
+ return sub ? this.#state.fallbacks.subAgents : this.#state.fallbacks.agents;
7902
+ }
7903
+ /** Replace one fallback list; a model listed twice is kept once (the first). */
7904
+ async setFallbacks(sub, models) {
7905
+ await this.loaded;
7906
+ const list = distinct(models.map(clean3));
7907
+ this.#state = { ...this.#state, fallbacks: { ...this.#state.fallbacks, [sub ? "subAgents" : "agents"]: list } };
7908
+ await this.#save();
7909
+ }
7677
7910
  /** @param selection - null: follow the layer above again. */
7678
7911
  async set(target, selection) {
7679
7912
  await this.loaded;
@@ -7684,6 +7917,9 @@ var AgentModels = class {
7684
7917
  const put = (record, key) => value === void 0 ? without(record, key) : { ...record, [key]: value };
7685
7918
  const state = this.#state;
7686
7919
  this.#state = target.sub !== true ? { ...state, agents: put(state.agents, target.agentId) } : target.agentId === void 0 ? { ...state, subAgents: value ?? null } : { ...state, subAgentsOf: put(state.subAgentsOf, target.agentId) };
7920
+ await this.#save();
7921
+ }
7922
+ async #save() {
7687
7923
  if (this.#file === void 0)
7688
7924
  return;
7689
7925
  mkdirSync3(dirname4(this.#file), { recursive: true });
@@ -7699,8 +7935,15 @@ var AgentModels = class {
7699
7935
  const selection = selectionOf(s);
7700
7936
  return selection === void 0 ? [] : [[id, selection]];
7701
7937
  }));
7938
+ const list = (value) => distinct(Array.isArray(value) ? value.flatMap((s) => selectionOf(s) ?? []) : []);
7702
7939
  const state = isObject(saved) ? saved : {};
7703
- this.#state = { agents: record(state["agents"]), subAgents: selectionOf(state["subAgents"]) ?? null, subAgentsOf: record(state["subAgentsOf"]) };
7940
+ const fallbacks = isObject(state["fallbacks"]) ? state["fallbacks"] : {};
7941
+ this.#state = {
7942
+ agents: record(state["agents"]),
7943
+ subAgents: selectionOf(state["subAgents"]) ?? null,
7944
+ subAgentsOf: record(state["subAgentsOf"]),
7945
+ fallbacks: { agents: list(fallbacks["agents"]), subAgents: list(fallbacks["subAgents"]) }
7946
+ };
7704
7947
  return;
7705
7948
  }
7706
7949
  const legacy = this.#legacyFile === void 0 ? void 0 : selectionOf(await readJson(this.#legacyFile));
@@ -7726,6 +7969,190 @@ function selectionOf(value) {
7726
7969
  function clean3(selection) {
7727
7970
  return { provider: selection.provider, model: selection.model, ...typeof selection.reasoningEffort === "string" ? { reasoningEffort: selection.reasoningEffort } : {} };
7728
7971
  }
7972
+ function distinct(list) {
7973
+ const seen = /* @__PURE__ */ new Set();
7974
+ return list.filter((s) => {
7975
+ const key = `${s.provider}/${s.model}`;
7976
+ if (seen.has(key))
7977
+ return false;
7978
+ seen.add(key);
7979
+ return true;
7980
+ });
7981
+ }
7982
+
7983
+ // packages/gateway/lib/model-fallback.js
7984
+ import { randomUUID as randomUUID4 } from "node:crypto";
7985
+ function failureOf(error) {
7986
+ if (error === null || typeof error !== "object")
7987
+ return void 0;
7988
+ const e = error;
7989
+ const failure = e.failure !== null && typeof e.failure === "object" ? e.failure : void 0;
7990
+ const code = typeof failure?.code === "string" ? failure.code : typeof e.code === "string" ? e.code : void 0;
7991
+ if (code === void 0)
7992
+ return void 0;
7993
+ const message = typeof failure?.message === "string" ? failure.message : typeof e.message === "string" ? e.message : "";
7994
+ return { code, message, ...typeof failure?.status === "number" ? { status: failure.status } : {} };
7995
+ }
7996
+ var QUOTA_CODES = /* @__PURE__ */ new Set(["QUOTA", "ACCOUNT_QUOTA", "HTTP_402"]);
7997
+ var AUTH_CODES = /* @__PURE__ */ new Set(["AUTH", "INVALID_CREDENTIAL", "MISSING_CREDENTIAL", "ACCOUNT_TOKEN_INVALID", "ACCOUNT_SIGN_IN_REQUIRED", "NO_CREDENTIAL_STORE", "HTTP_401", "HTTP_403"]);
7998
+ var GONE_CODES = /* @__PURE__ */ new Set(["NO_ADAPTER", "UNKNOWN_MODEL", "MODEL_UNSUPPORTED", "HTTP_404"]);
7999
+ var LIMIT_CODES = /* @__PURE__ */ new Set(["RATE_LIMIT", "HTTP_429"]);
8000
+ var QUOTA_WORDS = /insufficient[\s_-]*(account[\s_-]*)?(balance|quota|funds|credit)|exceeded your current quota|quota[\s_-]*(exceeded|exhausted)|out of credits|credit balance is too low|arrears|余额不足|欠费|额度(已)?(用完|用尽|不足|耗尽)|账户余额/i;
8001
+ function fallbackReason(failure) {
8002
+ const { code } = failure;
8003
+ if (QUOTA_CODES.has(code) || failure.status === 402 || QUOTA_WORDS.test(failure.message))
8004
+ return "\u4F59\u989D\u6216\u989D\u5EA6\u4E0D\u8DB3";
8005
+ if (AUTH_CODES.has(code))
8006
+ return "Key \u65E0\u6548\u6216\u6CA1\u6709\u6743\u9650";
8007
+ if (GONE_CODES.has(code))
8008
+ return "\u6A21\u578B\u4E0D\u53EF\u7528";
8009
+ if (LIMIT_CODES.has(code))
8010
+ return "\u8BF7\u6C42\u592A\u9891\u7E41\uFF0C\u91CD\u8BD5\u540E\u4ECD\u88AB\u9650\u6D41";
8011
+ if (code === "SERVER" || /^HTTP_5\d\d$/.test(code))
8012
+ return "\u6A21\u578B\u670D\u52A1\u51FA\u9519\uFF0C\u91CD\u8BD5\u540E\u4ECD\u7136\u5931\u8D25";
8013
+ return void 0;
8014
+ }
8015
+ var keyOf2 = (s) => `${s.provider}/${s.model}`;
8016
+ function nextFallback(current, list, tried, usable) {
8017
+ const at = list.findIndex((s) => keyOf2(s) === keyOf2(current));
8018
+ const order = at < 0 ? list : [...list.slice(at + 1), ...list.slice(0, at)];
8019
+ return order.find((s) => keyOf2(s) !== keyOf2(current) && !tried.has(keyOf2(s)) && usable(s));
8020
+ }
8021
+ function fallbackText(notice) {
8022
+ const name = (r) => `\u300C${r.providerName}\u300D\u7684 ${r.modelName}`;
8023
+ return [
8024
+ `\uFF08\u8F6F\u4EF6\u901A\u77E5\uFF1A\u521A\u624D\u7528\u7684${name(notice.from)}\u51FA\u9519\u4E86\uFF0C\u539F\u56E0\uFF1A${notice.reason}\uFF08${notice.error.trim() || notice.code}\uFF09\u3002`,
8025
+ `\u5DF2\u7ECF\u81EA\u52A8\u6362\u6210\u5907\u7528\u6A21\u578B${name(notice.to)}\uFF0C\u8FD9\u4E2A\u5BF9\u8BDD\u63A5\u4E0B\u6765\u90FD\u7528\u5B83\u3002\u7528\u6237\u80FD\u770B\u5230\u8FD9\u6B21\u5207\u6362\u7684\u5361\u7247\u3002`,
8026
+ "\u63A5\u7740\u505A\u521A\u624D\u6CA1\u505A\u5B8C\u7684\u4E8B\uFF0C\u5DF2\u7ECF\u505A\u5B8C\u7684\u6B65\u9AA4\u4E0D\u8981\u91CD\u505A\uFF1B\u9700\u8981\u7684\u8BDD\u53EF\u4EE5\u5728\u56DE\u590D\u91CC\u63D0\u4E00\u53E5\u6362\u4E86\u6A21\u578B\u3002\uFF09"
8027
+ ].join("");
8028
+ }
8029
+ function fallbackSummary(notice) {
8030
+ const line2 = `${notice.from.modelName} ${notice.reason}\uFF0C\u5DF2\u6362\u6210 ${notice.to.providerName} / ${notice.to.modelName}`;
8031
+ return line2.length > 120 ? `${line2.slice(0, 119)}\u2026` : line2;
8032
+ }
8033
+ function fallbackMessage(notice) {
8034
+ return Object.freeze({
8035
+ id: randomUUID4(),
8036
+ role: "user",
8037
+ content: Object.freeze([Object.freeze({ type: "text", text: fallbackText(notice) })]),
8038
+ source: Object.freeze({ kind: MODEL_FALLBACK_SOURCE, form: "notice", summary: fallbackSummary(notice), fallback: notice })
8039
+ });
8040
+ }
8041
+ var ModelFallback = class {
8042
+ #deps;
8043
+ /** Sessions whose request of their own model is under way (from `agent/request` until its reply is logged). */
8044
+ #requesting = /* @__PURE__ */ new Set();
8045
+ /** The models each session has tried since its last completed turn. */
8046
+ #tried = /* @__PURE__ */ new Map();
8047
+ /** The switch decided as the turn failed, to be announced as the agent goes idle. */
8048
+ #pending = /* @__PURE__ */ new WeakMap();
8049
+ constructor(deps) {
8050
+ this.#deps = deps;
8051
+ }
8052
+ /** The agent is about to call its model (dsh's `agent/request`). */
8053
+ requested(sessionId) {
8054
+ this.#requesting.add(sessionId);
8055
+ }
8056
+ /** A session's event was logged: its model answered, or a turn ended. */
8057
+ logged(sessionId, event) {
8058
+ if (event.type === "assistant/message")
8059
+ this.#requesting.delete(sessionId);
8060
+ else if (event.type === "turn/end") {
8061
+ const reason = event.data?.reason;
8062
+ if (reason?.kind === "completed")
8063
+ this.#tried.delete(sessionId);
8064
+ }
8065
+ }
8066
+ /**
8067
+ * The agent's turn failed (dsh's `agent/error`, before the turn's end is
8068
+ * logged). A failure of its own model's request that another model would
8069
+ * not have: the next model is chosen now (so the log shows the switch
8070
+ * before the turn's end) and announced as the agent goes idle.
8071
+ * @returns the switch, if one was made.
8072
+ */
8073
+ failed(agent, error) {
8074
+ const sessionId = agent.session.id;
8075
+ const requesting = this.#requesting.delete(sessionId);
8076
+ if (!requesting || agent.model === void 0 || this.#deps.isOwn?.(sessionId) === false)
8077
+ return void 0;
8078
+ const failure = failureOf(error);
8079
+ const reason = failure === void 0 ? void 0 : fallbackReason(failure);
8080
+ const current = agent.model.current();
8081
+ if (failure === void 0 || reason === void 0 || current === void 0)
8082
+ return void 0;
8083
+ const sub = agent.session.header?.origin === "subagent";
8084
+ let tried = this.#tried.get(sessionId);
8085
+ if (tried === void 0)
8086
+ this.#tried.set(sessionId, tried = /* @__PURE__ */ new Set());
8087
+ tried.add(keyOf2(current));
8088
+ const list = this.#deps.list(sub);
8089
+ const next = nextFallback(current, list, tried, (s) => this.#deps.route(s) !== void 0);
8090
+ if (next === void 0) {
8091
+ if (list.length > 0)
8092
+ this.#deps.log?.warn(`${sessionId}: ${current.provider}/${current.model} failed (${failure.code}) and no fallback model is left to try`);
8093
+ return void 0;
8094
+ }
8095
+ const route = (s) => {
8096
+ const names = this.#deps.route(s);
8097
+ return { provider: s.provider, model: s.model, providerName: names?.providerName ?? s.provider, modelName: names?.modelName ?? s.model };
8098
+ };
8099
+ const notice = {
8100
+ from: route(current),
8101
+ to: route(next),
8102
+ reason,
8103
+ error: failure.message,
8104
+ code: failure.code,
8105
+ ...sub ? { sub: true } : {}
8106
+ };
8107
+ try {
8108
+ agent.model.select({ provider: next.provider, model: next.model, ...next.reasoningEffort === void 0 ? {} : { reasoningEffort: next.reasoningEffort } });
8109
+ } catch (selectError) {
8110
+ this.#deps.log?.warn(`${sessionId}: could not switch to the fallback model ${next.provider}/${next.model}: ${selectError instanceof Error ? selectError.message : String(selectError)}`);
8111
+ return void 0;
8112
+ }
8113
+ this.#pending.set(agent, notice);
8114
+ this.#deps.log?.info(`${sessionId}: ${current.provider}/${current.model} failed (${failure.code}), going on with ${next.provider}/${next.model}`);
8115
+ return notice;
8116
+ }
8117
+ /**
8118
+ * The agent went idle (dsh's `agent/status`): after a switch, a new turn
8119
+ * opens with the person's lost messages and the card. Not inside dsh's
8120
+ * emit (the listeners after this one would hear 「idle」 after the new turn's
8121
+ * 「running」) but in the microtask right after it: still before the end of
8122
+ * the failed turn resolves, so whoever waits for the agent (`whenIdle`,
8123
+ * dsh's sub-agent service) finds it running again and waits on.
8124
+ * @returns whether a new turn is about to open.
8125
+ */
8126
+ idle(agent) {
8127
+ const notice = this.#pending.get(agent);
8128
+ if (notice === void 0 || agent.status !== "idle")
8129
+ return false;
8130
+ this.#pending.delete(agent);
8131
+ queueMicrotask(() => this.#goOn(agent, notice));
8132
+ return true;
8133
+ }
8134
+ #goOn(agent, notice) {
8135
+ if (agent.lifetimeSignal?.aborted === true)
8136
+ return;
8137
+ try {
8138
+ const messages = [...this.#deps.lost?.(agent.session.id) ?? [], fallbackMessage(notice)];
8139
+ for (const message of messages.slice(0, -1)) {
8140
+ if (agent.send !== void 0)
8141
+ agent.send(message, "next-turn", false);
8142
+ else
8143
+ agent.followup(message);
8144
+ }
8145
+ agent.followup(messages.at(-1));
8146
+ } catch (error) {
8147
+ this.#deps.log?.warn(`${agent.session.id}: could not go on with the fallback model: ${error instanceof Error ? error.message : String(error)}`);
8148
+ }
8149
+ }
8150
+ /** The session is gone. */
8151
+ forget(sessionId) {
8152
+ this.#requesting.delete(sessionId);
8153
+ this.#tried.delete(sessionId);
8154
+ }
8155
+ };
7729
8156
 
7730
8157
  // packages/gateway/lib/peer.js
7731
8158
  var CANCEL_REQUEST = "$/cancelRequest";
@@ -8629,6 +9056,7 @@ var MAIN_AGENT = {
8629
9056
  "script_help",
8630
9057
  "script_search",
8631
9058
  "script_tasks",
9059
+ "script_mcp_list",
8632
9060
  "game_list",
8633
9061
  "game_activities",
8634
9062
  "game_report",
@@ -8655,7 +9083,7 @@ function mainDuty(roles) {
8655
9083
  return [
8656
9084
  "# \u4F60\u7684\u89D2\u8272\uFF1A\u52A9\u624B",
8657
9085
  "\u4F60\u662F\u7528\u6237\u7684\u52A9\u624B\uFF1A\u548C\u7528\u6237\u5BF9\u8BDD\uFF0C\u5F04\u6E05\u8981\u505A\u4EC0\u4E48\uFF0C\u5B89\u6392\u8C01\u6765\u505A\u3002\u622A\u56FE\u70B9\u51FB\u3001\u8FD0\u884C\u548C\u5B89\u88C5\u811A\u672C\u3001\u5206\u6790\u811A\u672C\u548C\u5199\u811A\u672C\u5305\u3001\u8BFB\u6E38\u620F\u8FD9\u4E9B\u5177\u4F53\u7684\u4E8B\u4EA4\u7ED9\u5BF9\u5E94\u7684 agent\uFF08agent_delegate\uFF09\uFF0C\u4F60\u81EA\u5DF1\u4E0D\u505A\u3002\u5206\u6790\u811A\u672C\u3001\u5199\u6216\u6539\u811A\u672C\u5305\u4EA4\u7ED9\u300C\u811A\u672C\u300D\uFF1A\u4FDD\u5B58\u811A\u672C\u5305\u7684 pack_propose \u53EA\u6709\u5B83\u6709\uFF0C\u4F60\u7684\u5B50 agent \u6CA1\u6709\u3002",
8658
- "\u7528\u6237\u8981\u5728\u6E38\u620F\u91CC\u505A\u4E00\u4EF6\u4E8B\u65F6\uFF0C\u4EA4\u51FA\u53BB\u4E4B\u524D\u5148\u7528 script_list\u3001script_tasks \u770B\u8FD9\u4E2A\u6E38\u620F\u4E0B\u7684\u811A\u672C\u6709\u6CA1\u6709\u8FD9\u4E2A\u529F\u80FD\uFF1A\u6709\uFF0C\u5C31\u4EA4\u7ED9\u300C\u811A\u672C\u300Dagent\uFF0C\u5199\u660E\u7528\u54EA\u4E2A\u811A\u672C\u7684\u54EA\u4E2A\u4EFB\u52A1\u53BB\u505A\uFF1B\u786E\u8BA4\u811A\u672C\u90FD\u505A\u4E0D\u4E86\uFF0C\u624D\u4EA4\u7ED9\u80FD\u622A\u56FE\u70B9\u51FB\u7684 agent \u81EA\u5DF1\u52A8\u624B\uFF0C\u5E76\u5728\u4EFB\u52A1\u91CC\u5199\u4E0A\u811A\u672C\u4E3A\u4EC0\u4E48\u505A\u4E0D\u4E86\u3002",
9086
+ "\u7528\u6237\u8981\u5728\u6E38\u620F\u91CC\u505A\u4E00\u4EF6\u4E8B\u65F6\uFF0C\u4EA4\u51FA\u53BB\u4E4B\u524D\u5148\u7528 script_list\u3001script_tasks \u770B\u8FD9\u4E2A\u6E38\u620F\u4E0B\u7684\u811A\u672C\u6709\u6CA1\u6709\u8FD9\u4E2A\u529F\u80FD\uFF1A\u6709\uFF0C\u5C31\u4EA4\u7ED9\u300C\u811A\u672C\u300Dagent\uFF0C\u5199\u660E\u7528\u54EA\u4E2A\u811A\u672C\u7684\u54EA\u4E2A\u4EFB\u52A1\u53BB\u505A\uFF1B\u811A\u672C\u81EA\u5E26 MCP \u670D\u52A1\u65F6\uFF08script_mcp_list\uFF09\uFF0C\u300C\u811A\u672C\u300Dagent \u8FD8\u80FD\u76F4\u63A5\u8C03\u7528\u5B83\u7684\u5DE5\u5177\uFF0C\u505A\u5230\u6574\u4E2A\u4EFB\u52A1\u4E4B\u5916\u7684\u7EC6\u7C92\u5EA6\u64CD\u4F5C\uFF08\u67E5\u72B6\u6001\u3001\u53EA\u8DD1\u67D0\u4E00\u9879\u3001\u6539\u8BBE\u7F6E\uFF09\uFF0C\u4E5F\u4EA4\u7ED9\u5B83\uFF1B\u786E\u8BA4\u811A\u672C\u90FD\u505A\u4E0D\u4E86\uFF0C\u624D\u4EA4\u7ED9\u80FD\u622A\u56FE\u70B9\u51FB\u7684 agent \u81EA\u5DF1\u52A8\u624B\uFF0C\u5E76\u5728\u4EFB\u52A1\u91CC\u5199\u4E0A\u811A\u672C\u4E3A\u4EC0\u4E48\u505A\u4E0D\u4E86\u3002",
8659
9087
  roles.length === 0 ? "\u73B0\u5728\u6CA1\u6709\u53EF\u4EE5\u4EA4\u7ED9\u7684 agent\uFF0C\u80FD\u505A\u7684\u4F60\u81EA\u5DF1\u505A\u3002" : `\u53EF\u4EE5\u4EA4\u7ED9\u7684 agent\uFF1A
8660
9088
  ${roles.map((r) => `- ${r.name}\uFF1A${r.description}`).join("\n")}`,
8661
9089
  "\u8FD0\u884C\u547D\u4EE4\u3001\u6539\u6587\u4EF6\u8FD9\u4E9B\u5DE5\u5177\u4E0D\u5728\u4F60\u7684\u5BF9\u8BDD\u91CC\uFF1A\u7528\u6237\u8981\u7684\u8FD9\u7C7B\u4E8B\uFF08\u6574\u7406\u6587\u4EF6\u3001\u5BFC\u51FA\u8BB0\u5F55\u3001\u67E5\u7CFB\u7EDF\uFF09\uFF0C\u8FD8\u6709\u67E5\u8D44\u6599\u3001\u8BFB\u65E5\u5FD7\u3001\u6BD4\u8F83\u51E0\u4E2A\u65B9\u6848\uFF0C\u90FD\u5F00\u81EA\u5DF1\u7684\u5B50 agent\uFF08subagent\uFF09\u53BB\u505A\uFF0C\u5B83\u628A\u7ED3\u679C\u4EA4\u56DE\u6765\uFF0C\u4F60\u544A\u8BC9\u7528\u6237\u3002\u622A\u56FE\u70B9\u51FB\u3001\u8FD0\u884C\u548C\u5B89\u88C5\u811A\u672C\u3001\u5206\u6790\u811A\u672C\u548C\u5199\u811A\u672C\u5305\u8FD9\u4E9B\u4EA4\u7ED9\u5BF9\u5E94\u7684\u4E3B agent\u3002",
@@ -8672,6 +9100,10 @@ var AdgGateway = class extends Service {
8672
9100
  archived = /* @__PURE__ */ new Set();
8673
9101
  /** The latest context projections per session (a control frame carries only the keys its event changed). */
8674
9102
  contexts = /* @__PURE__ */ new Map();
9103
+ /** The latest non-empty inbox projection per session, so the queue can be sent again when only the taken messages change. */
9104
+ inboxes = /* @__PURE__ */ new Map();
9105
+ /** The person's messages the agent took for a step and has not logged yet (queue.ts). */
9106
+ taken = new TakenInput((sessionId) => this.broadcast("session/queue", { sessionId, items: toQueue(this.inboxes.get(sessionId), this.taken.items(sessionId)) }));
8675
9107
  peers = /* @__PURE__ */ new Set();
8676
9108
  approvals;
8677
9109
  questions;
@@ -8698,6 +9130,10 @@ var AdgGateway = class extends Service {
8698
9130
  roles;
8699
9131
  /** Which model each agent and its sub-agents use (agent-models.ts). */
8700
9132
  agentModels;
9133
+ /** For 备用模型 (model-fallback.ts), the model catalog as last read: services and their models by id, with their names; undefined: not read yet. */
9134
+ catalogNames;
9135
+ catalogReadAt = 0;
9136
+ catalogReading = false;
8701
9137
  /** Choosing a session's model runs one at a time: each puts the default back as it found it (selectSessionModel). */
8702
9138
  modelChoices = Promise.resolve();
8703
9139
  /** Each agent's one conversation, and the work they hand each other (homes.ts). */
@@ -8723,6 +9159,8 @@ var AdgGateway = class extends Service {
8723
9159
  */
8724
9160
  memoryViews;
8725
9161
  compaction;
9162
+ /** A model's declared output limit, from the routes in 设置 → 模型服务 (while that service is there). */
9163
+ outputLimit;
8726
9164
  log;
8727
9165
  /** The skills kept in this app's skills folder (`skillsDir`): written by skill_save and the 技能 page. */
8728
9166
  savedSkills;
@@ -8799,6 +9237,7 @@ var AdgGateway = class extends Service {
8799
9237
  },
8800
9238
  selectModel: (sessionId, selection) => this.selectSessionModel(sessionId, selection),
8801
9239
  lastReplies: new LastReplies(ctx.sessionController),
9240
+ takenOf: (sessionId) => this.taken.items(sessionId),
8802
9241
  approvals: this.approvals,
8803
9242
  serverInfo: { name: "adg-gateway", version: "0.1.0" },
8804
9243
  compact: (sessionId, signal) => compactSession(ctx, sessionId, signal),
@@ -8913,6 +9352,11 @@ var AdgGateway = class extends Service {
8913
9352
  }
8914
9353
  return next();
8915
9354
  }));
9355
+ ctx.on("tools/result", ((exec, result) => {
9356
+ if (result.isError || exec.name !== "schedule_task_save" && exec.name !== "schedule_create")
9357
+ return;
9358
+ void this.announceSchedule(exec, result.value).catch((error) => log.warn(`could not announce a timed task: ${String(error)}`));
9359
+ }));
8916
9360
  ctx.on("agent/disposed", ((payload) => {
8917
9361
  if (this.agents.get(payload.agent.session.id) === payload.agent)
8918
9362
  this.agents.delete(payload.agent.session.id);
@@ -8965,6 +9409,13 @@ var AdgGateway = class extends Service {
8965
9409
  if (n > 0)
8966
9410
  ctx.logger("adg-gateway").info(`updated ${n} model route(s) with the retry policy or the system role`);
8967
9411
  }).catch((error) => ctx.logger("adg-gateway").warn(`updating model routes failed: ${String(error)}`));
9412
+ const namespace = config.providersNamespace ?? "llm-pi-ai";
9413
+ scoped.effect(() => {
9414
+ this.outputLimit = (provider, model) => declaredMaxTokens(scoped.settings, namespace, provider, model);
9415
+ return () => {
9416
+ this.outputLimit = void 0;
9417
+ };
9418
+ }, "adg-gateway output limits");
8968
9419
  scoped.effect(() => this.registry.register(providersCapability({
8969
9420
  settings: scoped.settings,
8970
9421
  llm: scoped.llm,
@@ -9032,6 +9483,13 @@ var AdgGateway = class extends Service {
9032
9483
  if (sub !== true && agentId !== void 0)
9033
9484
  void this.refreshHomes([agentId]);
9034
9485
  return model === null ? {} : await this.visionWarning(model, target);
9486
+ },
9487
+ "models/setFallbacks": async (params) => {
9488
+ const { sub, models } = params;
9489
+ await this.agentModels.setFallbacks(sub, models);
9490
+ this.broadcast("models/agentModelsChanged", this.agentModels.state());
9491
+ this.readCatalog(true);
9492
+ return {};
9035
9493
  }
9036
9494
  }
9037
9495
  }), "adg-gateway capability agent-models");
@@ -9166,7 +9624,9 @@ var AdgGateway = class extends Service {
9166
9624
  modelInvocable: s.invocation.modelInvocable,
9167
9625
  userInvocable: s.invocation.userInvocable,
9168
9626
  ...ownerInfo(this.skillScope.ownerOf(s.name)),
9169
- ...this.savedSkills?.registered.has(s.name) === true ? { removable: true } : {}
9627
+ ...this.savedSkills?.registered.has(s.name) === true ? { removable: true } : {},
9628
+ ...this.skillScope.kindOf(s.name) === void 0 ? {} : { kind: this.skillScope.kindOf(s.name) },
9629
+ ...this.skillScope.packOf(s.name)
9170
9630
  });
9171
9631
  const saved = () => {
9172
9632
  if (this.savedSkills === void 0)
@@ -9174,6 +9634,10 @@ var AdgGateway = class extends Service {
9174
9634
  return this.savedSkills;
9175
9635
  };
9176
9636
  const options = (signal) => ({ ...this.workspace === void 0 ? {} : { cwd: this.workspace }, signal });
9637
+ scoped.effect(() => this.skillScope.onFocus((sessionId, focus) => {
9638
+ if (this.isOwn(sessionId))
9639
+ this.broadcast("skills/focused", { sessionId, scripts: [...focus.scripts], games: [...focus.games] });
9640
+ }), "adg-gateway skill focus");
9177
9641
  scoped.effect(() => this.registry.register({
9178
9642
  id: SKILLS_CAPABILITY,
9179
9643
  version: 1,
@@ -9186,6 +9650,10 @@ var AdgGateway = class extends Service {
9186
9650
  throw new RpcError(ErrorCode.NotFound, `no skill ${name}`);
9187
9651
  return { ...info(skill), content: skill.content };
9188
9652
  },
9653
+ "skills/focus": async (params) => {
9654
+ const focus = this.skillScope.focusOf(params.sessionId);
9655
+ return { scripts: [...focus?.scripts ?? []], games: [...focus?.games ?? []] };
9656
+ },
9189
9657
  "skills/save": async (params) => {
9190
9658
  const p = params;
9191
9659
  try {
@@ -9234,6 +9702,80 @@ var AdgGateway = class extends Service {
9234
9702
  return decision;
9235
9703
  }
9236
9704
  }), true));
9705
+ this.agentPart("adg-gateway taken input", (scope) => {
9706
+ const failed = /* @__PURE__ */ new WeakSet();
9707
+ const offs = [
9708
+ scope.on("agent/inbox/claimed", (({ agent, message }) => {
9709
+ this.taken.take(agent.session.id, message);
9710
+ })),
9711
+ scope.on("session/event", ((session, event) => {
9712
+ if (event.type === "user/message" && typeof event.data?.id === "string")
9713
+ this.taken.logged(session.id, event.data.id);
9714
+ })),
9715
+ scope.on("agent/error", (({ agent }) => {
9716
+ failed.add(agent);
9717
+ })),
9718
+ scope.on("agent/status", (({ agent, status }) => {
9719
+ if (status !== "idle")
9720
+ return;
9721
+ setTimeout(() => {
9722
+ if (!failed.delete(agent)) {
9723
+ if (agent.status === "idle")
9724
+ this.taken.clear(agent.session.id);
9725
+ return;
9726
+ }
9727
+ try {
9728
+ const handed = resumeAfterError(agent, this.taken);
9729
+ if (handed > 0)
9730
+ log.info(`gave ${handed} waiting message(s) of ${agent.session.id} to a new turn after its turn failed`);
9731
+ } catch (error) {
9732
+ log.warn(`could not hand the waiting messages of ${agent.session.id} to a new turn: ${error instanceof Error ? error.message : String(error)}`);
9733
+ }
9734
+ }, 0);
9735
+ }))
9736
+ ];
9737
+ return () => {
9738
+ for (const off of offs)
9739
+ off();
9740
+ };
9741
+ });
9742
+ const fallback = new ModelFallback({
9743
+ list: (sub) => this.agentModels.fallbacksOf(sub),
9744
+ route: (selection) => this.routeNames(selection),
9745
+ lost: (sessionId) => this.taken.lost(sessionId),
9746
+ isOwn: (sessionId) => this.isOwn(sessionId),
9747
+ log
9748
+ });
9749
+ this.agentPart("adg-gateway model fallback", (scope) => {
9750
+ const offs = [
9751
+ scope.on("agent/request", ((payload, next) => {
9752
+ if (payload.agent !== void 0) {
9753
+ fallback.requested(payload.agent.session.id);
9754
+ this.readCatalog(false);
9755
+ }
9756
+ return next();
9757
+ }), true),
9758
+ scope.on("session/event", ((session, event) => {
9759
+ fallback.logged(session.id, event);
9760
+ })),
9761
+ scope.on("agent/error", (({ agent, error }) => {
9762
+ fallback.failed(agent, error);
9763
+ })),
9764
+ scope.on("agent/status", (({ agent, status }) => {
9765
+ if (status === "idle")
9766
+ fallback.idle(agent);
9767
+ })),
9768
+ scope.on("agent/disposed", (({ agent }) => {
9769
+ fallback.forget(agent.session.id);
9770
+ }))
9771
+ ];
9772
+ return () => {
9773
+ for (const off of offs)
9774
+ off();
9775
+ };
9776
+ });
9777
+ ctx.on("llm/adapters-updated", (() => this.readCatalog(true)));
9778
+ void this.agentModels.loaded.then(() => this.readCatalog(true));
9237
9779
  if (config.dataDir !== void 0) {
9238
9780
  const persona = new PersonaStore(config.dataDir);
9239
9781
  const loaded = persona.load();
@@ -9383,7 +9925,7 @@ var AdgGateway = class extends Service {
9383
9925
  version: 1,
9384
9926
  methods: {
9385
9927
  "compaction/get": () => compaction.state(),
9386
- "compaction/set": (params) => compaction.set(params.settings)
9928
+ "compaction/set": (params) => compaction.set(params.settings, this.outputLimit)
9387
9929
  }
9388
9930
  }), "adg-gateway capability compaction");
9389
9931
  }
@@ -9736,6 +10278,38 @@ Content-Length: 0
9736
10278
  const spec = this.specOf(sessionId);
9737
10279
  return spec === void 0 || spec.subAgentOf !== void 0 ? void 0 : { id: spec.id, name: spec.name };
9738
10280
  }
10281
+ /**
10282
+ * Tell the UI that an agent set a timed task (schedule_task_save, whose
10283
+ * value carries the task) or a reminder for itself (schedule_create, found
10284
+ * again among the reminders by its words). Only the app's own agents: a
10285
+ * shared dsh's other chats are nothing of ours.
10286
+ */
10287
+ async announceSchedule(exec, value) {
10288
+ if (exec.agent === void 0)
10289
+ return;
10290
+ const spec = this.specOf(exec.agent.session.id);
10291
+ if (spec === void 0)
10292
+ return;
10293
+ const by = spec.subAgentOf === void 0 ? spec.id : spec.id.replace(/:sub$/, "");
10294
+ if (exec.name === "schedule_task_save") {
10295
+ const task = value?.task;
10296
+ if (task === void 0)
10297
+ return;
10298
+ this.broadcast("schedule/agentSet", { kind: "task", id: task.id, by, agent: task.agent, title: task.title, when: timetableText(task.schedule), changed: typeof exec.arguments["id"] === "string" });
10299
+ return;
10300
+ }
10301
+ const prompt = typeof exec.arguments["prompt"] === "string" ? exec.arguments["prompt"] : "";
10302
+ const reminder = (await this.reminders().catch(() => [])).find((r) => r.prompt === prompt);
10303
+ this.broadcast("schedule/agentSet", {
10304
+ kind: "reminder",
10305
+ ...reminder === void 0 ? {} : { id: reminder.id },
10306
+ by,
10307
+ agent: reminder?.agent ?? by,
10308
+ title: reminder?.title ?? (prompt.split("\n")[0] ?? "").slice(0, 40),
10309
+ when: reminder === void 0 ? "" : reminder.rule === "\u4E00\u6B21" ? `\u4E00\u6B21 \xB7 ${new Date(reminder.next).toLocaleString("zh-CN", { hour12: false, month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })}` : reminder.rule,
10310
+ changed: false
10311
+ });
10312
+ }
9739
10313
  /**
9740
10314
  * What an agent in this session is: its role, 助手 for the app's other
9741
10315
  * sessions, and for a sub-agent, its parent's made into a sub-agent's.
@@ -9822,6 +10396,29 @@ Content-Length: 0
9822
10396
  return void 0;
9823
10397
  return this.agentModels.of(agentId);
9824
10398
  }
10399
+ /**
10400
+ * Read the model catalog again for the fallback card's names and which
10401
+ * fallback models can be used; `force` false: at most once a minute. Never throws.
10402
+ */
10403
+ readCatalog(force) {
10404
+ if (this.catalogReading || !force && Date.now() - this.catalogReadAt < 6e4)
10405
+ return;
10406
+ this.catalogReading = true;
10407
+ this.catalogReadAt = Date.now();
10408
+ void this.ctx.sessionController.modelCatalog().then((catalog) => {
10409
+ this.catalogNames = new Map(catalog.groups.map((g) => [g.id, { name: g.name, models: new Map(g.models.map((m) => [m.id, m.name])) }]));
10410
+ }).catch((error) => this.log.warn(`reading the model catalog for the fallback models: ${error instanceof Error ? error.message : String(error)}`)).finally(() => {
10411
+ this.catalogReading = false;
10412
+ });
10413
+ }
10414
+ /** A model's service and model names; undefined: the catalog was read and has no such model now. */
10415
+ routeNames(selection) {
10416
+ if (this.catalogNames === void 0)
10417
+ return { providerName: selection.provider, modelName: selection.model };
10418
+ const group = this.catalogNames.get(selection.provider);
10419
+ const model = group?.models.get(selection.model);
10420
+ return group === void 0 || model === void 0 ? void 0 : { providerName: group.name, modelName: model };
10421
+ }
9825
10422
  /** The model an agent's sub-agents are given: theirs, else every sub-agent's; undefined: whatever the agent is using. */
9826
10423
  subAgentModel(agentId) {
9827
10424
  return this.agentModels.subOf(agentId);
@@ -9961,6 +10558,27 @@ Content-Length: 0
9961
10558
  this.log.info(`${role?.name ?? MAIN_AGENT.name}'s conversation: ${sessionId}${kept === void 0 ? "" : ` (the one before, ${kept}, is gone)`}`);
9962
10559
  return sessionId;
9963
10560
  }
10561
+ /**
10562
+ * Put a skill from elsewhere (a script's own skills) among this app's
10563
+ * skills (the skills folder, the 技能 page), for its agents at once.
10564
+ * @returns the name it was saved under; throws without a skills folder.
10565
+ */
10566
+ async importSkill(input) {
10567
+ const saved = this.savedSkills;
10568
+ if (saved === void 0)
10569
+ throw new Error("\u8FD9\u91CC\u6CA1\u6709\u53EF\u4EE5\u5199\u7684\u6280\u80FD\u6587\u4EF6\u5939");
10570
+ const { name, replaced } = await importSkill(saved.deps, input);
10571
+ this.log.info(`skill ${replaced ? "imported again" : "imported"}: ${name} (${input.origin.kind}${typeof input.origin["script"] === "string" ? ` ${input.origin["script"]}` : ""})`);
10572
+ return { name, replaced };
10573
+ }
10574
+ /** The skills imported into this app's skills folder (`importSkill`), each with whether it was changed here since. */
10575
+ async importedSkills() {
10576
+ const saved = this.savedSkills;
10577
+ if (saved === void 0)
10578
+ return [];
10579
+ const dir = saved.deps.dir;
10580
+ return Promise.all((await importedSkills(dir)).map(async (item) => ({ ...item, changed: !await importUnchanged(dir, item) })));
10581
+ }
9964
10582
  /** Count a session the app just created as its own (session/created came before it was). */
9965
10583
  async adopt(sessionId) {
9966
10584
  if (!this.shared)
@@ -10119,8 +10737,14 @@ Content-Length: 0
10119
10737
  }
10120
10738
  if (changed.has("modelSelection"))
10121
10739
  this.broadcast("session/model", { sessionId: frame.sessionId, ...toSessionModel(changed.get("modelSelection")) });
10122
- if (changed.has("inbox"))
10123
- this.broadcast("session/queue", { sessionId: frame.sessionId, items: toQueue(changed.get("inbox")) });
10740
+ if (changed.has("inbox")) {
10741
+ const inbox = changed.get("inbox");
10742
+ if (toQueue(inbox).length === 0)
10743
+ this.inboxes.delete(frame.sessionId);
10744
+ else
10745
+ this.inboxes.set(frame.sessionId, inbox);
10746
+ this.broadcast("session/queue", { sessionId: frame.sessionId, items: toQueue(inbox, this.taken.items(frame.sessionId)) });
10747
+ }
10124
10748
  if (changed.has("contextPressure") || changed.has("contextBreakdown")) {
10125
10749
  const known = this.contexts.get(frame.sessionId) ?? {};
10126
10750
  const next = {
@@ -10145,6 +10769,10 @@ var lib_default = AdgGateway;
10145
10769
 
10146
10770
  export {
10147
10771
  pluginVersion,
10772
+ importedSkills,
10773
+ importSkill,
10774
+ importUnchanged,
10775
+ userSkills,
10148
10776
  SkillScope,
10149
10777
  streamFacts,
10150
10778
  convertEvent,