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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { accessSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
3
+ import { accessSync, closeSync, constants, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
4
4
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { homedir } from "node:os";
@@ -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,
@@ -598,6 +612,9 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
598
612
  translateSkipSameModel: asBool(get("translateSkipSameModel")) ?? base.translateSkipSameModel,
599
613
  translateBindConversation: asBool(get("translateBindConversation")) ?? base.translateBindConversation,
600
614
  translateMinIntervalMs: asNum(get("translateMinIntervalMs")) ?? base.translateMinIntervalMs,
615
+ showHeaderBadge: asBool(get("showHeaderBadge")) ?? base.showHeaderBadge,
616
+ showTranslateAction: asBool(get("showTranslateAction")) ?? base.showTranslateAction,
617
+ poolWideCatalog: asBool(get("poolWideCatalog")) ?? base.poolWideCatalog,
601
618
  imageModel: asString(get("imageModel")) ?? base.imageModel,
602
619
  imageEffort: asString(get("imageEffort")) ?? base.imageEffort,
603
620
  imageTimeoutMs: asNum(get("imageTimeoutMs")) ?? base.imageTimeoutMs,
@@ -702,6 +719,18 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
702
719
  if (env.DSH_AGY_TRANSLATE_MODEL) cfg.translateModel = env.DSH_AGY_TRANSLATE_MODEL;
703
720
  if (env.DSH_AGY_TRANSLATE_EFFORT) cfg.translateEffort = env.DSH_AGY_TRANSLATE_EFFORT;
704
721
  if (env.DSH_AGY_TRANSLATE_LANG) cfg.translateTargetLanguage = env.DSH_AGY_TRANSLATE_LANG;
722
+ if (env.DSH_AGY_SHOW_HEADER_BADGE !== void 0) {
723
+ const shb = asBool(env.DSH_AGY_SHOW_HEADER_BADGE);
724
+ if (shb !== void 0) cfg.showHeaderBadge = shb;
725
+ }
726
+ if (env.DSH_AGY_SHOW_TRANSLATE_ACTION !== void 0) {
727
+ const sta = asBool(env.DSH_AGY_SHOW_TRANSLATE_ACTION);
728
+ if (sta !== void 0) cfg.showTranslateAction = sta;
729
+ }
730
+ if (env.DSH_AGY_POOL_WIDE_CATALOG !== void 0) {
731
+ const pwc = asBool(env.DSH_AGY_POOL_WIDE_CATALOG);
732
+ if (pwc !== void 0) cfg.poolWideCatalog = pwc;
733
+ }
705
734
  if (env.DSH_AGY_IMAGE_MODEL) cfg.imageModel = env.DSH_AGY_IMAGE_MODEL;
706
735
  if (env.DSH_AGY_IMAGE_EFFORT) cfg.imageEffort = env.DSH_AGY_IMAGE_EFFORT;
707
736
  if (env.DSH_AGY_IMAGE_TIMEOUT_MS) {
@@ -1905,7 +1934,7 @@ function buildMirrorRunCode(runId, eventIndex, toolName, brief) {
1905
1934
  step: eventIndex
1906
1935
  });
1907
1936
  return {
1908
- code: "// dsh-agy-link mirror: replay recorded agy tool step " + eventIndex + " (" + toolName + ")\nreturn await tools['agy_tool'](" + invocation + ")",
1937
+ code: "// dsh-agy-link mirror: replay recorded agy tool step " + eventIndex + " (" + toolName + ")\nawait tools['agy_tool'](" + invocation + ")",
1909
1938
  description: brief !== void 0 && brief !== "" ? brief + " · " + toolName : toolName
1910
1939
  };
1911
1940
  }
@@ -2036,9 +2065,14 @@ function toolStepBrief(toolName, args, server) {
2036
2065
  return timing ? "schedule " + timing : prompt ? "schedule " + prompt.slice(0, 40) : "schedule";
2037
2066
  }
2038
2067
  if (effTool === "invoke_subagent") {
2068
+ const directRole = pickStr("Role", "role", "TypeName", "typeName");
2039
2069
  const subs = a.Subagents ?? a.subagents;
2040
- const firstRole = Array.isArray(subs) && subs.length > 0 && typeof subs[0].Role === "string" ? subs[0].Role : "";
2041
- return firstRole ? "subagent: " + firstRole : "invoke subagent";
2070
+ 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 : "";
2071
+ let role = (directRole || subRole).trim();
2072
+ if (role.startsWith("\"") && role.endsWith("\"")) try {
2073
+ role = JSON.parse(role);
2074
+ } catch {}
2075
+ return role ? "subagent: " + role : "invoke subagent";
2042
2076
  }
2043
2077
  if (effTool === "send_message") {
2044
2078
  const recipient = pickStr("Recipient", "recipient", "to");
@@ -2081,6 +2115,19 @@ function rewriteImageMarkdown(text, mediaBaseUrl) {
2081
2115
  return `![${alt}](${`${mediaBaseUrl}?path=${encodeURIComponent(cleanTarget)}`})`;
2082
2116
  });
2083
2117
  }
2118
+ /** 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. */
2119
+ function normalizeFileLinks(text) {
2120
+ if (!text) return text;
2121
+ return text.replace(/(^|[^\!])\[([^\]]+)\]\((file:\/\/\/[^\s)]+|file:\/\/[^\s)]+)\)/g, (_, prefix, label, url) => {
2122
+ let target = url.trim();
2123
+ if (target.startsWith("file://")) {
2124
+ target = target.slice(7);
2125
+ if (/^\/[A-Za-z]:/.test(target)) target = target.slice(1);
2126
+ }
2127
+ target = target.replace(/\\/g, "/");
2128
+ return `${prefix}[${label}](${target})`;
2129
+ });
2130
+ }
2084
2131
  //#endregion
2085
2132
  //#region src/host/recording.ts
