dsh-agy-link 0.6.21 → 0.6.23

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/dist/index.js CHANGED
@@ -2,8 +2,8 @@ import { createRequire } from "node:module";
2
2
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { defineTool } from "@deepseek-ai/dsh-tools";
5
- import { execFile, execFileSync, spawn } from "node:child_process";
6
- import { accessSync, chmodSync, constants, copyFileSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
5
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
6
+ import { accessSync, chmodSync, closeSync, constants, copyFileSync, createReadStream, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { mkdir, mkdtemp, readFile, readdir, rm, stat, unlink, writeFile } from "node:fs/promises";
9
9
  import * as dshLlm from "@deepseek-ai/dsh-llm";
@@ -16,12 +16,23 @@ import { EventEmitter } from "node:events";
16
16
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
17
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
18
18
  //#endregion
19
- //#region src/common/types/config.ts
20
- const PROVIDER_ID = "antigravity";
19
+ //#region src/common/model-lineup.ts
20
+ /** Gemini Flash — the cheap, always-available workhorse. */
21
+ const PREFERRED_GEMINI_FLASH = "gemini-3.8-flash";
22
+ /** Anthropic tier (Sonnet — the default Anthropic pick). */
23
+ const PREFERRED_CLAUDE = "claude-sonnet-5-5";
24
+ /** Anthropic top tier; reached through the bare `claude-opus` alias. */
25
+ const PREFERRED_CLAUDE_OPUS = "claude-opus-5-5";
26
+ /** OpenAI tier. */
27
+ const PREFERRED_OPENAI = "gpt-oss-120b-medium";
28
+ /**
29
+ * Offline/signed-out lineup. Mirrors `agy models` (agy 1.5.7) exactly —
30
+ * same ids, same effort sets, same order.
31
+ */
21
32
  const DEFAULT_FALLBACK_MODELS = [
22
33
  {
23
- id: "gemini-4-carbon",
24
- name: "Gemini 4 Carbon",
34
+ id: "gemini-4-argon",
35
+ name: "Gemini 4 Argon",
25
36
  efforts: [
26
37
  "low",
27
38
  "medium",
@@ -29,17 +40,22 @@ const DEFAULT_FALLBACK_MODELS = [
29
40
  ]
30
41
  },
31
42
  {
32
- id: "gemini-3.8-flash",
33
- name: "Gemini 3.8 Flash",
43
+ id: "gemini-4-hydrogen",
44
+ name: "Gemini 4 Hydrogen",
34
45
  efforts: [
35
46
  "low",
36
47
  "medium",
37
- "high"
48
+ "high",
49
+ "xhigh"
38
50
  ]
39
51
  },
40
52
  {
41
- id: "gemini-4-argon",
42
- name: "Gemini 4 Argon",
53
+ id: "gemini-pro-orchestrator-g1-pro",
54
+ name: "Orchestrator (Argon)"
55
+ },
56
+ {
57
+ id: "gemini-3.8-flash",
58
+ name: "Gemini 3.8 Flash",
43
59
  efforts: [
44
60
  "low",
45
61
  "medium",
@@ -47,16 +63,8 @@ const DEFAULT_FALLBACK_MODELS = [
47
63
  ]
48
64
  },
49
65
  {
50
- id: "claude-sonnet-4-6",
51
- name: "Claude Sonnet 4.6 (Thinking)"
52
- },
53
- {
54
- id: "claude-opus-4-6-thinking",
55
- name: "Claude Opus 4.6 (Thinking)"
56
- },
57
- {
58
- id: "claude-sonnet-5-5",
59
- name: "Claude Sonnet 5.5",
66
+ id: "claude-opus-5-5",
67
+ name: "Claude Opus 5.5",
60
68
  efforts: [
61
69
  "low",
62
70
  "medium",
@@ -64,8 +72,8 @@ const DEFAULT_FALLBACK_MODELS = [
64
72
  ]
65
73
  },
66
74
  {
67
- id: "claude-opus-5-5",
68
- name: "Claude Opus 5.5",
75
+ id: "claude-sonnet-5-5",
76
+ name: "Claude Sonnet 5.5",
69
77
  efforts: [
70
78
  "low",
71
79
  "medium",
@@ -77,6 +85,9 @@ const DEFAULT_FALLBACK_MODELS = [
77
85
  name: "GPT-OSS 120B (Medium)"
78
86
  }
79
87
  ];
88
+ //#endregion
89
+ //#region src/common/types/config.ts
90
+ const PROVIDER_ID = "antigravity";
80
91
  function defaultConfig() {
81
92
  return {
82
93
  enabled: true,
@@ -146,9 +157,9 @@ function defaultConfig() {
146
157
  proxyUrl: "",
147
158
  suppressAgyAutoUpdate: process.platform === "win32",
148
159
  autoWarmup: false,
149
- warmupModels: ["gemini-3.8-flash", "claude-sonnet-5-5"],
160
+ warmupModels: [PREFERRED_GEMINI_FLASH, PREFERRED_CLAUDE],
150
161
  autoTranslate: false,
151
- translateModel: "gemini-3.8-flash",
162
+ translateModel: PREFERRED_GEMINI_FLASH,
152
163
  translateEffort: "medium",
153
164
  translateTargetLanguage: "中文(简体)",
154
165
  translateMaxChars: 8e3,
@@ -158,6 +169,9 @@ function defaultConfig() {
158
169
  translateBindConversation: true,
159
170
  translateSkipSameModel: true,
160
171
  translateMinIntervalMs: 3e3,
172
+ showHeaderBadge: true,
173
+ showTranslateAction: true,
174
+ poolWideCatalog: false,
161
175
  imageModel: "",
162
176
  imageEffort: "low",
163
177
  imageTimeoutMs: 24e4,
@@ -597,6 +611,80 @@ function defaultPoolData() {
597
611
  };
598
612
  }
599
613
  //#endregion
614
+ //#region src/common/reasoning.ts
615
+ /** Every effort id agy accepts, in ascending intensity order. */
616
+ const REASONING_EFFORTS = [
617
+ "low",
618
+ "medium",
619
+ "high",
620
+ "xhigh",
621
+ "max"
622
+ ];
623
+ /**
624
+ * Display names, matching agy's own model picker ("Extra" is `xhigh`, which is
625
+ * how the GUI labels it while `agy --help` spells it `xhigh`).
626
+ */
627
+ const EFFORT_LABELS = {
628
+ low: "Low",
629
+ medium: "Medium",
630
+ high: "High",
631
+ xhigh: "Extra",
632
+ max: "Max"
633
+ };
634
+ /** Display name for an effort id; unknown ids are shown verbatim. */
635
+ function effortLabel(id) {
636
+ const key = typeof id === "string" ? id.trim().toLowerCase() : "";
637
+ return EFFORT_LABELS[key] ?? (typeof id === "string" ? id.trim() : "");
638
+ }
639
+ /**
640
+ * Effort suffixes ordered so a LONGER suffix always wins: `gemini-4-hydrogen-xhigh`
641
+ * must fold as `gemini-4-hydrogen` + `xhigh`, never as `gemini-4-hydrogen-x` + `high`.
642
+ */
643
+ const EFFORT_SUFFIXES = [...REASONING_EFFORTS].sort((a, b) => b.length - a.length || a.localeCompare(b));
644
+ /**
645
+ * Split a discovered agy slug into (base, effort).
646
+ *
647
+ * Returns `effort: undefined` when the slug carries no effort suffix. The
648
+ * caller still decides whether the base is real — a lone `gemini-x-medium`
649
+ * with no siblings must stay verbatim rather than inventing a base.
650
+ */
651
+ function splitEffortSuffix(slug) {
652
+ const id = typeof slug === "string" ? slug.trim() : "";
653
+ for (const effort of EFFORT_SUFFIXES) {
654
+ const suffix = "-" + effort;
655
+ if (id.length > suffix.length && id.endsWith(suffix)) return {
656
+ base: id.slice(0, -suffix.length),
657
+ effort
658
+ };
659
+ }
660
+ return { base: id };
661
+ }
662
+ /**
663
+ * Canonical ordering + de-duplication of an effort set.
664
+ *
665
+ * Order is always `REASONING_EFFORTS`, so the picker and the settings
666
+ * dropdowns can never disagree about the order of Low/Medium/High/Extra.
667
+ *
668
+ * Ids this build does not know yet (a newer agy level, or a hand-written
669
+ * `fallbackModels` entry) are kept AFTER the known ones in first-seen order —
670
+ * dropping them would silently delete a user's configuration.
671
+ */
672
+ function normalizeEfforts(list) {
673
+ if (list === void 0 || list === null) return [];
674
+ const present = /* @__PURE__ */ new Set();
675
+ const order = [];
676
+ for (const raw of list) {
677
+ if (typeof raw !== "string") continue;
678
+ const id = raw.trim().toLowerCase();
679
+ if (id === "" || present.has(id)) continue;
680
+ present.add(id);
681
+ order.push(id);
682
+ }
683
+ const known = REASONING_EFFORTS.filter((e) => present.has(e));
684
+ const unknown = order.filter((e) => !REASONING_EFFORTS.includes(e));
685
+ return [...known, ...unknown];
686
+ }
687
+ //#endregion
600
688
  //#region src/host/models.ts
601
689
  /** Check whether any enabled account in the pool has confirmed access to Argon. */
602
690
  function poolHasArgon(pool, catalog) {
@@ -679,15 +767,16 @@ function extractModelList(parsed) {
679
767
  }
680
768
  return out;
681
769
  }
682
- const EFFORT_SUFFIXES = [
683
- "low",
684
- "medium",
685
- "high"
686
- ];
687
770
  /** Fold Gemini/Argon/Claude effort variants into base + effort set (spec ADR-10).
688
771
  * Claude 5.5 is listed only as tiered slugs by agy 1.5.3; the base slug is the
689
772
  * one that accepts `--effort`, and passing a tiered slug together with the flag
690
- * is rejected ("--model … conflicts with --effort=…"). */
773
+ * is rejected ("--model … conflicts with --effort=…").
774
+ *
775
+ * The effort vocabulary itself (including agy 1.5.7's `xhigh`, which its picker
776
+ * labels "Extra") comes from `common/reasoning.ts` — folding must never carry
777
+ * its own copy of the list, or a new level silently becomes a bogus MODEL:
778
+ * a missed `xhigh` used to surface `gemini-4-hydrogen-xhigh` next to
779
+ * `gemini-4-hydrogen` in DSH's picker. */
691
780
  function foldEfforts(raw) {
692
781
  const bases = /* @__PURE__ */ new Map();
693
782
  const verbatim = [];
@@ -701,26 +790,23 @@ function foldEfforts(raw) {
701
790
  });
702
791
  continue;
703
792
  }
704
- let folded = false;
705
- for (const eff of EFFORT_SUFFIXES) {
706
- const suffix = "-" + eff;
707
- if (r.slug.endsWith(suffix)) {
708
- const base = r.slug.slice(0, -suffix.length);
709
- const hasBare = slugSet.has(base);
710
- const hasSibling = raw.some((x) => x.slug.startsWith(base + "-") && EFFORT_SUFFIXES.some((e) => x.slug.endsWith("-" + e)) && x.slug !== r.slug);
711
- if (hasBare || hasSibling) {
712
- const entry = bases.get(base) ?? {
713
- label: stripEffortLabel(r.label, eff),
714
- efforts: /* @__PURE__ */ new Set()
715
- };
716
- entry.efforts.add(eff);
717
- bases.set(base, entry);
718
- folded = true;
719
- break;
720
- }
793
+ const split = splitEffortSuffix(r.slug);
794
+ if (split.effort !== void 0) {
795
+ const base = split.base;
796
+ const eff = split.effort;
797
+ const hasBare = slugSet.has(base);
798
+ const hasSibling = raw.some((x) => x.slug !== r.slug && splitEffortSuffix(x.slug).base === base);
799
+ if (hasBare || hasSibling) {
800
+ const entry = bases.get(base) ?? {
801
+ label: stripEffortLabel(r.label, eff),
802
+ efforts: /* @__PURE__ */ new Set()
803
+ };
804
+ entry.efforts.add(eff);
805
+ bases.set(base, entry);
806
+ continue;
721
807
  }
722
808
  }
723
- if (!folded) verbatim.push({
809
+ verbatim.push({
724
810
  id: r.slug,
725
811
  name: r.label,
726
812
  efforts: null
@@ -728,7 +814,7 @@ function foldEfforts(raw) {
728
814
  }
729
815
  const folded = [];
730
816
  for (const [id, v] of bases) {
731
- const efforts = EFFORT_SUFFIXES.filter((e) => v.efforts.has(e));
817
+ const efforts = normalizeEfforts(v.efforts);
732
818
  folded.push({
733
819
  id,
734
820
  name: v.label !== "" ? v.label : id,
@@ -741,9 +827,7 @@ function foldEfforts(raw) {
741
827
  for (const r of raw) if (r.slug === e.id || r.slug.startsWith(e.id + "-")) best = Math.min(best, rawOrder.get(r.slug) ?? Infinity);
742
828
  return best;
743
829
  };
744
- folded.sort((a, b) => rank(a) - rank(b));
745
- verbatim.sort((a, b) => rank(a) - rank(b));
746
- return [...folded, ...verbatim.filter((e) => !bases.has(e.id))];
830
+ return [...folded, ...verbatim.filter((e) => !bases.has(e.id))].sort((a, b) => rank(a) - rank(b));
747
831
  }
748
832
  function stripEffortLabel(label, eff) {
749
833
  const re = new RegExp("\\s*\\(?" + eff + "\\)?\\s*$", "i");
@@ -778,7 +862,8 @@ function sanitizeCatalogEntries(models) {
778
862
  const name = typeof m.name === "string" && m.name.trim() !== "" ? m.name.trim() : id;
779
863
  entries.push({
780
864
  id,
781
- name
865
+ name,
866
+ efforts: normalizeEfforts(m.efforts)
782
867
  });
783
868
  }
784
869
  return {
@@ -802,6 +887,12 @@ var ModelCatalog = class ModelCatalog {
802
887
  */
803
888
  static FALLBACK_RETRY_MS = 6e4;
804
889
  lastAttemptAt = 0;
890
+ /**
891
+ * Per-account probe timestamps. `refreshIfNeeded(accountId)` used to skip
892
+ * the throttle whenever the account had no catalog yet, so a signed-out /
893
+ * expired account could be probed on EVERY listModels() read (issue #106).
894
+ */
895
+ accountAttemptAt = /* @__PURE__ */ new Map();
805
896
  constructor(discover, fallbackDefs, ttlMs, onUpdate) {
806
897
  this.discover = discover;
807
898
  this.fallbackDefs = fallbackDefs;
@@ -885,6 +976,9 @@ var ModelCatalog = class ModelCatalog {
885
976
  const age = now - targetCat.discoveredAt;
886
977
  if (targetCat.source === "discovered" && age < this.ttlMs) return;
887
978
  if (targetCat.source === "fallback" && now - this.lastAttemptAt < ModelCatalog.FALLBACK_RETRY_MS) return;
979
+ } else {
980
+ if (now - (this.accountAttemptAt.get(accountId) ?? 0) < ModelCatalog.FALLBACK_RETRY_MS) return;
981
+ this.accountAttemptAt.set(accountId, now);
888
982
  }
889
983
  this.lastAttemptAt = now;
890
984
  this.refreshing = this.refresh(accountId).finally(() => {
@@ -892,6 +986,20 @@ var ModelCatalog = class ModelCatalog {
892
986
  });
893
987
  return this.refreshing;
894
988
  }
989
+ /**
990
+ * Read-path discovery for one account (listModels). Unlike
991
+ * `forceRefreshAndNotify()` this is throttled and NEVER broadcasts on a
992
+ * failed probe: an unconditional `adapters-updated` made DSH's browser
993
+ * re-read the catalog, which called listModels() again — a self-exciting
994
+ * 1:1 read/probe/announce loop while signed out (issue #106). `refresh()`
995
+ * itself announces only when the catalog contents actually changed, so a
996
+ * successful first build still updates the picker exactly once.
997
+ */
998
+ async ensureAccountCatalog(accountId) {
999
+ if (!accountId || this.accountCatalogs.has(accountId)) return this.get(accountId);
1000
+ await this.refreshIfNeeded(accountId);
1001
+ return this.get(accountId);
1002
+ }
895
1003
  async forceRefresh(accountId) {
896
1004
  await this.refresh(accountId);
897
1005
  return this.get(accountId);
@@ -910,8 +1018,10 @@ var ModelCatalog = class ModelCatalog {
910
1018
  * switching to a Pro/Ultra account).
911
1019
  */
912
1020
  async forceRefreshAndNotify(accountId) {
1021
+ const hadCatalog = accountId ? this.hasAccountCatalog(accountId) : true;
913
1022
  await this.refresh(accountId, false);
914
- this.onUpdate?.();
1023
+ const hasCatalog = accountId ? this.hasAccountCatalog(accountId) : true;
1024
+ if (hadCatalog || hasCatalog) this.onUpdate?.();
915
1025
  return this.get(accountId);
916
1026
  }
917
1027
  /**
@@ -970,11 +1080,11 @@ var ModelCatalog = class ModelCatalog {
970
1080
  };
971
1081
  function resolveModelSlug(id) {
972
1082
  const s = id.trim().toLowerCase();
973
- if (s === "claude-opus") return "claude-opus-5-5";
974
- if (s === "claude-sonnet") return "claude-sonnet-5-5";
1083
+ if (s === "claude-opus") return PREFERRED_CLAUDE_OPUS;
1084
+ if (s === "claude-sonnet") return PREFERRED_CLAUDE;
975
1085
  if (s === "claude-opus-4-6" || s === "claude-opus-4-8" || s === "claude-opus-4.6" || s === "claude-opus-4-5") return "claude-opus-4-6-thinking";
976
1086
  if (s === "claude-sonnet-4.6" || s === "claude-sonnet-4-5") return "claude-sonnet-4-6";
977
- if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return "gpt-oss-120b-medium";
1087
+ if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return PREFERRED_OPENAI;
978
1088
  const claude55 = s.match(/^(claude-(?:sonnet|opus)-5-5)-(?:low|medium|high)$/);
979
1089
  if (claude55 !== null && claude55[1] !== void 0) return claude55[1];
980
1090
  return id.trim();
@@ -1783,6 +1893,33 @@ function nodeScriptEnv(env) {
1783
1893
  ELECTRON_RUN_AS_NODE: "1"
1784
1894
  };
1785
1895
  }
1896
+ //#endregion
1897
+ //#region src/common/timeouts.ts
1898
+ /** Host-side hard deadline for any plugin route; the last line of defence. */
1899
+ const ROUTE_TIMEOUT_MS = 3e4;
1900
+ /** Slack above a job's own deadline before its route may give up. */
1901
+ const ROUTE_DEADLINE_SLACK_MS = 15e3;
1902
+ /**
1903
+ * Deadline for a route that fronts a genuinely long job (a translation is a
1904
+ * full agy turn: `translateTimeoutMs` defaults to 120s and medium effort
1905
+ * typically takes 20–45s). The general 30s route deadline would answer 504
1906
+ * first, and because `sendJson` is exactly-once the real 200 would then be
1907
+ * discarded — every slow translation would look like a failure.
1908
+ */
1909
+ function longRouteTimeout(jobTimeoutMs) {
1910
+ return Math.max(ROUTE_TIMEOUT_MS, (Number.isFinite(jobTimeoutMs) && jobTimeoutMs > 0 ? jobTimeoutMs : ROUTE_TIMEOUT_MS) + ROUTE_DEADLINE_SLACK_MS);
1911
+ }
1912
+ /** How long a manual quota refresh keeps its dedupe entry when work never settles. */
1913
+ const QUOTA_REFRESH_DEDUP_MS = 9e4;
1914
+ /**
1915
+ * Grace the idle watchdog grants before killing a quiet child. libuv runs the
1916
+ * timers phase BEFORE the poll phase: when the DSH host's event loop is blocked
1917
+ * (a large parse, many parallel workers), an expired watchdog can fire before
1918
+ * queued stdout/stderr from a still-active child is delivered. One short grace
1919
+ * lets that output arrive instead of killing a healthy run. Capped at the run's
1920
+ * own idle budget so short-budget tests and genuine idle kills stay prompt.
1921
+ */
1922
+ const WATCHDOG_GRACE_MS = 5e3;
1786
1923
  function nonBlank(v) {
1787
1924
  return (v ?? "").trim();
1788
1925
  }
@@ -1959,6 +2096,7 @@ function createRunState(opts) {
1959
2096
  settled: false,
1960
2097
  idleBudgetMs: opts.timeoutMs,
1961
2098
  watchdog: null,
2099
+ watchdogGraceUsed: false,
1962
2100
  turnCap: null
1963
2101
  };
1964
2102
  }
@@ -2016,13 +2154,22 @@ function writeInitialStdin(opts, child) {
2016
2154
  } catch {}
2017
2155
  }
2018
2156
  function makeRefreshWatchdog(child, state) {
2019
- return () => {
2020
- if (!state.idleBudgetMs || state.idleBudgetMs <= 0 || state.settled) return;
2157
+ const arm = (budgetMs) => {
2021
2158
  if (state.watchdog) clearTimeout(state.watchdog);
2022
2159
  state.watchdog = setTimeout(() => {
2160
+ if (!state.watchdogGraceUsed) {
2161
+ state.watchdogGraceUsed = true;
2162
+ arm(Math.min(budgetMs, WATCHDOG_GRACE_MS));
2163
+ return;
2164
+ }
2023
2165
  state.timedOut = true;
2024
2166
  killTree(child);
2025
- }, state.idleBudgetMs);
2167
+ }, budgetMs);
2168
+ };
2169
+ return () => {
2170
+ if (!state.idleBudgetMs || state.idleBudgetMs <= 0 || state.settled) return;
2171
+ state.watchdogGraceUsed = false;
2172
+ arm(state.idleBudgetMs);
2026
2173
  };
2027
2174
  }
2028
2175
  function armTurnCap(child, opts, state) {
@@ -3201,7 +3348,7 @@ function buildMirrorRunCode(runId, eventIndex, toolName, brief) {
3201
3348
  step: eventIndex
3202
3349
  });
3203
3350
  return {
3204
- code: "// dsh-agy-link mirror: replay recorded agy tool step " + eventIndex + " (" + toolName + ")\nreturn await tools['agy_tool'](" + invocation + ")",
3351
+ code: "// dsh-agy-link mirror: replay recorded agy tool step " + eventIndex + " (" + toolName + ")\nawait tools['agy_tool'](" + invocation + ")",
3205
3352
  description: brief !== void 0 && brief !== "" ? brief + " · " + toolName : toolName
3206
3353
  };
3207
3354
  }
@@ -3358,9 +3505,14 @@ function toolStepBrief(toolName, args, server) {
3358
3505
  return timing ? "schedule " + timing : prompt ? "schedule " + prompt.slice(0, 40) : "schedule";
3359
3506
  }
3360
3507
  if (effTool === "invoke_subagent") {
3508
+ const directRole = pickStr("Role", "role", "TypeName", "typeName");
3361
3509
  const subs = a.Subagents ?? a.subagents;
3362
- const firstRole = Array.isArray(subs) && subs.length > 0 && typeof subs[0].Role === "string" ? subs[0].Role : "";
3363
- return firstRole ? "subagent: " + firstRole : "invoke subagent";
3510
+ const subRole = Array.isArray(subs) && subs.length > 0 && typeof subs[0].Role === "string" ? subs[0].Role : Array.isArray(subs) && subs.length > 0 && typeof subs[0].TypeName === "string" ? subs[0].TypeName : "";
3511
+ let role = (directRole || subRole).trim();
3512
+ if (role.startsWith("\"") && role.endsWith("\"")) try {
3513
+ role = JSON.parse(role);
3514
+ } catch {}
3515
+ return role ? "subagent: " + role : "invoke subagent";
3364
3516
  }
3365
3517
  if (effTool === "send_message") {
3366
3518
  const recipient = pickStr("Recipient", "recipient", "to");
@@ -3510,12 +3662,23 @@ function presentScheduleCall(input) {
3510
3662
  rawInput: input
3511
3663
  };
3512
3664
  }
3665
+ function cleanRole(raw) {
3666
+ if (!raw) return void 0;
3667
+ let s = raw.trim();
3668
+ if (s.startsWith("\"") && s.endsWith("\"")) try {
3669
+ s = JSON.parse(s);
3670
+ } catch {}
3671
+ return s || void 0;
3672
+ }
3513
3673
  function presentSubagentCall(input) {
3514
3674
  const subs = input.Subagents ?? input.subagents;
3515
- const firstRole = Array.isArray(subs) && subs.length > 0 && typeof subs[0].Role === "string" ? subs[0].Role : Array.isArray(subs) && subs.length > 0 && typeof subs[0].TypeName === "string" ? subs[0].TypeName : void 0;
3675
+ const subRole = Array.isArray(subs) && subs.length > 0 && typeof subs[0].Role === "string" ? subs[0].Role : Array.isArray(subs) && subs.length > 0 && typeof subs[0].TypeName === "string" ? subs[0].TypeName : void 0;
3676
+ const directRole = cleanRole(pick(input, "Role", "role"));
3677
+ const directTypeName = cleanRole(pick(input, "TypeName", "typeName"));
3678
+ const effRole = cleanRole(subRole) ?? (directRole && directTypeName ? `${directRole} (${directTypeName})` : directRole ?? directTypeName);
3516
3679
  return {
3517
3680
  card: "generic",
3518
- title: pick(input, "Description", "description", "toolAction", "toolSummary") ?? (firstRole ? `Subagent: ${firstRole}` : "Invoke subagent"),
3681
+ title: pick(input, "Description", "description", "toolAction", "toolSummary") ?? (effRole ? `Subagent: ${effRole}` : "Invoke subagent"),
3519
3682
  kind: "execute",
3520
3683
  rawInput: input
3521
3684
  };
@@ -3776,6 +3939,19 @@ function rewriteImageMarkdown(text, mediaBaseUrl) {
3776
3939
  return `![${alt}](${`${mediaBaseUrl}?path=${encodeURIComponent(cleanTarget)}`})`;
3777
3940
  });
3778
3941
  }
3942
+ /** Normalize Markdown file links: strip file:/// prefix so DSH's native markdown compiler treats them as local files and opens them in the native right sidebar. */
3943
+ function normalizeFileLinks(text) {
3944
+ if (!text) return text;
3945
+ return text.replace(/(^|[^\!])\[([^\]]+)\]\((file:\/\/\/[^\s)]+|file:\/\/[^\s)]+)\)/g, (_, prefix, label, url) => {
3946
+ let target = url.trim();
3947
+ if (target.startsWith("file://")) {
3948
+ target = target.slice(7);
3949
+ if (/^\/[A-Za-z]:/.test(target)) target = target.slice(1);
3950
+ }
3951
+ target = target.replace(/\\/g, "/");
3952
+ return `${prefix}[${label}](${target})`;
3953
+ });
3954
+ }
3779
3955
  //#endregion
3780
3956
  //#region src/host/recording.ts
3781
3957
  function classifyToolError(error) {
@@ -4398,7 +4574,7 @@ var EventMapper = class {
4398
4574
  this.sawTextStep = true;
4399
4575
  yield* this.ensureBlock("text");
4400
4576
  let d;
4401
- const processedText = this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text;
4577
+ const processedText = normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text);
4402
4578
  if (ev.fragment === true) {
4403
4579
  const acc = (this.emittedByKey.get(ev.stepKey) ?? "") + processedText;
4404
4580
  this.emittedByKey.set(ev.stepKey, acc);
@@ -4434,7 +4610,7 @@ var EventMapper = class {
4434
4610
  const prev = this.emittedByKey.get(ev.stepKey) ?? "";
4435
4611
  const deltaText = suffixDelta(prev, ev.text);
4436
4612
  this.emittedByKey.set(ev.stepKey, ev.text);
4437
- const banner = prev === "" ? "[agy subagent] " : "";
4613
+ const banner = prev === "" && !ev.text.startsWith("[") ? "[agy subagent] " : "";
4438
4614
  const d = this.appendDelta(banner + deltaText);
4439
4615
  if (d) yield d;
4440
4616
  }
@@ -4478,9 +4654,10 @@ var EventMapper = class {
4478
4654
  }
4479
4655
  if (!ev.ok) {
4480
4656
  if (ev.response === "") return;
4657
+ const respText = normalizeFileLinks(ev.response);
4481
4658
  if (!this.sawTextStep) {
4482
4659
  yield* this.ensureBlock("text");
4483
- const d = this.appendDelta(ev.response);
4660
+ const d = this.appendDelta(respText);
4484
4661
  if (d) yield d;
4485
4662
  }
4486
4663
  if (ev.error !== void 0 && ev.error !== "") {
@@ -4490,7 +4667,7 @@ var EventMapper = class {
4490
4667
  }
4491
4668
  } else if (!this.sawTextStep && ev.response !== "") {
4492
4669
  yield* this.ensureBlock("text");
4493
- const d = this.appendDelta(ev.response);
4670
+ const d = this.appendDelta(normalizeFileLinks(ev.response));
4494
4671
  if (d) yield d;
4495
4672
  }
4496
4673
  yield* this.flushBannerOnlyThoughts();
@@ -4609,6 +4786,21 @@ function findConversationDb(conversationId, accountHome) {
4609
4786
  }
4610
4787
  return null;
4611
4788
  }
4789
+ /** Candidate brain directories for a conversation id across system + pool homes. */
4790
+ function brainDirCandidates(accountHome) {
4791
+ return conversationsDirCandidates(accountHome).map((d) => join(d, "..", "brain"));
4792
+ }
4793
+ /** Locate an existing conversation brain directory across system + pool homes. */
4794
+ function findBrainDir(conversationId, accountHome) {
4795
+ if (!isSafeConversationId(conversationId)) return null;
4796
+ for (const dir of brainDirCandidates(accountHome)) {
4797
+ const p = join(dir, conversationId);
4798
+ try {
4799
+ if (existsSync(p)) return p;
4800
+ } catch {}
4801
+ }
4802
+ return null;
4803
+ }
4612
4804
  /** agy conversation ids are path-safe tokens; reject anything else before join(). */
4613
4805
  const SAFE_CONVERSATION_ID = /^[A-Za-z0-9_-]{1,64}$/;
4614
4806
  function isSafeConversationId(id) {
@@ -5522,9 +5714,9 @@ function listAvailableModels(deps) {
5522
5714
  const cfg = deps.getConfig();
5523
5715
  const activeAcc = activeAccount(deps);
5524
5716
  let models;
5525
- if (activeAcc && pool) {
5717
+ if (activeAcc && pool && !cfg.poolWideCatalog) {
5526
5718
  models = deps.catalog.getModelsForAccount(activeAcc, pool);
5527
- if (!deps.catalog.hasAccountCatalog(activeAcc.id)) deps.catalog.forceRefreshAndNotify(activeAcc.id).catch(() => void 0);
5719
+ if (!deps.catalog.hasAccountCatalog(activeAcc.id)) deps.catalog.ensureAccountCatalog(activeAcc.id).catch(() => void 0);
5528
5720
  } else models = deps.catalog.getUnion(accounts, pool);
5529
5721
  const { entries, dropped } = sanitizeCatalogEntries(models);
5530
5722
  if (dropped.length > 0) deps.warnOnce("catalog-dupes", "model catalog contained duplicate ids [" + dropped.join(", ") + "] — kept first occurrence so DSH does not drop the whole provider group (INVALID_CATALOG)");
@@ -5558,7 +5750,7 @@ function resolveModelInfo(deps, model) {
5558
5750
  defaultMaxTokens: typeof cfg.maxTokensDefault === "number" && cfg.maxTokensDefault > 0 ? cfg.maxTokensDefault : 8192
5559
5751
  };
5560
5752
  if (deps.isEffortUnsupported(cleanId)) {} else if (entry && Array.isArray(entry.efforts) && entry.efforts.length > 0) {
5561
- const cleanEfforts = Array.from(new Set(entry.efforts.filter((e) => typeof e === "string" && e.trim() !== "")));
5753
+ const cleanEfforts = normalizeEfforts(entry.efforts);
5562
5754
  if (cleanEfforts.length > 0) {
5563
5755
  const def = defaultEffortFor({
5564
5756
  ...entry,
@@ -5568,7 +5760,7 @@ function resolveModelInfo(deps, model) {
5568
5760
  resolved.reasoning = {
5569
5761
  efforts: cleanEfforts.map((e) => ({
5570
5762
  id: e,
5571
- name: e
5763
+ name: effortLabel(e)
5572
5764
  })),
5573
5765
  ...validDef ? { defaultEffort: validDef } : {}
5574
5766
  };
@@ -5794,6 +5986,9 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
5794
5986
  translateSkipSameModel: asBool(get("translateSkipSameModel")) ?? base.translateSkipSameModel,
5795
5987
  translateBindConversation: asBool(get("translateBindConversation")) ?? base.translateBindConversation,
5796
5988
  translateMinIntervalMs: asNum(get("translateMinIntervalMs")) ?? base.translateMinIntervalMs,
5989
+ showHeaderBadge: asBool(get("showHeaderBadge")) ?? base.showHeaderBadge,
5990
+ showTranslateAction: asBool(get("showTranslateAction")) ?? base.showTranslateAction,
5991
+ poolWideCatalog: asBool(get("poolWideCatalog")) ?? base.poolWideCatalog,
5797
5992
  imageModel: asString(get("imageModel")) ?? base.imageModel,
5798
5993
  imageEffort: asString(get("imageEffort")) ?? base.imageEffort,
5799
5994
  imageTimeoutMs: asNum(get("imageTimeoutMs")) ?? base.imageTimeoutMs,
@@ -5898,6 +6093,18 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
5898
6093
  if (env.DSH_AGY_TRANSLATE_MODEL) cfg.translateModel = env.DSH_AGY_TRANSLATE_MODEL;
5899
6094
  if (env.DSH_AGY_TRANSLATE_EFFORT) cfg.translateEffort = env.DSH_AGY_TRANSLATE_EFFORT;
5900
6095
  if (env.DSH_AGY_TRANSLATE_LANG) cfg.translateTargetLanguage = env.DSH_AGY_TRANSLATE_LANG;
6096
+ if (env.DSH_AGY_SHOW_HEADER_BADGE !== void 0) {
6097
+ const shb = asBool(env.DSH_AGY_SHOW_HEADER_BADGE);
6098
+ if (shb !== void 0) cfg.showHeaderBadge = shb;
6099
+ }
6100
+ if (env.DSH_AGY_SHOW_TRANSLATE_ACTION !== void 0) {
6101
+ const sta = asBool(env.DSH_AGY_SHOW_TRANSLATE_ACTION);
6102
+ if (sta !== void 0) cfg.showTranslateAction = sta;
6103
+ }
6104
+ if (env.DSH_AGY_POOL_WIDE_CATALOG !== void 0) {
6105
+ const pwc = asBool(env.DSH_AGY_POOL_WIDE_CATALOG);
6106
+ if (pwc !== void 0) cfg.poolWideCatalog = pwc;
6107
+ }
5901
6108
  if (env.DSH_AGY_IMAGE_MODEL) cfg.imageModel = env.DSH_AGY_IMAGE_MODEL;
5902
6109
  if (env.DSH_AGY_IMAGE_EFFORT) cfg.imageEffort = env.DSH_AGY_IMAGE_EFFORT;
5903
6110
  if (env.DSH_AGY_IMAGE_TIMEOUT_MS) {
@@ -6601,9 +6808,9 @@ function crossFamilyFallback(deps, family) {
6601
6808
  const pool = deps.pool;
6602
6809
  if (pool === void 0) return null;
6603
6810
  const familyModel = {
6604
- google: "gemini-3.8-flash",
6605
- anthropic: "claude-sonnet-5-5",
6606
- openai: "gpt-oss-120b-medium"
6811
+ google: PREFERRED_GEMINI_FLASH,
6812
+ anthropic: PREFERRED_CLAUDE,
6813
+ openai: PREFERRED_OPENAI
6607
6814
  };
6608
6815
  for (const fbFam of [
6609
6816
  "google",
@@ -7131,14 +7338,15 @@ function writeJsonAtomic(file, body) {
7131
7338
  } catch {}
7132
7339
  throw lastErr;
7133
7340
  }
7134
- function defaultPoolDir(home = homedir()) {
7135
- if (process.env.DSH_STATE_DIR) return join(process.env.DSH_STATE_DIR, "agy-accounts");
7136
- const idx = home.replace(/\\/g, "/").indexOf("/.dsh/agy-accounts/");
7341
+ function defaultPoolDir(home) {
7342
+ if (home === void 0 && process.env.DSH_STATE_DIR) return join(process.env.DSH_STATE_DIR, "agy-accounts");
7343
+ const effectiveHome = home ?? homedir();
7344
+ const idx = effectiveHome.replace(/\\/g, "/").indexOf("/.dsh/agy-accounts/");
7137
7345
  if (idx !== -1) {
7138
- const realHome = home.slice(0, idx);
7346
+ const realHome = effectiveHome.slice(0, idx);
7139
7347
  return join(realHome, ".dsh", "agy-accounts");
7140
7348
  }
7141
- return join(home, ".dsh", "agy-accounts");
7349
+ return join(effectiveHome, ".dsh", "agy-accounts");
7142
7350
  }
7143
7351
  /**
7144
7352
  * True when a family's cached quota snapshot benches the account.
@@ -33075,6 +33283,263 @@ async function acquireCredentialSlot(account, pool, options = {}) {
33075
33283
  });
33076
33284
  }
33077
33285
  //#endregion
33286
+ //#region src/features/subagent/tracker.ts
33287
+ /**
33288
+ * Swallow the failures a live transcript produces by design — a row still being
33289
+ * written, a file replaced under us — and surface anything else, so a plain code
33290
+ * bug cannot hide behind an empty `catch`.
33291
+ */
33292
+ function noteFailure(log, what, err) {
33293
+ if (err instanceof SyntaxError) return;
33294
+ const code = err?.code;
33295
+ if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
33296
+ log?.(`subagent tracker: ${what} — ${String(err)}`);
33297
+ }
33298
+ function stripQuotes(s) {
33299
+ if (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1);
33300
+ return s;
33301
+ }
33302
+ function parseJsonObj(v) {
33303
+ if (!v) return {};
33304
+ if (typeof v === "object" && !Array.isArray(v)) return v;
33305
+ if (typeof v === "string") try {
33306
+ const p = JSON.parse(v);
33307
+ if (p && typeof p === "object" && !Array.isArray(p)) return p;
33308
+ } catch {}
33309
+ return {};
33310
+ }
33311
+ function stringArg(obj, ...keys) {
33312
+ for (const k of keys) {
33313
+ const v = obj[k];
33314
+ if (typeof v === "string" && v !== "") return stripQuotes(v);
33315
+ }
33316
+ return "";
33317
+ }
33318
+ function formatSubagentAction(role, tool, rawArgs) {
33319
+ const args = parseJsonObj(rawArgs);
33320
+ const prefix = `[子代理 · ${role}]`;
33321
+ switch (tool) {
33322
+ case "view_file":
33323
+ case "read_file": {
33324
+ const p = stringArg(args, "Path", "path", "TargetFile", "target_file", "AbsolutePath", "targetFile");
33325
+ return `${prefix} 正在查阅文件: ${(p ? basename(p.replace(/\\/g, "/")) : "") || p || "file"}`;
33326
+ }
33327
+ case "edit_file":
33328
+ case "replace_file_content":
33329
+ case "write_file":
33330
+ case "create_file": {
33331
+ const p = stringArg(args, "Path", "path", "TargetFile", "target_file", "AbsolutePath");
33332
+ return `${prefix} 正在修改/创建文件: ${(p ? basename(p.replace(/\\/g, "/")) : "") || p || "file"}`;
33333
+ }
33334
+ case "search_web":
33335
+ case "web_search": return `${prefix} 正在检索网络: "${stringArg(args, "query", "Query", "q").slice(0, 80)}"`;
33336
+ case "grep_search":
33337
+ case "find_by_name": return `${prefix} 正在检索代码: "${stringArg(args, "pattern", "Pattern", "query", "Query", "filename", "Target").slice(0, 60)}"`;
33338
+ case "list_dir":
33339
+ case "ls": return `${prefix} 正在浏览目录: ${stringArg(args, "Path", "path", "Directory", "dir") || "."}`;
33340
+ case "run_command":
33341
+ case "bash":
33342
+ case "execute_command": {
33343
+ const summary = stringArg(args, "toolSummary", "description", "Description");
33344
+ const cmd = stringArg(args, "CommandLine", "command_line", "command", "cmd");
33345
+ return `${prefix} 正在执行终端命令: ${summary || cmd.slice(0, 70)}`;
33346
+ }
33347
+ case "generate_image": return `${prefix} 正在生成参考图像: ${stringArg(args, "prompt", "Prompt", "image_name").slice(0, 60)}`;
33348
+ case "send_message": return `${prefix} 阶段调研完成,正在向主代理提交报告`;
33349
+ case "invoke_subagent": return `${prefix} 启动协同专员: ${stringArg(args, "Role", "role", "TypeName", "typeName") || "subagent"}`;
33350
+ case "manage_subagents": return `${prefix} 正在协调子代理状态 (${stringArg(args, "Action", "action") || "status"})`;
33351
+ case "schedule": return `${prefix} 设置后台定时任务`;
33352
+ default: return `${prefix} 执行操作: ${tool}`;
33353
+ }
33354
+ }
33355
+ var SubagentTracker = class {
33356
+ opts;
33357
+ conversationId;
33358
+ accountHome;
33359
+ brainDir = null;
33360
+ trackedSubagents = /* @__PURE__ */ new Map();
33361
+ seenStepKeys = /* @__PURE__ */ new Set();
33362
+ timer = null;
33363
+ active = false;
33364
+ polling = false;
33365
+ pollIntervalMs;
33366
+ constructor(opts) {
33367
+ this.opts = opts;
33368
+ this.conversationId = opts.conversationId ?? "";
33369
+ this.accountHome = opts.accountHome;
33370
+ this.pollIntervalMs = opts.pollIntervalMs ?? 500;
33371
+ }
33372
+ /** Follow the conversation agy reported in its stream-json init/result envelope. */
33373
+ setConversationId(cid) {
33374
+ if (cid === "" || cid === this.conversationId) return;
33375
+ this.conversationId = cid;
33376
+ this.brainDir = null;
33377
+ if (this.active) this.poll();
33378
+ }
33379
+ start() {
33380
+ if (this.active) return;
33381
+ this.active = true;
33382
+ this.poll();
33383
+ this.timer = setInterval(() => this.poll(), this.pollIntervalMs);
33384
+ this.timer.unref?.();
33385
+ }
33386
+ stop() {
33387
+ this.active = false;
33388
+ if (this.timer) {
33389
+ clearInterval(this.timer);
33390
+ this.timer = null;
33391
+ }
33392
+ }
33393
+ /** Run one scan across known conversations and subagents. */
33394
+ poll() {
33395
+ if (this.polling || !this.active) return;
33396
+ if (!this.conversationId) return;
33397
+ this.polling = true;
33398
+ try {
33399
+ if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
33400
+ if (!this.brainDir) return;
33401
+ const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
33402
+ for (const cid of convsToScan) this.scanSubagentsForConv(cid);
33403
+ for (const sub of this.trackedSubagents.values()) this.pollSubagentTranscript(sub);
33404
+ } catch (err) {
33405
+ noteFailure(this.opts.log, "poll", err);
33406
+ } finally {
33407
+ this.polling = false;
33408
+ }
33409
+ }
33410
+ scanSubagentsForConv(cid) {
33411
+ const bDir = cid === this.conversationId ? this.brainDir : findBrainDir(cid, this.accountHome);
33412
+ if (!bDir) return;
33413
+ const subagentsDir = join(bDir, ".system_generated", "subagents");
33414
+ if (!existsSync(subagentsDir)) return;
33415
+ let files;
33416
+ try {
33417
+ files = readdirSync(subagentsDir);
33418
+ } catch {
33419
+ return;
33420
+ }
33421
+ for (const f of files) {
33422
+ if (!f.endsWith(".json")) continue;
33423
+ const fullPath = join(subagentsDir, f);
33424
+ try {
33425
+ const raw = readFileSync(fullPath, "utf8");
33426
+ const obj = JSON.parse(raw);
33427
+ const subId = typeof obj?.conversationId === "string" ? obj.conversationId : f.replace(/\.json$/, "");
33428
+ if (!subId || this.trackedSubagents.has(subId)) continue;
33429
+ const desc = obj?.subagentDescriptor;
33430
+ const role = typeof desc?.role === "string" && desc.role !== "" ? desc.role : "专员";
33431
+ const typeName = typeof desc?.typeName === "string" && desc.typeName !== "" ? desc.typeName : "Subagent";
33432
+ const tracked = {
33433
+ conversationId: subId,
33434
+ role,
33435
+ typeName,
33436
+ brainDir: findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId),
33437
+ offset: 0,
33438
+ rest: "",
33439
+ lines: 0
33440
+ };
33441
+ this.trackedSubagents.set(subId, tracked);
33442
+ const spawnKey = `subagent-spawn-${subId}`;
33443
+ if (!this.seenStepKeys.has(spawnKey)) {
33444
+ this.seenStepKeys.add(spawnKey);
33445
+ const ev = {
33446
+ kind: "step",
33447
+ stepKey: spawnKey,
33448
+ stepKind: "subagent",
33449
+ text: `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`,
33450
+ raw: obj
33451
+ };
33452
+ this.opts.onEvent(ev);
33453
+ this.opts.noteActivity?.();
33454
+ }
33455
+ } catch (err) {
33456
+ noteFailure(this.opts.log, `descriptor ${f}`, err);
33457
+ }
33458
+ }
33459
+ }
33460
+ /**
33461
+ * Read the transcript lines appended since the last poll.
33462
+ *
33463
+ * agy rewrites nothing and only appends, so the tracker keeps a byte offset
33464
+ * instead of re-reading (and re-splitting) a transcript that grows to hundreds
33465
+ * of kilobytes: each poll costs one bounded read of the new bytes.
33466
+ */
33467
+ readNewLines(sub) {
33468
+ const logPath = join(sub.brainDir, ".system_generated", "logs", "transcript.jsonl");
33469
+ let size;
33470
+ try {
33471
+ const st = statSync(logPath);
33472
+ if (!st.isFile()) return [];
33473
+ size = st.size;
33474
+ } catch {
33475
+ return [];
33476
+ }
33477
+ if (size < sub.offset) {
33478
+ sub.offset = 0;
33479
+ sub.rest = "";
33480
+ }
33481
+ if (size === sub.offset) return [];
33482
+ const length = size - sub.offset;
33483
+ const buffer = Buffer.allocUnsafe(length);
33484
+ try {
33485
+ const fd = openSync(logPath, "r");
33486
+ try {
33487
+ readSync(fd, buffer, 0, length, sub.offset);
33488
+ } finally {
33489
+ closeSync(fd);
33490
+ }
33491
+ } catch {
33492
+ return [];
33493
+ }
33494
+ sub.offset = size;
33495
+ const parts = (sub.rest + buffer.toString("utf8")).split("\n");
33496
+ sub.rest = parts.pop() ?? "";
33497
+ return parts.filter((line) => line.trim() !== "");
33498
+ }
33499
+ pollSubagentTranscript(sub) {
33500
+ for (const line of this.readNewLines(sub)) try {
33501
+ const o = JSON.parse(line);
33502
+ sub.lines += 1;
33503
+ const stepIdx = typeof o.step_index === "number" ? o.step_index : sub.lines;
33504
+ const baseKey = `subagent-${sub.conversationId}-${stepIdx}`;
33505
+ if (Array.isArray(o.tool_calls) && o.tool_calls.length > 0) for (let tcIdx = 0; tcIdx < o.tool_calls.length; tcIdx++) {
33506
+ const tc = o.tool_calls[tcIdx];
33507
+ const toolName = typeof tc?.name === "string" ? tc.name : "";
33508
+ if (toolName === "") continue;
33509
+ const k = `${baseKey}-tc-${tcIdx}`;
33510
+ if (this.seenStepKeys.has(k)) continue;
33511
+ this.seenStepKeys.add(k);
33512
+ const ev = {
33513
+ kind: "step",
33514
+ stepKey: k,
33515
+ stepKind: "subagent",
33516
+ text: `${formatSubagentAction(sub.role, toolName, tc.args)}\n`,
33517
+ raw: o
33518
+ };
33519
+ this.opts.onEvent(ev);
33520
+ this.opts.noteActivity?.();
33521
+ }
33522
+ else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
33523
+ const k = `${baseKey}-content`;
33524
+ if (this.seenStepKeys.has(k)) continue;
33525
+ this.seenStepKeys.add(k);
33526
+ const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
33527
+ if (firstLine !== "") {
33528
+ const ev = {
33529
+ kind: "step",
33530
+ stepKey: k,
33531
+ stepKind: "subagent",
33532
+ text: `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`,
33533
+ raw: o
33534
+ };
33535
+ this.opts.onEvent(ev);
33536
+ this.opts.noteActivity?.();
33537
+ }
33538
+ }
33539
+ } catch {}
33540
+ }
33541
+ };
33542
+ //#endregion
33078
33543
  //#region src/provider/attempt.ts
33079
33544
  function brief$1(s) {
33080
33545
  const flat = s.trim().replace(/\s+/g, " ");
@@ -33215,7 +33680,7 @@ function createToolWatchdog(log, cfg) {
33215
33680
  };
33216
33681
  }
33217
33682
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
33218
- function createAttemptRecorder(deps, cfg, account) {
33683
+ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
33219
33684
  const rec = deps.runs.create();
33220
33685
  rec.accountHome = account && account.dir ? account.dir : void 0;
33221
33686
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -33223,20 +33688,41 @@ function createAttemptRecorder(deps, cfg, account) {
33223
33688
  const parser = new StreamJsonParser();
33224
33689
  deps.onParser?.(parser);
33225
33690
  const watchdog = createToolWatchdog(deps.log, cfg);
33691
+ const tracker = new SubagentTracker({
33692
+ conversationId: initialConversationId,
33693
+ accountHome: rec.accountHome,
33694
+ log: deps.log,
33695
+ onEvent: (ev) => {
33696
+ rec.append(ev);
33697
+ },
33698
+ noteActivity: () => {
33699
+ watchdog.markEvent();
33700
+ }
33701
+ });
33226
33702
  const state = {
33227
33703
  rec,
33228
33704
  parser,
33229
33705
  conversationsDir,
33230
33706
  before,
33231
- streamCid: null,
33707
+ streamCid: initialConversationId ?? null,
33232
33708
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
33233
- attachProcess: (proc) => watchdog.attach(proc),
33709
+ attachProcess: (proc) => {
33710
+ watchdog.attach(proc);
33711
+ tracker.start();
33712
+ proc.outcome.finally(() => tracker.stop());
33713
+ },
33234
33714
  feedLine: (line, onEvent, onFirstEvent) => {
33235
33715
  watchdog.markEvent();
33236
33716
  onFirstEvent?.();
33237
33717
  for (const ev of parser.feed(line + "\n")) {
33238
- if (ev.kind === "init" && ev.conversationId) state.streamCid = ev.conversationId;
33239
- if (ev.kind === "result" && ev.conversationId !== "") state.streamCid = ev.conversationId;
33718
+ if (ev.kind === "init" && ev.conversationId) {
33719
+ state.streamCid = ev.conversationId;
33720
+ tracker.setConversationId(ev.conversationId);
33721
+ }
33722
+ if (ev.kind === "result" && ev.conversationId !== "") {
33723
+ state.streamCid = ev.conversationId;
33724
+ tracker.setConversationId(ev.conversationId);
33725
+ }
33240
33726
  watchdog.trackStep(ev);
33241
33727
  rec.append(ev);
33242
33728
  if (typeof onEvent === "function") try {
@@ -33246,14 +33732,20 @@ function createAttemptRecorder(deps, cfg, account) {
33246
33732
  },
33247
33733
  drain: (onEvent) => {
33248
33734
  for (const ev of parser.flush()) {
33249
- if (ev.kind === "result" && ev.conversationId !== "") state.streamCid = ev.conversationId;
33735
+ if (ev.kind === "result" && ev.conversationId !== "") {
33736
+ state.streamCid = ev.conversationId;
33737
+ tracker.setConversationId(ev.conversationId);
33738
+ }
33250
33739
  rec.append(ev);
33251
33740
  if (typeof onEvent === "function") try {
33252
33741
  onEvent(ev);
33253
33742
  } catch {}
33254
33743
  }
33255
33744
  },
33256
- stop: () => watchdog.stop(),
33745
+ stop: () => {
33746
+ watchdog.stop();
33747
+ tracker.stop();
33748
+ },
33257
33749
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
33258
33750
  };
33259
33751
  return state;
@@ -33806,7 +34298,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
33806
34298
  * queue notices; the outcome closure runs detached exactly as before.
33807
34299
  */
33808
34300
  async function* runAgyAttempt(deps, input) {
33809
- const recorder = createAttemptRecorder(deps, input.cfg, input.account);
34301
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
33810
34302
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
33811
34303
  const slot = yield* dispatchCredentialSlot(deps, {
33812
34304
  ...input,
@@ -34255,26 +34747,38 @@ const ALIASES = {
34255
34747
  "gpt-oss": "gpt-oss",
34256
34748
  oss: "gpt-oss"
34257
34749
  };
34750
+ /**
34751
+ * Split a model word into (base, effort): `"gemini-3.8-flash high"`,
34752
+ * `"gemini-high"` and `"hydrogen extra"` all carry a level. The effort list is
34753
+ * the canonical one (common/reasoning.ts), longest suffix first, so `xhigh`
34754
+ * is never read as `high`.
34755
+ */
34756
+ function splitAskQuery(input) {
34757
+ const q = input.trim().toLowerCase();
34758
+ const prefix = ALIASES[q] ?? q.replace(/\s+/g, "-");
34759
+ for (const eff of EFFORT_SUFFIXES) if (q.endsWith(" " + eff) || q.endsWith("-" + eff)) return {
34760
+ base: prefix.slice(0, -(eff.length + 1)),
34761
+ effort: eff
34762
+ };
34763
+ return { base: prefix };
34764
+ }
34765
+ /** The effort a model word asks for, if any (`"hydrogen extra"` → `xhigh`). */
34766
+ function resolveAskEffort(input) {
34767
+ const q = input.trim();
34768
+ if (q === "") return void 0;
34769
+ return splitAskQuery(q).effort;
34770
+ }
34258
34771
  /** Resolve a user-facing model word against the live catalog. */
34259
34772
  function resolveAskModel(input, catalog, defaultModel) {
34260
34773
  const q = input.trim().toLowerCase();
34261
34774
  if (q === "") return defaultModel;
34262
34775
  const ids = catalog.models.map((m) => m.id);
34263
34776
  if (ids.includes(q)) return q;
34264
- const prefix = ALIASES[q] ?? q.replace(/\s+/g, "-");
34265
- let level = "";
34266
- for (const eff of [
34267
- "high",
34268
- "medium",
34269
- "low"
34270
- ]) if (q.endsWith(" " + eff) || q.endsWith("-" + eff)) level = eff;
34271
- const base = level !== "" ? prefix.replace(/-?(high|medium|low)$/, "") : prefix;
34777
+ const { base } = splitAskQuery(q);
34272
34778
  const candidates = ids.filter((id) => id.startsWith(base));
34273
34779
  if (candidates.length === 0) return defaultModel !== "" ? defaultModel : q;
34274
34780
  const sorted = candidates.slice().sort(compareNatural$1);
34275
- const last = sorted[sorted.length - 1] ?? q;
34276
- if (level === "") return last;
34277
- return sorted.find((id) => id.endsWith("-" + level)) ?? last;
34781
+ return sorted[sorted.length - 1] ?? q;
34278
34782
  }
34279
34783
  function compareNatural$1(a, b) {
34280
34784
  const na = a.split(/(\d+)/);
@@ -34290,7 +34794,22 @@ function compareNatural$1(a, b) {
34290
34794
  }
34291
34795
  return 0;
34292
34796
  }
34797
+ /**
34798
+ * The `model` parameter's help text, built from the LIVE catalog: the model list
34799
+ * and the effort list are never retyped here (a hardcoded "flash, pro, gemini,
34800
+ * sonnet, opus" line is the same drift that put models in the picker agy does
34801
+ * not have). Family words still work through ALIASES.
34802
+ */
34803
+ function askModelHelp(catalog) {
34804
+ const ids = catalog.models.map((m) => m.id);
34805
+ return "Model to ask: " + (ids.length > 0 ? ids.join(", ") : "any agy model id") + ", a family word (" + Object.keys(ALIASES).join(", ") + "), or an exact slug (default: the bridge default model).";
34806
+ }
34807
+ /** The `effort` parameter's help text, from the canonical effort vocabulary. */
34808
+ function askEffortHelp() {
34809
+ return "Reasoning effort for effort-capable models: " + REASONING_EFFORTS.join(", ") + ".";
34810
+ }
34293
34811
  function defineAgyAskTool(deps) {
34812
+ const catalogNow = deps.catalog();
34294
34813
  return defineTool({
34295
34814
  name: "agy_ask",
34296
34815
  description: "Delegate a one-shot task to a Google Antigravity model via the agy CLI (e.g. ask Gemini for a review while keeping the current model). Returns the final answer text.",
@@ -34302,11 +34821,11 @@ function defineAgyAskTool(deps) {
34302
34821
  },
34303
34822
  model: {
34304
34823
  type: "string",
34305
- description: "Model to ask: flash, pro, gemini, sonnet, opus, gpt-oss, or an exact slug (default: the bridge default model)."
34824
+ description: askModelHelp(catalogNow)
34306
34825
  },
34307
34826
  effort: {
34308
34827
  type: "string",
34309
- description: "Reasoning effort for effort-capable models: low, medium, or high."
34828
+ description: askEffortHelp()
34310
34829
  },
34311
34830
  mode: {
34312
34831
  type: "string",
@@ -34345,7 +34864,8 @@ function defineAgyAskTool(deps) {
34345
34864
  }
34346
34865
  const readPaths = typeof args.readPaths === "string" && args.readPaths.trim() !== "" ? args.readPaths.split(/[ ,]+/).filter(Boolean) : [];
34347
34866
  const entry = findEntry(deps.catalog(), model);
34348
- const wanted = args.effort ?? (entry?.efforts ? defaultEffortFor(entry, cfg) : void 0);
34867
+ const askedEffort = resolveAskEffort(args.model ?? "");
34868
+ const wanted = args.effort ?? askedEffort ?? (entry?.efforts ? defaultEffortFor(entry, cfg) : void 0);
34349
34869
  const learned = deps.effortUnsupported?.() ?? [];
34350
34870
  const refusedBefore = wanted !== void 0 && learned.some((m) => m !== "" && (m === model || m === entry?.id));
34351
34871
  const call = (effort) => runAgyOnce(deps, {
@@ -35570,6 +36090,43 @@ function writeMcpConfig(file, bridge) {
35570
36090
  }
35571
36091
  //#endregion
35572
36092
  //#region src/host/boot-hygiene.ts
36093
+ /**
36094
+ * On macOS, agy uses go-keyring which stores OAuth credentials inside the
36095
+ * account's isolated keychain (acc.dir/Library/Keychains/login.keychain-db) rather
36096
+ * than writing a file to ~/.gemini/antigravity-cli/antigravity-oauth-token.
36097
+ * When the disk token file is absent, recover it from the keychain so the account
36098
+ * is not falsely quarantined as auth_required.
36099
+ */
36100
+ function restoreTokenFromMacKeychain(accDir, tokenFile, log) {
36101
+ if (process.platform !== "darwin") return null;
36102
+ const targetKc = [join(accDir, "Library", "Keychains", "login.keychain-db"), join(accDir, "Library", "Keychains", "login.keychain")].find((p) => existsSync(p));
36103
+ if (!targetKc) return null;
36104
+ try {
36105
+ const raw = execFileSync("security", [
36106
+ "find-generic-password",
36107
+ "-s",
36108
+ "gemini",
36109
+ "-a",
36110
+ "antigravity",
36111
+ "-w",
36112
+ targetKc
36113
+ ], {
36114
+ encoding: "utf8",
36115
+ timeout: 3e3,
36116
+ windowsHide: true
36117
+ }).trim();
36118
+ if (!raw.startsWith("go-keyring-base64:")) return null;
36119
+ const jsonStr = Buffer.from(raw.slice(18), "base64").toString("utf8");
36120
+ if (!hasRefreshToken(jsonStr)) return null;
36121
+ mkdirSync(dirname(tokenFile), { recursive: true });
36122
+ writeFileSync(tokenFile, jsonStr, { mode: 384 });
36123
+ saveCredentialBackup(tokenFile, jsonStr);
36124
+ log?.(`[agy-link] restored account credential from macOS isolated keychain for ${accDir}`);
36125
+ return jsonStr;
36126
+ } catch {
36127
+ return null;
36128
+ }
36129
+ }
35573
36130
  function runBootHygiene(services) {
35574
36131
  const { pool, store, log, getConfig } = services;
35575
36132
  try {
@@ -35587,7 +36144,9 @@ function runBootHygiene(services) {
35587
36144
  for (const acc of pool.getAccounts()) if (acc.dir && !acc.systemHome) {
35588
36145
  purgeStaleIsolatedKeychain(acc.dir);
35589
36146
  if (ensureIsolatedKeychain(acc.dir)) kcProvisioned++;
35590
- const token = readAccountCredential(join(acc.dir, ".gemini", "antigravity-cli", "antigravity-oauth-token"), log);
36147
+ const tokenFile = join(acc.dir, ".gemini", "antigravity-cli", "antigravity-oauth-token");
36148
+ let token = readAccountCredential(tokenFile, log);
36149
+ if (!token && process.platform === "darwin") token = restoreTokenFromMacKeychain(acc.dir, tokenFile, log);
35591
36150
  if (!token && !acc.authRequired) {
35592
36151
  pool.markAuthRequired?.(acc.id, "credential file is missing or corrupted");
35593
36152
  log(`account ${acc.alias || acc.id} has no valid credential file; marked as auth_required`);
@@ -36236,7 +36795,7 @@ function clip(text, max) {
36236
36795
  * An explicit request (command flag) is honoured even when the advisory catalog
36237
36796
  * has never listed it — the adapter accepts unknown ids. The DEFAULT goes
36238
36797
  * through a fallback chain so a plan without Gemini 3.8 still translates:
36239
- * `gemini-3.8-flash` → newest `gemini-*-flash` → `defaultModel` → first model.
36798
+ * `PREFERRED_GEMINI_FLASH` → newest `gemini-*-flash` → `defaultModel` → first model.
36240
36799
  */
36241
36800
  function resolveTranslateTarget(cfg, catalog, override) {
36242
36801
  const requested = (override?.model ?? cfg.translateModel ?? "").trim();
@@ -36248,7 +36807,7 @@ function resolveTranslateTarget(cfg, catalog, override) {
36248
36807
  model = resolveModelSlug(requested);
36249
36808
  entry = findEntry(catalog, model);
36250
36809
  } else {
36251
- const candidates = ["gemini-3.8-flash"];
36810
+ const candidates = [PREFERRED_GEMINI_FLASH];
36252
36811
  if (cfg.defaultModel !== "") candidates.push(cfg.defaultModel);
36253
36812
  for (const cand of candidates) {
36254
36813
  const found = findEntry(catalog, cand);
@@ -38063,7 +38622,26 @@ async function getStoredToken(deps, account, allowKeychainFallback = true) {
38063
38622
  if (keychainToken && (keychainToken.accessToken || keychainToken.refreshToken)) return keychainToken;
38064
38623
  }
38065
38624
  }
38066
- return disk;
38625
+ if (disk) return disk;
38626
+ if (account.dir && !account.systemHome && process.platform === "darwin" && allowKeychainFallback) {
38627
+ const targetKc = [join(account.dir, "Library", "Keychains", "login.keychain-db"), join(account.dir, "Library", "Keychains", "login.keychain")].find((p) => existsSync(p));
38628
+ if (targetKc) try {
38629
+ const raw = (await execFileT("security", [
38630
+ "find-generic-password",
38631
+ "-s",
38632
+ "gemini",
38633
+ "-a",
38634
+ "antigravity",
38635
+ "-w",
38636
+ targetKc
38637
+ ], 3e3)).trim();
38638
+ if (raw) {
38639
+ const tok = parseGoKeyringPayload(raw);
38640
+ if (tok && (tok.accessToken || tok.refreshToken)) return tok;
38641
+ }
38642
+ } catch {}
38643
+ }
38644
+ return null;
38067
38645
  }
38068
38646
  /**
38069
38647
  * Persist a refreshed access token in agy's own on-disk shape.
@@ -39371,10 +39949,45 @@ function createHostServices(ctx, entryConfig = {}) {
39371
39949
  }
39372
39950
  //#endregion
39373
39951
  //#region src/transport/http/respond.ts
39952
+ /** Every plugin HTTP response has a hard deadline (see common/timeouts.ts). */
39953
+ /** WeakSet: `sendJson` must be exactly-once per response, even after a timeout. */
39954
+ const answered = /* @__PURE__ */ new WeakSet();
39374
39955
  const sendJson = (res, status, body) => {
39375
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
39376
- res.end(JSON.stringify(body));
39956
+ if (answered.has(res)) return;
39957
+ answered.add(res);
39958
+ try {
39959
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
39960
+ res.end(JSON.stringify(body));
39961
+ } catch {}
39377
39962
  };
39963
+ /**
39964
+ * Run one async route body with a GUARANTEED single response:
39965
+ * - normal path: the body sends whatever it likes;
39966
+ * - a rejection (thrown by a dependency, or a bug): 500 with `ok:false`;
39967
+ * - a hung promise past `ROUTE_TIMEOUT_MS`: 504 with `ok:false`.
39968
+ *
39969
+ * `sendJson` is exactly-once, so a late body can never write a second head
39970
+ * (`ERR_HTTP_HEADERS_SENT`) after a timeout. Every async route uses this one
39971
+ * helper instead of a bare `void (async () => …)()` — there is no second
39972
+ * error-handling copy to drift.
39973
+ */
39974
+ function runRoute(res, body, timeoutMs = ROUTE_TIMEOUT_MS) {
39975
+ const raw = res;
39976
+ const timer = setTimeout(() => {
39977
+ sendJson(raw, 504, {
39978
+ ok: false,
39979
+ error: "request timed out"
39980
+ });
39981
+ }, timeoutMs);
39982
+ timer.unref?.();
39983
+ body().catch((err) => {
39984
+ const message = err instanceof Error ? err.message : String(err);
39985
+ sendJson(raw, 500, {
39986
+ ok: false,
39987
+ error: message
39988
+ });
39989
+ }).finally(() => clearTimeout(timer));
39990
+ }
39378
39991
  const readBody = async (req, strict = false) => {
39379
39992
  const result = await readJsonBody(req);
39380
39993
  if (result.invalid || result.tooLarge) return strict ? { __invalidJson: true } : {};
@@ -39401,13 +40014,15 @@ const queryParam = (req, key) => {
39401
40014
  function handleStatus(services, req, res) {
39402
40015
  const { getConfig, bin, store, pool, catalog, auth, poolAuth, adapter, translation, lastRun } = services;
39403
40016
  const { version: versionCache, dormantReason } = services.status;
39404
- (async () => {
40017
+ runRoute(res, async () => {
39405
40018
  const cfg = getConfig();
39406
40019
  const cat = catalog.get();
39407
40020
  const poolData = pool?.getPoolData ? pool.getPoolData(cfg.proxyUrl?.trim() || void 0) : void 0;
39408
40021
  const activeId = typeof pool?.getActiveAccountId === "function" ? pool.getActiveAccountId("google") : poolData?.lastActiveAccountId ?? poolData?.primaryAccountId;
39409
40022
  const activeAcc = activeId && typeof pool?.getAccount === "function" ? pool.getAccount(activeId) : void 0;
39410
- const supportedModels = activeAcc && pool && typeof catalog.getModelsForAccount === "function" ? catalog.getModelsForAccount(activeAcc, pool) : typeof catalog.getUnion === "function" ? catalog.getUnion(pool?.getAccounts ? pool.getAccounts() : [], pool) : typeof catalog.getAllKnownModels === "function" ? catalog.getAllKnownModels(pool?.getAccounts ? pool.getAccounts() : []) : catalog.get().models ?? [];
40023
+ let supportedModels;
40024
+ if (cfg.poolWideCatalog || !activeAcc || !pool || typeof catalog.getModelsForAccount !== "function") supportedModels = typeof catalog.getUnion === "function" ? catalog.getUnion(pool?.getAccounts ? pool.getAccounts() : [], pool) : typeof catalog.getAllKnownModels === "function" ? catalog.getAllKnownModels(pool?.getAccounts ? pool.getAccounts() : []) : catalog.get().models ?? [];
40025
+ else supportedModels = catalog.getModelsForAccount(activeAcc, pool);
39411
40026
  sendJson(res, 200, {
39412
40027
  plugin: "dsh-agy-link",
39413
40028
  bin: bin(),
@@ -39435,6 +40050,9 @@ function handleStatus(services, req, res) {
39435
40050
  translateModel: cfg.translateModel,
39436
40051
  translateEffort: cfg.translateEffort,
39437
40052
  translateTargetLanguage: cfg.translateTargetLanguage,
40053
+ showHeaderBadge: cfg.showHeaderBadge,
40054
+ showTranslateAction: cfg.showTranslateAction,
40055
+ poolWideCatalog: cfg.poolWideCatalog,
39438
40056
  imageModel: cfg.imageModel,
39439
40057
  imageEffort: cfg.imageEffort,
39440
40058
  imageOutputDir: cfg.imageOutputDir,
@@ -39446,7 +40064,7 @@ function handleStatus(services, req, res) {
39446
40064
  effortUnsupported: adapter.effortUnsupportedModels(),
39447
40065
  lastRun
39448
40066
  });
39449
- })();
40067
+ });
39450
40068
  }
39451
40069
  function register$5(reg, services) {
39452
40070
  reg({
@@ -39463,7 +40081,7 @@ function handlePoolList(services, req, res) {
39463
40081
  }
39464
40082
  function handlePoolBeginAdd(services, req, res) {
39465
40083
  const { getConfig, poolAuth } = services;
39466
- (async () => {
40084
+ runRoute(res, async () => {
39467
40085
  if (methodOf(req) !== "POST") {
39468
40086
  sendJson(res, 405, { error: "POST only" });
39469
40087
  return;
@@ -39473,11 +40091,11 @@ function handlePoolBeginAdd(services, req, res) {
39473
40091
  const proxyUrl = typeof body.proxyUrl === "string" && body.proxyUrl.trim() !== "" ? body.proxyUrl.trim() : getConfig().proxyUrl.trim() || detectSystemProxy() || void 0;
39474
40092
  const st = await poolAuth.begin(alias, proxyUrl);
39475
40093
  sendJson(res, st.ok ? 200 : 500, st);
39476
- })();
40094
+ });
39477
40095
  }
39478
40096
  function handlePoolCompleteAdd(services, req, res) {
39479
40097
  const { pool, poolAuth } = services;
39480
- (async () => {
40098
+ runRoute(res, async () => {
39481
40099
  if (methodOf(req) !== "POST") {
39482
40100
  sendJson(res, 405, { error: "POST only" });
39483
40101
  return;
@@ -39499,11 +40117,11 @@ function handlePoolCompleteAdd(services, req, res) {
39499
40117
  code: st.code,
39500
40118
  pool: pool.getPoolData()
39501
40119
  });
39502
- })();
40120
+ });
39503
40121
  }
39504
40122
  function handlePoolCancelAdd(services, req, res) {
39505
40123
  const { pool, poolAuth } = services;
39506
- (async () => {
40124
+ runRoute(res, async () => {
39507
40125
  if (methodOf(req) !== "POST") {
39508
40126
  sendJson(res, 405, { error: "POST only" });
39509
40127
  return;
@@ -39514,11 +40132,11 @@ function handlePoolCancelAdd(services, req, res) {
39514
40132
  ok: true,
39515
40133
  pool: pool.getPoolData()
39516
40134
  });
39517
- })();
40135
+ });
39518
40136
  }
39519
40137
  function handlePoolAdd(services, req, res) {
39520
40138
  const { getConfig, pool, bridgeState } = services;
39521
- (async () => {
40139
+ runRoute(res, async () => {
39522
40140
  if (methodOf(req) !== "POST") {
39523
40141
  sendJson(res, 405, { error: "POST only" });
39524
40142
  return;
@@ -39540,11 +40158,11 @@ function handlePoolAdd(services, req, res) {
39540
40158
  account: acc,
39541
40159
  pool: pool.getPoolData()
39542
40160
  });
39543
- })();
40161
+ });
39544
40162
  }
39545
40163
  function handlePoolOpenTerminal(services, req, res) {
39546
40164
  const { pool } = services;
39547
- (async () => {
40165
+ runRoute(res, async () => {
39548
40166
  if (methodOf(req) !== "POST") {
39549
40167
  sendJson(res, 405, { error: "POST only" });
39550
40168
  return;
@@ -39561,11 +40179,11 @@ function handlePoolOpenTerminal(services, req, res) {
39561
40179
  ok: true,
39562
40180
  dir: acc.dir
39563
40181
  });
39564
- })();
40182
+ });
39565
40183
  }
39566
40184
  function handlePoolRemove(services, req, res) {
39567
40185
  const { pool, notifyPicker } = services;
39568
- (async () => {
40186
+ runRoute(res, async () => {
39569
40187
  if (methodOf(req) !== "POST") {
39570
40188
  sendJson(res, 405, { error: "POST only" });
39571
40189
  return;
@@ -39578,11 +40196,11 @@ function handlePoolRemove(services, req, res) {
39578
40196
  ok: true,
39579
40197
  pool: pool.getPoolData()
39580
40198
  });
39581
- })();
40199
+ });
39582
40200
  }
39583
40201
  function handlePoolEnable(services, req, res) {
39584
40202
  const { pool, notifyPicker } = services;
39585
- (async () => {
40203
+ runRoute(res, async () => {
39586
40204
  if (methodOf(req) !== "POST") {
39587
40205
  sendJson(res, 405, { error: "POST only" });
39588
40206
  return;
@@ -39596,11 +40214,11 @@ function handlePoolEnable(services, req, res) {
39596
40214
  ok,
39597
40215
  pool: pool.getPoolData()
39598
40216
  });
39599
- })();
40217
+ });
39600
40218
  }
39601
40219
  function handlePoolProxy(services, req, res) {
39602
40220
  const { pool } = services;
39603
- (async () => {
40221
+ runRoute(res, async () => {
39604
40222
  if (methodOf(req) !== "POST") {
39605
40223
  sendJson(res, 405, { error: "POST only" });
39606
40224
  return;
@@ -39613,11 +40231,11 @@ function handlePoolProxy(services, req, res) {
39613
40231
  ok: true,
39614
40232
  pool: pool.getPoolData()
39615
40233
  });
39616
- })();
40234
+ });
39617
40235
  }
39618
40236
  function handlePoolPrimary(services, req, res) {
39619
40237
  const { pool, catalog, notifyPicker } = services;
39620
- (async () => {
40238
+ runRoute(res, async () => {
39621
40239
  if (methodOf(req) !== "POST") {
39622
40240
  sendJson(res, 405, { error: "POST only" });
39623
40241
  return;
@@ -39632,11 +40250,11 @@ function handlePoolPrimary(services, req, res) {
39632
40250
  ok: true,
39633
40251
  pool: pool.getPoolData()
39634
40252
  });
39635
- })();
40253
+ });
39636
40254
  }
39637
40255
  function handlePoolMode(services, req, res) {
39638
40256
  const { pool } = services;
39639
- (async () => {
40257
+ runRoute(res, async () => {
39640
40258
  if (methodOf(req) !== "POST") {
39641
40259
  sendJson(res, 405, { error: "POST only" });
39642
40260
  return;
@@ -39647,31 +40265,54 @@ function handlePoolMode(services, req, res) {
39647
40265
  ok: true,
39648
40266
  pool: pool.getPoolData()
39649
40267
  });
39650
- })();
40268
+ });
39651
40269
  }
40270
+ /**
40271
+ * In-flight quota refreshes, keyed by account id ('' = all). A manual refresh
40272
+ * runs `agy /usage` (20s cap) plus several REST calls; waiting for all of that
40273
+ * before answering is what made the console's "同步中" spin. Rapid clicks must
40274
+ * not stack duplicate pipelines either.
40275
+ */
40276
+ const quotaRefreshInFlight = /* @__PURE__ */ new Map();
39652
40277
  function handlePoolRefreshQuota(services, req, res) {
39653
- const { pool, quota, catalog, notifyPicker } = services;
39654
- (async () => {
40278
+ const { pool, quota, catalog } = services;
40279
+ runRoute(res, async () => {
39655
40280
  if (methodOf(req) !== "POST") {
39656
40281
  sendJson(res, 405, { error: "POST only" });
39657
40282
  return;
39658
40283
  }
39659
40284
  const body = await readBody(req);
39660
40285
  const id = typeof body.id === "string" ? body.id : "";
39661
- if (id) {
39662
- const acc = pool.getAccount(id);
39663
- if (acc) await quota.refreshAccountQuota(acc, true);
39664
- } else await quota.refreshAllQuotas(true);
39665
- catalog.forceRefresh().catch(() => void 0);
40286
+ const key = id || "__all__";
40287
+ if (!quotaRefreshInFlight.has(key)) {
40288
+ const work = (async () => {
40289
+ if (id) {
40290
+ const acc = pool.getAccount(id);
40291
+ if (acc) await quota.refreshAccountQuota(acc, true);
40292
+ } else await quota.refreshAllQuotas(true);
40293
+ await catalog.forceRefresh().catch(() => void 0);
40294
+ })().catch(() => void 0);
40295
+ let releaseTimer;
40296
+ const entry = work.finally(() => {
40297
+ if (releaseTimer !== void 0) clearTimeout(releaseTimer);
40298
+ if (quotaRefreshInFlight.get(key) === entry) quotaRefreshInFlight.delete(key);
40299
+ });
40300
+ quotaRefreshInFlight.set(key, entry);
40301
+ releaseTimer = setTimeout(() => {
40302
+ if (quotaRefreshInFlight.get(key) === entry) quotaRefreshInFlight.delete(key);
40303
+ }, QUOTA_REFRESH_DEDUP_MS);
40304
+ releaseTimer.unref?.();
40305
+ }
39666
40306
  sendJson(res, 200, {
39667
40307
  ok: true,
40308
+ pending: true,
39668
40309
  pool: pool.getPoolData()
39669
40310
  });
39670
- })();
40311
+ });
39671
40312
  }
39672
40313
  function handlePoolWarmup(services, req, res) {
39673
40314
  const { pool, quota, warmup } = services;
39674
- (async () => {
40315
+ runRoute(res, async () => {
39675
40316
  try {
39676
40317
  if (methodOf(req) !== "POST") {
39677
40318
  sendJson(res, 405, { error: "POST only" });
@@ -39718,11 +40359,11 @@ function handlePoolWarmup(services, req, res) {
39718
40359
  } catch (e) {
39719
40360
  sendJson(res, 500, { error: String(e) });
39720
40361
  }
39721
- })();
40362
+ });
39722
40363
  }
39723
40364
  function handlePoolClearCooldown(services, req, res) {
39724
40365
  const { pool } = services;
39725
- (async () => {
40366
+ runRoute(res, async () => {
39726
40367
  if (methodOf(req) !== "POST") {
39727
40368
  sendJson(res, 405, { error: "POST only" });
39728
40369
  return;
@@ -39735,11 +40376,11 @@ function handlePoolClearCooldown(services, req, res) {
39735
40376
  ok: true,
39736
40377
  pool: pool.getPoolData()
39737
40378
  });
39738
- })();
40379
+ });
39739
40380
  }
39740
40381
  function handlePoolSetActive(services, req, res) {
39741
40382
  const { pool, catalog, notifyPicker } = services;
39742
- (async () => {
40383
+ runRoute(res, async () => {
39743
40384
  if (methodOf(req) !== "POST") {
39744
40385
  sendJson(res, 405, { error: "POST only" });
39745
40386
  return;
@@ -39756,11 +40397,11 @@ function handlePoolSetActive(services, req, res) {
39756
40397
  ok,
39757
40398
  pool: pool.getPoolData()
39758
40399
  });
39759
- })();
40400
+ });
39760
40401
  }
39761
40402
  function handlePoolReorder(services, req, res) {
39762
40403
  const { pool, catalog, notifyPicker } = services;
39763
- (async () => {
40404
+ runRoute(res, async () => {
39764
40405
  if (methodOf(req) !== "POST") {
39765
40406
  sendJson(res, 405, { error: "POST only" });
39766
40407
  return;
@@ -39777,11 +40418,11 @@ function handlePoolReorder(services, req, res) {
39777
40418
  ok: true,
39778
40419
  pool: pool.getPoolData()
39779
40420
  });
39780
- })();
40421
+ });
39781
40422
  }
39782
40423
  function handlePoolImport(services, req, res) {
39783
40424
  const { poolAuth, pool, notifyPicker } = services;
39784
- (async () => {
40425
+ runRoute(res, async () => {
39785
40426
  if (methodOf(req) !== "POST") {
39786
40427
  sendJson(res, 405, { error: "POST only" });
39787
40428
  return;
@@ -39812,7 +40453,7 @@ function handlePoolImport(services, req, res) {
39812
40453
  error: result.error || "Import failed",
39813
40454
  code: result.code
39814
40455
  });
39815
- })();
40456
+ });
39816
40457
  }
39817
40458
  function register$4(reg, services) {
39818
40459
  reg({
@@ -39905,7 +40546,7 @@ function register$4(reg, services) {
39905
40546
  //#region src/transport/http/routes/auth.ts
39906
40547
  function handleAuthBegin(services, req, res) {
39907
40548
  const { getConfig, auth } = services;
39908
- (async () => {
40549
+ runRoute(res, async () => {
39909
40550
  if (methodOf(req) !== "POST") {
39910
40551
  sendJson(res, 405, { error: "POST only" });
39911
40552
  return;
@@ -39916,11 +40557,11 @@ function handleAuthBegin(services, req, res) {
39916
40557
  const proxyUrl = typeof body.proxyUrl === "string" && body.proxyUrl.trim() !== "" ? body.proxyUrl.trim() : getConfig().proxyUrl.trim() || detectSystemProxy() || void 0;
39917
40558
  const st = await auth.begin(homeDir, accountId, proxyUrl);
39918
40559
  sendJson(res, 200, st);
39919
- })();
40560
+ });
39920
40561
  }
39921
40562
  function handleAuthCode(services, req, res) {
39922
40563
  const { store, pool, quota, catalog, auth } = services;
39923
- (async () => {
40564
+ runRoute(res, async () => {
39924
40565
  if (methodOf(req) !== "POST") {
39925
40566
  sendJson(res, 405, { error: "POST only" });
39926
40567
  return;
@@ -39941,11 +40582,11 @@ function handleAuthCode(services, req, res) {
39941
40582
  catalog.forceRefresh().catch(() => void 0);
39942
40583
  }
39943
40584
  sendJson(res, 200, st);
39944
- })();
40585
+ });
39945
40586
  }
39946
40587
  function handleAuthCancel(services, req, res) {
39947
40588
  const { auth } = services;
39948
- (async () => {
40589
+ runRoute(res, async () => {
39949
40590
  if (methodOf(req) !== "POST") {
39950
40591
  sendJson(res, 405, { error: "POST only" });
39951
40592
  return;
@@ -39953,11 +40594,11 @@ function handleAuthCancel(services, req, res) {
39953
40594
  await readBody(req);
39954
40595
  const st = auth.cancelAuth();
39955
40596
  sendJson(res, 200, st);
39956
- })();
40597
+ });
39957
40598
  }
39958
40599
  function handleAuthQr(services, req, res) {
39959
40600
  const { auth } = services;
39960
- (async () => {
40601
+ runRoute(res, async () => {
39961
40602
  const st = auth.status();
39962
40603
  const url = st.phase === "pending" ? st.url : void 0;
39963
40604
  if (!url) {
@@ -39981,7 +40622,7 @@ function handleAuthQr(services, req, res) {
39981
40622
  } catch {
39982
40623
  sendJson(res, 500, { error: "qr generation failed" });
39983
40624
  }
39984
- })();
40625
+ });
39985
40626
  }
39986
40627
  function register$3(reg, services) {
39987
40628
  reg({
@@ -40009,7 +40650,7 @@ function register$3(reg, services) {
40009
40650
  //#region src/transport/http/routes/config.ts
40010
40651
  function handleConfig(services, req, res) {
40011
40652
  const { setOverride, notifyPicker, onConfigWritten } = services;
40012
- (async () => {
40653
+ runRoute(res, async () => {
40013
40654
  if (methodOf(req) !== "POST") {
40014
40655
  sendJson(res, 405, { error: "POST only" });
40015
40656
  return;
@@ -40038,7 +40679,10 @@ function handleConfig(services, req, res) {
40038
40679
  "imageTimeoutMs",
40039
40680
  "imageMaxBytes",
40040
40681
  "imageOutputDir",
40041
- "imageRetries"
40682
+ "imageRetries",
40683
+ "showHeaderBadge",
40684
+ "showTranslateAction",
40685
+ "poolWideCatalog"
40042
40686
  ].includes(key)) {
40043
40687
  sendJson(res, 400, { error: "key not settable" });
40044
40688
  return;
@@ -40059,7 +40703,7 @@ function handleConfig(services, req, res) {
40059
40703
  key,
40060
40704
  value: body.value
40061
40705
  });
40062
- })();
40706
+ });
40063
40707
  }
40064
40708
  function register$2(reg, services) {
40065
40709
  reg({
@@ -40071,8 +40715,8 @@ function register$2(reg, services) {
40071
40715
  //#endregion
40072
40716
  //#region src/transport/http/routes/translate.ts
40073
40717
  function handleTranslate(services, req, res) {
40074
- const { translation } = services;
40075
- (async () => {
40718
+ const { translation, getConfig } = services;
40719
+ runRoute(res, async () => {
40076
40720
  if (methodOf(req) !== "POST") {
40077
40721
  sendJson(res, 405, { error: "POST only" });
40078
40722
  return;
@@ -40121,7 +40765,7 @@ function handleTranslate(services, req, res) {
40121
40765
  } catch (e) {
40122
40766
  sendJson(res, 500, { error: String(e) });
40123
40767
  }
40124
- })();
40768
+ }, longRouteTimeout(getConfig().translateTimeoutMs));
40125
40769
  }
40126
40770
  function handleTranslatePending(services, req, res) {
40127
40771
  const { translation } = services;
@@ -40239,6 +40883,7 @@ function safeDecodeUri(s) {
40239
40883
  }
40240
40884
  function parseRawMediaUri(raw) {
40241
40885
  let p = raw;
40886
+ if (p.startsWith("~/") || p.startsWith("~\\")) p = join(homedir(), p.slice(2));
40242
40887
  if (p.startsWith("file://")) {
40243
40888
  let converted = null;
40244
40889
  try {
@@ -40294,8 +40939,9 @@ function resolveLocalMediaPath(rawPath, workspaceRoots) {
40294
40939
  if (!rawPath || typeof rawPath !== "string") return null;
40295
40940
  const p = parseRawMediaUri(rawPath.trim());
40296
40941
  if (p === null) return null;
40297
- if (IS_WIN && (/^[A-Za-z]:/.test(p) || p.startsWith("\\\\")) || !IS_WIN && p.startsWith("/")) {
40298
- const resolved = resolve(p);
40942
+ const cleanPath = p.split(/[?#]/)[0] ?? p;
40943
+ if (IS_WIN && (/^[A-Za-z]:/.test(cleanPath) || cleanPath.startsWith("\\\\")) || !IS_WIN && cleanPath.startsWith("/")) {
40944
+ const resolved = resolve(cleanPath);
40299
40945
  if (existsSync(resolved)) return resolved;
40300
40946
  }
40301
40947
  const roots = [];
@@ -40303,12 +40949,12 @@ function resolveLocalMediaPath(rawPath, workspaceRoots) {
40303
40949
  else if (Array.isArray(workspaceRoots)) {
40304
40950
  for (const r of workspaceRoots) if (typeof r === "string" && r !== "") roots.push(r);
40305
40951
  }
40306
- const strippedRel = p.replace(/^[/\\]+/, "");
40307
- const baseName = extname(p) ? p.split(/[/\\]/).pop() : p;
40952
+ const strippedRel = cleanPath.replace(/^[/\\]+/, "");
40953
+ const baseName = extname(cleanPath) ? cleanPath.split(/[/\\]/).pop() : cleanPath;
40308
40954
  for (const root of roots) {
40309
- const candidate = resolve(root, p);
40955
+ const candidate = resolve(root, cleanPath);
40310
40956
  if (existsSync(candidate)) return candidate;
40311
- if (strippedRel !== p) {
40957
+ if (strippedRel !== cleanPath) {
40312
40958
  const relCandidate = resolve(root, strippedRel);
40313
40959
  if (existsSync(relCandidate)) return relCandidate;
40314
40960
  }
@@ -40317,7 +40963,7 @@ function resolveLocalMediaPath(rawPath, workspaceRoots) {
40317
40963
  const found = searchInDirectory(root, strippedRel, baseName, root === homedir() || root === "/" || IS_WIN && /^[A-Za-z]:\\?$/.test(root) ? 1 : 3);
40318
40964
  if (found) return found;
40319
40965
  }
40320
- const resolved = resolve(p);
40966
+ const resolved = resolve(cleanPath);
40321
40967
  if (existsSync(resolved)) return resolved;
40322
40968
  return null;
40323
40969
  }
@@ -40432,20 +41078,71 @@ function executeOpenInSystem(targetPath, reveal = false) {
40432
41078
  return { ok: true };
40433
41079
  }
40434
41080
  if (process.platform === "win32") {
40435
- if (reveal) spawn("explorer.exe", ["/select,", targetPath], {
40436
- detached: true,
40437
- stdio: "ignore"
40438
- }).unref();
40439
- else spawn("cmd.exe", [
40440
- "/c",
40441
- "start",
40442
- "\"\"",
40443
- targetPath
40444
- ], {
40445
- detached: true,
40446
- stdio: "ignore"
40447
- }).unref();
40448
- return { ok: true };
41081
+ if (reveal) {
41082
+ spawn("explorer.exe", [`/select,${targetPath}`], {
41083
+ detached: true,
41084
+ stdio: "ignore"
41085
+ }).unref();
41086
+ return { ok: true };
41087
+ }
41088
+ try {
41089
+ const psCmd = `Start-Process -FilePath "${targetPath.replace(/"/g, "`\"")}" -ErrorAction Stop`;
41090
+ if (spawnSync("powershell.exe", [
41091
+ "-NoProfile",
41092
+ "-NonInteractive",
41093
+ "-Command",
41094
+ psCmd
41095
+ ], {
41096
+ timeout: 4e3,
41097
+ encoding: "utf-8",
41098
+ windowsHide: true
41099
+ }).status === 0) return { ok: true };
41100
+ } catch {}
41101
+ const ext = extname(targetPath).toLowerCase();
41102
+ if ([
41103
+ ".md",
41104
+ ".txt",
41105
+ ".json",
41106
+ ".jsonl",
41107
+ ".yaml",
41108
+ ".yml",
41109
+ ".ts",
41110
+ ".js",
41111
+ ".py",
41112
+ ".gd",
41113
+ ".log",
41114
+ ".env"
41115
+ ].includes(ext)) {
41116
+ try {
41117
+ if (spawnSync("cmd.exe", [
41118
+ "/c",
41119
+ "code",
41120
+ targetPath
41121
+ ], {
41122
+ timeout: 3e3,
41123
+ windowsHide: true
41124
+ }).status === 0) return { ok: true };
41125
+ } catch {}
41126
+ try {
41127
+ spawn("notepad.exe", [targetPath], {
41128
+ detached: true,
41129
+ stdio: "ignore"
41130
+ }).unref();
41131
+ return { ok: true };
41132
+ } catch {}
41133
+ }
41134
+ try {
41135
+ spawn("explorer.exe", [`/select,${targetPath}`], {
41136
+ detached: true,
41137
+ stdio: "ignore"
41138
+ }).unref();
41139
+ return { ok: true };
41140
+ } catch (err) {
41141
+ return {
41142
+ ok: false,
41143
+ error: String(err)
41144
+ };
41145
+ }
40449
41146
  }
40450
41147
  spawn("xdg-open", [targetPath], {
40451
41148
  detached: true,
@@ -40639,6 +41336,9 @@ function collectWorkspaceRoots(services) {
40639
41336
  if (existsSync(desktop) && !roots.includes(desktop)) roots.push(desktop);
40640
41337
  if (existsSync(downloads) && !roots.includes(downloads)) roots.push(downloads);
40641
41338
  if (!roots.includes(home)) roots.push(home);
41339
+ try {
41340
+ for (const b of brainDirCandidates()) if (existsSync(b) && !roots.includes(b)) roots.push(b);
41341
+ } catch {}
40642
41342
  return roots;
40643
41343
  }
40644
41344
  function handleMedia(services, req, res) {