dsh-multigameassistant 2.2.0 → 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.
package/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-multigameassistant 2.2.0
1
+ # dsh-multigameassistant 2.2.1
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-NOZCFSQP.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-IBPJC6DX.js";
19
+ import "./chunk-YSTZL6HE.js";
20
+ import "./chunk-OFVGRKTD.js";
21
+ import "./chunk-52LYI7WP.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-F7ZQE7BT.js";
28
28
  import {
29
29
  external_exports
30
30
  } from "./chunk-6DSSLS7I.js";
@@ -4,7 +4,7 @@ import {
4
4
  LOW_CONTEXT_WINDOW_MS,
5
5
  MAX_ARCHIVE_DAYS,
6
6
  MIN_ARCHIVE_DAYS
7
- } from "./chunk-NEUZQ7TI.js";
7
+ } from "./chunk-F7ZQE7BT.js";
8
8
 
9
9
  // packages/gateway/lib/low-context.js
10
10
  import { appendFile, mkdir, readFile, stat } from "node:fs/promises";
@@ -4,11 +4,11 @@ import {
4
4
  guideView,
5
5
  renderTask,
6
6
  require_dist
7
- } from "./chunk-26JIEF6M.js";
7
+ } from "./chunk-IBPJC6DX.js";
8
8
  import {
9
9
  RUNS_CAPABILITY,
10
10
  ScriptId
11
- } from "./chunk-NEUZQ7TI.js";
11
+ } from "./chunk-F7ZQE7BT.js";
12
12
  import {
13
13
  external_exports
14
14
  } from "./chunk-6DSSLS7I.js";