2086
2133
  const waiters = Symbol("waiters");
@@ -2697,7 +2744,7 @@ var EventMapper = class {
2697
2744
  this.sawTextStep = true;
2698
2745
  yield* this.ensureBlock("text");
2699
2746
  let d;
2700
- const processedText = this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text;
2747
+ const processedText = normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text);
2701
2748
  if (ev.fragment === true) {
2702
2749
  const acc = (this.emittedByKey.get(ev.stepKey) ?? "") + processedText;
2703
2750
  this.emittedByKey.set(ev.stepKey, acc);
@@ -2733,7 +2780,7 @@ var EventMapper = class {
2733
2780
  const prev = this.emittedByKey.get(ev.stepKey) ?? "";
2734
2781
  const deltaText = suffixDelta(prev, ev.text);
2735
2782
  this.emittedByKey.set(ev.stepKey, ev.text);
2736
- const banner = prev === "" ? "[agy subagent] " : "";
2783
+ const banner = prev === "" && !ev.text.startsWith("[") ? "[agy subagent] " : "";
2737
2784
  const d = this.appendDelta(banner + deltaText);
2738
2785
  if (d) yield d;
2739
2786
  }
@@ -2777,9 +2824,10 @@ var EventMapper = class {
2777
2824
  }
2778
2825
  if (!ev.ok) {
2779
2826
  if (ev.response === "") return;
2827
+ const respText = normalizeFileLinks(ev.response);
2780
2828
  if (!this.sawTextStep) {
2781
2829
  yield* this.ensureBlock("text");
2782
- const d = this.appendDelta(ev.response);
2830
+ const d = this.appendDelta(respText);
2783
2831
  if (d) yield d;
2784
2832
  }
2785
2833
  if (ev.error !== void 0 && ev.error !== "") {
@@ -2789,7 +2837,7 @@ var EventMapper = class {
2789
2837
  }
2790
2838
  } else if (!this.sawTextStep && ev.response !== "") {
2791
2839
  yield* this.ensureBlock("text");
2792
- const d = this.appendDelta(ev.response);
2840
+ const d = this.appendDelta(normalizeFileLinks(ev.response));
2793
2841
  if (d) yield d;
2794
2842
  }
2795
2843
  yield* this.flushBannerOnlyThoughts();
@@ -2908,6 +2956,21 @@ function findConversationDb(conversationId, accountHome) {
2908
2956
  }
2909
2957
  return null;
2910
2958
  }
2959
+ /** Candidate brain directories for a conversation id across system + pool homes. */
2960
+ function brainDirCandidates(accountHome) {
2961
+ return conversationsDirCandidates(accountHome).map((d) => join(d, "..", "brain"));
2962
+ }
2963
+ /** Locate an existing conversation brain directory across system + pool homes. */
2964
+ function findBrainDir(conversationId, accountHome) {
2965
+ if (!isSafeConversationId(conversationId)) return null;
2966
+ for (const dir of brainDirCandidates(accountHome)) {
2967
+ const p = join(dir, conversationId);
2968
+ try {
2969
+ if (existsSync(p)) return p;
2970
+ } catch {}
2971
+ }
2972
+ return null;
2973
+ }
2911
2974
  /** agy conversation ids are path-safe tokens; reject anything else before join(). */
2912
2975
  const SAFE_CONVERSATION_ID = /^[A-Za-z0-9_-]{1,64}$/;
2913
2976
  function isSafeConversationId(id) {
@@ -3808,6 +3871,80 @@ var FailoverBudget = class FailoverBudget {
3808
3871
  }
3809
3872
  };
3810
3873
  //#endregion
3874
+ //#region src/common/reasoning.ts
3875
+ /** Every effort id agy accepts, in ascending intensity order. */
3876
+ const REASONING_EFFORTS = [
3877
+ "low",
3878
+ "medium",
3879
+ "high",
3880
+ "xhigh",
3881
+ "max"
3882
+ ];
3883
+ /**
3884
+ * Display names, matching agy's own model picker ("Extra" is `xhigh`, which is
3885
+ * how the GUI labels it while `agy --help` spells it `xhigh`).
3886
+ */
3887
+ const EFFORT_LABELS = {
3888
+ low: "Low",
3889
+ medium: "Medium",
3890
+ high: "High",
3891
+ xhigh: "Extra",
3892
+ max: "Max"
3893
+ };
3894
+ /** Display name for an effort id; unknown ids are shown verbatim. */
3895
+ function effortLabel(id) {
3896
+ const key = typeof id === "string" ? id.trim().toLowerCase() : "";
3897
+ return EFFORT_LABELS[key] ?? (typeof id === "string" ? id.trim() : "");
3898
+ }
3899
+ /**
3900
+ * Effort suffixes ordered so a LONGER suffix always wins: `gemini-4-hydrogen-xhigh`
3901
+ * must fold as `gemini-4-hydrogen` + `xhigh`, never as `gemini-4-hydrogen-x` + `high`.
3902
+ */
3903
+ const EFFORT_SUFFIXES = [...REASONING_EFFORTS].sort((a, b) => b.length - a.length || a.localeCompare(b));
3904
+ /**
3905
+ * Split a discovered agy slug into (base, effort).
3906
+ *
3907
+ * Returns `effort: undefined` when the slug carries no effort suffix. The
3908
+ * caller still decides whether the base is real — a lone `gemini-x-medium`
3909
+ * with no siblings must stay verbatim rather than inventing a base.
3910
+ */
3911
+ function splitEffortSuffix(slug) {
3912
+ const id = typeof slug === "string" ? slug.trim() : "";
3913
+ for (const effort of EFFORT_SUFFIXES) {
3914
+ const suffix = "-" + effort;
3915
+ if (id.length > suffix.length && id.endsWith(suffix)) return {
3916
+ base: id.slice(0, -suffix.length),
3917
+ effort
3918
+ };
3919
+ }
3920
+ return { base: id };
3921
+ }
3922
+ /**
3923
+ * Canonical ordering + de-duplication of an effort set.
3924
+ *
3925
+ * Order is always `REASONING_EFFORTS`, so the picker and the settings
3926
+ * dropdowns can never disagree about the order of Low/Medium/High/Extra.
3927
+ *
3928
+ * Ids this build does not know yet (a newer agy level, or a hand-written
3929
+ * `fallbackModels` entry) are kept AFTER the known ones in first-seen order —
3930
+ * dropping them would silently delete a user's configuration.
3931
+ */
3932
+ function normalizeEfforts(list) {
3933
+ if (list === void 0 || list === null) return [];
3934
+ const present = /* @__PURE__ */ new Set();
3935
+ const order = [];
3936
+ for (const raw of list) {
3937
+ if (typeof raw !== "string") continue;
3938
+ const id = raw.trim().toLowerCase();
3939
+ if (id === "" || present.has(id)) continue;
3940
+ present.add(id);
3941
+ order.push(id);
3942
+ }
3943
+ const known = REASONING_EFFORTS.filter((e) => present.has(e));
3944
+ const unknown = order.filter((e) => !REASONING_EFFORTS.includes(e));
3945
+ return [...known, ...unknown];
3946
+ }
3947
+ //#endregion
3811
3948
  //#region src/host/models.ts
3812
3949
  /** Check whether any enabled account in the pool has confirmed access to Argon. */
3813
3950
  function poolHasArgon(pool, catalog) {
@@ -3890,15 +4027,16 @@ function extractModelList(parsed) {
3890
4027
  }
3891
4028
  return out;
3892
4029
  }
3893
- const EFFORT_SUFFIXES = [
3894
- "low",
3895
- "medium",
3896
- "high"
3897
- ];
3898
4030
  /** Fold Gemini/Argon/Claude effort variants into base + effort set (spec ADR-10).
3899
4031
  * Claude 5.5 is listed only as tiered slugs by agy 1.5.3; the base slug is the
3900
4032
  * one that accepts `--effort`, and passing a tiered slug together with the flag
3901
- * is rejected ("--model … conflicts with --effort=…"). */
4033
+ * is rejected ("--model … conflicts with --effort=…").
4034
+ *
4035
+ * The effort vocabulary itself (including agy 1.5.7's `xhigh`, which its picker
4036
+ * labels "Extra") comes from `common/reasoning.ts` — folding must never carry
4037
+ * its own copy of the list, or a new level silently becomes a bogus MODEL:
4038
+ * a missed `xhigh` used to surface `gemini-4-hydrogen-xhigh` next to
4039
+ * `gemini-4-hydrogen` in DSH's picker. */
3902
4040
  function foldEfforts(raw) {
3903
4041
  const bases = /* @__PURE__ */ new Map();
3904
4042
  const verbatim = [];
@@ -3912,26 +4050,23 @@ function foldEfforts(raw) {
3912
4050
  });
3913
4051
  continue;
3914
4052
  }
