dsh-agy-link 0.6.58 → 0.6.60

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,73 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.60 (2026-11-22)
4
+
5
+ ### English
6
+
7
+ - **Fix(acp): report the real token usage instead of the context-window figure (merges PR #165, fixes #158).** agy 1.5.x's `usage_update` carries only `{ used, size }` — a context-window occupancy figure, **not** a usage sample. Writing `used` into `input_tokens` made the run's final usage `{ inputTokens: used, outputTokens: 0 }`, which zeroed the cache-hit rate and the token speed and inflated the uncached input count (multi-step runs accumulated 10M+). `used` is now recorded as a diagnostic-only `lastContextUsed` and never promoted to a usage sample; a future update that really carries cache-read/output counts is still honoured. 178 lines of new tests.
8
+ - **Feat(wakeup): cross-turn background wakeup, opt-in (merges PR #164, supersedes #156).** When an agy `schedule` timer, a detached task/subagent, or a persistent ACP update finishes **after** the turn returned, an idle DSH session can now be woken with a followup prompt. Three slices in one PR: keep one-shot `schedule` timers alive across turns, wake on detached task/message/subagent completion, and keep an ACP session alive while its background work runs.
9
+ - **It is off by default** (`backgroundWakeup: false`): a session that speaks on its own after the turn is a behaviour change every user has to ask for. Turn it on in Settings → Runtime controls, with `/agy wakeup <on|off|status>`, or `DSH_AGY_BACKGROUND_WAKEUP=1`.
10
+ - Guardrails: 30-minute TTL, at most 12 wakeups per session between real human turns, archived sessions skipped, an active run blocks the wake, message ids de-duplicated, and language-server restart notices ignored so dead CLI subagents cannot cause retry loops.
11
+
12
+ ### 中文
13
+
14
+ - **修复(acp):报告真实的 token 用量,而不是上下文窗口占用(合并 PR #165,修复 #158)。** agy 1.5.x 的 `usage_update` 只携带 `{ used, size }`——这是**上下文窗口占用**,不是用量样本。把 `used` 写进 `input_tokens`,会让该轮最终用量变成 `{ inputTokens: used, outputTokens: 0 }`,于是缓存命中率与输出速度归零、未缓存输入虚高(多步运行可累加到 10M+)。现在 `used` 只作为诊断字段 `lastContextUsed` 记录,绝不提升为用量样本;若未来版本真的携带 cache-read/output 计数,仍会被采纳。新增 178 行测试。
15
+ - **特性(唤醒):跨轮后台唤醒,可选开启(合并 PR #164,取代 #156)。** 当 agy 的 `schedule` 定时器、游离任务/子代理、或持久 ACP 更新在**回合结束之后**才完成时,空闲的 DSH 会话现在可以被一条 followup prompt 唤醒。一个 PR 内含三片:让一次性 `schedule` 定时器跨轮存活、在游离任务/消息/子代理完成时唤醒、在 ACP 会话仍有后台工作时保活。
16
+ - **默认关闭**(`backgroundWakeup: false`):会话在回合结束后自己说话,是每个用户都必须主动要求的行为变更。可在 设置 → 运行时控制、`/agy wakeup <on|off|status>`、或 `DSH_AGY_BACKGROUND_WAKEUP=1` 开启。
17
+ - 护栏:30 分钟 TTL、每会话在两次真人回合之间最多 12 次唤醒、归档会话跳过、活跃 run 阻止唤醒、消息 id 去重、语言服务器重启通知被忽略(避免死掉的 CLI 子代理引发重试循环)。
18
+
19
+ ## 0.6.60 (2026-11-22)
20
+
21
+ ### English
22
+
23
+ - **Fix(usage): the ACP transport reports the real token usage again (closes #158).** `agy acp` streams `session/update` with `usage_update` carrying only `{ used, size }` — the context-window occupancy at the end of an internal call, not a measurement of the call. The plugin promoted that number to `input_tokens`, and since a run reports `lastStepUsageRaw ?? resultRaw`, the placeholder shadowed the real `PromptResponse.usage`: the cache-hit rate stayed at 0%, the token speed read 0 tok/s, and the uncached input count was inflated (one multi-step turn could add up to 10M+).
24
+ - **`src/features/acp/protocol.ts`**: `usage_update` now records `used` in a new diagnostic field `lastContextUsed` and leaves `lastUsage` alone. An update that really carries `outputTokens` / `cachedReadTokens` still counts as a sample.
25
+ - **`src/host/recording.ts`**: `finalUsage()` prefers the last per-call sample only when it carries a token breakdown (`hasUsageBreakdown()`: output / cache read / cache write / thinking / total). An input-only sample now yields to the envelope, so the per-call-vs-cumulative protection the class was built for still holds.
26
+ - **Token speed has an honest fallback**: when no step reported output tokens, `speedStats()` measures the envelope's output count over the run's own event span (never below a 500 ms window) instead of reporting 0 tok/s.
27
+ - **No more placeholder `0/0` usage chunks**: a tool cut or a failed turn with no measurement now omits the usage chunk. DSH reads an absent chunk as "no new measurement", while an explicit `0/0` resets the context meter and drags the speed down.
28
+ - **Regression tests**: `test/usage-acp.test.ts` (11 cases) pins the whole chain — a context reading never rides along on streamed steps, an update with real counts still does, a full ACP turn's final usage equals the `PromptResponse` usage, an input-only sample yields to the envelope, the no-measurement cases emit no chunk, and the speed fallback reports the envelope rate.
29
+
30
+ ### 中文
31
+
32
+ - **修复(用量):ACP 传输重新上报真实的 token 用量(关闭 #158)。** `agy acp` 的 `session/update` 里,`usage_update` 只带 `{ used, size }`——那是内部调用结束时的**上下文占用**,不是这次调用的用量。插件曾把它写进 `input_tokens`,而一次运行上报的是 `lastStepUsageRaw ?? resultRaw`,于是这个占位值盖掉了真实的 `PromptResponse.usage`:缓存命中率长期 0%、输出速度显示 0 tok/s、未命中 token 虚高(多步切分可累加到 10M+)。
33
+ - **`src/features/acp/protocol.ts`**:`usage_update` 改为把 `used` 记进新的诊断字段 `lastContextUsed`,不再碰 `lastUsage`;确实携带 `outputTokens` / `cachedReadTokens` 的更新仍算真实样本。
34
+ - **`src/host/recording.ts`**:`finalUsage()` 只在最后一条 per-call 样本确实带分项计数时才优先(`hasUsageBreakdown()`:output / cache read / cache write / thinking / total),只有 input 的样本让位给信封值——这个类原本要防的「per-call 与累计值混用」依然成立。
35
+ - **输出速度有了诚实的兜底**:没有任何 step 报过 output token 时,`speedStats()` 用信封的 output 数除以本轮事件跨度(窗口不小于 500ms)计算,而不是报 0 tok/s。
36
+ - **不再发占位的 `0/0` usage chunk**:没有测量的工具切步或失败回合直接省略该 chunk。DSH 把「没有 chunk」理解为「没有新的测量」,而显式 `0/0` 会重置上下文计量并把速度拖到 0。
37
+ - **回归测试**:`test/usage-acp.test.ts`(11 个用例)钉住整条链路——上下文读数不会附着在流式 step 上、带真实计数的更新仍算样本、整轮 ACP 的最终 usage 与 `PromptResponse` 一致、只有 input 的样本让位给信封、无测量的两种情况不发 chunk、速度兜底给出信封速率。
38
+
39
+ ## 0.6.59 (2026-11-22)
40
+
41
+ ### English
42
+
43
+ - **Fix(open): a stale path is never handed to the OS opener (merges PR #159).** On Windows `explorer.exe /select,<missing>` does not fail — it silently opens the Desktop folder, so clicking a link whose file had since moved looked like the plugin randomly opening the user's Desktop. `executeOpenInSystem()` now checks the target exists first and answers with a real error otherwise. The opener is also injectable, so the unit test no longer launches a real Explorer/Finder/xdg-open on the developer's machine during a test run.
44
+ - **Fix(quota): never spawn `agy` with a token that is about to die (merges PR #160).** agy authenticates from the machine credential store at process start and gives that read a fixed 10s budget; when the stored access token is expired or expires inside that window the refresh can lose the race and agy falls back to **interactive OAuth** — it opens a browser and waits for a human. Measured on the reporter's machine: 9 of 375 hourly polls did this (2.4%), **every one with ≤60s of token life left**, and none of the 746 polls with ≥1min left. The hourly CLI poll now refreshes a comfortable margin ahead (`CLI_TOKEN_SAFETY_MS` = 2 minutes, far above both the observed failure band and the 1.5–5s refresh round-trip) and, when it cannot reach that window, **skips the CLI for that round and lets the REST path answer** — a skipped round costs nothing, a browser window costs the user's attention.
45
+
46
+ ### 中文
47
+
48
+ - **修复(open):过期路径不再交给系统打开器(合并 PR #159)。** Windows 上 `explorer.exe /select,<缺失>` 不会失败,而是**静默打开桌面文件夹**,于是点击一个文件已被移动的链接看起来像插件随机打开了用户的桌面。`executeOpenInSystem()` 现在先确认目标存在,否则返回真实错误。打开器也改为可注入,因此单元测试不再在开发者机器上真的拉起 Explorer/Finder/xdg-open。
49
+ - **修复(配额):绝不用即将失效的 token 去 spawn `agy`(合并 PR #160)。** agy 在进程启动时从系统凭证库取 token,该读取有固定 10 秒预算;当存储的 access token 已过期或在该窗口内过期时,刷新可能输掉这场竞争,agy 便回退到**交互式 OAuth**——弹浏览器等人来处理。报告者机器实测:375 次每小时轮询里 9 次发生(2.4%),**全部是 token 剩余寿命 ≤60 秒的情形**,而 746 次 ≥1 分钟的轮询一次都没有。现在每小时的 CLI 轮询会提前一个舒适边际刷新(`CLI_TOKEN_SAFETY_MS` = 2 分钟,远高于观察到的失败带与 1.5–5 秒的刷新往返),若无法进入该窗口则**跳过本轮 CLI、让 REST 路径作答**——跳过一轮没有代价,弹一个浏览器窗口要的是用户的注意力。
50
+
51
+ ## 0.6.59 (2026-11-22)
52
+
53
+ ### English
54
+
55
+ - **Fix(quota): the hourly CLI quota poll can no longer make `agy` open the user's browser.** Every hour the plugin runs `agy -p /usage` for the account that owns the machine credential store. `agy` reads that store at startup with a FIXED 10s budget and runs the token refresh in a separate goroutine; when the stored access token was already dying the budget lost the race, `agy` fell back to INTERACTIVE OAuth and opened the system browser to wait for a human. Measured on one machine: **9 of 375 hourly polls (2.4%) opened a browser, every single one with at most 60s of token life left, and 0 of the 746 polls that had at least 1 minute left**.
56
+ - **New pure module `src/features/quota/cli-token.ts`**: `CLI_TOKEN_SAFETY_MS = 120_000` (two minutes sits far outside the observed failure band and far above the measured 1.5-5s refresh round-trip), `tokenRemainingMs()`, `isTokenSafeForCli()` and `prepareCliToken()`. A credential with no known expiry counts as UNSAFE: `agy` would refresh at startup, which is exactly the browser-popping path, and "no expiry means valid forever" is the misreading that turned issue #112 into a permanent 401 loop.
57
+ - **`QuotaService.readCliUsageFamilies` now brings the credential into the safety window before it spawns anything** (`src/host/quota.ts`): read the stored token, refresh once when it is dying, write the result into the OS store `agy` actually loads, re-read, and only then spawn. If any step fails the CLI stands down for that round and the REST path answers - a skipped round costs one quota sample an hour, a browser window costs the user their attention.
58
+ - **The slot write-back is a host seam** (`syncSlot`): `persistRefreshedToken` only rewrites the on-disk document, which on Windows is a mirror - `agy` authenticates from Credential Manager. The host wires the write and it runs inside the `credentialSlotMutex` this read already holds. Left unwired in tests, so no unit test can write the real machine slot.
59
+ - **`getValidAccessToken` / `isAccessTokenFresh` take the required validity as a parameter** (`src/features/quota/token.ts`, default unchanged at 60s): an HTTP call needs 60s, but a child process spends seconds before its first request, so the CLI path asks for the full two minutes. Without this the refresh would return a token with 90s left that the gate then rejects - a wasted refresh round-trip and a skipped CLI anyway.
60
+ - Eleven new cases in `test/quota-cli-token.test.ts` pin the decision (expiry unknown, one second short, exactly at the boundary), the refresh window (90s is fresh for HTTP, not for a spawn) and the ordering (refresh, slot write, verification read, spawn).
61
+
62
+ ### 中文
63
+
64
+ - **修复(配额):每小时的 CLI 配额轮询不会再让 `agy` 打开用户的浏览器。** 插件每小时对「拥有系统凭据库」的账号执行一次 `agy -p /usage`。`agy` 启动时读该凭据库只有**固定的 10 秒预算**,而令牌刷新跑在另一个 goroutine 里;当已存的 access token 临近过期时,这 10 秒会输掉竞态,`agy` 于是回退到**交互式 OAuth**——打开系统浏览器等人操作。单机实测:**375 次每小时轮询中有 9 次(2.4%)弹出浏览器,全部落在令牌剩余不超过 60 秒的情况;而剩余至少 1 分钟的 746 次一次都没有**。
65
+ - **新增纯函数模块 `src/features/quota/cli-token.ts`**:`CLI_TOKEN_SAFETY_MS = 120_000`(两分钟远高于实测失败带,也远高于实测 1.5-5 秒的刷新往返),以及 `tokenRemainingMs()`、`isTokenSafeForCli()`、`prepareCliToken()`。**没有过期时间的凭据一律视为不安全**——`agy` 会在启动时刷新,那正是弹浏览器的路径;而「没有过期时间等于永久有效」这种误读,正是 issue #112 变成永久 401 循环的原因。
66
+ - **`QuotaService.readCliUsageFamilies` 在拉起任何进程之前先把凭据送进安全窗**(`src/host/quota.ts`):读已存令牌,临期则刷新一次,把结果写进 `agy` 真正读取的系统凭据库,复读校验,才 spawn。任一步失败则本轮放弃 CLI、由 REST 兜底:少一次采样每小时只损失一个数据点,而一个浏览器窗口损失的是用户的注意力。
67
+ - **写槽是宿主侧的注入点**(`syncSlot`):`persistRefreshedToken` 只改磁盘文档,而在 Windows 上磁盘只是镜像——`agy` 是从 Credential Manager 取凭据的。宿主负责这次写入,它跑在本读取已持有的 `credentialSlotMutex` 内。测试里不注入该回调,因此任何单测都不可能写到真实的机器凭据槽。
68
+ - **`getValidAccessToken` / `isAccessTokenFresh` 把所需有效期改成参数**(`src/features/quota/token.ts`,默认仍是 60 秒):一次 HTTP 调用 60 秒够用,但子进程从启动到发出第一个请求要花几秒,所以 CLI 这条路径要求完整的两个小时窗。没有这一层,刷新会交回一个只剩 90 秒的令牌、随即被门禁拒掉——白跑一次刷新,CLI 照样跳过。
69
+ - **`test/quota-cli-token.test.ts` 新增十一个用例**:既钉住判定(无过期时间、差一秒、恰好等于边界),也钉住刷新窗口(90 秒对 HTTP 算新鲜、对 spawn 不算),以及顺序(刷新、写槽、复读校验、spawn)。
70
+
3
71
  ## 0.6.58 (2026-11-22)
4
72
 
5
73
  ### English
@@ -189,7 +189,10 @@ function defaultConfig() {
189
189
  imageTimeoutMs: 24e4,
190
190
  imageMaxBytes: 20971520,
191
191
  imageOutputDir: "",
192
- imageRetries: 1
192
+ imageRetries: 1,
193
+ backgroundWakeup: false,
194
+ backgroundWakeupTtlMinutes: 30,
195
+ backgroundWakeupMaxPerSession: 12
193
196
  };
194
197
  }
195
198
  //#endregion
@@ -708,7 +711,10 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
708
711
  imageTimeoutMs: asNum(get("imageTimeoutMs")) ?? base.imageTimeoutMs,
709
712
  imageMaxBytes: asNum(get("imageMaxBytes")) ?? base.imageMaxBytes,
710
713
  imageOutputDir: asString(get("imageOutputDir")) ?? base.imageOutputDir,
711
- imageRetries: asNum(get("imageRetries")) ?? base.imageRetries
714
+ imageRetries: asNum(get("imageRetries")) ?? base.imageRetries,
715
+ backgroundWakeup: asBool(get("backgroundWakeup")) ?? base.backgroundWakeup,
716
+ backgroundWakeupTtlMinutes: asNum(get("backgroundWakeupTtlMinutes")) ?? base.backgroundWakeupTtlMinutes,
717
+ backgroundWakeupMaxPerSession: asNum(get("backgroundWakeupMaxPerSession")) ?? base.backgroundWakeupMaxPerSession
712
718
  };
713
719
  if (env.DSH_AGY_ENABLED !== void 0) cfg.enabled = asBool(env.DSH_AGY_ENABLED) ?? cfg.enabled;
714
720
  if (env.DSH_AGY_BIN) cfg.agyBin = env.DSH_AGY_BIN;
@@ -864,6 +870,20 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
864
870
  const v = asNum(env.DSH_AGY_IMAGE_RETRIES);
865
871
  if (v !== void 0) cfg.imageRetries = v;
866
872
  }
873
+ if (env.DSH_AGY_BACKGROUND_WAKEUP !== void 0) {
874
+ const bw = asBool(env.DSH_AGY_BACKGROUND_WAKEUP);
875
+ if (bw !== void 0) cfg.backgroundWakeup = bw;
876
+ }
877
+ if (env.DSH_AGY_BACKGROUND_WAKEUP_TTL_MINUTES) {
878
+ const ttl = asNum(env.DSH_AGY_BACKGROUND_WAKEUP_TTL_MINUTES);
879
+ if (ttl !== void 0 && ttl > 0) cfg.backgroundWakeupTtlMinutes = Math.min(240, Math.max(1, Math.floor(ttl)));
880
+ }
881
+ if (env.DSH_AGY_BACKGROUND_WAKEUP_MAX_PER_SESSION) {
882
+ const max = asNum(env.DSH_AGY_BACKGROUND_WAKEUP_MAX_PER_SESSION);
883
+ if (max !== void 0 && max > 0) cfg.backgroundWakeupMaxPerSession = Math.min(100, Math.max(1, Math.floor(max)));
884
+ }
885
+ cfg.backgroundWakeupTtlMinutes = Math.min(240, Math.max(1, Math.floor(cfg.backgroundWakeupTtlMinutes)));
886
+ cfg.backgroundWakeupMaxPerSession = Math.min(100, Math.max(1, Math.floor(cfg.backgroundWakeupMaxPerSession)));
867
887
  return cfg;
868
888
  }
869
889
  //#endregion
@@ -1976,6 +1996,15 @@ const waiters = Symbol("waiters");
1976
1996
  function isConsumableResult(ev) {
1977
1997
  return (ev.ok || ev.response !== "") && !isNonConsumableResultError(ev.ok, ev.error, ev.response);
1978
1998
  }
1999
+ /**
2000
+ * True when a usage sample carries a token breakdown rather than a bare input
2001
+ * count. Only such samples may stand in for the result envelope's usage; see
2002
+ * `finalUsage` and issue #158.
2003
+ */
2004
+ function hasUsageBreakdown(raw) {
2005
+ const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
2006
+ return positive(raw.output_tokens) || positive(raw.cache_read_tokens) || positive(raw.cache_write_tokens) || positive(raw.thinking_tokens) || positive(raw.total_tokens);
2007
+ }
1979
2008
  /** One agy run's append-only event log plus its settlement state. */
1980
2009
  var RunRecording = class {
1981
2010
  now;
@@ -2077,6 +2106,17 @@ var RunRecording = class {
2077
2106
  if (s.outputTokens > 0 && s.lastAt - s.startedAt >= 500) lastTps = s.outputTokens / ((s.lastAt - s.startedAt) / 1e3);
2078
2107
  break;
2079
2108
  }
2109
+ if (tokens === 0) {
2110
+ const envelope = this.envelopeOutputTokens();
2111
+ const spanMs = this.eventSpanMs();
2112
+ if (envelope > 0 && spanMs >= 500) return {
2113
+ lastTps: envelope / (spanMs / 1e3),
2114
+ avgTps: envelope / (spanMs / 1e3),
2115
+ outputTokens: envelope,
2116
+ measuredSteps: 1,
2117
+ generatingMs: spanMs
2118
+ };
2119
+ }
2080
2120
  return {
2081
2121
  lastTps,
2082
2122
  avgTps: ms > 0 ? tokens / (ms / 1e3) : null,
@@ -2085,6 +2125,23 @@ var RunRecording = class {
2085
2125
  generatingMs: ms
2086
2126
  };
2087
2127
  }
2128
+ /** Output tokens reported by the last result envelope (0 when it has none). */
2129
+ envelopeOutputTokens() {
2130
+ for (let i = this.events.length - 1; i >= 0; i--) {
2131
+ const ev = this.events[i];
2132
+ if (ev === void 0 || ev.kind !== "result" || ev.usage === void 0) continue;
2133
+ const out = ev.usage.output_tokens;
2134
+ return typeof out === "number" && Number.isFinite(out) && out > 0 ? out : 0;
2135
+ }
2136
+ return 0;
2137
+ }
2138
+ /** Wall-clock span between the first and the last recorded event. */
2139
+ eventSpanMs() {
2140
+ const first = this.eventTimes[0];
2141
+ const last = this.eventTimes[this.eventTimes.length - 1];
2142
+ if (first === void 0 || last === void 0) return 0;
2143
+ return last - first;
2144
+ }
2088
2145
  /**
2089
2146
  * Usage accounting (verified against agy 1.1.16 stream-json): step_update
2090
2147
  * usage is PER-CALL (the current context size at that internal LLM call),
@@ -2101,9 +2158,22 @@ var RunRecording = class {
2101
2158
  get lastUsage() {
2102
2159
  return this.lastStepUsageRaw;
2103
2160
  }
2104
- /** The usage to report for the result envelope: last per-call step sample. */
2161
+ /**
2162
+ * The usage to report for the result envelope: the last per-call step sample
2163
+ * when it actually carries a token breakdown, otherwise the envelope's own
2164
+ * usage.
2165
+ *
2166
+ * The sample is only preferred when it reports output / cache / thinking
2167
+ * tokens. A sample that carries nothing but an input figure is a context
2168
+ * occupancy reading, not a usage sample: agy's ACP `usage_update` sends
2169
+ * `{ used, size }`, and promoting that to `{inputTokens: used,
2170
+ * outputTokens: 0}` used to shadow the real `PromptResponse.usage` (0%
2171
+ * cache hit, 0 tok/s, inflated uncached input — issue #158).
2172
+ */
2105
2173
  finalUsage(resultRaw) {
2106
- return this.lastStepUsageRaw ?? resultRaw;
2174
+ const step = this.lastStepUsageRaw;
2175
+ if (step === null) return resultRaw;
2176
+ return hasUsageBreakdown(step) ? step : resultRaw;
2107
2177
  }
2108
2178
  /** Settle the recording: no further events will arrive. */
2109
2179
  settle(failure) {
@@ -2180,6 +2250,10 @@ var RunRecording = class {
2180
2250
  eventAt(index) {
2181
2251
  return this.events[index];
2182
2252
  }
2253
+ /** Arrival timestamp (ms) of the event at `index`, when recorded. */
2254
+ eventTimestampAt(index) {
2255
+ return this.eventTimes[index];
2256
+ }
2183
2257
  /** Number of recorded events so far. */
2184
2258
  get length() {
2185
2259
  return this.events.length;
@@ -4257,13 +4331,10 @@ function buildToolCallBlock(input) {
4257
4331
  arguments: argumentsJson
4258
4332
  }
4259
4333
  },
4260
- {
4334
+ ...trackedCut !== void 0 && Object.keys(trackedCut).length > 0 ? [{
4261
4335
  type: "usage",
4262
- usage: trackedCut !== void 0 && Object.keys(trackedCut).length > 0 ? usageFromRaw(trackedCut) : {
4263
- inputTokens: 0,
4264
- outputTokens: 0
4265
- }
4266
- },
4336
+ usage: usageFromRaw(trackedCut)
4337
+ }] : [],
4267
4338
  {
4268
4339
  type: "finish",
4269
4340
  reason: { kind: "tool-calls" }
@@ -4634,12 +4705,9 @@ var EventMapper = class {
4634
4705
  const close = this.closeOpen();
4635
4706
  if (close) yield close;
4636
4707
  const tracked = this.opts.usage?.finalUsage({});
4637
- yield {
4708
+ if (tracked !== void 0 && Object.keys(tracked).length > 0) yield {
4638
4709
  type: "usage",
4639
- usage: tracked !== void 0 && Object.keys(tracked).length > 0 ? usageFromRaw(tracked) : {
4640
- inputTokens: 0,
4641
- outputTokens: 0
4642
- }
4710
+ usage: usageFromRaw(tracked)
4643
4711
  };
4644
4712
  const failure = {
4645
4713
  message,
@@ -36460,6 +36528,15 @@ async function handleAttemptOutcome(deps, input, ctx) {
36460
36528
  } finally {
36461
36529
  rec.settle(failure);
36462
36530
  }
36531
+ if (!input.isAux && sessionKey !== "") deps.backgroundObserver?.onAttemptSettled?.({
36532
+ sessionKey,
36533
+ conversationId,
36534
+ ...rec.accountHome === void 0 ? {} : { accountHome: rec.accountHome },
36535
+ transport: "cli",
36536
+ recording: rec,
36537
+ failure,
36538
+ superseded
36539
+ });
36463
36540
  }
36464
36541
  /**
36465
36542
  * Run one attempt: recorder → slot dispatch → spawn → concurrent outcome.
@@ -36533,6 +36610,10 @@ var AgyAdapter = class extends LlmAdapter {
36533
36610
  effortUnsupportedModels() {
36534
36611
  return this.effortPolicy.unsupportedModels();
36535
36612
  }
36613
+ /** Live in-flight recording for `sessionKey`, if any. */
36614
+ getActiveRun(sessionKey) {
36615
+ return this.activeRuns.get(sessionKey);
36616
+ }
36536
36617
  /** True when `--effort` must not be passed to this model. */
36537
36618
  isEffortUnsupported(model) {
36538
36619
  return this.effortPolicy.isUnsupported(model);
@@ -36827,6 +36908,11 @@ var AgyAdapter = class extends LlmAdapter {
36827
36908
  inFlight: true
36828
36909
  });
36829
36910
  }
36911
+ if (!isAux && sessionKey !== "") {
36912
+ const lastUser = [...messages].reverse().find((m) => m.role === "user");
36913
+ if (!(lastUser?.source?.kind === "plugin" && lastUser?.source?.plugin === "agy-link" && lastUser?.source?.form === "notice")) this.deps.backgroundObserver?.onHumanTurn?.(sessionKey);
36914
+ this.deps.backgroundObserver?.onAttemptStart?.(sessionKey);
36915
+ }
36830
36916
  const rec = yield* runAgyAttempt({
36831
36917
  acquire: (signal) => this.deps.acquire(signal),
36832
36918
  pool: this.deps.pool,
@@ -36849,7 +36935,8 @@ var AgyAdapter = class extends LlmAdapter {
36849
36935
  lastAccountSpawnTime: this.lastAccountSpawnTime,
36850
36936
  minSpawnIntervalMs: this.minSpawnIntervalMs,
36851
36937
  spawnLimiter: this.spawnLimiter,
36852
- ...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp }
36938
+ ...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp },
36939
+ ...this.deps.backgroundObserver === void 0 ? {} : { backgroundObserver: this.deps.backgroundObserver }
36853
36940
  }, {
36854
36941
  cfg,
36855
36942
  bin,
package/dist/client.js CHANGED
@@ -301,6 +301,8 @@ window.__ModuleLoader__.load({
301
301
  "config.imageToolDesc": "注册 agy_image 工具,让任意 DSH 模型都能直接调用 Antigravity 生图/改图",
302
302
  "config.syncCustomizations": "多账号定制同步",
303
303
  "config.syncCustomizationsDesc": "自动将主账号的 Plugins、MCP、Skills、Rules 与 Agents 镜像同步到隔离账号池",
304
+ "config.backgroundWakeup": "跨回合后台自动唤醒",
305
+ "config.backgroundWakeupDesc": "默认关闭。开启后,当定时任务到期、后台命令/子代理完成或 ACP 常驻推送更新时,自动唤醒空闲的 DSH 会话",
304
306
  "config.agent": "默认自定义 Agent (--agent)",
305
307
  "config.agentDesc": "指定 Markdown 自定义 Agent 名称,留空使用 agy 默认行为",
306
308
  "config.agentPlaceholder": "输入 agent 名称(留空默认)",
@@ -639,6 +641,8 @@ window.__ModuleLoader__.load({
639
641
  "config.imageToolDesc": "Register the agy_image DSH tool so any model can generate or edit images via agy",
640
642
  "config.syncCustomizations": "Multi-account ecosystem sync",
641
643
  "config.syncCustomizationsDesc": "Automatically mirror primary Plugins, MCP servers, Skills, Rules, and Agents into isolated pool accounts",
644
+ "config.backgroundWakeup": "Cross-turn background wakeup",
645
+ "config.backgroundWakeupDesc": "Off by default. When on, idle DSH sessions wake up on their own when an agy timer fires or a background task / ACP session finishes",
642
646
  "config.agent": "Default custom agent (--agent)",
643
647
  "config.agentDesc": "Select a Markdown custom agent name; leave blank for the default agy agent",
644
648
  "config.agentPlaceholder": "Custom agent name (blank = default)",
@@ -977,6 +981,8 @@ window.__ModuleLoader__.load({
977
981
  "config.imageToolDesc": "Registra agy_image para qualquer modelo gerar ou editar imagens via agy",
978
982
  "config.syncCustomizations": "Sincronização de ecossistema multi-conta",
979
983
  "config.syncCustomizationsDesc": "Espelha Plugins, MCP, Skills, Rules e Agents da conta principal para contas isoladas do pool",
984
+ "config.backgroundWakeup": "Despertar automático em segundo plano",
985
+ "config.backgroundWakeupDesc": "Desativado por padrão. Quando ativado, sessões ociosas do DSH despertam sozinhas ao vencer um timer ou concluir uma tarefa/ACP",
980
986
  "config.agent": "Agente personalizado (--agent)",
981
987
  "config.agentDesc": "Nome do agente Markdown personalizado; deixe em branco para usar o padrão",
982
988
  "config.agentPlaceholder": "Nome do agente (vazio = padrão)",
@@ -1315,6 +1321,8 @@ window.__ModuleLoader__.load({
1315
1321
  "config.imageToolDesc": "Registra agy_image para que cualquier modelo genere o edite imágenes con agy",
1316
1322
  "config.syncCustomizations": "Sincronización de ecosistema multi-cuenta",
1317
1323
  "config.syncCustomizationsDesc": "Refleja automáticamente Plugins, MCP, Skills, Rules y Agents en cuentas aisladas del pool",
1324
+ "config.backgroundWakeup": "Despertar automático en segundo plano",
1325
+ "config.backgroundWakeupDesc": "Desactivado por defecto. Al activarlo, las sesiones inactivas de DSH se reactivan cuando vence un temporizador o termina una tarea/ACP",
1318
1326
  "config.agent": "Agente personalizado (--agent)",
1319
1327
  "config.agentDesc": "Nombre del agente Markdown personalizado; déjalo vacío para el agente predeterminado",
1320
1328
  "config.agentPlaceholder": "Nombre del agente (vacío = predeterminado)",
@@ -11328,6 +11336,14 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
11328
11336
  value: status.syncAccountCustomizations !== false,
11329
11337
  loadingAction,
11330
11338
  setCfg
11339
+ }), boolRow({
11340
+ t,
11341
+ title: t("config.backgroundWakeup"),
11342
+ desc: t("config.backgroundWakeupDesc"),
11343
+ cfgKey: "backgroundWakeup",
11344
+ value: status.backgroundWakeup === true,
11345
+ loadingAction,
11346
+ setCfg
11331
11347
  }), renderAgentRow({
11332
11348
  ...props,
11333
11349
  draft: agentDraft,