dsh-agy-link 0.6.45 → 0.6.47

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/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.47 (2026-11-20)
4
+
5
+ ### English
6
+
7
+ - **Perf(translation): warm persistent `agy` worker pool + `low` default effort + zero-enrichment aux path.**
8
+ - Added `TranslationWorkerPool` (`src/features/translation/worker.ts`) for POSIX hosts: keeps at most one warm `agy -p --output-format stream-json --input-format stream-json --mode plan` child (`cwd = tmpdir()`, no `--add-dir` / `--disable-slash-commands`) keyed by `${accountId}|${model}|${effort}`, with idle TTL (`5m`) and turn/char recycle (`8` turns / `32,000` chars). Subsequent translations skip the ~8–9s cold CLI startup and exit wait (~4–9s end-to-end vs ~20–40s before). Windows keeps `ctx.llm.stream` to preserve OS Credential Manager slot locking.
9
+ - Changed default `translateEffort` from `medium` to `low` (plain-language rewriting does not benefit from extended chain-of-thought latency) and updated the four locale hints accordingly.
10
+ - Auxiliary non-image runs (`isAux && !isImage`) now skip `SubagentTracker` and SQLite thought/tool-arg polling in `driveSpan`, and `startAttemptProcess` eagerly persists successful conversation bindings on `result` so rapid back-to-back bound calls never race child exit.
11
+ - **Fix(accounts/models): zero-redundancy per-account model lists, orchestrator model eligibility, and authoritative catalog attribution.**
12
+ - Fixed false `lack model "gemini-pro-orchestrator-neon" in their catalog` rejections on Pro/Ultra accounts: Google's REST `fetchAvailableModels` breakdown never includes CLI-synthesized orchestrator slugs (`gemini-pro-orchestrator-neon`, `gemini-pro-orchestrator-g1-pro`), so whenever an account's per-account `agy models` cache was absent or stale, `accountSupportsModel` vetoed it. `accountSupportsModel` now recognizes backing quota evidence (`gemini-4-neon` for `gemini-pro-orchestrator-neon`, Argon access for `gemini-pro-orchestrator-g1-pro`) and `baseModelSlug` strips `-xhigh` and `-tiered-*` suffixes; global `ModelCatalog.refresh()` now also attributes its result to the exact `probedAccount.id` it ran under, and the issue-#125 self-heal `refreshQuota` also warms undiscovered accounts.
13
+ - Added `buildAccountModelRows()` (`src/common/account-models.ts`) and surfaced `status.accountModels` (keyed by account id) from each account's real `agy models` discovery; `status.catalog.count` now tracks the active account's actual supported model count.
14
+ - Account cards render the deduplicated per-account list (with effort tags when applicable) instead of raw 30+ row REST quota dumps, filtering `-sonar`/`-image` noise, folding `-tiered`/effort suffixes in fallback mode, and leaving unknown quota percentages blank instead of fabricating `100%`.
15
+ - `POST /plugins/agy-link/pool/refresh-quota` now passes `id` to `catalog.forceRefresh(id)` on single-account sync and triggers `catalog.warmAccounts()` on full sync.
16
+ - **Fix(credentials): guard macOS/Linux `systemHome` against stale Keychain/disk clobbering and disabled-primary fallback.**
17
+ - When refreshing an OAuth token for `systemHome` (`acc_primary`) on macOS/Linux, `getValidAccessToken` re-verifies the live OS Keychain `refreshToken` before persisting and discards the response if the user switched accounts in `Antigravity.app` mid-flight; `persistRefreshedToken` also avoids creating a new disk token file under real `HOME` when none exists.
18
+ - Global `ModelCatalog` discovery now strictly skips disabled/unhealthy `lastActiveAccountId` and `primaryAccountId` entries and refuses to fall back to unisolated real `HOME` when all pool accounts are disabled.
19
+ - **Fix(quota): distinguish `VALIDATION_REQUIRED` and `TOS_VIOLATION` from free-tier `403 PERMISSION_DENIED` refusals.**
20
+ - `classifySummaryRefusal()` now checks `TOS_VIOLATION` and `VALIDATION_REQUIRED` BEFORE the generic `403 PERMISSION_DENIED` free-tier branch, preventing Pro/Ultra accounts that require Google web verification from being mislabeled as "free-tier · weekly quota only". Extracts Google's `validation_url` into `quotaUnavailable.actionUrl` and renders a red warning banner with a direct "Verify now" link in the console (all 4 locales).
21
+ - **Fix(adapter): eliminate `agy stream ended without a result event` crashes and dead 3x retry replays on idle-grace termination.**
22
+ - When `agy 1.5+` catches `SIGTERM` from the idle-grace reaper, it can emit a bare `{ ok: false, response: '' }` error result before exiting — which `EventMapper` ignores while `rec.hasResult` became `true`, skipping synthetic reply recovery and settling `failureInfo = null` (causing `agy stream ended without a result event` followed by 3 identical dead-recording replays). `handleAttemptOutcome` now checks for a *consumable* result (`ok || response !== ''`) before skipping recovery, and `AgyAdapter` forgets a settled recording lacking any consumable result past the cursor on retry instead of re-driving it.
23
+ - **Fix(client): eliminate Antigravity console/menu scroll flicker.**
24
+ - Static unreported (`—`) quota bars no longer run infinite `.agy-shimmer-track` GPU animations (shimmer runs only during active refresh), removed `contain: paint` / `transform: translateZ(0)` / `isolation: isolate` from `.agy-shimmer-track` and `transform` / `filter` from `.agy-btn:hover` / `.agy-card-hover`, and added ref-counted `acquireOverlaySuspend()` while `SettingsSection` is mounted so scrolling inside DSH's native Settings -> Antigravity view suspends background conversation scanners.
25
+
26
+ ### 中文
27
+
28
+ - **性能(翻译):常驻热进程池 + 默认 `low` 思考档 + 辅助通道免 SQLite 轮询。**
29
+ - 在 macOS/Linux 新增常驻翻译进程池 `TranslationWorkerPool`(`src/features/translation/worker.ts`):最多保留 1 个 `agy -p --output-format stream-json --input-format stream-json --mode plan`(`cwd = tmpdir()`,不传 `--add-dir` 与 `--disable-slash-commands`),按 `${accountId}|${model}|${effort}` 复用,空闲 `5m` 或累计 `8` 轮 / `32,000` 字符自动回收;后续翻译免除约 8–9 秒 CLI 冷启动与退出等待(端到端降至约 4–9 秒)。Windows 维持 `ctx.llm.stream` 以遵守系统凭据槽互斥锁。
30
+ - 默认 `translateEffort` 由 `medium` 调整为 `low`(口语化「译成人话」无需冗长思维链),同步更新四语言提示文案。
31
+ - 非生图辅助调用(`isAux && !isImage`)跳过 `SubagentTracker` 与 `driveSpan` 的 SQLite 思考/工具参数重试轮询,并在 `result` 成功事件到达时即刻落盘会话绑定,避免连续调用与子进程退出竞态。
32
+ - **修复(账号/模型列表与选号):单账号模型展示 0 冗余、修复编排模型误判不可用及全局发现目录归属。**
33
+ - 修复 Pro/Ultra 账号偶发误报 `lack model "gemini-pro-orchestrator-neon" in their catalog`:Google REST 配额接口(`fetchAvailableModels`)不会返回 CLI 虚拟编排模型(`gemini-pro-orchestrator-neon`、`gemini-pro-orchestrator-g1-pro`),导致账号尚未预热单账号 `agy models` 目录(如刚重启或刚加号)或缓存陈旧时被 `accountSupportsModel` 误拒。现支持分别通过 `gemini-4-neon` 配额与 Argon 权限证据识别编排模型,`baseModelSlug` 同步兼容 `-xhigh` 与 `-tiered-*` 后缀;全局 `ModelCatalog.refresh()` 成功时同步写入实际被探测的 `probedAccount.id` 账号目录,选号自愈 `refreshQuota` 亦补齐 `warmAccounts()`。
34
+ - 新增纯投影模块 `buildAccountModelRows()`(`src/common/account-models.ts`),并在 `/plugins/agy-link/status` 返回分账号发现目录 `accountModels`;`catalog.count` 同步对齐当前活跃账号真实可用模型数。
35
+ - 账号卡片展开列表不再直接平铺原始 REST 配额里的 30+ 冗余行,而是优先展示该账号自身 `agy models` 发现的去重模型与档位,回退时自动折叠 `-tiered`/档位后缀、过滤 `-sonar`/`-image` 内部项、按名称去重,且未知余量留空不伪造 `100%`。
36
+ - `POST /plugins/agy-link/pool/refresh-quota` 单账号刷新时显式传 `catalog.forceRefresh(id)`,全量刷新时同步触发 `catalog.warmAccounts()`。
37
+ - **修复(凭据隔离):加固 macOS/Linux `systemHome` 防切号踩踏与禁用主账号回退防护。**
38
+ - 非 Windows 下刷新 `systemHome`(`acc_primary`)OAuth token 落盘前,再次校验实时系统钥匙串 `refreshToken` 未切换;若刷新途中用户在 `Antigravity.app` 切号则丢弃旧响应,且当真实 `HOME` 下原本无磁盘 token 文件时不新建残片。
39
+ - `ModelCatalog` 全局发现回退严格跳过已停用或异常的 `lastActiveAccountId` / `primaryAccountId`,池内全部账号禁用时拒绝回退真实 `HOME` 触发无隔离探测。
40
+ - **修复(额度提示):区分 `VALIDATION_REQUIRED` / `TOS_VIOLATION` 与免费账号 `403 PERMISSION_DENIED`。**
41
+ - `classifySummaryRefusal()` 现优先识别 `TOS_VIOLATION` 与 `VALIDATION_REQUIRED`,不再把需要 Google 网页验证的 Pro/Ultra 账号误报为「免费账号 · 仅限周配额」;并从 403 响应提取 `validation_url` 存入 `quotaUnavailable.actionUrl`,在控制台以红色提示条直接给出「前往验证」链接(四语言)。
42
+ - **修复(运行稳定性):消除 `agy stream ended without a result event` 偶发失败与 3 次无效重放。**
43
+ - `agy 1.5+` 收到空闲收割 `SIGTERM` 时可能先吐出一个空的 `{ ok: false, response: '' }` 结果信封:`EventMapper` 会忽略该空错误,但原先 `rec.hasResult` 已为 `true` 导致跳过 SQLite 末条回复恢复并落入 `failureInfo = null`,进而触发 `agy stream ended without a result event` 且重试时 3 次重放同一条死记录。现改为判断是否存在可消费结果(`ok || response !== ''`),且续接命中无结果的已结束记录时主动忘记旧记录重新恢复。
44
+ - **修复(客户端):根治滚动 Antigravity 控制台/设置菜单闪屏。**
45
+ - 静态未上报(`—`)的配额条不再常驻无限 `.agy-shimmer-track` 动画(仅真正刷新中显示),移除 `.agy-shimmer-track` 的 `contain: paint` / `transform: translateZ(0)` / `isolation: isolate` 及 `.agy-btn:hover` / `.agy-card-hover` 的 `transform` / `filter` 合成层抖动,并为原生设置页挂载的 `SettingsSection` 增加引用计数 `acquireOverlaySuspend()` 暂停后台会话 DOM 扫描器。
46
+
47
+ ## 0.6.46 (2026-11-20)
48
+
49
+ ### English
50
+
51
+ - **Fix(idle-grace): a turn waiting on its own background work is no longer reaped (fixes #144, merges PR #146).** agy prints `root agent idle; waiting for N background task(s)` while it finishes a build, integration test or Docker job it launched. The reaper that guards against genuinely orphaned waits gave that line a **hard-coded 5 seconds** and then SIGTERM'd the whole tree, so healthy turns died mid-flight and surfaced as `agy stream ended without a result event` (`INVALID_OUTPUT`, retried three times with the same outcome). Two independent problems, both fixed:
52
+ - **The grace is configurable**: `idleGraceMinutes` / `DSH_AGY_IDLE_GRACE_MINUTES`, default **10 minutes** (deliberately below the normal generation idle budget so a real orphan is still reclaimed). `0` disables the reaper entirely, leaving the activity watchdog and `maxTurnMinutes` to bound the turn.
53
+ - **The reaper stays suspended while any tool step is open**, not just the subagent hand-offs from #124 — a `run_command` build is exactly the same situation. It re-arms when the last step completes.
54
+ - **The count agy prints is now authoritative** (maintainer follow-up on top of the PR): `N > 0` means agy knows work is still running, so the reaper is not armed at all — no grace length makes killing it correct. Only `N = 0` (or a line without a count) takes the grace path, which keeps the conservative behaviour for older builds and chunk boundaries. The parsing lives in `src/runtime/agy/idle-line.ts`.
55
+ - Two existing tests encoded the old assumption (reap even with one pending task) and were split into "0 pending → reaped after grace" and "N pending → never reaped".
56
+
57
+ ### 中文
58
+
59
+ - **修复(idle-grace):等待自身后台任务的轮次不再被收割(修复 #144,合并 PR #146)。** agy 在等待自己派发的构建、集成测试或 Docker 任务时会打印 `root agent idle; waiting for N background task(s)`。负责回收真正僵尸等待的收割器给这一行**硬编码 5 秒**,随后 SIGTERM 整棵进程树,于是健康轮次被杀在半路,表现为 `agy stream ended without a result event`(`INVALID_OUTPUT`,退避重试三次仍是同一结局)。两个独立问题都已修复:
60
+ - **宽限期可配置**:`idleGraceMinutes` / `DSH_AGY_IDLE_GRACE_MINUTES`,默认 **10 分钟**(刻意低于普通生成的空闲预算,真正被遗弃的任务仍会被回收)。`0` 彻底关闭收割器,由活动看门狗与 `maxTurnMinutes` 兜底。
61
+ - **任意未完成的工具步骤期间收割器挂起**,不再只限 #124 的子代理交接——`run_command` 启动的构建是同一情形;最后一步完成后重新武装。
62
+ - **agy 自己打印的任务数现在具有权威性**(维护者在 PR 基础上补充):`N > 0` 表示 agy 明确知道还有工作未完成,此时**完全不武装**收割器——任何宽限期长度都不足以让终止变得正确。只有 `N = 0`(或该行没有数字)才走宽限期路径,从而为旧版本与分块边界保留保守行为。解析逻辑位于 `src/runtime/agy/idle-line.ts`。
63
+ - 两条既有测试固化了「即使有一个待完成任务也要收割」的旧假设,现拆为「0 个待完成 → 宽限期后收割」与「N 个待完成 → 永不收割」。
64
+
3
65
  ## 0.6.45 (2026-11-20)
4
66
 
5
67
  ### English
@@ -100,6 +100,7 @@ function defaultConfig() {
100
100
  timeoutMs: 6e5,
101
101
  longToolIdleMinutes: 240,
102
102
  maxTurnMinutes: 0,
103
+ idleGraceMinutes: 10,
103
104
  /**
104
105
  * Hard cap (minutes) on waiting for the Windows credential slot before the
105
106
  * dispatch releases, backs off and retries (dispatchRetries). Each attempt
@@ -161,7 +162,7 @@ function defaultConfig() {
161
162
  warmupModels: [PREFERRED_GEMINI_FLASH, PREFERRED_CLAUDE],
162
163
  autoTranslate: false,
163
164
  translateModel: PREFERRED_GEMINI_FLASH,
164
- translateEffort: "medium",
165
+ translateEffort: "low",
165
166
  translateTargetLanguage: "中文(简体)",
166
167
  translateMaxChars: 8e3,
167
168
  translateMaxTokens: 4096,
@@ -589,6 +590,7 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
589
590
  timeoutMs: asNum(get("timeoutMs")) ?? base.timeoutMs,
590
591
  longToolIdleMinutes: asNum(get("longToolIdleMinutes")) ?? base.longToolIdleMinutes,
591
592
  maxTurnMinutes: asNum(get("maxTurnMinutes")) ?? base.maxTurnMinutes,
593
+ idleGraceMinutes: asNum(get("idleGraceMinutes")) ?? base.idleGraceMinutes,
592
594
  dispatchTimeoutMinutes: asNum(get("dispatchTimeoutMinutes")) ?? base.dispatchTimeoutMinutes,
593
595
  dispatchRetries: asNum(get("dispatchRetries")) ?? base.dispatchRetries,
594
596
  parallelSameAccount: asBool(get("parallelSameAccount")) ?? base.parallelSameAccount,
@@ -668,6 +670,10 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
668
670
  const mt = asNum(env.DSH_AGY_MAX_TURN_MINUTES);
669
671
  if (mt !== void 0 && mt >= 0) cfg.maxTurnMinutes = mt;
670
672
  }
673
+ if (env.DSH_AGY_IDLE_GRACE_MINUTES) {
674
+ const g = asNum(env.DSH_AGY_IDLE_GRACE_MINUTES);
675
+ if (g !== void 0 && g >= 0) cfg.idleGraceMinutes = g;
676
+ }
671
677
  if (env.DSH_AGY_CONTEXT_WINDOW) {
672
678
  const w = asNum(env.DSH_AGY_CONTEXT_WINDOW);
673
679
  if (w !== void 0 && w > 0) cfg.contextWindowDefault = Math.floor(w);
@@ -1474,7 +1480,7 @@ function accountHasArgon(acc, pool, catalog) {
1474
1480
  if (catalog && catalog.source === "discovered") return catalog.models?.some((m) => isArgonModel(m.id)) ?? false;
1475
1481
  return false;
1476
1482
  }
1477
- const EFFORT_SUFFIX_RE = /-(?:low|medium|high|tiered|thinking)$/i;
1483
+ const EFFORT_SUFFIX_RE = /-(?:tiered-)?(?:low|medium|high|xhigh|tiered|thinking)$/i;
1478
1484
  /**
1479
1485
  * Return the un-tiered base model slug (e.g. claude-opus-4-6-thinking -> claude-opus-4-6,
1480
1486
  * claude-opus-5-5-high -> claude-opus-5-5).
@@ -1496,6 +1502,14 @@ function modelMatches(requestedModel, candidateModelId) {
1496
1502
  if (r === c) return true;
1497
1503
  return baseModelSlug(r) === baseModelSlug(c);
1498
1504
  }
1505
+ function quotaSupportsModel(acc, clean, pool, catalog) {
1506
+ const familyQuotaModels = acc.quotas?.[modelFamilyOf(clean)]?.models;
1507
+ if (Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches(clean, m.modelId))) return true;
1508
+ const lower = clean.toLowerCase();
1509
+ if (lower === "gemini-pro-orchestrator-neon") return Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches("gemini-4-neon", m.modelId));
1510
+ if (lower === "gemini-pro-orchestrator-g1-pro") return accountHasArgon(acc, pool, catalog);
1511
+ return false;
1512
+ }
1499
1513
  /**
1500
1514
  * Determine whether a managed account supports a specific model.
1501
1515
  * If the account's quota or discovered catalog enumerates models for that family,
@@ -1508,14 +1522,13 @@ function accountSupportsModel(acc, model, pool, catalog) {
1508
1522
  if (isArgonModel(clean)) return accountHasArgon(acc, pool, catalog);
1509
1523
  if (catalog && catalog.source === "discovered" && Array.isArray(catalog.models) && catalog.models.length > 0) {
1510
1524
  if (catalog.models.some((m) => modelMatches(clean, m.id))) return true;
1511
- const familyQuotaModels = acc.quotas?.[modelFamilyOf(clean)]?.models;
1512
- if (Array.isArray(familyQuotaModels) && familyQuotaModels.some((m) => modelMatches(clean, m.modelId))) return true;
1525
+ if (quotaSupportsModel(acc, clean, pool, catalog)) return true;
1513
1526
  return false;
1514
1527
  }
1515
1528
  const family = modelFamilyOf(clean);
1516
1529
  const familyQuota = acc.quotas?.[family];
1517
1530
  if (familyQuota) {
1518
- if (Array.isArray(familyQuota.models) && familyQuota.models.length > 0) return familyQuota.models.some((m) => modelMatches(clean, m.modelId));
1531
+ if (Array.isArray(familyQuota.models) && familyQuota.models.length > 0) return quotaSupportsModel(acc, clean, pool, catalog);
1519
1532
  return true;
1520
1533
  }
1521
1534
  if (acc.quotas && Object.keys(acc.quotas).length > 0 && acc.quotas.google !== void 0) return false;
@@ -2495,6 +2508,20 @@ var RunRecording = class {
2495
2508
  }
2496
2509
  return null;
2497
2510
  }
2511
+ /**
2512
+ * True when at least one consumable `result` event (`ok` or non-empty
2513
+ * `response`) exists at index >= `from`. A settled recording with
2514
+ * `failureInfo === null` and no consumable result at `>= from` would always
2515
+ * fail with `agy stream ended without a result event` if re-driven.
2516
+ */
2517
+ hasConsumableResultFrom(from) {
2518
+ const start = Math.max(0, from);
2519
+ for (let i = start; i < this.events.length; i++) {
2520
+ const ev = this.events[i];
2521
+ if (ev !== void 0 && ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
2522
+ }
2523
+ return false;
2524
+ }
2498
2525
  /** Event at an absolute index (bounds-checked). */
2499
2526
  eventAt(index) {
2500
2527
  return this.events[index];
@@ -3858,7 +3885,7 @@ async function resolveEventToolArgs(rec, ev, i, resolved) {
3858
3885
  }
3859
3886
  }
3860
3887
  }
3861
- async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
3888
+ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
3862
3889
  if (signal?.aborted) {
3863
3890
  rec.requestAbort?.();
3864
3891
  yield {
@@ -3876,14 +3903,14 @@ async function* driveSpan(deps, rec, from, cutOnTool, useCodeWrapper, goalContex
3876
3903
  deps.runs.remember(rec);
3877
3904
  deps.runs.pin(rec.runId);
3878
3905
  try {
3879
- yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice);
3906
+ yield* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment);
3880
3907
  } finally {
3881
3908
  deps.runs.unpin(rec.runId);
3882
3909
  deps.runs.remember(rec);
3883
3910
  }
3884
3911
  }
3885
3912
  /** Body of {@link driveSpan}: map recorded events until the span finishes. */
3886
- async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
3913
+ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice, skipDbEnrichment = false) {
3887
3914
  const queue = new ChunkQueue();
3888
3915
  let abortedLocally = false;
3889
3916
  const onAbort = () => {
@@ -3924,9 +3951,11 @@ async function* driveSpanBody(deps, rec, from, cutOnTool, useCodeWrapper, goalCo
3924
3951
  try {
3925
3952
  for await (const ev of rec.eventsFrom(from)) {
3926
3953
  if (abortedLocally || signal?.aborted) break;
3927
- await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
3928
- if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
3929
- await resolveEventToolArgs(rec, ev, i, resolved);
3954
+ if (!skipDbEnrichment) {
3955
+ await resolveEventThought(rec, ev, i, resolvedThoughts, pendingThoughtSteps);
3956
+ if (pendingThoughtSteps.size > 0) await resolvePendingThoughts(rec, ev, resolvedThoughts, pendingThoughtSteps);
3957
+ await resolveEventToolArgs(rec, ev, i, resolved);
3958
+ }
3930
3959
  for (const ch of mapper.map(ev, i)) queue.push(ch);
3931
3960
  i++;
3932
3961
  if (mapper.isFinished) {
@@ -4777,7 +4806,7 @@ var ModelCatalog = class ModelCatalog {
4777
4806
  const ac = new AbortController();
4778
4807
  const timer = setTimeout(() => ac.abort(), 3e4);
4779
4808
  try {
4780
- const { stdout, stderr } = await this.discover(ac.signal, accountId);
4809
+ const { stdout, stderr, accountId: probedAccountId } = await this.discover(ac.signal, accountId);
4781
4810
  if (isUnauthenticatedModelsFallback(stdout, stderr)) {
4782
4811
  const msg = "agy models returned unauthenticated fallback output";
4783
4812
  if (accountId) {
@@ -4806,7 +4835,10 @@ var ModelCatalog = class ModelCatalog {
4806
4835
  if (accountId) {
4807
4836
  this.accountCatalogs.set(accountId, newCatalog);
4808
4837
  if (this.current.source !== "discovered") this.current = newCatalog;
4809
- } else this.current = newCatalog;
4838
+ } else {
4839
+ this.current = newCatalog;
4840
+ if (probedAccountId) this.accountCatalogs.set(probedAccountId, newCatalog);
4841
+ }
4810
4842
  this.persistToDisk();
4811
4843
  if (changed && announce) this.onUpdate?.();
4812
4844
  return;
@@ -5286,6 +5318,27 @@ function preemptAgyAutoUpdate(env = process.env, now = Date.now()) {
5286
5318
  return result;
5287
5319
  }
5288
5320
  //#endregion
5321
+ //#region src/runtime/agy/idle-line.ts
5322
+ /**
5323
+ * Parse agy's background-wait line.
5324
+ *
5325
+ * While a turn is finishing, agy prints
5326
+ * `root agent idle; waiting for N background task(s)` — and N is its OWN count
5327
+ * of work it launched and is still waiting on (a build, an integration test, a
5328
+ * Docker job). That count is authoritative: as long as N > 0 the wait is
5329
+ * legitimate, so no grace period can make terminating the tree correct
5330
+ * (issue #144 — the reaper used a hard-coded 5 s and killed those turns).
5331
+ *
5332
+ * Returns `null` when the text carries no count (older agy builds, or a chunk
5333
+ * boundary cut the line), which keeps the conservative "arm the grace" path.
5334
+ */
5335
+ function backgroundTasksFrom(text) {
5336
+ const match = /root agent idle;\s*waiting\s+for\s+(\d+)\s+background/i.exec(text);
5337
+ if (match === null) return null;
5338
+ const count = Number(match[1]);
5339
+ return Number.isSafeInteger(count) && count >= 0 ? count : null;
5340
+ }
5341
+ //#endregion
5289
5342
  //#region src/runtime/agy/process.ts
5290
5343
  const IS_WIN$1 = process.platform === "win32";
5291
5344
  /**
@@ -5387,7 +5440,8 @@ function createRunState(opts) {
5387
5440
  idleGraceTimer: null,
5388
5441
  idleGraceTerminated: false,
5389
5442
  idleGraceExempt: false,
5390
- idleObserved: false
5443
+ idleObserved: false,
5444
+ idleBackgroundTasks: null
5391
5445
  };
5392
5446
  }
5393
5447
  function spawnAgyChild(opts, env, viaCmd, isNode) {
@@ -5492,7 +5546,9 @@ function clearIdleGrace(state) {
5492
5546
  */
5493
5547
  function armIdleGrace(child, opts, state) {
5494
5548
  if (state.idleGraceTimer !== null || state.settled) return;
5549
+ if ((state.idleBackgroundTasks ?? 0) > 0) return;
5495
5550
  const graceMs = opts.idleGraceMs ?? 5e3;
5551
+ if (graceMs <= 0) return;
5496
5552
  state.idleGraceTimer = setTimeout(() => {
5497
5553
  state.idleGraceTimer = null;
5498
5554
  if (state.settled) return;
@@ -5530,6 +5586,8 @@ function attachOutputStreams(child, opts, state, refreshWatchdog) {
5530
5586
  state.stderr = (state.stderr + text).slice(-4096);
5531
5587
  if (/root agent idle;\s*waiting/i.test(text)) {
5532
5588
  state.idleObserved = true;
5589
+ const waiting = backgroundTasksFrom(text);
5590
+ if (waiting !== null) state.idleBackgroundTasks = waiting;
5533
5591
  armIdleGrace(child, opts, state);
5534
5592
  } else if (opts.stderrKeepalive && !isBackgroundStderrNoise(text)) refreshWatchdog();
5535
5593
  }
@@ -6842,13 +6900,21 @@ function createToolWatchdog(log, cfg) {
6842
6900
  let lastOutputAt = 0;
6843
6901
  const TOOL_HEARTBEAT_MS = 3e5;
6844
6902
  let toolHeartbeat = null;
6903
+ let idleGraceExempt = false;
6904
+ const syncIdleGraceExempt = () => {
6905
+ const next = awaitingSubagent || openToolKeys.size > 0;
6906
+ if (next === idleGraceExempt) return;
6907
+ idleGraceExempt = next;
6908
+ runningProc?.exemptIdleGrace(next);
6909
+ };
6845
6910
  const apply = () => {
6846
6911
  runningProc?.noteActivity(openToolKeys.size > 0 ? longToolIdleMs : generationIdleMs);
6912
+ syncIdleGraceExempt();
6847
6913
  };
6848
6914
  const setAwaitingSubagent = (next) => {
6849
6915
  if (awaitingSubagent === next) return;
6850
6916
  awaitingSubagent = next;
6851
- runningProc?.exemptIdleGrace(next);
6917
+ syncIdleGraceExempt();
6852
6918
  };
6853
6919
  const stop = () => {
6854
6920
  if (toolHeartbeat !== null) {
@@ -6875,7 +6941,7 @@ function createToolWatchdog(log, cfg) {
6875
6941
  printTimeoutMinutes,
6876
6942
  attach: (proc) => {
6877
6943
  runningProc = proc;
6878
- proc?.exemptIdleGrace(awaitingSubagent);
6944
+ proc?.exemptIdleGrace(idleGraceExempt);
6879
6945
  apply();
6880
6946
  },
6881
6947
  markEvent: () => {
@@ -6912,9 +6978,10 @@ function createToolWatchdog(log, cfg) {
6912
6978
  },
6913
6979
  stop: () => {
6914
6980
  stop();
6915
- setAwaitingSubagent(false);
6981
+ awaitingSubagent = false;
6916
6982
  openToolKeys.clear();
6917
6983
  openToolSince.clear();
6984
+ syncIdleGraceExempt();
6918
6985
  }
6919
6986
  };
6920
6987
  }
@@ -34060,7 +34127,7 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
34060
34127
  };
34061
34128
  }
34062
34129
  /** Create the recording, parser, HOME snapshot and tool watchdog for one run. */
34063
- function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34130
+ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackSubagents = true) {
34064
34131
  const rec = deps.runs.create();
34065
34132
  rec.accountHome = account && account.dir ? account.dir : void 0;
34066
34133
  const conversationsDir = conversationsDirFor(rec.accountHome);
@@ -34068,7 +34135,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34068
34135
  const parser = new StreamJsonParser();
34069
34136
  deps.onParser?.(parser);
34070
34137
  const watchdog = createToolWatchdog(deps.log, cfg);
34071
- const tracker = new SubagentTracker({
34138
+ const tracker = trackSubagents ? new SubagentTracker({
34072
34139
  conversationId: initialConversationId,
34073
34140
  resumed: Boolean(initialConversationId),
34074
34141
  accountHome: rec.accountHome,
@@ -34079,7 +34146,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34079
34146
  noteActivity: () => {
34080
34147
  watchdog.markEvent();
34081
34148
  }
34082
- });
34149
+ }) : void 0;
34083
34150
  const state = {
34084
34151
  rec,
34085
34152
  parser,
@@ -34089,8 +34156,8 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34089
34156
  printTimeoutMinutes: watchdog.printTimeoutMinutes,
34090
34157
  attachProcess: (proc) => {
34091
34158
  watchdog.attach(proc);
34092
- tracker.start();
34093
- proc.outcome.finally(() => tracker.stop());
34159
+ tracker?.start();
34160
+ proc.outcome.finally(() => tracker?.stop());
34094
34161
  },
34095
34162
  feedLine: (line, onEvent, onFirstEvent) => {
34096
34163
  watchdog.markEvent();
@@ -34098,11 +34165,11 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34098
34165
  for (const ev of parser.feed(line + "\n")) {
34099
34166
  if (ev.kind === "init" && ev.conversationId) {
34100
34167
  state.streamCid = ev.conversationId;
34101
- tracker.setConversationId(ev.conversationId);
34168
+ tracker?.setConversationId(ev.conversationId);
34102
34169
  }
34103
34170
  if (ev.kind === "result" && ev.conversationId !== "") {
34104
34171
  state.streamCid = ev.conversationId;
34105
- tracker.setConversationId(ev.conversationId);
34172
+ tracker?.setConversationId(ev.conversationId);
34106
34173
  }
34107
34174
  watchdog.trackStep(ev);
34108
34175
  rec.append(ev);
@@ -34115,7 +34182,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34115
34182
  for (const ev of parser.flush()) {
34116
34183
  if (ev.kind === "result" && ev.conversationId !== "") {
34117
34184
  state.streamCid = ev.conversationId;
34118
- tracker.setConversationId(ev.conversationId);
34185
+ tracker?.setConversationId(ev.conversationId);
34119
34186
  }
34120
34187
  rec.append(ev);
34121
34188
  if (typeof onEvent === "function") try {
@@ -34125,7 +34192,7 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId) {
34125
34192
  },
34126
34193
  stop: () => {
34127
34194
  watchdog.stop();
34128
- tracker.stop();
34195
+ tracker?.stop();
34129
34196
  },
34130
34197
  conversationId: () => state.streamCid ?? diffConversations(before, conversationsDir).conversationId
34131
34198
  };
@@ -34189,6 +34256,19 @@ async function waitForRunSettle(run, timeoutMs) {
34189
34256
  }
34190
34257
  return run.isSettled;
34191
34258
  }
34259
+ function persistBindingOnResult(deps, input, recorder, ev) {
34260
+ if (ev.kind !== "result" || !ev.ok || looksLikeTosViolation(ev.response) || !input.persistBinding || input.sessionAccountKey === "" || deps.isSuperseded(input.sessionKey, recorder.rec)) return;
34261
+ const finalId = input.binding !== void 0 ? input.binding.conversationId : ev.conversationId || recorder.streamCid;
34262
+ if (!finalId) return;
34263
+ const mergedImages = input.binding?.sentImageIds || input.newlySentImageIds.length > 0 ? [.../* @__PURE__ */ new Set([...input.binding?.sentImageIds ?? [], ...input.newlySentImageIds])] : void 0;
34264
+ deps.store.set(input.sessionAccountKey, {
34265
+ conversationId: finalId,
34266
+ lastMessageCount: input.messages.length,
34267
+ updatedAt: Date.now(),
34268
+ model: input.activeModel,
34269
+ ...mergedImages && mergedImages.length > 0 ? { sentImageIds: mergedImages } : {}
34270
+ });
34271
+ }
34192
34272
  /**
34193
34273
  * Spawn the child under the held slot. Installs the line callback (parser feed
34194
34274
  * + tool watchdog + first-event hand-off), registers the run for steer
@@ -34226,14 +34306,16 @@ async function startAttemptProcess(deps, input, spawn, recorder, slot) {
34226
34306
  cwd: workspaceRoot,
34227
34307
  timeoutMs: cfg.timeoutMs,
34228
34308
  maxTurnMs: cfg.maxTurnMinutes > 0 ? cfg.maxTurnMinutes * 6e4 : void 0,
34309
+ idleGraceMs: cfg.idleGraceMinutes > 0 ? Math.round(cfg.idleGraceMinutes * 6e4) : 0,
34229
34310
  signal,
34230
34311
  env,
34231
34312
  stdinPayload: spawn.stdinPayload,
34232
34313
  preemptAutoUpdate: cfg.suppressAgyAutoUpdate,
34233
34314
  stderrKeepalive: true,
34234
- onLine: (line) => {
34235
- recorder.feedLine(line, input.agyOnEvent, () => slotHandoff?.onFirstEvent());
34236
- }
34315
+ onLine: (line) => recorder.feedLine(line, (ev) => {
34316
+ persistBindingOnResult(deps, input, recorder, ev);
34317
+ input.agyOnEvent?.(ev);
34318
+ }, () => slotHandoff?.onFirstEvent())
34237
34319
  });
34238
34320
  spawned = true;
34239
34321
  recorder.attachProcess(proc);
@@ -34743,7 +34825,8 @@ async function handleAttemptOutcome(deps, input, ctx) {
34743
34825
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
34744
34826
  recorder.drain(input.agyOnEvent);
34745
34827
  const conversationId = recorder.conversationId();
34746
- if (!rec.hasResult && outcome.idleGraceTerminated) {
34828
+ const existingRes = rec.getResultEvent();
34829
+ if (!(existingRes !== null && (existingRes.ok || existingRes.response !== "")) && outcome.idleGraceTerminated) {
34747
34830
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
34748
34831
  const synthResult = {
34749
34832
  kind: "result",
@@ -34804,7 +34887,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
34804
34887
  * queue notices; the outcome closure runs detached exactly as before.
34805
34888
  */
34806
34889
  async function* runAgyAttempt(deps, input) {
34807
- const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
34890
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId, !input.isAux);
34808
34891
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
34809
34892
  const slot = yield* dispatchCredentialSlot(deps, {
34810
34893
  ...input,
@@ -35049,13 +35132,14 @@ var AgyAdapter = class extends LlmAdapter {
35049
35132
  if (continuation !== null) {
35050
35133
  const rec = this.deps.runs.get(continuation.runId);
35051
35134
  const deadFailure = rec !== void 0 && rec.isSettled ? rec.failureInfo : null;
35052
- if (rec !== void 0 && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35135
+ const deadMissingResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasConsumableResultFrom(continuation.eventIndex + 1);
35136
+ if (rec !== void 0 && !deadMissingResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35053
35137
  yield* driveSpan(this.deps, rec, continuation.eventIndex + 1, hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
35054
35138
  return;
35055
35139
  }
35056
35140
  if (rec !== void 0) {
35057
35141
  this.deps.runs.forget(continuation.runId);
35058
- this.warnOnce("dead-continuation:" + continuation.runId, "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35142
+ this.warnOnce("dead-continuation:" + continuation.runId, deadMissingResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying an empty stream" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35059
35143
  } else this.warnOnce("stale-continuation:" + continuation.runId, "agy run " + continuation.runId + " is no longer available in memory (server restarted?) — falling back to fresh turn prompt assembly");
35060
35144
  }
35061
35145
  const catalog = this.deps.catalog.get();
@@ -35240,7 +35324,7 @@ var AgyAdapter = class extends LlmAdapter {
35240
35324
  signal: options.signal,
35241
35325
  agyOnEvent: options.agyOnEvent
35242
35326
  });
35243
- yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
35327
+ yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice, isAux && !isImage);
35244
35328
  }
35245
35329
  };
35246
35330
  //#endregion