dsh-agy-link 0.6.58 → 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,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.59 (2026-11-22)
4
+
5
+ ### English
6
+
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.
9
+
10
+ ### 中文
11
+
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 路径作答**——跳过一轮没有代价,弹一个浏览器窗口要的是用户的注意力。
14
+
15
+ ## 0.6.59 (2026-11-22)
16
+
17
+ ### English
18
+
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).
25
+
26
+ ### 中文
27
+
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)。
34
+
3
35
  ## 0.6.58 (2026-11-22)
4
36
 
5
37
  ### English
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);
@@ -48887,10 +48973,25 @@ function spawnDetachedOpener(command, args, spawnImpl = spawn) {
48887
48973
  return false;
48888
48974
  }
48889
48975
  }
48890
- 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) {
48891
48988
  try {
48989
+ if (!existsSync(targetPath)) return {
48990
+ ok: false,
48991
+ error: "target does not exist: " + targetPath
48992
+ };
48892
48993
  if (process.platform === "darwin") {
48893
- if (!spawnDetachedOpener("open", reveal ? ["-R", targetPath] : [targetPath])) return {
48994
+ if (!opener("open", reveal ? ["-R", targetPath] : [targetPath])) return {
48894
48995
  ok: false,
48895
48996
  error: "failed to launch the system opener"
48896
48997
  };
@@ -48898,7 +48999,7 @@ function executeOpenInSystem(targetPath, reveal = false) {
48898
48999
  }
48899
49000
  if (process.platform === "win32") {
48900
49001
  if (reveal) {
48901
- if (!spawnDetachedOpener("explorer.exe", [`/select,${targetPath}`])) return {
49002
+ if (!opener("explorer.exe", [`/select,${targetPath}`])) return {
48902
49003
  ok: false,
48903
49004
  error: "failed to launch explorer.exe"
48904
49005
  };
@@ -48934,15 +49035,15 @@ function executeOpenInSystem(targetPath, reveal = false) {
48934
49035
  ".gd",
48935
49036
  ".log"
48936
49037
  ].includes(ext)) {
48937
- if (spawnDetachedOpener("notepad.exe", [targetPath])) return { ok: true };
49038
+ if (opener("notepad.exe", [targetPath])) return { ok: true };
48938
49039
  }
48939
- if (!spawnDetachedOpener("explorer.exe", [`/select,${targetPath}`])) return {
49040
+ if (!opener("explorer.exe", [`/select,${targetPath}`])) return {
48940
49041
  ok: false,
48941
49042
  error: "failed to launch explorer.exe"
48942
49043
  };
48943
49044
  return { ok: true };
48944
49045
  }
48945
- if (!spawnDetachedOpener("xdg-open", [targetPath])) return {
49046
+ if (!opener("xdg-open", [targetPath])) return {
48946
49047
  ok: false,
48947
49048
  error: "failed to launch xdg-open"
48948
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.58",
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",