3915
- let folded = false;
3916
- for (const eff of EFFORT_SUFFIXES) {
3917
- const suffix = "-" + eff;
3918
- if (r.slug.endsWith(suffix)) {
3919
- const base = r.slug.slice(0, -suffix.length);
3920
- const hasBare = slugSet.has(base);
3921
- const hasSibling = raw.some((x) => x.slug.startsWith(base + "-") && EFFORT_SUFFIXES.some((e) => x.slug.endsWith("-" + e)) && x.slug !== r.slug);
3922
- if (hasBare || hasSibling) {
3923
- const entry = bases.get(base) ?? {
3924
- label: stripEffortLabel(r.label, eff),
3925
- efforts: /* @__PURE__ */ new Set()
3926
- };
3927
- entry.efforts.add(eff);
3928
- bases.set(base, entry);
3929
- folded = true;
3930
- break;
3931
- }
4053
+ const split = splitEffortSuffix(r.slug);
4054
+ if (split.effort !== void 0) {
4055
+ const base = split.base;
4056
+ const eff = split.effort;
4057
+ const hasBare = slugSet.has(base);
4058
+ const hasSibling = raw.some((x) => x.slug !== r.slug && splitEffortSuffix(x.slug).base === base);
4059
+ if (hasBare || hasSibling) {
4060
+ const entry = bases.get(base) ?? {
4061
+ label: stripEffortLabel(r.label, eff),
4062
+ efforts: /* @__PURE__ */ new Set()
4063
+ };
4064
+ entry.efforts.add(eff);
4065
+ bases.set(base, entry);
4066
+ continue;
3932
4067
  }
3933
4068
  }
3934
- if (!folded) verbatim.push({
4069
+ verbatim.push({
3935
4070
  id: r.slug,
3936
4071
  name: r.label,
3937
4072
  efforts: null
@@ -3939,7 +4074,7 @@ function foldEfforts(raw) {
3939
4074
  }
3940
4075
  const folded = [];
3941
4076
  for (const [id, v] of bases) {
3942
- const efforts = EFFORT_SUFFIXES.filter((e) => v.efforts.has(e));
4077
+ const efforts = normalizeEfforts(v.efforts);
3943
4078
  folded.push({
3944
4079
  id,
3945
4080
  name: v.label !== "" ? v.label : id,
@@ -3952,9 +4087,7 @@ function foldEfforts(raw) {
3952
4087
  for (const r of raw) if (r.slug === e.id || r.slug.startsWith(e.id + "-")) best = Math.min(best, rawOrder.get(r.slug) ?? Infinity);
3953
4088
  return best;
3954
4089
  };
3955
- folded.sort((a, b) => rank(a) - rank(b));
3956
- verbatim.sort((a, b) => rank(a) - rank(b));
3957
- return [...folded, ...verbatim.filter((e) => !bases.has(e.id))];
4090
+ return [...folded, ...verbatim.filter((e) => !bases.has(e.id))].sort((a, b) => rank(a) - rank(b));
3958
4091
  }
3959
4092
  function stripEffortLabel(label, eff) {
3960
4093
  const re = new RegExp("\\s*\\(?" + eff + "\\)?\\s*$", "i");
@@ -3989,7 +4122,8 @@ function sanitizeCatalogEntries(models) {
3989
4122
  const name = typeof m.name === "string" && m.name.trim() !== "" ? m.name.trim() : id;
3990
4123
  entries.push({
3991
4124
  id,
3992
- name
4125
+ name,
4126
+ efforts: normalizeEfforts(m.efforts)
3993
4127
  });
3994
4128
  }
3995
4129
  return {
@@ -4013,6 +4147,12 @@ var ModelCatalog = class ModelCatalog {
4013
4147
  */
4014
4148
  static FALLBACK_RETRY_MS = 6e4;
4015
4149
  lastAttemptAt = 0;
4150
+ /**
4151
+ * Per-account probe timestamps. `refreshIfNeeded(accountId)` used to skip
4152
+ * the throttle whenever the account had no catalog yet, so a signed-out /
4153
+ * expired account could be probed on EVERY listModels() read (issue #106).
4154
+ */
4155
+ accountAttemptAt = /* @__PURE__ */ new Map();
4016
4156
  constructor(discover, fallbackDefs, ttlMs, onUpdate) {
4017
4157
  this.discover = discover;
4018
4158
  this.fallbackDefs = fallbackDefs;
@@ -4096,6 +4236,9 @@ var ModelCatalog = class ModelCatalog {
4096
4236
  const age = now - targetCat.discoveredAt;
4097
4237
  if (targetCat.source === "discovered" && age < this.ttlMs) return;
4098
4238
  if (targetCat.source === "fallback" && now - this.lastAttemptAt < ModelCatalog.FALLBACK_RETRY_MS) return;
4239
+ } else {
4240
+ if (now - (this.accountAttemptAt.get(accountId) ?? 0) < ModelCatalog.FALLBACK_RETRY_MS) return;
4241
+ this.accountAttemptAt.set(accountId, now);
4099
4242
  }
4100
4243
  this.lastAttemptAt = now;
4101
4244
  this.refreshing = this.refresh(accountId).finally(() => {
@@ -4103,6 +4246,20 @@ var ModelCatalog = class ModelCatalog {
4103
4246
  });
4104
4247
  return this.refreshing;
4105
4248
  }
4249
+ /**
4250
+ * Read-path discovery for one account (listModels). Unlike
4251
+ * `forceRefreshAndNotify()` this is throttled and NEVER broadcasts on a
4252
+ * failed probe: an unconditional `adapters-updated` made DSH's browser
4253
+ * re-read the catalog, which called listModels() again — a self-exciting
4254
+ * 1:1 read/probe/announce loop while signed out (issue #106). `refresh()`
4255
+ * itself announces only when the catalog contents actually changed, so a
4256
+ * successful first build still updates the picker exactly once.
4257
+ */
4258
+ async ensureAccountCatalog(accountId) {
4259
+ if (!accountId || this.accountCatalogs.has(accountId)) return this.get(accountId);
4260
+ await this.refreshIfNeeded(accountId);
4261
+ return this.get(accountId);
4262
+ }
4106
4263
  async forceRefresh(accountId) {
4107
4264
  await this.refresh(accountId);
4108
4265
  return this.get(accountId);
@@ -4121,8 +4278,10 @@ var ModelCatalog = class ModelCatalog {
4121
4278
  * switching to a Pro/Ultra account).
4122
4279
  */
4123
4280
  async forceRefreshAndNotify(accountId) {
4281
+ const hadCatalog = accountId ? this.hasAccountCatalog(accountId) : true;
4124
4282
  await this.refresh(accountId, false);
4125
- this.onUpdate?.();
4283
+ const hasCatalog = accountId ? this.hasAccountCatalog(accountId) : true;
4284
+ if (hadCatalog || hasCatalog) this.onUpdate?.();
4126
4285
  return this.get(accountId);
4127
4286
  }
4128
4287
  /**
@@ -4181,11 +4340,11 @@ var ModelCatalog = class ModelCatalog {
4181
4340
  };
4182
4341
  function resolveModelSlug(id) {
4183
4342
  const s = id.trim().toLowerCase();
4184
- if (s === "claude-opus") return "claude-opus-5-5";
4185
- if (s === "claude-sonnet") return "claude-sonnet-5-5";
4343
+ if (s === "claude-opus") return PREFERRED_CLAUDE_OPUS;
4344
+ if (s === "claude-sonnet") return PREFERRED_CLAUDE;
4186
4345
  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";
4187
4346
  if (s === "claude-sonnet-4.6" || s === "claude-sonnet-4-5") return "claude-sonnet-4-6";
4188
- if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return "gpt-oss-120b-medium";
4347
+ if (s === "gpt-oss-120b" || s === "gpt-oss-20b" || s === "gpt-oss") return PREFERRED_OPENAI;
4189
4348
  const claude55 = s.match(/^(claude-(?:sonnet|opus)-5-5)-(?:low|medium|high)$/);
4190
4349
  if (claude55 !== null && claude55[1] !== void 0) return claude55[1];
4191
4350
  return id.trim();
@@ -4220,9 +4379,9 @@ function listAvailableModels(deps) {
4220
4379
  const cfg = deps.getConfig();
4221
4380
  const activeAcc = activeAccount(deps);
4222
4381
  let models;
4223
- if (activeAcc && pool) {
4382
+ if (activeAcc && pool && !cfg.poolWideCatalog) {
4224
4383
  models = deps.catalog.getModelsForAccount(activeAcc, pool);
4225
- if (!deps.catalog.hasAccountCatalog(activeAcc.id)) deps.catalog.forceRefreshAndNotify(activeAcc.id).catch(() => void 0);
4384
+ if (!deps.catalog.hasAccountCatalog(activeAcc.id)) deps.catalog.ensureAccountCatalog(activeAcc.id).catch(() => void 0);
4226
4385
  } else models = deps.catalog.getUnion(accounts, pool);
4227
4386
  const { entries, dropped } = sanitizeCatalogEntries(models);
4228
4387
  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)");
@@ -4256,7 +4415,7 @@ function resolveModelInfo(deps, model) {
4256
4415
  defaultMaxTokens: typeof cfg.maxTokensDefault === "number" && cfg.maxTokensDefault > 0 ? cfg.maxTokensDefault : 8192
4257
4416
  };
4258
4417
  if (deps.isEffortUnsupported(cleanId)) {} else if (entry && Array.isArray(entry.efforts) && entry.efforts.length > 0) {
4259
- const cleanEfforts = Array.from(new Set(entry.efforts.filter((e) => typeof e === "string" && e.trim() !== "")));
4418
+ const cleanEfforts = normalizeEfforts(entry.efforts);
4260
4419
  if (cleanEfforts.length > 0) {
4261
4420
  const def = defaultEffortFor({
4262
4421
  ...entry,
@@ -4266,7 +4425,7 @@ function resolveModelInfo(deps, model) {
4266
4425
  resolved.reasoning = {
4267
4426
  efforts: cleanEfforts.map((e) => ({
4268
4427
  id: e,
4269
- name: e
4428
+ name: effortLabel(e)
4270
4429
  })),
4271
4430
  ...validDef ? { defaultEffort: validDef } : {}
4272
4431
  };
@@ -4669,6 +4828,17 @@ function nodeScriptEnv(env) {
4669
4828
  };
4670
4829
  }
4671
4830
  //#endregion
4831
+ //#region src/common/timeouts.ts
4832
+ /**
4833
+ * Grace the idle watchdog grants before killing a quiet child. libuv runs the
4834
+ * timers phase BEFORE the poll phase: when the DSH host's event loop is blocked
4835
+ * (a large parse, many parallel workers), an expired watchdog can fire before
4836
+ * queued stdout/stderr from a still-active child is delivered. One short grace
4837
+ * lets that output arrive instead of killing a healthy run. Capped at the run's
4838
+ * own idle budget so short-budget tests and genuine idle kills stay prompt.
4839
+ */
4840
+ const WATCHDOG_GRACE_MS = 5e3;
4841
+ //#endregion
4672
4842
  //#region src/host/auto-updater.ts
4673
4843
  function nonBlank(v) {
4674
4844
  return (v ?? "").trim();
@@ -4828,6 +4998,7 @@ function createRunState(opts) {
4828
4998
  settled: false,
4829
4999
  idleBudgetMs: opts.timeoutMs,
4830
5000
  watchdog: null,
5001
+ watchdogGraceUsed: false,
4831
5002
  turnCap: null
4832
5003
  };
4833
5004
  }
@@ -4885,13 +5056,22 @@ function writeInitialStdin(opts, child) {
4885
5056
  } catch {}
4886
5057
  }
4887
5058
  function makeRefreshWatchdog(child, state) {
4888
- return () => {
4889
- if (!state.idleBudgetMs || state.idleBudgetMs <= 0 || state.settled) return;
5059
+ const arm = (budgetMs) => {
4890
5060
  if (state.watchdog) clearTimeout(state.watchdog);
4891
5061
  state.watchdog = setTimeout(() => {
5062
+ if (!state.watchdogGraceUsed) {
5063
+ state.watchdogGraceUsed = true;
5064
+ arm(Math.min(budgetMs, WATCHDOG_GRACE_MS));
5065
+ return;
5066
+ }
4892
5067
  state.timedOut = true;
4893
5068
  killTree(child);
4894
- }, state.idleBudgetMs);
5069
+ }, budgetMs);
5070
+ };
5071
+ return () => {
5072
+ if (!state.idleBudgetMs || state.idleBudgetMs <= 0 || state.settled) return;
5073
+ state.watchdogGraceUsed = false;
5074
+ arm(state.idleBudgetMs);
4895
5075
  };
4896
5076
  }
4897
5077
  function armTurnCap(child, opts, state) {
@@ -5687,9 +5867,9 @@ function crossFamilyFallback(deps, family) {
5687
5867
  const pool = deps.pool;
5688
5868
  if (pool === void 0) return null;
5689
5869
  const familyModel = {
5690
- google: "gemini-3.8-flash",
5691
- anthropic: "claude-sonnet-5-5",
5692
- openai: "gpt-oss-120b-medium"
5870
+ google: PREFERRED_GEMINI_FLASH,
5871
+ anthropic: PREFERRED_CLAUDE,
5872
+ openai: PREFERRED_OPENAI
5693
5873
  };
5694
5874
  for (const fbFam of [
5695
5875
  "google",
@@ -6583,14 +6763,15 @@ function writeJsonAtomic(file, body) {
6583
6763
  } catch {}
6584
6764
  throw lastErr;
6585
6765
  }
6586
- function defaultPoolDir(home = homedir()) {
6587
- if (process.env.DSH_STATE_DIR) return join(process.env.DSH_STATE_DIR, "agy-accounts");
6588
- const idx = home.replace(/\\/g, "/").indexOf("/.dsh/agy-accounts/");
6766
+ function defaultPoolDir(home) {
6767
+ if (home === void 0 && process.env.DSH_STATE_DIR) return join(process.env.DSH_STATE_DIR, "agy-accounts");
6768
+ const effectiveHome = home ?? homedir();
6769
+ const idx = effectiveHome.replace(/\\/g, "/").indexOf("/.dsh/agy-accounts/");
6589
6770
  if (idx !== -1) {
6590
- const realHome = home.slice(0, idx);
6771
+ const realHome = effectiveHome.slice(0, idx);
6591
6772
  return join(realHome, ".dsh", "agy-accounts");
6592
6773
  }
6593
- return join(home, ".dsh", "agy-accounts");
6774
+ return join(effectiveHome, ".dsh", "agy-accounts");
6594
6775
  }
6595
6776
  /**
6596
6777
  * True when a family's cached quota snapshot benches the account.
@@ -32591,6 +32772,263 @@ function buildAgyEnv(input) {
32591
32772
  return env;
32592
32773
  }
32593
32774
  //#endregion
32775
+ //#region src/features/subagent/tracker.ts
32776
+ /**
32777
+ * Swallow the failures a live transcript produces by design — a row still being
32778
+ * written, a file replaced under us — and surface anything else, so a plain code
32779
+ * bug cannot hide behind an empty `catch`.
32780
+ */
32781
+ function noteFailure(log, what, err) {
32782
+ if (err instanceof SyntaxError) return;
32783
+ const code = err?.code;
32784
+ if (code === "ENOENT" || code === "EACCES" || code === "EPERM" || code === "EBUSY") return;
32785
+ log?.(`subagent tracker: ${what} — ${String(err)}`);
32786
+ }
32787
+ function stripQuotes(s) {
32788
+ if (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1);
32789
+ return s;
32790
+ }
32791
+ function parseJsonObj(v) {
32792
+ if (!v) return {};
32793
+ if (typeof v === "object" && !Array.isArray(v)) return v;
32794
+ if (typeof v === "string") try {
32795
+ const p = JSON.parse(v);
32796
+ if (p && typeof p === "object" && !Array.isArray(p)) return p;
32797
+ } catch {}
32798
+ return {};
32799
+ }
32800
+ function stringArg(obj, ...keys) {
32801
+ for (const k of keys) {
32802
+ const v = obj[k];
32803
+ if (typeof v === "string" && v !== "") return stripQuotes(v);
32804
+ }
32805
+ return "";
32806
+ }
32807
+ function formatSubagentAction(role, tool, rawArgs) {
32808
+ const args = parseJsonObj(rawArgs);
32809
+ const prefix = `[子代理 · ${role}]`;
32810
+ switch (tool) {
32811
+ case "view_file":
32812
+ case "read_file": {
32813
+ const p = stringArg(args, "Path", "path", "TargetFile", "target_file", "AbsolutePath", "targetFile");
32814
+ return `${prefix} 正在查阅文件: ${(p ? basename(p.replace(/\\/g, "/")) : "") || p || "file"}`;
32815
+ }
32816
+ case "edit_file":
32817
+ case "replace_file_content":
32818
+ case "write_file":
32819
+ case "create_file": {
32820
+ const p = stringArg(args, "Path", "path", "TargetFile", "target_file", "AbsolutePath");
32821
+ return `${prefix} 正在修改/创建文件: ${(p ? basename(p.replace(/\\/g, "/")) : "") || p || "file"}`;
32822
+ }
32823
+ case "search_web":
32824
+ case "web_search": return `${prefix} 正在检索网络: "${stringArg(args, "query", "Query", "q").slice(0, 80)}"`;
32825
+ case "grep_search":
32826
+ case "find_by_name": return `${prefix} 正在检索代码: "${stringArg(args, "pattern", "Pattern", "query", "Query", "filename", "Target").slice(0, 60)}"`;
32827
+ case "list_dir":
32828
+ case "ls": return `${prefix} 正在浏览目录: ${stringArg(args, "Path", "path", "Directory", "dir") || "."}`;
32829
+ case "run_command":
32830
+ case "bash":
32831
+ case "execute_command": {
32832
+ const summary = stringArg(args, "toolSummary", "description", "Description");
32833
+ const cmd = stringArg(args, "CommandLine", "command_line", "command", "cmd");
32834
+ return `${prefix} 正在执行终端命令: ${summary || cmd.slice(0, 70)}`;
32835
+ }
32836
+ case "generate_image": return `${prefix} 正在生成参考图像: ${stringArg(args, "prompt", "Prompt", "image_name").slice(0, 60)}`;
32837
+ case "send_message": return `${prefix} 阶段调研完成,正在向主代理提交报告`;
32838
+ case "invoke_subagent": return `${prefix} 启动协同专员: ${stringArg(args, "Role", "role", "TypeName", "typeName") || "subagent"}`;
32839
+ case "manage_subagents": return `${prefix} 正在协调子代理状态 (${stringArg(args, "Action", "action") || "status"})`;
32840
+ case "schedule": return `${prefix} 设置后台定时任务`;
32841
+ default: return `${prefix} 执行操作: ${tool}`;
32842
+ }
32843
+ }
32844
+ var SubagentTracker = class {
32845
+ opts;
32846
+ conversationId;
32847
+ accountHome;
32848
+ brainDir = null;
32849
+ trackedSubagents = /* @__PURE__ */ new Map();
32850
+ seenStepKeys = /* @__PURE__ */ new Set();
32851
+ timer = null;
32852
+ active = false;
32853
+ polling = false;
32854
+ pollIntervalMs;
32855
+ constructor(opts) {
32856
+ this.opts = opts;
32857
+ this.conversationId = opts.conversationId ?? "";
32858
+ this.accountHome = opts.accountHome;
32859
+ this.pollIntervalMs = opts.pollIntervalMs ?? 500;
32860
+ }
32861
+ /** Follow the conversation agy reported in its stream-json init/result envelope. */
32862
+ setConversationId(cid) {
32863
+ if (cid === "" || cid === this.conversationId) return;
32864
+ this.conversationId = cid;
32865
+ this.brainDir = null;
32866
+ if (this.active) this.poll();
32867
+ }
32868
+ start() {
32869
+ if (this.active) return;
32870
+ this.active = true;
32871
+ this.poll();
32872
+ this.timer = setInterval(() => this.poll(), this.pollIntervalMs);
32873
+ this.timer.unref?.();
32874
+ }
32875
+ stop() {
32876
+ this.active = false;
32877
+ if (this.timer) {
32878
+ clearInterval(this.timer);
32879
+ this.timer = null;
32880
+ }
32881
+ }
32882
+ /** Run one scan across known conversations and subagents. */
32883
+ poll() {
32884
+ if (this.polling || !this.active) return;
32885
+ if (!this.conversationId) return;
32886
+ this.polling = true;
32887
+ try {
32888
+ if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
32889
+ if (!this.brainDir) return;
32890
+ const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
32891
+ for (const cid of convsToScan) this.scanSubagentsForConv(cid);
32892
+ for (const sub of this.trackedSubagents.values()) this.pollSubagentTranscript(sub);
32893
+ } catch (err) {
32894
+ noteFailure(this.opts.log, "poll", err);
32895
+ } finally {
32896
+ this.polling = false;
32897
+ }
32898
+ }
32899
+ scanSubagentsForConv(cid) {
32900
+ const bDir = cid === this.conversationId ? this.brainDir : findBrainDir(cid, this.accountHome);
32901
+ if (!bDir) return;
32902
+ const subagentsDir = join(bDir, ".system_generated", "subagents");
32903
+ if (!existsSync(subagentsDir)) return;
32904
+ let files;
32905
+ try {
32906
+ files = readdirSync(subagentsDir);
32907
+ } catch {
32908
+ return;
32909
+ }
32910
+ for (const f of files) {
32911
+ if (!f.endsWith(".json")) continue;
32912
+ const fullPath = join(subagentsDir, f);
32913
+ try {
32914
+ const raw = readFileSync(fullPath, "utf8");
32915
+ const obj = JSON.parse(raw);
32916
+ const subId = typeof obj?.conversationId === "string" ? obj.conversationId : f.replace(/\.json$/, "");
32917
+ if (!subId || this.trackedSubagents.has(subId)) continue;
32918
+ const desc = obj?.subagentDescriptor;
32919
+ const role = typeof desc?.role === "string" && desc.role !== "" ? desc.role : "专员";
32920
+ const typeName = typeof desc?.typeName === "string" && desc.typeName !== "" ? desc.typeName : "Subagent";
32921
+ const tracked = {
32922
+ conversationId: subId,
32923
+ role,
32924
+ typeName,
32925
+ brainDir: findBrainDir(subId, this.accountHome) ?? join(bDir, "..", subId),
32926
+ offset: 0,
32927
+ rest: "",
32928
+ lines: 0
32929
+ };
32930
+ this.trackedSubagents.set(subId, tracked);
32931
+ const spawnKey = `subagent-spawn-${subId}`;
32932
+ if (!this.seenStepKeys.has(spawnKey)) {
32933
+ this.seenStepKeys.add(spawnKey);
32934
+ const ev = {
32935
+ kind: "step",
32936
+ stepKey: spawnKey,
32937
+ stepKind: "subagent",
32938
+ text: `[子代理 · ${role}] 已启动协同专员 (${typeName})\n`,
32939
+ raw: obj
32940
+ };
32941
+ this.opts.onEvent(ev);
32942
+ this.opts.noteActivity?.();
32943
+ }
32944
+ } catch (err) {
32945
+ noteFailure(this.opts.log, `descriptor ${f}`, err);
32946
+ }
32947
+ }
32948
+ }
32949
+ /**
32950
+ * Read the transcript lines appended since the last poll.
32951
+ *
32952
+ * agy rewrites nothing and only appends, so the tracker keeps a byte offset
32953
+ * instead of re-reading (and re-splitting) a transcript that grows to hundreds
32954
+ * of kilobytes: each poll costs one bounded read of the new bytes.
32955
+ */
32956
+ readNewLines(sub) {
32957
+ const logPath = join(sub.brainDir, ".system_generated", "logs", "transcript.jsonl");
32958
+ let size;
32959
+ try {
32960
+ const st = statSync(logPath);
32961
+ if (!st.isFile()) return [];
32962
+ size = st.size;
32963
+ } catch {
32964
+ return [];
32965
+ }
32966
+ if (size < sub.offset) {
32967
+ sub.offset = 0;
32968
+ sub.rest = "";
32969
+ }
32970
+ if (size === sub.offset) return [];
32971
+ const length = size - sub.offset;
32972
+ const buffer = Buffer.allocUnsafe(length);
32973
+ try {
32974
+ const fd = openSync(logPath, "r");
32975
+ try {
32976
+ readSync(fd, buffer, 0, length, sub.offset);
32977
+ } finally {
32978
+ closeSync(fd);
32979
+ }
32980
+ } catch {
32981
+ return [];
32982
+ }
32983
+ sub.offset = size;
32984
+ const parts = (sub.rest + buffer.toString("utf8")).split("\n");
32985
+ sub.rest = parts.pop() ?? "";
32986
+ return parts.filter((line) => line.trim() !== "");
32987
+ }
32988
+ pollSubagentTranscript(sub) {
32989
+ for (const line of this.readNewLines(sub)) try {
32990
+ const o = JSON.parse(line);
32991
+ sub.lines += 1;
32992
+ const stepIdx = typeof o.step_index === "number" ? o.step_index : sub.lines;
32993
+ const baseKey = `subagent-${sub.conversationId}-${stepIdx}`;
32994
+ if (Array.isArray(o.tool_calls) && o.tool_calls.length > 0) for (let tcIdx = 0; tcIdx < o.tool_calls.length; tcIdx++) {
32995
+ const tc = o.tool_calls[tcIdx];
32996
+ const toolName = typeof tc?.name === "string" ? tc.name : "";
32997
+ if (toolName === "") continue;
32998
+ const k = `${baseKey}-tc-${tcIdx}`;
32999
+ if (this.seenStepKeys.has(k)) continue;
33000
+ this.seenStepKeys.add(k);
33001
+ const ev = {
33002
+ kind: "step",
33003
+ stepKey: k,
33004
+ stepKind: "subagent",
33005
+ text: `${formatSubagentAction(sub.role, toolName, tc.args)}\n`,
33006
+ raw: o
33007
+ };
33008
+ this.opts.onEvent(ev);
33009
+ this.opts.noteActivity?.();
33010
+ }
33011
+ else if (o.type === "PLANNER_RESPONSE" && typeof o.content === "string" && o.content.trim() !== "") {
33012
+ const k = `${baseKey}-content`;
33013
+ if (this.seenStepKeys.has(k)) continue;
33014
+ this.seenStepKeys.add(k);
33015
+ const firstLine = o.content.trim().split("\n")[0].replace(/^#+\s*/, "").slice(0, 100);
33016
+ if (firstLine !== "") {
33017
+ const ev = {
33018
+ kind: "step",
33019
+ stepKey: k,
33020
+ stepKind: "subagent",
33021
+ text: `[子代理 · ${sub.role}] 阶段进展: ${firstLine}\n`,
33022
+ raw: o
33023
+ };
33024
+ this.opts.onEvent(ev);
33025
+ this.opts.noteActivity?.();
33026
+ }
33027
+ }
33028
+ } catch {}
33029
+ }
33030
+ };
33031
+ //#endregion
32594
33032
  //#region src/provider/attempt.ts
32595
33033
  function brief$1(s) {
32596
33034
  const flat = s.trim().replace(/\s+/g, " ");
@@ -32731,7 +33169,7 @@ function createToolWatchdog(log, cfg) {
32731
33169
  };
32732
33170
  }
32733
33171
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
32734
- function createAttemptRecorder(deps, cfg, account) {
33172
+ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
32735
33173
  const rec = deps.runs.create();
32736
33174
  rec.accountHome = account && account.dir ? account.dir : void 0;
32737
33175
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -32739,20 +33177,41 @@ function createAttemptRecorder(deps, cfg, account) {
32739
33177
  const parser = new StreamJsonParser();
32740
33178
  deps.onParser?.(parser);
32741
33179
  const watchdog = createToolWatchdog(deps.log, cfg);
33180
+ const tracker = new SubagentTracker({
33181
+ conversationId: initialConversationId,
33182
+ accountHome: rec.accountHome,
33183
+ log: deps.log,
33184
+ onEvent: (ev) => {
33185
+ rec.append(ev);
33186
+ },
33187
+ noteActivity: () => {
33188
+ watchdog.markEvent();
33189
+ }
33190
+ });
32742
33191
  const state = {
32743
33192
  rec,
32744
33193
  parser,
32745
33194
  conversationsDir,
32746
33195
  before,
32747
- streamCid: null,
33196
+ streamCid: initialConversationId ?? null,
32748
33197
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
32749
- attachProcess: (proc) => watchdog.attach(proc),
33198
+ attachProcess: (proc) => {
33199
+ watchdog.attach(proc);
33200
+ tracker.start();
33201
+ proc.outcome.finally(() => tracker.stop());
33202
+ },
32750
33203
  feedLine: (line, onEvent, onFirstEvent) => {
32751
33204
  watchdog.markEvent();
32752
33205
  onFirstEvent?.();
32753
33206
  for (const ev of parser.feed(line + "\n")) {
32754
- if (ev.kind === "init" && ev.conversationId) state.streamCid = ev.conversationId;
32755
- if (ev.kind === "result" && ev.conversationId !== "") state.streamCid = ev.conversationId;
33207
+ if (ev.kind === "init" && ev.conversationId) {
33208
+ state.streamCid = ev.conversationId;
33209
+ tracker.setConversationId(ev.conversationId);
33210
+ }
33211
+ if (ev.kind === "result" && ev.conversationId !== "") {
33212
+ state.streamCid = ev.conversationId;
33213
+ tracker.setConversationId(ev.conversationId);
33214
+ }
32756
33215
  watchdog.trackStep(ev);
32757
33216
  rec.append(ev);
32758
33217
  if (typeof onEvent === "function") try {
@@ -32762,14 +33221,20 @@ function createAttemptRecorder(deps, cfg, account) {
32762
33221
  },
32763
33222
  drain: (onEvent) => {
32764
33223
  for (const ev of parser.flush()) {
32765
- if (ev.kind === "result" && ev.conversationId !== "") state.streamCid = ev.conversationId;
33224
+ if (ev.kind === "result" && ev.conversationId !== "") {
33225
+ state.streamCid = ev.conversationId;
33226
+ tracker.setConversationId(ev.conversationId);
33227
+ }
32766
33228
  rec.append(ev);
32767
33229
  if (typeof onEvent === "function") try {
32768
33230
  onEvent(ev);
32769
33231
  } catch {}
32770
33232
  }
32771
33233
  },
32772
- stop: () => watchdog.stop(),
33234
+ stop: () => {
33235
+ watchdog.stop();
33236
+ tracker.stop();
33237
+ },
32773
33238
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
32774
33239
  };
32775
33240
  return state;
@@ -33322,7 +33787,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
33322
33787
  * queue notices; the outcome closure runs detached exactly as before.
33323
33788
  */
33324
33789
  async function* runAgyAttempt(deps, input) {
33325
- const recorder = createAttemptRecorder(deps, input.cfg, input.account);
33790
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
33326
33791
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
33327
33792
  const slot = yield* dispatchCredentialSlot(deps, {
33328
33793
  ...input,