dsh-agy-link 0.6.57 → 0.6.59

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,68 +1,68 @@
1
1
  # Changelog
2
2
 
3
- ## 0.6.57 (2026-11-22)
3
+ ## 0.6.59 (2026-11-22)
4
4
 
5
5
  ### English
6
6
 
7
- - **Fix(failover): full-chain quota exhaustion failover alignment across main runs, embedded subagents, delegated tools, auxiliary routes, translation, image generation, and ACP.**
8
- - **Authoritative quota refusal detection & partial-response safety**: Extended `looksLikeHardRateLimit` / `parseResetDurationMs` (`"quotaResetDelay"`, `reset after`, `Individual quota reached`, `QUOTA_EXHAUSTED`), added `isTransientBurstRateLimit` (<= 30s `RATE_LIMIT_EXCEEDED` burst guard), `extractQuotaErrorModel`, `isHardQuotaResultError`, and `isNonConsumableResultError`. `EventMapper`, `attempt-outcome.ts`, `oneshot.ts`, and ACP no longer soft-finish partial responses carrying a hard quota refusal — they cool down the exact exhausted model family and rotate cleanly.
9
- - **Live subagent & tool quota failover (`src/provider/quota-failover.ts`, `SubagentTracker`)**: Tails parent `SYSTEM_MESSAGE` errors and subagent `ERROR`/`FAILED` transcripts (with resumed-run EOF baselining and strict provenance checks) plus `generate_image`/`invoke_subagent`/`swarm`/`run_workflow` tool failures; cools the exhausted family and interrupts stuck runs with `ERR_RATE_LIMIT` whenever an eligible spare account exists, while keeping `TOS_VIOLATION` non-rotatable.
10
- - **Auxiliary, one-shot, image & translation parity**: Scaled `providerRetryPolicyFor` and `canRetryAuxQuota` across pool depth (`isAux` fails over inside `streamWithEffortRetry`), aligned `runAgyOnce` (`oneshot.ts`), `ImageService`, `TranslationService`, and `isQuotaBenched` (`quotaGateClearedAt` & per-model exhaustion).
11
- - **Docs: updated READMEs, configuration/architecture/known-gaps/security guides, and refreshed all `docs/assets/*.png` screenshots (PII-redacted) for v0.6.55–v0.6.57.**
7
+ - **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.
8
+ - **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.
12
9
 
13
10
  ### 中文
14
11
 