@@ -1619,6 +1619,8 @@ var GameInfo = external_exports.object({
1619
1619
  builtin: external_exports.boolean(),
1620
1620
  /** The game pack's own picture (https; fetch it with `games/image`). */
1621
1621
  art: external_exports.string().optional(),
1622
+ /** The picture the user chose for the banner across the game's page (`own:…`, fetch it with `games/image`); none: the version's art. */
1623
+ banner: external_exports.string().optional(),
1622
1624
  /** Followed from the SRA public API without a Game Pack (no scripts, no screen reading): can be unfollowed. */
1623
1625
  followed: external_exports.boolean().optional(),
1624
1626
  /** The SRA public API's ids its sources read (to match it with the 技能库's packs for the game). */
@@ -1841,6 +1843,21 @@ var GamesRequests = {
1841
1843
  * (kept by the host, it becomes `cover`). A new one needs a `name`; one
1842
1844
  * with the same name already in the calendar is that one.
1843
1845
  */
1846
+ /**
1847
+ * The picture across the top of a game's page: one the user picked (`image`,
1848
+ * its bytes; or `path`, a file on the host's computer from a file dialog),
1849
+ * kept under the host's data folder; neither: the version's art again.
1850
+ */
1851
+ "games/banner/set": {
1852
+ capability: GAMES_CAPABILITY,
1853
+ params: external_exports.object({
1854
+ game: external_exports.string().min(1),
1855
+ image: ActivityImage.optional(),
1856
+ path: external_exports.string().trim().min(1).max(1e3).optional()
1857
+ }).refine((p) => p.image === void 0 || p.path === void 0, "\u56FE\u7247\u548C\u8DEF\u5F84\u53EA\u80FD\u7ED9\u4E00\u4E2A"),
1858
+ /** No `banner`: back to the version's art. */
1859
+ result: external_exports.object({ banner: external_exports.string().optional() })
1860
+ },
1844
1861
  "games/activity/save": {
1845
1862
  capability: GAMES_CAPABILITY,
1846
1863
  params: external_exports.object({
@@ -2729,13 +2746,34 @@ var TurnEndReason = external_exports.object({
2729
2746
  kind: external_exports.string(),
2730
2747
  message: external_exports.string().optional()
2731
2748
  });
2749
+ var FallbackRoute = external_exports.object({
2750
+ provider: external_exports.string(),
2751
+ providerName: external_exports.string(),
2752
+ model: external_exports.string(),
2753
+ modelName: external_exports.string()
2754
+ });
2755
+ var ModelFallbackNotice = external_exports.object({
2756
+ from: FallbackRoute,
2757
+ to: FallbackRoute,
2758
+ /** Why it was switched, in a few words (余额不足, Key 无效, …). */
2759
+ reason: external_exports.string(),
2760
+ /** The model service's own error message. */
2761
+ error: external_exports.string(),
2762
+ /** dsh's failure code (QUOTA, AUTH, HTTP_402, …). */
2763
+ code: external_exports.string(),
2764
+ /** A sub-agent's model (the sub-agent list), else an agent's own conversation (the agent list). */
2765
+ sub: external_exports.boolean().optional()
2766
+ });
2767
+ var MODEL_FALLBACK_SOURCE = "adg-model-fallback";
2732
2768
  var MessageOrigin = external_exports.object({
2733
2769
  /** Upstream source kind: `user`, `user-rpc`, injected-context producers, goal rounds, ... */
2734
2770
  kind: external_exports.string(),
2735
2771
  /** True for a direct human prompt; false for injected context. */
2736
2772
  human: external_exports.boolean(),
2737
2773
  /** One-line account for `notice`-form injected context. */
2738
- summary: external_exports.string().optional()
2774
+ summary: external_exports.string().optional(),
2775
+ /** A model failed and the agent went on with the next of its fallback list (kind MODEL_FALLBACK_SOURCE). */
2776
+ fallback: ModelFallbackNotice.optional()
2739
2777
  });
2740
2778
  var base = { seq: external_exports.number(), time: external_exports.number() };
2741
2779
  var SessionEvent = external_exports.discriminatedUnion("type", [
@@ -3087,13 +3125,19 @@ var ModelSelection = external_exports.object({
3087
3125
  model: external_exports.string(),
3088
3126
  reasoningEffort: external_exports.string().optional()
3089
3127
  });
3128
+ var ModelFallbacks = external_exports.object({
3129
+ agents: external_exports.array(ModelSelection),
3130
+ subAgents: external_exports.array(ModelSelection)
3131
+ });
3090
3132
  var AgentModels = external_exports.object({
3091
3133
  /** Role agents' own models, by agent id. */
3092
3134
  agents: external_exports.record(external_exports.string(), ModelSelection),
3093
3135
  /** Every agent's sub-agents. */
3094
3136
  subAgents: ModelSelection.nullable(),
3095
3137
  /** One agent's sub-agents, by agent id (`main`: 助手's). */
3096
- subAgentsOf: external_exports.record(external_exports.string(), ModelSelection)
3138
+ subAgentsOf: external_exports.record(external_exports.string(), ModelSelection),
3139
+ /** The fallback lists; absent from a gateway that has none. */
3140
+ fallbacks: ModelFallbacks.optional()
3097
3141
  });
3098
3142
  var AGENTS_CAPABILITY = "agents";
3099
3143
  var ThreadMessage = external_exports.object({
@@ -3449,6 +3493,12 @@ var Requests = {
3449
3493
  params: external_exports.object({ agentId: external_exports.string().optional(), sub: external_exports.boolean().optional(), model: ModelSelection.nullable() }),
3450
3494
  result: external_exports.object({ warning: external_exports.string().optional() })
3451
3495
  },
3496
+ /** Set one fallback list (ModelFallbacks): the agents' (`sub` false) or the sub-agents'. Empty: no fallback. */
3497
+ "models/setFallbacks": {
3498
+ capability: "agent-models",
3499
+ params: external_exports.object({ sub: external_exports.boolean(), models: external_exports.array(ModelSelection) }),
3500
+ result: Empty2
3501
+ },
3452
3502
  "models/catalog": {
3453
3503
  capability: "models",
3454
3504
  params: Empty2,
@@ -3867,6 +3917,8 @@ function parseGitHubLink(text) {
3867
3917
  var UPDATE_RULE = "\u66F4\u65B0\u811A\u672C\u53EA\u8D70\u5B98\u65B9\u6E20\u9053\uFF1A\u5148\u7528 script_update\uFF08Mirror\u9171 \u6216\u5B98\u65B9\u53D1\u5E03\u5305\uFF0C\u914D\u7F6E\u4F1A\u63A5\u4E0A\uFF09\uFF1B\u5B83\u6CA1\u6709\u66F4\u65B0\u6765\u6E90\u6216\u5931\u8D25\u65F6\uFF0C\u7528\u811A\u672C\u81EA\u5DF1\u7684\u66F4\u65B0\u529F\u80FD\uFF08\u5B83\u7684\u66F4\u65B0\u7A0B\u5E8F\u3001\u542F\u52A8\u5668\u6216\u8BBE\u7F6E\u91CC\u7684\u300C\u68C0\u67E5\u66F4\u65B0\u300D\uFF09\u3002\u4E0D\u8981\u7528 git clone / pull / checkout \u62C9\u4EE3\u7801\uFF0C\u4E0D\u8981\u81EA\u5DF1\u4E0B\u8F7D\u6E90\u7801\u6216\u624B\u52A8\u89E3\u538B\u8986\u76D6\u6587\u4EF6\u2014\u2014\u9664\u975E\u6CA1\u6709\u4EFB\u4F55\u5B98\u65B9\u6E20\u9053\uFF0C\u5E76\u4E14\u7528\u6237\u540C\u610F\u3002";
3868
3918
 
3869
3919
  export {
3920
+ ModelFallbackNotice,
3921
+ MODEL_FALLBACK_SOURCE,
3870
3922
  EMULATORS_CAPABILITY,
3871
3923
  EmulatorSettings,
3872
3924
  SCRIPTS_CAPABILITY,
@@ -2,7 +2,7 @@ import { createRequire as __adgCreateRequire } from 'node:module'; import { dirn
2
2
  import {
3
3
  ScriptFamily,
4
4
  ScriptId
5
- } from "./chunk-NEUZQ7TI.js";
5
+ } from "./chunk-F7ZQE7BT.js";
6
6
  import {
7
7
  external_exports
8
8
  } from "./chunk-6DSSLS7I.js";
@@ -35,13 +35,13 @@ import {
35
35
  parseJsonc,
36
36
  parseManifest,
37
37
  versionOfTag
38
- } from "./chunk-26JIEF6M.js";
38
+ } from "./chunk-IBPJC6DX.js";
39
39
  import {
40
40
  sessionConversations
41
- } from "./chunk-I4NHWXKH.js";
41
+ } from "./chunk-YSTZL6HE.js";
42
42
  import {
43
43
  pluginVersion
44
- } from "./chunk-KTOQFJ7R.js";
44
+ } from "./chunk-OFVGRKTD.js";
45
45
  import {
46
46
  ExeIcons,
47
47
  writeFileAtomic
@@ -64,7 +64,7 @@ import {
64
64
  optimizeScriptPrompt,
65
65
  parseGitHubLink,
66
66
  taskMessage
67
- } from "./chunk-NEUZQ7TI.js";
67
+ } from "./chunk-F7ZQE7BT.js";
68
68
  import {
69
69
  NEVER,
70
70
  ZodIssueCode,
@@ -22941,4 +22941,4 @@ export {
22941
22941
  AdgScripts,
22942
22942
  lib_default
22943
22943
  };
22944
- /*! For license information please see chunk-J4QJC6UZ.js.LEGAL.txt */
22944
+ /*! For license information please see chunk-NOZCFSQP.js.LEGAL.txt */
@@ -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-ICJLH3DP.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,
@@ -41,7 +43,7 @@ import {
41
43
  personaPrompt,
42
44
  threadsBetween,
43
45
  timetableText
44
- } from "./chunk-NEUZQ7TI.js";
46
+ } from "./chunk-F7ZQE7BT.js";
45
47
  import {
46
48
  external_exports
47
49
  } from "./chunk-6DSSLS7I.js";
@@ -6481,6 +6483,10 @@ var RecallLog = class {
6481
6483
  };
6482
6484
 
6483
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
+ }
6484
6490
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6485
6491
  var str2 = (v) => typeof v === "string" ? v : void 0;
6486
6492
  var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
@@ -6642,7 +6648,8 @@ function convertEvent(event) {
6642
6648
  origin: {
6643
6649
  kind,
6644
6650
  human: HUMAN_SOURCES.has(kind),
6645
- ...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)
6646
6653
  },
6647
6654
  ...opt("requestId", str2(source.rpcId)),
6648
6655
  ...replaces ? { replacesHistory: true } : {}
@@ -7866,7 +7873,7 @@ import { readFile as readFile9 } from "node:fs/promises";
7866
7873
  import { mkdirSync as mkdirSync3 } from "node:fs";
7867
7874
  import { dirname as dirname4 } from "node:path";
7868
7875
  var LEGACY_ROLES = ["intervene", "games", "scripts", "pipelines"];
7869
- var EMPTY = { agents: {}, subAgents: null, subAgentsOf: {} };
7876
+ var EMPTY = { agents: {}, subAgents: null, subAgentsOf: {}, fallbacks: { agents: [], subAgents: [] } };
7870
7877
  var AgentModels = class {
7871
7878
  #file;
7872
7879
  #legacyFile;
@@ -7889,6 +7896,17 @@ var AgentModels = class {
7889
7896
  subOf(agentId) {
7890
7897
  return this.#state.subAgentsOf[agentId] ?? this.#state.subAgents ?? void 0;
7891
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
+ }
7892
7910
  /** @param selection - null: follow the layer above again. */
7893
7911
  async set(target, selection) {
7894
7912
  await this.loaded;
@@ -7899,6 +7917,9 @@ var AgentModels = class {
7899
7917
  const put = (record, key) => value === void 0 ? without(record, key) : { ...record, [key]: value };
7900
7918
  const state = this.#state;
7901
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() {
7902
7923
  if (this.#file === void 0)
7903
7924
  return;
7904
7925
  mkdirSync3(dirname4(this.#file), { recursive: true });
@@ -7914,8 +7935,15 @@ var AgentModels = class {
7914
7935
  const selection = selectionOf(s);
7915
7936
  return selection === void 0 ? [] : [[id, selection]];
7916
7937
  }));
7938
+ const list = (value) => distinct(Array.isArray(value) ? value.flatMap((s) => selectionOf(s) ?? []) : []);
7917
7939
  const state = isObject(saved) ? saved : {};
7918
- 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
+ };
7919
7947
  return;
7920
7948
  }
7921
7949
  const legacy = this.#legacyFile === void 0 ? void 0 : selectionOf(await readJson(this.#legacyFile));
@@ -7941,6 +7969,190 @@ function selectionOf(value) {
7941
7969
  function clean3(selection) {
7942
7970
  return { provider: selection.provider, model: selection.model, ...typeof selection.reasoningEffort === "string" ? { reasoningEffort: selection.reasoningEffort } : {} };
7943
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
+ };
7944
8156
 
7945
8157
  // packages/gateway/lib/peer.js
7946
8158
  var CANCEL_REQUEST = "$/cancelRequest";
@@ -8918,6 +9130,10 @@ var AdgGateway = class extends Service {
8918
9130
  roles;
8919
9131
  /** Which model each agent and its sub-agents use (agent-models.ts). */
8920
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;
8921
9137
  /** Choosing a session's model runs one at a time: each puts the default back as it found it (selectSessionModel). */
8922
9138
  modelChoices = Promise.resolve();
8923
9139
  /** Each agent's one conversation, and the work they hand each other (homes.ts). */
@@ -9267,6 +9483,13 @@ var AdgGateway = class extends Service {
9267
9483
  if (sub !== true && agentId !== void 0)
9268
9484
  void this.refreshHomes([agentId]);
9269
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 {};
9270
9493
  }
9271
9494
  }
9272
9495
  }), "adg-gateway capability agent-models");
@@ -9516,6 +9739,43 @@ var AdgGateway = class extends Service {
9516
9739
  off();
9517
9740
  };
9518
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));
9519
9779
  if (config.dataDir !== void 0) {
9520
9780
  const persona = new PersonaStore(config.dataDir);
9521
9781
  const loaded = persona.load();
@@ -10136,6 +10396,29 @@ Content-Length: 0
10136
10396
  return void 0;
10137
10397
  return this.agentModels.of(agentId);
10138
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
+ }
10139
10422
  /** The model an agent's sub-agents are given: theirs, else every sub-agent's; undefined: whatever the agent is using. */
10140
10423
  subAgentModel(agentId) {
10141
10424
  return this.agentModels.subOf(agentId);
@@ -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-OFVGRKTD.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-F7ZQE7BT.js";
24
24
  import {
25
25
  external_exports
26
26
  } from "./chunk-6DSSLS7I.js";
@@ -599,12 +599,15 @@ async function workReply(iterator, requestId, text, turn, settled) {
599
599
  let cut = false;
600
600
  const turns = [];
601
601
  let reply = new TurnReply();
602
+ let switched = false;
602
603
  const take = (frame) => {
603
604
  if (frame.type !== "event")
604
605
  return false;
605
606
  const event = convertRecord(frame);
606
607
  if (event === null)
607
608
  return false;
609
+ const afterSwitch = switched;
610
+ switched = event.type === "unknown" && event.upstreamType === "model/selection";
608
611
  if (event.type === "user/message") {
609
612
  const body = event.content.map((p) => p.type === "text" ? p.text : "").join("");
610
613
  if (event.requestId === requestId || event.requestId === void 0 && !mine && body.trim() === text.trim())
@@ -620,6 +623,11 @@ async function workReply(iterator, requestId, text, turn, settled) {
620
623
  }
621
624
  if (event.type === "tool/call" && SUB_AGENT_TOOLS.has(event.name))
622
625
  opened = true;
626
+ if (event.type === "turn/end" && event.reason.kind === "error" && afterSwitch) {
627
+ turns.push(reply.reply);
628
+ reply = new TurnReply();
629
+ return false;
630
+ }
623
631
  if (event.type === "turn/end" && event.reason.kind !== "completed" && event.reason.kind !== "stop")
624
632
  cut = true;
625
633
  if (!reply.add(event))
package/lib/emulator.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  EMULATORS_CAPABILITY,
11
11
  EmulatorSettings
12
- } from "./chunk-NEUZQ7TI.js";
12
+ } from "./chunk-F7ZQE7BT.js";
13
13
  import {
14
14
  external_exports
15
15
  } from "./chunk-6DSSLS7I.js";