15
- - **修复(容灾):主代理、内嵌子代理、委派工具、辅助路由、翻译、生图与 ACP 全链路额度耗尽自动切号对齐。**
16
- - **权威硬配额识别与部分响应拦截**:扩展 `looksLikeHardRateLimit` 与 `parseResetDurationMs`(支持 `quotaResetDelay`、`reset after`、`Individual quota reached`、`QUOTA_EXHAUSTED`),新增 30 秒内瞬时突发过滤 `isTransientBurstRateLimit`、模型提取 `extractQuotaErrorModel` 及 `isHardQuotaResultError` / `isNonConsumableResultError`。`EventMapper`、`attempt-outcome.ts`、`oneshot.ts` 与 ACP 不再将携带硬配额报错的部分输出当作正常回合放行,而是按精确模型族与服务端重置时间冷却并切号。
17
- - **子代理与工具实时额度切号(`src/provider/quota-failover.ts`、`SubagentTracker`)**:严格按来源监听父对话 `SYSTEM_MESSAGE`、子代理 `ERROR`/`FAILED` transcript(含续跑 EOF 基线防重放)及 `generate_image`/`invoke_subagent`/`swarm`/`run_workflow` 工具失败;存在可用备用账号时立即冷却耗尽族并以 `ERR_RATE_LIMIT` 中断卡死回合切号,同时保留 `TOS_VIOLATION` 防跨号连坐保护。
18
- - **辅助通道、一次性调用、生图与翻译对齐**:将 `providerRetryPolicyFor` / `canRetryAuxQuota` 按号池深度扩展(`isAux` 在 `streamWithEffortRetry` 内自动换号),并对齐 `runAgyOnce`、`ImageService`、`TranslationService` 与 `isQuotaBenched`(尊重 `quotaGateClearedAt` 与单模型耗尽)。
19
- - **文档:同步更新中英文 README、配置/架构/已知限制/安全文档,并全面刷新脱敏后的最新版界面截图(`docs/assets/*.png`)。**
12
+ - **修复(open):过期路径不再交给系统打开器(合并 PR #159)。** Windows 上 `explorer.exe /select,<缺失>` 不会失败,而是**静默打开桌面文件夹**,于是点击一个文件已被移动的链接看起来像插件随机打开了用户的桌面。`executeOpenInSystem()` 现在先确认目标存在,否则返回真实错误。打开器也改为可注入,因此单元测试不再在开发者机器上真的拉起 Explorer/Finder/xdg-open。
13
+ - **修复(配额):绝不用即将失效的 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 路径作答**——跳过一轮没有代价,弹一个浏览器窗口要的是用户的注意力。
20
14
 
21
- ## 0.6.56 (2026-11-22)
15
+ ## 0.6.59 (2026-11-22)
22
16
 
23
17
  ### English
24
18
 
25
- - **Fix(visibility): live background-task logs and ACP tracker activity are now surfaced, and a false "previous turn was interrupted" banner is gone (merges PR #155).** Two independent problems:
26
- - Backgrounded `run_command` task logs (`.system_generated/tasks/*.log`) and completion/cancellation notices (`.system_generated/messages/{,undelivered/}*.json`) were not tailed in real time, and `runAcpAttempt()` created its attempt recorder with the tracker disabled. A new `TaskActivityTracker` (`src/features/subagent/task-activity.ts`) tails them incrementally (UTF-8 multi-byte safe, burst-bounded, EOF baselined on resumed runs, message ids de-duplicated) and is wired into `SubagentTracker` with a final synchronous flush in `stop()`; ACP runs now enable the tracker. `RUNNING` step fallback text and the mirror card carry task-id / log-path / timer hints.
27
- - In `streamAttempt()`, a prior run that had **already produced a consumable result** but took slightly over 1.5s to tear down was still marked `binding.interrupted = true` and had `[the previous turn was interrupted before it finished …]` prepended to the next prompt — a lie about a turn that actually answered. Only runs **without** a consumable result are marked interrupted now.
28
- - Note: `hasConsumableResult` (added in 0.6.51) is what distinguishes the two cases; the change is a net reduction in `adapter.ts`.
19
+ - **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**.
20
+ - **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.
21
+ - **`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.
22
+ - **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.
23
+ - **`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.
24
+ - 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).
29
25
 
30
26
  ### 中文
31
27
 
32
- - **修复(可见性):实时后台任务日志与 ACP tracker 活动现在会展示,且错误插入的「上一轮被中断」横幅已消除(合并 PR #155)。** 两个独立问题:
33
- - 转后台的 `run_command` 任务日志(`.system_generated/tasks/*.log`)与完成/取消通知(`.system_generated/messages/{,undelivered/}*.json`)此前不会被实时跟随,且 `runAcpAttempt()` 创建 recorder 时未启用 tracker。新增 `TaskActivityTracker`(`src/features/subagent/task-activity.ts`)增量跟随(UTF-8 多字节安全、突发有界、续跑时以 EOF 为基线、消息 id 去重),接入 `SubagentTracker` 并在 `stop()` 做最终同步 flush;ACP 运行现在会启用 tracker。`RUNNING` 步骤的兜底文案与镜像卡片会带上 task-id / 日志路径 / 定时提示。
34
- - `streamAttempt()` 里,上一轮**已经产出可消费结果**、只是收尾超过 1.5 秒的情形,仍会被标记 `binding.interrupted = true` 并把「上一轮在完成前被中断…」插到下一条 prompt 前面——对一个实际已经作答的回合说谎。现在只有**没有**可消费结果的 run 才会被标记为中断。
35
- - 说明:区分这两种情形依靠 0.6.51 引入的 `hasConsumableResult`;该改动使 `adapter.ts` 净减少代码。
28
+ - **修复(配额):每小时的 CLI 配额轮询不会再让 `agy` 打开用户的浏览器。** 插件每小时对「拥有系统凭据库」的账号执行一次 `agy -p /usage`。`agy` 启动时读该凭据库只有**固定的 10 秒预算**,而令牌刷新跑在另一个 goroutine 里;当已存的 access token 临近过期时,这 10 秒会输掉竞态,`agy` 于是回退到**交互式 OAuth**——打开系统浏览器等人操作。单机实测:**375 次每小时轮询中有 9 次(2.4%)弹出浏览器,全部落在令牌剩余不超过 60 秒的情况;而剩余至少 1 分钟的 746 次一次都没有**。
29
+ - **新增纯函数模块 `src/features/quota/cli-token.ts`**:`CLI_TOKEN_SAFETY_MS = 120_000`(两分钟远高于实测失败带,也远高于实测 1.5-5 秒的刷新往返),以及 `tokenRemainingMs()`、`isTokenSafeForCli()`、`prepareCliToken()`。**没有过期时间的凭据一律视为不安全**——`agy` 会在启动时刷新,那正是弹浏览器的路径;而「没有过期时间等于永久有效」这种误读,正是 issue #112 变成永久 401 循环的原因。
30
+ - **`QuotaService.readCliUsageFamilies` 在拉起任何进程之前先把凭据送进安全窗**(`src/host/quota.ts`):读已存令牌,临期则刷新一次,把结果写进 `agy` 真正读取的系统凭据库,复读校验,才 spawn。任一步失败则本轮放弃 CLI、由 REST 兜底:少一次采样每小时只损失一个数据点,而一个浏览器窗口损失的是用户的注意力。
31
+ - **写槽是宿主侧的注入点**(`syncSlot`):`persistRefreshedToken` 只改磁盘文档,而在 Windows 上磁盘只是镜像——`agy` 是从 Credential Manager 取凭据的。宿主负责这次写入,它跑在本读取已持有的 `credentialSlotMutex` 内。测试里不注入该回调,因此任何单测都不可能写到真实的机器凭据槽。
32
+ - **`getValidAccessToken` / `isAccessTokenFresh` 把所需有效期改成参数**(`src/features/quota/token.ts`,默认仍是 60 秒):一次 HTTP 调用 60 秒够用,但子进程从启动到发出第一个请求要花几秒,所以 CLI 这条路径要求完整的两个小时窗。没有这一层,刷新会交回一个只剩 90 秒的令牌、随即被门禁拒掉——白跑一次刷新,CLI 照样跳过。
33
+ - **`test/quota-cli-token.test.ts` 新增十一个用例**:既钉住判定(无过期时间、差一秒、恰好等于边界),也钉住刷新窗口(90 秒对 HTTP 算新鲜、对 spawn 不算),以及顺序(刷新、写槽、复读校验、spawn)。
36
34
 
37
- ## 0.6.55 (2026-11-21)
35
+ ## 0.6.58 (2026-11-22)
38
36
 
39
37
  ### English
40
38
 
41
- - **Feat(parity): full `agy` high- and medium-value parity suite — in-chat image generation, persistent ACP transport, multi-account ecosystem sync, Generative UI embeds, extended toolview cards, multimodal staging, slash bridges, and CLI security/passthrough flags.**
42
- - **In-chat image generation & balanced defaults**: Added the `agy_image` DSH tool (`imageTool` config), `/agy image` (`/agy img`) slash command, and `image-generator` subagent image preview card. Updated defaults to balanced `imageEffort: 'medium'` and auto-preference for discovered `gemini-4-hydrogen` (falling back to `gemini-3.8-flash`).
43
- - **Execution security & CLI passthrough**: Extended `PermissionMode` with `'auto'` (`--mode auto`), added `--sandbox` (`sandbox` config / request option), and wired `--agent`, `--settings`, and `--json-schema` passthrough into CLI arg assembly.
44
- - **Multimodal input staging & audio playback**: Added PDF, audio, and video attachment staging up to `mediaMaxFileBytes` (20 MiB default) alongside an inline `<audio>` player enhancer (`src/client/images/audio.ts`).
45
- - **Extended toolview cards**: Added dedicated cards and models for `swarm`, `run_workflow`, `schedule`, `manage_task`, subagent lifecycle (`invoke_subagent`, `define_subagent`, `manage_subagents`, `send_message`), and browser/devtools tools.
46
- - **Generative UI `<agent-embed>`**: Added streaming `<agent-embed src="...">` tag buffering in `EventMapper`/`text.ts`, a strict-CSP `/plugins/agy-link/embed` route, and a sandboxed `<iframe sandbox="allow-scripts">` auto-resizing/theme-synced renderer (`src/client/embed.ts`).
47
- - **Persistent `agy acp` session pool**: Added stdio JSON-RPC `AcpProcess` + `AcpSessionPool` (`transport: 'cli' | 'acp'`, lazy idle sweep timer, Windows single-account eviction, and automatic pre-stream CLI `-p` fallback).
48
- - **Multi-account ecosystem inventory & sync**: Added discovery across `plugins`, `mcp`, `skills`, `rules`, and `agents`, allowlist sync into isolated pool accounts, `/ecosystem` HTTP routes, Settings `EcosystemPanel`, and `/agy plugins|mcp|agents|skills|sync-ecosystem`.
49
- - **Slash command bridges**: Added `/agy btw`, `/agy fork` (including `list`/`restore`), `/agy grill` / `grill-me`, `/agy learn [--apply]`, and `/agy compact`.
50
- - **Per-family account scoping & host-backed warmup bar**: Preserved per-family active account pins (`manualPinAtByFamily`, `resolvedActiveAccountIds`) and host-backed `WarmupStatusBar` + warmup resilience improvements.
51
- - **i18n & Windows test hardening**: Localized all newly introduced DOM surfaces (`embed.ts`, `audio.ts`, `extended-cards.ts`, `image-card.ts`) onto `src/client/i18n-bridge.ts` across `en`/`zh`/`es`/`ptBR`, and fixed Windows path/CRLF handling in `test/issue153-client-locale.test.ts`.
39
+ - **Feat(accounts): a pool account's label is now editable from the console (fixes #152, part 1).** `pool.setAccountAlias()` existed but nothing exposed it — the alias could only be set while adding an account, so a typo, or a Google account that was renamed, left a stale label forever.
40
+ - **New route `POST /plugins/agy-link/pool/alias`** (`{ id, alias }`): non-empty, ≤64 chars, 404 for an unknown id. A successful rename clears `defaultAlias`, which is exactly what makes the card stop rendering the generated "Backup Google account N" label and show the typed one instead.
41
+ - **Inline rename in the card**: a "Rename" action opens an input under the card and saves through the host. The proxy editor and this one were the same layout written twice, so both now share `src/client/sections/inline-editor.ts` (which also keeps `AccountsPanel.ts` inside the file-size budget).
42
+ - Four locales carry the copy. `saveAlias` lives with the other account-lifecycle actions, not with quota actions — renaming has nothing to do with quota, and keeping it there would have pushed `quotaActions` past the line budget.
52
43
 
53
44
  ### 中文
54
45
 
55
- - **特性(能力对齐):全面补齐 `agy` 高/中优先级能力——对话内生图、持久化 ACP 传输池、多账号生态清点与同步、Generative UI 内嵌页、扩展工具卡片、多模态附件暂存、斜杠命令桥接与安全透传参数。**
56
- - **对话内生图与均衡默认参数**:新增 `agy_image` DSH 工具(`imageTool` 配置)、`/agy image`(`/agy img`)命令以及 `image-generator` 子代理图片预览卡片;将默认生图思考深度调整为均衡 `imageEffort: 'medium'`,并在发现 `gemini-4-hydrogen` 时自动优先选用(否则回退 `gemini-3.8-flash`)。
57
- - **安全执行与 CLI 参数透传**:为 `PermissionMode` 新增 `'auto'`(`--mode auto`),新增 `--sandbox` 沙箱开关,并打通 `--agent`、`--settings`、`--json-schema` 参数透传。
58
- - **多模态输入暂存与音频播放器**:支持 PDF、音频、视频附件暂存(默认单文件上限 `mediaMaxFileBytes` 20 MiB)与聊天内联 `<audio>` 播放器(`src/client/images/audio.ts`)。
59
- - **扩展工具详情卡片**:为 `swarm`、`run_workflow`、`schedule`、`manage_task`、子代理生命周期(`invoke_subagent` / `define_subagent` / `manage_subagents` / `send_message`)及浏览器/DevTools 工具提供专用卡片渲染。
60
- - **Generative UI `<agent-embed>`**:在 `EventMapper`/`text.ts` 中实现流式标签缓冲,新增严格 CSP 的 `/plugins/agy-link/embed` 路由与支持自适应高度及主题同步的沙箱 `<iframe sandbox="allow-scripts">` 渲染器(`src/client/embed.ts`)。
61
- - **持久化 `agy acp` 会话池**:实现 stdio JSON-RPC `AcpProcess` 与 `AcpSessionPool`(`transport: 'cli' | 'acp'`、懒启动空闲清理定时器、Windows 单账号驱逐与流前自动回退 CLI `-p`)。
62
- - **多账号生态清点与同步**:支持 `plugins`/`mcp`/`skills`/`rules`/`agents` 跨账号清点、白名单同步到隔离池账号、`/ecosystem` HTTP 路由、设置页 `EcosystemPanel` 及 `/agy plugins|mcp|agents|skills|sync-ecosystem`。
63
- - **斜杠命令桥接**:新增 `/agy btw`、`/agy fork`(含 `list`/`restore`)、`/agy grill` / `grill-me`、`/agy learn [--apply]` 与 `/agy compact`。
64
- - **按模型家族的活跃账号隔离与宿主级预热条**:保留 `manualPinAtByFamily`、`resolvedActiveAccountIds` 及宿主后端驱动的 `WarmupStatusBar` 与预热韧性增强。
65
- - **国际化与 Windows 测试加固**:将全部新增客户端 DOM 界面(`embed.ts`、`audio.ts`、`extended-cards.ts`、`image-card.ts`)接入 `src/client/i18n-bridge.ts` 并补齐 `en`/`zh`/`es`/`ptBR` 文案,同时修复 `test/issue153-client-locale.test.ts` 的 Windows 路径与 CRLF 注释处理。
46
+ - **特性(账号):池账号的显示名称现在可在控制台编辑(修复 #152 第一部分)。** `pool.setAccountAlias()` 早就存在,但没有任何入口暴露它——别名只能在添加账号时设定,于是打错字、或 Google 账号改名后,卡片上的旧名字会一直留着。
47
+ - **新增路由 `POST /plugins/agy-link/pool/alias`**(`{ id, alias }`):非空、≤64 字符、未知 id 返回 404。改名成功会清除 `defaultAlias`——这正是让卡片不再渲染自动生成的「备用 Google 账号 N」、改为显示用户输入的机制。
48
+ - **卡片内联重命名**:一个「重命名」动作在卡片下展开输入框,经宿主保存。代理编辑器与它原本是同一套布局写了两遍,现在共用 `src/client/sections/inline-editor.ts`(同时让 `AccountsPanel.ts` 保持在行数预算内)。
49
+ - 四语言文案齐全。`saveAlias` 归入账号生命周期动作而非配额动作——改名与配额无关,放在配额里会把 `quotaActions` 顶出行数预算。
50
+
51
+ ## 0.6.56 (2026-11-21)
52
+
53
+ ### English
54
+
55
+ - **Feat(accounts): a pool account's label is now editable from the console (fixes #152, part 1).** `pool.setAccountAlias()` existed but nothing exposed it — the alias could only be set while adding an account, so a typo or a renamed Google account left a stale label forever.
56
+ - **New route `POST /plugins/agy-link/pool/alias`** (`{ id, alias }`) with the validations the UI relies on: non-empty, ≤64 chars, and a 404 for an unknown id. A successful rename clears `defaultAlias`, which is what makes the card stop rendering the generated "Backup Google account N" label and show the typed one.
57
+ - **Inline rename in the card**: a "Rename" action opens an input under the card, saving through the host and refreshing the pool. The proxy editor and this one were the same layout twice, so both now share `src/client/sections/inline-editor.ts` (which also keeps `AccountsPanel.ts` inside the file-size budget).
58
+ - **Test(dx): the SIGKILL-escalation test no longer asserts a wall-clock upper bound.** `durationMs` spans spawn→exit, so on a saturated host it read **16 minutes** during a full coverage run while the escalation itself was correct. The lower bound (must wait out the 3s window) and the semantic `signal === 'SIGKILL'` assertion stay; "hangs forever" is covered by the race guard, which reaps the child.
59
+
60
+ ### 中文
61
+
62
+ - **特性(账号):池账号的显示名称现在可在控制台直接编辑(修复 #152 第一部分)。** `pool.setAccountAlias()` 早就存在,但没有任何入口暴露它——别名只能在添加账号时设定,于是打错字或 Google 账号改名后,卡片上的旧名字会一直留着。
63
+ - **新增路由 `POST /plugins/agy-link/pool/alias`**(`{ id, alias }`),带 UI 依赖的校验:非空、≤64 字符、未知 id 返回 404。改名成功会清除 `defaultAlias`,这正是让卡片不再渲染自动生成的「备用 Google 账号 N」、改为显示用户输入的关键。
64
+ - **卡片内联重命名**:一个「重命名」动作在卡片下展开输入框,经宿主保存后刷新池。代理编辑器与它原本是同一套布局写了两遍,现在共用 `src/client/sections/inline-editor.ts`(同时让 `AccountsPanel.ts` 保持在文件行数预算内)。
65
+ - **测试(开发体验):SIGKILL 升级用例不再断言墙钟上界。** `durationMs` 是 spawn→exit 的跨度,在饱和的宿主上于一次完整覆盖率运行中读到 **16 分钟**,而升级本身是正确的。保留了下界(必须等过 3 秒窗口)与语义断言 `signal === 'SIGKILL'`;「是否永久挂住」由带回收的 race 守卫覆盖。
66
66
 
67
67
  ## 0.6.54 (2026-11-21)
68
68
 
package/dist/client.js CHANGED
@@ -51,6 +51,11 @@ window.__ModuleLoader__.load({
51
51
  "account.add": "添加 Google 账号",
52
52
  "account.aliasDefault": "备用 Google 账号 {number}",
53
53
  "account.defaultAlias": "主账号(系统登录)",
54
+ "account.rename": "重命名",
55
+ "account.renameTitle": "编辑该账号的显示名称",
56
+ "account.renameEmpty": "账号名称不能为空",
57
+ "account.renamed": "账号名称已更新",
58
+ "account.renamePlaceholder": "账号名称",
54
59
  "decision.quickFill": "💬 点击选项快速填入:",
55
60
  "decision.insertTooltip": "点击填入: {text}",
56
61
  "decision.insertPayload": "我选择 {choice}",
@@ -384,6 +389,11 @@ window.__ModuleLoader__.load({
384
389
  "account.add": "Add Google account",
385
390
  "account.aliasDefault": "Backup Google account {number}",
386
391
  "account.defaultAlias": "Primary account (system sign-in)",
392
+ "account.rename": "Rename",
393
+ "account.renameTitle": "Edit this account label",
394
+ "account.renameEmpty": "Account label must not be empty",
395
+ "account.renamed": "Account label updated",
396
+ "account.renamePlaceholder": "Account label",
387
397
  "decision.quickFill": "💬 Click an option to fill it in:",
388
398
  "decision.insertTooltip": "Insert: {text}",
389
399
  "decision.insertPayload": "I choose {choice}",
@@ -717,6 +727,11 @@ window.__ModuleLoader__.load({
717
727
  "account.add": "Adicionar conta Google",
718
728
  "account.aliasDefault": "Conta Google reserva {number}",
719
729
  "account.defaultAlias": "Conta principal (login do sistema)",
730
+ "account.rename": "Renomear",
731
+ "account.renameTitle": "Editar o rótulo desta conta",
732
+ "account.renameEmpty": "O rótulo não pode ficar vazio",
733
+ "account.renamed": "Rótulo atualizado",
734
+ "account.renamePlaceholder": "Rótulo da conta",
720
735
  "decision.quickFill": "💬 Clique numa opção para preenchê-la:",
721
736
  "decision.insertTooltip": "Inserir: {text}",
722
737
  "decision.insertPayload": "Escolho {choice}",
@@ -1050,6 +1065,11 @@ window.__ModuleLoader__.load({
1050
1065
  "account.add": "Añadir cuenta de Google",
1051
1066
  "account.aliasDefault": "Cuenta de Google de respaldo {number}",
1052
1067
  "account.defaultAlias": "Cuenta principal (inicio de sesión del sistema)",
1068
+ "account.rename": "Renombrar",
1069
+ "account.renameTitle": "Editar la etiqueta de esta cuenta",
1070
+ "account.renameEmpty": "La etiqueta no puede estar vacía",
1071
+ "account.renamed": "Etiqueta actualizada",
1072
+ "account.renamePlaceholder": "Etiqueta de la cuenta",
1053
1073
  "decision.quickFill": "💬 Haz clic en una opción para rellenarla:",
1054
1074
  "decision.insertTooltip": "Insertar: {text}",
1055
1075
  "decision.insertPayload": "Elijo {choice}",
@@ -9067,7 +9087,30 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9067
9087
  };
9068
9088
  }
9069
9089
  function lifecycleActions(deps, actionFailed) {
9070
- const { refresh, showToast, setLoadingAction, t, setOptimisticActiveByFamily } = deps;
9090
+ const { refresh, showToast, setLoadingAction, t, setOptimisticActiveByFamily, aliasInputs, setEditingAliasId } = deps;
9091
+ const saveAlias = async (id) => {
9092
+ const alias = (aliasInputs[id] ?? "").trim();
9093
+ if (alias === "") {
9094
+ showToast(t("account.renameEmpty"), "error");
9095
+ return;
9096
+ }
9097
+ setLoadingAction(`alias:${id}`);
9098
+ try {
9099
+ const res = await postPool("alias", {
9100
+ id,
9101
+ alias
9102
+ });
9103
+ if (res === null || res?.ok === false) {
9104
+ actionFailed();
9105
+ return;
9106
+ }
9107
+ await refresh();
9108
+ setEditingAliasId(null);
9109
+ showToast(t("account.renamed"), "success");
9110
+ } finally {
9111
+ setLoadingAction(null);
9112
+ }
9113
+ };
9071
9114
  const setActiveAccount = async (id, family = "google") => {
9072
9115
  setOptimisticActiveByFamily((prev) => ({
9073
9116
  ...prev,
@@ -9135,7 +9178,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9135
9178
  return {
9136
9179
  setActiveAccount,
9137
9180
  removeAccount,
9138
- toggleAccountEnabled
9181
+ toggleAccountEnabled,
9182
+ saveAlias
9139
9183
  };
9140
9184
  }
9141
9185
  function quotaActions(deps, actionFailed) {
@@ -9924,6 +9968,38 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9924
9968
  return reason === "validation_required" || reason === "tos_violation";
9925
9969
  }
9926
9970
  //#endregion
9971
+ //#region src/client/sections/inline-editor.ts
9972
+ function renderInlineEditor(t, opts) {
9973
+ return h("div", {
9974
+ key: opts.key,
9975
+ style: {
9976
+ marginTop: "8px",
9977
+ padding: "10px 12px",
9978
+ background: "var(--agy-bg-subbox)",
9979
+ borderRadius: "7px",
9980
+ border: "1px solid var(--agy-border-subbox)"
9981
+ }
9982
+ }, h("div", { style: {
9983
+ display: "flex",
9984
+ gap: "8px"
9985
+ } }, h("input", {
9986
+ style: S.input,
9987
+ value: opts.value,
9988
+ placeholder: opts.placeholder,
9989
+ "aria-label": opts.ariaLabel,
9990
+ onChange: (e) => opts.onChange(e.target.value)
9991
+ }), h(Button, {
9992
+ variant: "primary",
9993
+ className: "agy-btn",
9994
+ disabled: opts.busy,
9995
+ onClick: () => opts.onSave()
9996
+ }, ...opts.busy ? [Spinner(), opts.saveLabel] : [opts.saveLabel]), h(Button, {
9997
+ variant: "default",
9998
+ className: "agy-btn",
9999
+ onClick: () => opts.onCancel()
10000
+ }, opts.cancelLabel)));
10001
+ }
10002
+ //#endregion
9927
10003
  //#region src/common/quota-pacing.ts
9928
10004
  /**
9929
10005
  * Compare remaining quota fraction against remaining reset window fraction.
@@ -10331,7 +10407,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10331
10407
  return out;
10332
10408
  }
10333
10409
  function AccountsPanel(props) {
10334
- const { t, pool, accounts, accountModels, loadingAction, quotaRefreshing = [], warmupState, proxyInputs, setProxyInputs, editingProxyId, setEditingProxyId, expandedModels, toggleExpand, optimisticActiveId, optimisticActiveByFamily, handlers } = props;
10410
+ const { t, pool, accounts, accountModels, loadingAction, quotaRefreshing = [], warmupState, proxyInputs, setProxyInputs, editingProxyId, setEditingProxyId, aliasInputs, setAliasInputs, editingAliasId, setEditingAliasId, expandedModels, toggleExpand, optimisticActiveId, optimisticActiveByFamily, handlers } = props;
10335
10411
  const accountActionBusy = (acc, action) => loadingAction === `${action}:${acc.id}`;
10336
10412
  const activeIds = resolveFamilyActiveIds(pool, optimisticActiveByFamily, optimisticActiveId);
10337
10413
  const now = Date.now();
@@ -10344,6 +10420,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10344
10420
  const hasAnyActiveFamily = Boolean(acc.enabled && !isAuthRequired && QUOTA_FAMILIES.some((fam) => (fam !== "argon" || acc.quotas.argon !== void 0) && !isFamilyCooling(acc, fam, now) && activeIds[fam] === acc.id));
10345
10421
  const dotColor = !acc.enabled ? "#64748b" : isAuthRequired ? "#ef4444" : isFullyCooling ? "#f59e0b" : "#10b981";
10346
10422
  const isEditingProxy = editingProxyId === acc.id;
10423
+ const isEditingAlias = editingAliasId === acc.id;
10347
10424
  const isExpanded = expandedModels[acc.id] ?? false;
10348
10425
  const accIndex = accounts.indexOf(acc);
10349
10426
  const cardStyle = {
@@ -10385,6 +10462,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10385
10462
  isEditingProxy,
10386
10463
  isSyncing,
10387
10464
  isWarming,
10465
+ isEditingAlias,
10388
10466
  displayAlias,
10389
10467
  accIndex,
10390
10468
  accounts,
@@ -10392,7 +10470,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10392
10470
  loadingAction,
10393
10471
  accountActionBusy,
10394
10472
  handlers,
10395
- setEditingProxyId
10473
+ setEditingProxyId,
10474
+ setEditingAliasId
10396
10475
  }), h("div", {
10397
10476
  key: "agy-body",
10398
10477
  style: S.quotaBox
@@ -10409,7 +10488,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10409
10488
  }, uiIcon(isExpanded ? "chevronUp" : "chevronDown", 10), h("span", null, isExpanded ? t("account.collapseOthers") : t("account.expandOthers")), !isExpanded && collapsedCoolingNames.length > 0 ? h("span", { style: {
10410
10489
  color: "#f59e0b",
10411
10490
  fontWeight: 700
10412
- } }, t("account.collapsedCoolingHint", { families: collapsedCoolingNames.join(", ") })) : null), isExpanded ? h("div", { key: "expanded-details" }, renderQuotaBar("Claude", "anthropic"), renderQuotaBar("GPT-OSS", "openai"), childModels.length > 0 ? renderChildModels(t, childModels) : null) : null), isEditingProxy ? renderProxyEditor(t, acc, pool, proxyInputs, setProxyInputs, setEditingProxyId, loadingAction, accountActionBusy, handlers) : null);
10491
+ } }, t("account.collapsedCoolingHint", { families: collapsedCoolingNames.join(", ") })) : null), isExpanded ? h("div", { key: "expanded-details" }, renderQuotaBar("Claude", "anthropic"), renderQuotaBar("GPT-OSS", "openai"), childModels.length > 0 ? renderChildModels(t, childModels) : null) : null), isEditingAlias ? renderAliasEditor(t, acc, aliasInputs, setAliasInputs, setEditingAliasId, displayAlias, loadingAction, accountActionBusy, handlers) : null, isEditingProxy ? renderProxyEditor(t, acc, pool, proxyInputs, setProxyInputs, setEditingProxyId, loadingAction, accountActionBusy, handlers) : null);
10413
10492
  });
10414
10493
  }
10415
10494
  function extractActionUrl(text) {
@@ -10569,7 +10648,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10569
10648
  }, ...badges);
10570
10649
  }
10571
10650
  function renderCardHeader(t, acc, ctx) {
10572
- const { isEditingProxy, isAuthRequired, isSyncing, isWarming, displayAlias, accounts, pool, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
10651
+ const { isEditingProxy, isAuthRequired, isSyncing, isWarming, isEditingAlias, displayAlias, accounts, pool, loadingAction, accountActionBusy, handlers, setEditingProxyId, setEditingAliasId } = ctx;
10573
10652
  return h("div", {
10574
10653
  className: "agy-card-header",
10575
10654
  style: {
@@ -10593,17 +10672,19 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10593
10672
  isAuthRequired,
10594
10673
  isSyncing,
10595
10674
  isWarming,
10675
+ isEditingAlias,
10596
10676
  displayAlias,
10597
10677
  showRemove: accounts.length > 1,
10598
10678
  pool,
10599
10679
  loadingAction,
10600
10680
  accountActionBusy,
10601
10681
  handlers,
10602
- setEditingProxyId
10682
+ setEditingProxyId,
10683
+ setEditingAliasId
10603
10684
  })), renderMetaRow(t, acc, ctx));
10604
10685
  }
10605
10686
  function renderActionButtons(t, acc, ctx) {
10606
- const { isEditingProxy, isAuthRequired, isSyncing, isWarming, displayAlias, showRemove, pool, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
10687
+ const { isEditingProxy, isAuthRequired, isSyncing, isWarming, isEditingAlias, displayAlias, showRemove, pool, loadingAction, accountActionBusy, handlers, setEditingProxyId, setEditingAliasId } = ctx;
10607
10688
  const effectiveProxy = acc.proxyUrl || pool?.systemProxy;
10608
10689
  return h("div", {
10609
10690
  className: "agy-card-actions",
@@ -10614,6 +10695,18 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10614
10695
  flexShrink: 0
10615
10696
  }
10616
10697
  }, h(Button, {
10698
+ variant: "default",
10699
+ size: "sm",
10700
+ className: "agy-btn",
10701
+ style: {
10702
+ gap: "3px",
10703
+ fontSize: "11px",
10704
+ padding: "1px 6px",
10705
+ height: "22px"
10706
+ },
10707
+ title: t("account.renameTitle"),
10708
+ onClick: () => setEditingAliasId(isEditingAlias ? null : acc.id)
10709
+ }, ` ${t("account.rename")}`), h(Button, {
10617
10710
  variant: acc.enabled ? "default" : "primary",
10618
10711
  size: "sm",
10619
10712
  className: "agy-btn",
@@ -10760,38 +10853,39 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10760
10853
  }, `↻ ${w.resetText}`) : null));
10761
10854
  }));
10762
10855
  }
10856
+ function renderAliasEditor(t, acc, aliasInputs, setAliasInputs, setEditingAliasId, displayAlias, loadingAction, accountActionBusy, handlers) {
10857
+ return renderInlineEditor(t, {
10858
+ key: "alias-body",
10859
+ value: aliasInputs[acc.id] ?? displayAlias,
10860
+ placeholder: t("account.renamePlaceholder"),
10861
+ ariaLabel: t("aria.aliasInput"),
10862
+ saveLabel: t("proxy.save"),
10863
+ cancelLabel: t("cancel"),
10864
+ busy: accountActionBusy(acc, "alias"),
10865
+ onChange: (next) => setAliasInputs({
10866
+ ...aliasInputs,
10867
+ [acc.id]: next
10868
+ }),
10869
+ onSave: () => void handlers.saveAlias(acc.id),
10870
+ onCancel: () => setEditingAliasId(null)
10871
+ });
10872
+ }
10763
10873
  function renderProxyEditor(t, acc, pool, proxyInputs, setProxyInputs, setEditingProxyId, loadingAction, accountActionBusy, handlers) {
10764
- return h("div", {
10874
+ return renderInlineEditor(t, {
10765
10875
  key: "proxy-body",
10766
- style: {
10767
- marginTop: "8px",
10768
- padding: "10px 12px",
10769
- background: "var(--agy-bg-subbox)",
10770
- borderRadius: "7px",
10771
- border: "1px solid var(--agy-border-subbox)"
10772
- }
10773
- }, h("div", { style: {
10774
- display: "flex",
10775
- gap: "8px"
10776
- } }, h("input", {
10777
- style: S.input,
10778
- value: proxyInputs[acc.id] !== void 0 ? proxyInputs[acc.id] : acc.proxyUrl ?? "",
10876
+ value: proxyInputs[acc.id] ?? acc.proxyUrl ?? "",
10779
10877
  placeholder: pool?.systemProxy ? `${t("proxy.placeholder")} (${pool.systemProxy})` : t("proxy.placeholder"),
10780
- "aria-label": t("aria.proxyInput"),
10781
- onChange: (e) => setProxyInputs({
10878
+ ariaLabel: t("aria.proxyInput"),
10879
+ saveLabel: t("proxy.save"),
10880
+ cancelLabel: t("cancel"),
10881
+ busy: accountActionBusy(acc, "proxy"),
10882
+ onChange: (next) => setProxyInputs({
10782
10883
  ...proxyInputs,
10783
- [acc.id]: e.target.value
10784
- })
10785
- }), h(Button, {
10786
- variant: "primary",
10787
- className: "agy-btn",
10788
- disabled: accountActionBusy(acc, "proxy"),
10789
- onClick: () => void handlers.saveProxy(acc.id)
10790
- }, ...loadingAction === `proxy:${acc.id}` ? [Spinner(), t("proxy.save")] : [t("proxy.save")]), h(Button, {
10791
- variant: "default",
10792
- className: "agy-btn",
10793
- onClick: () => setEditingProxyId(null)
10794
- }, t("cancel"))));
10884
+ [acc.id]: next
10885
+ }),
10886
+ onSave: () => void handlers.saveProxy(acc.id),
10887
+ onCancel: () => setEditingProxyId(null)
10888
+ });
10795
10889
  }
10796
10890
  //#endregion
10797
10891
  //#region src/client/sections/EcosystemPanel.ts
@@ -11476,6 +11570,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
11476
11570
  const [loadingAction, setLoadingAction] = useBusyAction();
11477
11571
  const [proxyInputs, setProxyInputs] = useState({});
11478
11572
  const [editingProxyId, setEditingProxyId] = useState(null);
11573
+ const [aliasInputs, setAliasInputs] = useState({});
11574
+ const [editingAliasId, setEditingAliasId] = useState(null);
11479
11575
  const [expandedModels, setExpandedModels] = useState({});
11480
11576
  const [optimisticActiveByFamily, setOptimisticActiveByFamily] = useState({});
11481
11577
  useEffect(() => {
@@ -11508,6 +11604,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
11508
11604
  t,
11509
11605
  proxyInputs,
11510
11606
  setEditingProxyId,
11607
+ aliasInputs,
11608
+ setEditingAliasId,
11511
11609
  setOptimisticActiveByFamily
11512
11610
  });
11513
11611
  const copyImageCommand = () => {
@@ -11584,6 +11682,10 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
11584
11682
  setProxyInputs,
11585
11683
  editingProxyId,
11586
11684
  setEditingProxyId,
11685
+ aliasInputs,
11686
+ setAliasInputs,
11687
+ editingAliasId,
11688
+ setEditingAliasId,
11587
11689
  expandedModels,
11588
11690
  toggleExpand,
11589
11691
  optimisticActiveByFamily,
package/dist/index.js CHANGED
@@ -43349,6 +43349,62 @@ async function readAgyUsage(opts) {
43349
43349
  }
43350
43350
  }
43351
43351
  //#endregion
43352
+ //#region src/features/quota/cli-token.ts
43353
+ /**
43354
+ * Token life a freshly spawned `agy` must still have.
43355
+ *
43356
+ * Two minutes is deliberately far from the observed failure band (<=60s) and
43357
+ * far above the refresh round-trip (1.5–5s measured), so a token that passes
43358
+ * this check cannot need a refresh during agy's startup window.
43359
+ */
43360
+ const CLI_TOKEN_SAFETY_MS = 12e4;
43361
+ /** Remaining life of a token, or -Infinity when the expiry is unknown. */
43362
+ function tokenRemainingMs(tok, now = Date.now()) {
43363
+ if (typeof tok?.expiryMs !== "number") return Number.NEGATIVE_INFINITY;
43364
+ return tok.expiryMs - now;
43365
+ }
43366
+ /**
43367
+ * True when the stored credential lets a new `agy` process authenticate
43368
+ * without refreshing anything at startup.
43369
+ *
43370
+ * A missing expiry counts as NOT safe: agy would treat it as "no usable
43371
+ * token" and refresh (the very path that pops a browser). Missing is not
43372
+ * "valid forever" here either — that reading is what made issue #112 a
43373
+ * permanent 401 loop.
43374
+ */
43375
+ function isTokenSafeForCli(tok, now = Date.now()) {
43376
+ if (!tok?.accessToken) return false;
43377
+ return tokenRemainingMs(tok, now) >= CLI_TOKEN_SAFETY_MS;
43378
+ }
43379
+ /**
43380
+ * Make the stored credential safe for a fresh `agy` spawn, or refuse.
43381
+ *
43382
+ * Returns false when the CLI must be skipped this round (the caller then lets
43383
+ * the REST path answer). A skipped round costs one quota sample an hour; a
43384
+ * spawn with a dying token costs the user a browser window they did not ask
43385
+ * for, and an auth state that looks broken if they close it.
43386
+ */
43387
+ async function prepareCliToken(deps) {
43388
+ const now = deps.now?.() ?? Date.now();
43389
+ const before = await deps.readStored();
43390
+ if (isTokenSafeForCli(before, now)) return true;
43391
+ const remaining = tokenRemainingMs(before, now);
43392
+ deps.log?.("[agy-link] CLI quota read: the stored token " + (Number.isFinite(remaining) ? "has " + Math.round(remaining / 1e3) + "s left" : "has no known expiry") + " — refreshing before the spawn instead of letting agy open a browser");
43393
+ if (!await deps.refresh()) {
43394
+ deps.log?.("[agy-link] CLI quota read skipped: the token could not be refreshed (REST will answer)");
43395
+ return false;
43396
+ }
43397
+ if (deps.syncSlot !== void 0 && !deps.syncSlot()) {
43398
+ deps.log?.("[agy-link] CLI quota read skipped: the refreshed token could not be written to the credential slot");
43399
+ return false;
43400
+ }
43401
+ if (!isTokenSafeForCli(await deps.readStored(), deps.now?.() ?? Date.now())) {
43402
+ deps.log?.("[agy-link] CLI quota read skipped: the credential agy would load is still outside the safety window");
43403
+ return false;
43404
+ }
43405
+ return true;
43406
+ }
43407
+ //#endregion
43352
43408
  //#region src/domain/quota/buckets.ts
43353
43409
  /**
43354
43410
  * When the quota-summary endpoint transiently fails, per-model fallback
@@ -44372,10 +44428,10 @@ function isCurrentAccountGrant(deps, account, refreshToken) {
44372
44428
  * risk-control exposure for the same outcome). The in-flight map itself is
44373
44429
  * owned by QuotaService so cached state is unchanged.
44374
44430
  */
44375
- async function getValidAccessToken(deps, account, tokenRefreshInFlight) {
44431
+ async function getValidAccessToken(deps, account, tokenRefreshInFlight, minValidityMs) {
44376
44432
  const existing = tokenRefreshInFlight.get(account.id);
44377
44433
  if (existing !== void 0) return existing;
44378
- const attempt = getValidAccessTokenUncached(deps, account).finally(() => {
44434
+ const attempt = getValidAccessTokenUncached(deps, account, minValidityMs).finally(() => {
44379
44435
  tokenRefreshInFlight.delete(account.id);
44380
44436
  });
44381
44437
  tokenRefreshInFlight.set(account.id, attempt);
@@ -44387,13 +44443,13 @@ async function getValidAccessToken(deps, account, tokenRefreshInFlight) {
44387
44443
  * imports must go through refresh/validation instead of being reused until
44388
44444
  * they 401 (issue #112).
44389
44445
  */
44390
- function isAccessTokenFresh(tok, now = Date.now()) {
44391
- return !!tok.accessToken && typeof tok.expiryMs === "number" && tok.expiryMs > now + 6e4;
44446
+ function isAccessTokenFresh(tok, now = Date.now(), bufferMs = 6e4) {
44447
+ return !!tok.accessToken && typeof tok.expiryMs === "number" && tok.expiryMs > now + bufferMs;
44392
44448
  }
44393
- async function getValidAccessTokenUncached(deps, account) {
44449
+ async function getValidAccessTokenUncached(deps, account, minValidityMs) {
44394
44450
  const tok = await deps.getStoredToken(account);
44395
44451
  if (!tok) return null;
44396
- if (tok.accessToken && isAccessTokenFresh(tok)) return tok.accessToken;
44452
+ if (tok.accessToken && isAccessTokenFresh(tok, Date.now(), minValidityMs)) return tok.accessToken;
44397
44453
  if (tok.refreshToken) try {
44398
44454
  const refreshed = await refreshTokens(tok.refreshToken, deps.proxyFor(account), account.id);
44399
44455
  if (!isCurrentAccountGrant(deps, account, tok.refreshToken)) return null;
@@ -44530,6 +44586,7 @@ var QuotaService = class {
44530
44586
  }
44531
44587
  try {
44532
44588
  if (!await this.cliSlotHoldsAccount(account)) return null;
44589
+ if (!await this.prepareCliToken(account)) return null;
44533
44590
  const groups = await readAgyUsage({
44534
44591
  bin,
44535
44592
  env: buildAgyEnvWithProxy({
@@ -44545,6 +44602,24 @@ var QuotaService = class {
44545
44602
  }
44546
44603
  }
44547
44604
  /**
44605
+ * Bring the credential `agy` would load into the safety window, or refuse.
44606
+ *
44607
+ * The CLI is only ever used for the slot owner, so a refresh here refreshes
44608
+ * the identity that is about to run — no cross-account risk. On Windows the
44609
+ * refreshed token also has to reach the Credential Manager slot, because that
44610
+ * is what agy loads (the on-disk document is only a mirror); `syncSlot` does
44611
+ * that and is wired by the host, which owns the mutex we are already holding.
44612
+ */
44613
+ async prepareCliToken(account) {
44614
+ const syncSlot = this.cliDeps.syncSlot;
44615
+ return prepareCliToken({
44616
+ readStored: () => this.getStoredToken(account, true),
44617
+ refresh: async () => await this.getValidAccessToken(account, CLI_TOKEN_SAFETY_MS) !== null,
44618
+ ...syncSlot === void 0 ? {} : { syncSlot: () => syncSlot(account) },
44619
+ ...this.cliDeps.log === void 0 ? {} : { log: this.cliDeps.log }
44620
+ });
44621
+ }
44622
+ /**
44548
44623
  * True when the machine credential slot provably holds this account's grant.
44549
44624
  *
44550
44625
  * This gates the CLI quota read, which can only ever see the slot owner.
@@ -44612,8 +44687,8 @@ var QuotaService = class {
44612
44687
  * used to race into duplicate refreshTokens for one account (double
44613
44688
  * risk-control exposure for the same outcome).
44614
44689
  */
44615
- async getValidAccessToken(account) {
44616
- return getValidAccessToken(this.tokenDeps(), account, this.tokenRefreshInFlight);
44690
+ async getValidAccessToken(account, minValidityMs) {
44691
+ return getValidAccessToken(this.tokenDeps(), account, this.tokenRefreshInFlight, minValidityMs);
44617
44692
  }
44618
44693
  isCurrentAccountGrant(account, refreshToken) {
44619
44694
  return isCurrentAccountGrant(this.tokenDeps(), account, refreshToken);
@@ -47157,7 +47232,18 @@ function createHostServices(ctx, entryConfig = {}) {
47157
47232
  const quota = new QuotaService(pool, () => getConfig().proxyUrl || detectSystemProxy() || "", version, {
47158
47233
  bin: () => bin(),
47159
47234
  viaCli: () => getConfig().quotaViaCli,
47160
- preemptAutoUpdate: () => getConfig().suppressAgyAutoUpdate
47235
+ preemptAutoUpdate: () => getConfig().suppressAgyAutoUpdate,
47236
+ ...process.platform === "win32" ? { syncSlot: () => {
47237
+ const raw = readPrimaryCredential(pool.dir)?.raw;
47238
+ if (raw === void 0 || raw === "") return false;
47239
+ try {
47240
+ installSlotOrThrow(defaultSlotIo(), raw, log, "quota token refresh");
47241
+ return true;
47242
+ } catch {
47243
+ return false;
47244
+ }
47245
+ } } : {},
47246
+ log
47161
47247
  });
47162
47248
  const warmup = new WarmupService(pool, quota, () => getConfig().proxyUrl || detectSystemProxy() || "", version, getConfig, log, void 0, { bin: () => bin() });
47163
47249
  const semaphore = new Semaphore(() => getConfig().maxConcurrent);
@@ -47819,6 +47905,52 @@ function handlePoolProxy(services, req, res) {
47819
47905
  });
47820
47906
  });
47821
47907
  }
47908
+ /** Longest alias we accept: it is a display label on a card, not free text. */
47909
+ const MAX_ALIAS_LEN = 64;
47910
+ function handlePoolAlias(services, req, res) {
47911
+ const { pool } = services;
47912
+ runRoute(res, async () => {
47913
+ if (methodOf(req) !== "POST") {
47914
+ sendJson(res, 405, { error: "POST only" });
47915
+ return;
47916
+ }
47917
+ const body = await readBody(req);
47918
+ const id = typeof body.id === "string" ? body.id.trim() : "";
47919
+ const alias = typeof body.alias === "string" ? body.alias.trim() : "";
47920
+ if (id === "") {
47921
+ sendJson(res, 400, {
47922
+ ok: false,
47923
+ error: "id is required"
47924
+ });
47925
+ return;
47926
+ }
47927
+ if (alias === "") {
47928
+ sendJson(res, 400, {
47929
+ ok: false,
47930
+ error: "alias must not be empty"
47931
+ });
47932
+ return;
47933
+ }
47934
+ if (alias.length > MAX_ALIAS_LEN) {
47935
+ sendJson(res, 400, {
47936
+ ok: false,
47937
+ error: "alias is too long (max 64)"
47938
+ });
47939
+ return;
47940
+ }
47941
+ if (!pool.setAccountAlias(id, alias)) {
47942
+ sendJson(res, 404, {
47943
+ ok: false,
47944
+ error: "account not found"
47945
+ });
47946
+ return;
47947
+ }
47948
+ sendJson(res, 200, {
47949
+ ok: true,
47950
+ pool: pool.getPoolData()
47951
+ });
47952
+ });
47953
+ }
47822
47954
  function handlePoolPrimary(services, req, res) {
47823
47955
  const { pool, catalog, notifyPicker } = services;
47824
47956
  runRoute(res, async () => {
@@ -48169,6 +48301,11 @@ function register$6(reg, services) {
48169
48301
  path: "/plugins/agy-link/pool/proxy",
48170
48302
  handler: (req, res) => handlePoolProxy(services, req, res)
48171
48303
  });
48304
+ reg({
48305
+ kind: "exact",
48306
+ path: "/plugins/agy-link/pool/alias",
48307
+ handler: (req, res) => handlePoolAlias(services, req, res)
48308
+ });
48172
48309
  reg({
48173
48310
  kind: "exact",
48174
48311
  path: "/plugins/agy-link/pool/primary",
@@ -48836,10 +48973,25 @@ function spawnDetachedOpener(command, args, spawnImpl = spawn) {
48836
48973
  return false;
48837
48974
  }
48838
48975
  }
48839
- function executeOpenInSystem(targetPath, reveal = false) {
48976
+ /**
48977
+ * Open `targetPath` with the platform handler, or reveal it in the file manager.
48978
+ *
48979
+ * A path that no longer exists must never reach the OS opener: on Windows,
48980
+ * `explorer.exe /select,<missing>` does not fail, it silently opens the Desktop
48981
+ * folder instead, so a stale click looks like the plugin randomly opening the
48982
+ * user's Desktop. Fail fast and let the route answer with a real error.
48983
+ *
48984
+ * @param opener injection seam for tests: a unit test must never launch a real
48985
+ * Explorer / Finder / xdg-open on the developer's machine.
48986
+ */
48987
+ function executeOpenInSystem(targetPath, reveal = false, opener = spawnDetachedOpener) {
48840
48988
  try {
48989
+ if (!existsSync(targetPath)) return {
48990
+ ok: false,
48991
+ error: "target does not exist: " + targetPath
48992
+ };
48841
48993
  if (process.platform === "darwin") {
48842
- if (!spawnDetachedOpener("open", reveal ? ["-R", targetPath] : [targetPath])) return {
48994
+ if (!opener("open", reveal ? ["-R", targetPath] : [targetPath])) return {
48843
48995
  ok: false,
48844
48996
  error: "failed to launch the system opener"
48845
48997
  };
@@ -48847,7 +48999,7 @@ function executeOpenInSystem(targetPath, reveal = false) {
48847
48999
  }
48848
49000
  if (process.platform === "win32") {
48849
49001
  if (reveal) {
48850
- if (!spawnDetachedOpener("explorer.exe", [`/select,${targetPath}`])) return {
49002
+ if (!opener("explorer.exe", [`/select,${targetPath}`])) return {
48851
49003
  ok: false,
48852
49004
  error: "failed to launch explorer.exe"
48853
49005
  };
@@ -48883,15 +49035,15 @@ function executeOpenInSystem(targetPath, reveal = false) {
48883
49035
  ".gd",
48884
49036
  ".log"
48885
49037
  ].includes(ext)) {
48886
- if (spawnDetachedOpener("notepad.exe", [targetPath])) return { ok: true };
49038
+ if (opener("notepad.exe", [targetPath])) return { ok: true };
48887
49039
  }
48888
- if (!spawnDetachedOpener("explorer.exe", [`/select,${targetPath}`])) return {
49040
+ if (!opener("explorer.exe", [`/select,${targetPath}`])) return {
48889
49041
  ok: false,
48890
49042
  error: "failed to launch explorer.exe"
48891
49043
  };
48892
49044
  return { ok: true };
48893
49045
  }
48894
- if (!spawnDetachedOpener("xdg-open", [targetPath])) return {
49046
+ if (!opener("xdg-open", [targetPath])) return {
48895
49047
  ok: false,
48896
49048
  error: "failed to launch xdg-open"
48897
49049
  };
@@ -89,7 +89,7 @@ Resolution order (highest first): `DSH_AGY_*` environment variable → runtime o
89
89
  | --- | --- | --- | --- |
90
90
  | `proxyUrl` | `DSH_AGY_PROXY_URL` | `''` | Global proxy for agy processes; per-account proxies take precedence |
91
91
  | `quotaPollIntervalMs` | `DSH_AGY_QUOTA_POLL_INTERVAL_MS` | `3600000` | Background quota poll interval (minimum 60 s) |
92
- | `quotaViaCli` | `DSH_AGY_QUOTA_VIA_CLI` | `true` | Prefer the agy CLI path for quota queries |
92
+ | `quotaViaCli` | `DSH_AGY_QUOTA_VIA_CLI` | `true` | Prefer the agy CLI path for quota queries. The CLI is only spawned once the account's access token has at least two minutes of life left (refreshed up front when it does not); otherwise that round falls back to the REST quota endpoint |
93
93
  | `autoWarmup` | `DSH_AGY_AUTO_WARMUP` | `false` | Opt-in weekly-quota warmup |
94
94
  | `warmupModels` | `DSH_AGY_WARMUP_MODELS` | `gemini-3.8-flash,claude-sonnet-5-5` | Models used for warmup probes |
95
95
  | `suppressAgyAutoUpdate` | `DSH_AGY_SUPPRESS_AUTOUPDATE` | `true` on Windows, `false` elsewhere | Refresh agy's update-check timestamp before every spawn to stop the `--bg-updater` console flash chain |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.6.57",
3
+ "version": "0.6.59",
4
4
  "description": "Google Antigravity (agy CLI) models for DeepSeek Harness — stream Gemini/Claude/GPT-OSS subscriptions into DSH with thinking, tool activity, token usage and in-GUI Google OAuth login.",
5
5
  "type": "module",
6
6
  "license": "MIT",