ccdeck 3.49.1 → 3.51.0

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.
Files changed (114) hide show
  1. package/README.md +7 -3
  2. package/THIRD_PARTY_NOTICES.md +28 -0
  3. package/bin/cli/commands.js +34 -3
  4. package/bin/cli/second-start.js +6 -1
  5. package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +1 -0
  6. package/dist/web/assets/IntegrationModal-BctMcNU8.js +7 -0
  7. package/dist/web/assets/{RadioPanel-gFYxdsBg.js → RadioPanel-DQNFtYOx.js} +1 -1
  8. package/dist/web/assets/{TrafficRadar-B9MfKca4.js → TrafficRadar-DRt3Al7E.js} +1 -1
  9. package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +1 -0
  10. package/dist/web/assets/{app-D2NP6IPl.js → app-4x4wTE-L.js} +73 -73
  11. package/dist/web/assets/{app-DfGYllmZ.css → app-o4kL0FgZ.css} +1 -1
  12. package/dist/web/assets/{index-Be6Ox-74.js → index-CWUj8Kqh.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/node_modules/bare-addon-resolve/LICENSE +201 -0
  15. package/node_modules/bare-addon-resolve/README.md +226 -0
  16. package/node_modules/bare-addon-resolve/index.d.ts +100 -0
  17. package/node_modules/bare-addon-resolve/index.js +531 -0
  18. package/node_modules/bare-addon-resolve/lib/errors.d.ts +16 -0
  19. package/node_modules/bare-addon-resolve/lib/errors.js +21 -0
  20. package/node_modules/bare-addon-resolve/package.json +57 -0
  21. package/node_modules/bare-module-resolve/LICENSE +201 -0
  22. package/node_modules/bare-module-resolve/README.md +322 -0
  23. package/node_modules/bare-module-resolve/index.d.ts +171 -0
  24. package/node_modules/bare-module-resolve/index.js +899 -0
  25. package/node_modules/bare-module-resolve/lib/errors.d.ts +31 -0
  26. package/node_modules/bare-module-resolve/lib/errors.js +37 -0
  27. package/node_modules/bare-module-resolve/package.json +56 -0
  28. package/node_modules/bare-semver/LICENSE +201 -0
  29. package/node_modules/bare-semver/README.md +147 -0
  30. package/node_modules/bare-semver/index.d.ts +61 -0
  31. package/node_modules/bare-semver/index.js +13 -0
  32. package/node_modules/bare-semver/lib/comparator.js +37 -0
  33. package/node_modules/bare-semver/lib/constants.js +7 -0
  34. package/node_modules/bare-semver/lib/errors.js +22 -0
  35. package/node_modules/bare-semver/lib/range.js +256 -0
  36. package/node_modules/bare-semver/lib/version.js +240 -0
  37. package/node_modules/bare-semver/package.json +43 -0
  38. package/node_modules/fs-native-extensions/CMakeLists.txt +118 -0
  39. package/node_modules/fs-native-extensions/LICENSE +201 -0
  40. package/node_modules/fs-native-extensions/README.md +160 -0
  41. package/node_modules/fs-native-extensions/binding.c +1825 -0
  42. package/node_modules/fs-native-extensions/binding.js +3 -0
  43. package/node_modules/fs-native-extensions/include/fs-ext.h +193 -0
  44. package/node_modules/fs-native-extensions/index.js +356 -0
  45. package/node_modules/fs-native-extensions/package.json +72 -0
  46. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.bare +0 -0
  47. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.node +0 -0
  48. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.bare +0 -0
  49. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.node +0 -0
  50. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.bare +0 -0
  51. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.node +0 -0
  52. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.bare +0 -0
  53. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.node +0 -0
  54. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.bare +0 -0
  55. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.node +0 -0
  56. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.bare +0 -0
  57. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.node +0 -0
  58. package/node_modules/fs-native-extensions/prebuilds/ios-arm64/fs-native-extensions.bare +0 -0
  59. package/node_modules/fs-native-extensions/prebuilds/ios-arm64-simulator/fs-native-extensions.bare +0 -0
  60. package/node_modules/fs-native-extensions/prebuilds/ios-x64-simulator/fs-native-extensions.bare +0 -0
  61. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.bare +0 -0
  62. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.node +0 -0
  63. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.bare +0 -0
  64. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.node +0 -0
  65. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.bare +0 -0
  66. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.node +0 -0
  67. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.bare +0 -0
  68. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.node +0 -0
  69. package/node_modules/fs-native-extensions/src/apple.c +197 -0
  70. package/node_modules/fs-native-extensions/src/linux.c +146 -0
  71. package/node_modules/fs-native-extensions/src/platform.h +51 -0
  72. package/node_modules/fs-native-extensions/src/posix.c +33 -0
  73. package/node_modules/fs-native-extensions/src/shared.c +397 -0
  74. package/node_modules/fs-native-extensions/src/win32/nt.h +226 -0
  75. package/node_modules/fs-native-extensions/src/win32.c +531 -0
  76. package/node_modules/require-addon/LICENSE +201 -0
  77. package/node_modules/require-addon/README.md +19 -0
  78. package/node_modules/require-addon/lib/bare.js +1 -0
  79. package/node_modules/require-addon/lib/default.js +7 -0
  80. package/node_modules/require-addon/lib/node.js +79 -0
  81. package/node_modules/require-addon/package.json +64 -0
  82. package/node_modules/which-runtime/LICENSE +201 -0
  83. package/node_modules/which-runtime/README.md +29 -0
  84. package/node_modules/which-runtime/index.js +36 -0
  85. package/node_modules/which-runtime/package.json +32 -0
  86. package/package.json +12 -2
  87. package/release-notes.json +25 -0
  88. package/src/server/claude-accounts.mjs +19 -3
  89. package/src/server/claude-collector.mjs +18 -2
  90. package/src/server/cswap-install.mjs +60 -18
  91. package/src/server/integrations/jira-comment.mjs +37 -0
  92. package/src/server/integrations/jira-move.mjs +37 -11
  93. package/src/server/integrations/jira-transition.mjs +43 -0
  94. package/src/server/integrations/jira-write-guard.mjs +218 -0
  95. package/src/server/integrations/jira.mjs +16 -0
  96. package/src/server/integrations/routes.mjs +70 -7
  97. package/src/server/lan-deck.mjs +9 -0
  98. package/src/server/lan-engine.mjs +17 -2
  99. package/src/server/lan-manifest.mjs +10 -3
  100. package/src/server/lifecycle.mjs +27 -2
  101. package/src/server/login-guard.mjs +4 -0
  102. package/src/server/npm-upgrade.mjs +46 -18
  103. package/src/server/pinned-build.mjs +5 -0
  104. package/src/server/quota-store-resets.mjs +13 -6
  105. package/src/server/quota.mjs +8 -1
  106. package/src/server/running-deck.mjs +14 -0
  107. package/src/server/static-cache.mjs +34 -16
  108. package/src/server/terminal-cli-update.mjs +189 -0
  109. package/src/server/terminal-cli.mjs +93 -0
  110. package/src/server/traffic-radar-wire.mjs +6 -0
  111. package/src/server/usage-share.mjs +444 -0
  112. package/dist/web/assets/BrowserWatchModal-CCARqAMn.js +0 -1
  113. package/dist/web/assets/IntegrationModal-B8t53aE5.js +0 -7
  114. package/dist/web/assets/UsageHistoryModal-DvYWhsYv.js +0 -1
@@ -59,9 +59,14 @@ const INSTALL_TIMEOUT_MS = 300_000; // a cold global install on a slow line
59
59
  * Exported for tests: the platform is a parameter so the Windows command line
60
60
  * can be checked from any OS, and `deps` stands in for the Windows filesystem
61
61
  * the shim lookup asks about. The same shape ccusage.mjs's installSpec has.
62
+ *
63
+ * `prefix` names the global prefix to install into, for a copy this process
64
+ * does not run (terminal-cli-update.mjs): the npm that answers here need not be
65
+ * the one that installed it, and only that copy's own prefix rewrites it.
62
66
  */
63
- export function upgradeSpec(target, platform = process.platform, deps) {
64
- const args = ["install", "-g", `${target}@latest`, "--no-audit", "--no-fund", "--loglevel", "error"];
67
+ export function upgradeSpec(target, platform = process.platform, deps, prefix = null) {
68
+ const args = ["install", "-g", ...(prefix ? ["--prefix", prefix] : []), `${target}@latest`,
69
+ "--no-audit", "--no-fund", "--loglevel", "error"];
65
70
  // POSIX: the npm-cli.js beside this node, and the bare name only when there
66
71
  // is none, because a deck started at login has no PATH that finds npm on a
67
72
  // Homebrew or nvm install (#1777). See npmCliLaunch.
@@ -164,8 +169,11 @@ function dirWritable(p) {
164
169
  }
165
170
  }
166
171
 
167
- /** The same question, answered against the real filesystem and environment. */
168
- export function upgradeBlock(pkgRoot) {
172
+ /** The same question, answered against the real filesystem and environment.
173
+ * `ownCopy: false` asks it about a copy this process does not run — the
174
+ * terminal's ccdeck (terminal-cli-update.mjs) — which the desktop app's own
175
+ * updates never reach, so being inside the app is no refusal there. */
176
+ export function upgradeBlock(pkgRoot, { ownCopy = true } = {}) {
169
177
  // Whatever `npm i -g` would rewrite is what has to be writable, and under the
170
178
  // stub layout that is not this directory: `npm i -g ccdeck` replaces
171
179
  // <prefix>/lib/node_modules/ccdeck, and the copy running out of its nested
@@ -195,7 +203,7 @@ export function upgradeBlock(pkgRoot) {
195
203
  writable: dirWritable(target) && dirWritable(resolve(target, "..")),
196
204
  // Inside the desktop app the app updates itself; an `npm i -g` here would
197
205
  // install a copy it never runs (app-host.mjs).
198
- optedOut: process.env.AGENTS_DECK_NO_INSTALL === "1" || inApp(),
206
+ optedOut: process.env.AGENTS_DECK_NO_INSTALL === "1" || (ownCopy && inApp()),
199
207
  // Whether the package that write would fetch is still a deck. Kept out of
200
208
  // the pure rule above, like every other input here, so the policy stays one
201
209
  // readable expression and this file owns the filesystem half of it.
@@ -244,13 +252,37 @@ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
244
252
  // about the deck rather than about their install.
245
253
  const command = `npm ${spec.plain.join(" ")}`;
246
254
  setUpgrade("running", command);
255
+ // Deliberately does not restart anything once it is done. The new files on
256
+ // disk make installedVersion() disagree with the running one, and the
257
+ // ordinary drift path takes it from there — including its wait for an idle
258
+ // moment.
259
+ if (!runInstall(spec, (state, error) => setUpgrade(state, command, error))) {
260
+ return { ok: false, reason: "spawn_failed", command };
261
+ }
262
+ return { ok: true, command };
263
+ }
264
+
265
+ /**
266
+ * Run one `npm install` from upgradeSpec to its end in the background, telling
267
+ * `report` the state it ends in — "done", or "failed" with npm's own reason.
268
+ * False when npm could not even be spawned, which has been reported by then.
269
+ *
270
+ * The deck's own update and the terminal's (terminal-cli-update.mjs) both run
271
+ * through here, each keeping its own state, so neither can be reported as the
272
+ * other.
273
+ */
274
+ export function runInstall(spec, report) {
275
+ // Whether this install has already been reported as failed — kept here, not
276
+ // read back from the caller's state, which a later install may have replaced.
277
+ let failed = false;
278
+ const fail = (error) => { failed = true; report("failed", error); };
247
279
 
248
280
  let child;
249
281
  try {
250
282
  child = spawn(spec.file, spec.args, { ...spec.opts, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
251
283
  } catch (err) {
252
- setUpgrade("failed", command, err?.message ?? String(err));
253
- return { ok: false, reason: "spawn_failed", command };
284
+ fail(err?.message ?? String(err));
285
+ return false;
254
286
  }
255
287
 
256
288
  // Only the tail is kept: npm's failures put the useful line near the end, and
@@ -273,13 +305,13 @@ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
273
305
  // could arrive minutes after the deadline — or never, if the tree kill could
274
306
  // not run at all — and until it did, /api/version kept reporting
275
307
  // `state: "running"` with the UI spinning on "installing…" and the guard at
276
- // the top of this function refusing every retry. When it finally arrived it
308
+ // the top of startUpgrade refusing every retry. When it finally arrived it
277
309
  // carried the killed wrapper's status, so a five-minute timeout was announced
278
310
  // to the user as "npm exited null".
279
311
  let timedOut = false;
280
312
  const timer = setTimeout(() => {
281
313
  timedOut = true;
282
- setUpgrade("failed", command, `timed out after ${Math.round(INSTALL_TIMEOUT_MS / 60_000)} minutes`);
314
+ fail(`timed out after ${Math.round(INSTALL_TIMEOUT_MS / 60_000)} minutes`);
283
315
  killTree(child);
284
316
  }, INSTALL_TIMEOUT_MS);
285
317
  timer.unref?.();
@@ -289,7 +321,7 @@ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
289
321
  // A kill can make the child emit one of these; whatever it says, the reason
290
322
  // this install failed is the deadline that has already been reported.
291
323
  if (timedOut) return;
292
- setUpgrade("failed", command, e?.message ?? String(e));
324
+ fail(e?.message ?? String(e));
293
325
  });
294
326
  child.on("close", (code) => {
295
327
  clearTimeout(timer);
@@ -297,22 +329,18 @@ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
297
329
  // A clean exit is a real install even if it lands after the deadline —
298
330
  // npm finishing in the same breath as the timer is the one case where the
299
331
  // files on disk disagree with the verdict above, and the files win.
300
- //
301
- // Deliberately does not restart anything. The new files on disk make
302
- // installedVersion() disagree with the running one, and the ordinary
303
- // drift path takes it from there — including its wait for an idle moment.
304
- setUpgrade("done", command);
305
- } else if (!timedOut && _upgrade?.state !== "failed") {
332
+ report("done", null);
333
+ } else if (!timedOut && !failed) {
306
334
  // Not over a failure the 'error' handler already explained. A missing npm
307
335
  // emits 'error' with ENOENT and THEN 'close' with a null code, and this
308
336
  // branch used to replace "spawn npm ENOENT" with "npm exited -2" — the
309
337
  // one message that says what is wrong, overwritten by the one that does
310
338
  // not.
311
- setUpgrade("failed", command, lastMeaningfulLine(err) || `npm exited ${code}`);
339
+ fail(lastMeaningfulLine(err) || `npm exited ${code}`);
312
340
  }
313
341
  });
314
342
 
315
- return { ok: true, command };
343
+ return true;
316
344
  }
317
345
 
318
346
  // The furniture around a Node crash, none of which is the reason anything
@@ -106,6 +106,11 @@ const PINNED_MODULES = [
106
106
  // memory through cswap-auto.mjs; named here because account-routes.mjs
107
107
  // reaches it through import().
108
108
  "cswap-auto-choice.mjs",
109
+ // Whether this claude-swap has import-usage, and the binary to hand paired
110
+ // decks' readings to (usage-share.mjs, #930). Already in memory through
111
+ // claude-accounts.mjs; named here because every LAN round reaches it
112
+ // through import().
113
+ "cswap-install.mjs",
109
114
  ];
110
115
 
111
116
  let _pinned = null;
@@ -26,6 +26,10 @@ const PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
26
26
  // out of a budget claude-swap plans to leave eight to ten of unspent. A forced
27
27
  // refresh, or an account not tried yet, waits SELF_POLL_MS.
28
28
  const CREDITS_POLL_MS = 30 * 60_000;
29
+ // The floor while another paired deck reads this account's windows (#930): its
30
+ // requests are what the hold saves, and two an hour from every machine on the
31
+ // account would spend the saving again. A grant lasts weeks.
32
+ const CREDITS_SHARED_POLL_MS = 3 * 60 * 60_000;
29
33
 
30
34
  // How long an inventory is shown after the last read that succeeded. Expiry is
31
35
  // worked out at every read, but a reset redeemed in Claude only leaves the
@@ -77,7 +81,7 @@ export function sameAccount(a, b) {
77
81
  /** The held inventory, if it was read for `account` and recently enough. */
78
82
  export function heldResetCredits(account, now) {
79
83
  if (!_credits || !sameAccount(_credits.account, account)) return null;
80
- if (now - _credits.at > CREDITS_TRUSTED_MS) return null;
84
+ if (now - _credits.at > (_credits.trustedMs ?? CREDITS_TRUSTED_MS)) return null;
81
85
  return availableResetCredits(_credits.grants, now);
82
86
  }
83
87
 
@@ -94,9 +98,10 @@ export function heldResetCredits(account, now) {
94
98
  * token, one budget — so a 429 here holds source 2 off as well, and the other
95
99
  * way round.
96
100
  */
97
- export function resetCreditsDue({ now, force, triedAt, rateLimitedUntil, triedThisAccount }) {
101
+ export function resetCreditsDue({ now, force, triedAt, rateLimitedUntil, triedThisAccount, shared = false }) {
98
102
  if (now < rateLimitedUntil) return false;
99
- return now - triedAt >= (triedThisAccount && !force ? CREDITS_POLL_MS : SELF_POLL_MS);
103
+ const floor = shared ? CREDITS_SHARED_POLL_MS : CREDITS_POLL_MS;
104
+ return now - triedAt >= (triedThisAccount && !force ? floor : SELF_POLL_MS);
100
105
  }
101
106
 
102
107
  /**
@@ -171,10 +176,12 @@ async function fetchResetGrants(token) {
171
176
  * by `cswap` in a terminal or by claude-swap's auto-switch, cannot carry one
172
177
  * account's resets onto the next account's card.
173
178
  */
174
- export function refreshStoreResetCredits({ now, force = false, account }) {
179
+ export function refreshStoreResetCredits({ now, force = false, account, shared = false }) {
175
180
  if (_creditsInflight || !account) return;
176
181
  const triedThisAccount = sameAccount(_creditsTriedFor, account);
177
- if (!resetCreditsDue({ now, force, triedAt: _creditsTriedAt, rateLimitedUntil: cooldownUntil(), triedThisAccount })) return;
182
+ if (!resetCreditsDue({ now, force, triedAt: _creditsTriedAt, rateLimitedUntil: cooldownUntil(), triedThisAccount, shared })) return;
183
+ // Shown for three floors, whichever floor it was read on.
184
+ const trustedMs = 3 * (shared ? CREDITS_SHARED_POLL_MS : CREDITS_POLL_MS);
178
185
  _creditsTriedAt = now;
179
186
  _creditsTriedFor = account;
180
187
  const run = (async () => {
@@ -183,7 +190,7 @@ export function refreshStoreResetCredits({ now, force = false, account }) {
183
190
  const owner = await tokenOwner(token);
184
191
  if (!sameAccount(owner, account)) return;
185
192
  const grants = await fetchResetGrants(token);
186
- if (grants !== undefined) _credits = { account, grants, at: now };
193
+ if (grants !== undefined) _credits = { account, grants, at: now, trustedMs };
187
194
  })();
188
195
  // Settles rather than rejects: nothing in here is news to anyone.
189
196
  _creditsInflight = run.catch(() => {}).finally(() => { _creditsInflight = null; });
@@ -306,6 +306,7 @@ async function storeQuota() {
306
306
  const credits = heldResetCredits(account, Date.now());
307
307
  const reading = credits ? { ...quota, resetCredits: credits } : quota;
308
308
  if (account) _accountOfReading.set(reading, account);
309
+ if (entry.heldUntil) _heldUntilOfReading.set(reading, entry.heldUntil);
309
310
  return reading;
310
311
  } catch {
311
312
  return null;
@@ -357,6 +358,10 @@ export async function withClaudePlan(reading, { login, account = quotaAccount(re
357
358
  // it is, and an identity is not something the panel needs. Weak, so a reading
358
359
  // nothing holds any more takes its entry with it.
359
360
  const _accountOfReading = new WeakMap();
361
+ // Until when a store reading's account is held for a paired deck's readings
362
+ // (#930), beside the reading for the same reason: the inventory read slows
363
+ // down while another deck spends the account's requests.
364
+ const _heldUntilOfReading = new WeakMap();
360
365
 
361
366
  // After asking claude-swap to collect, how long to keep looking for the row it
362
367
  // writes. Its fetch is a single HTTPS call; three tries covers a slow one
@@ -470,7 +475,9 @@ async function _doFetch(now, force = false, gen = _generation) {
470
475
  if (!readingLapsed(store, now)) {
471
476
  // The saved limit resets are the one thing the store cannot say. Read
472
477
  // behind this answer, never in front of it; see refreshStoreResetCredits.
473
- refreshStoreResetCredits({ now, force, account: _accountOfReading.get(store) });
478
+ refreshStoreResetCredits({
479
+ now, force, account: _accountOfReading.get(store), shared: (_heldUntilOfReading.get(store) ?? 0) > now,
480
+ });
474
481
  return publish(gen, store, now, { good: true, who });
475
482
  }
476
483
  }
@@ -373,3 +373,17 @@ export function versionNote(running, ours) {
373
373
  ? `running v${running}, older than the v${ours} you launched`
374
374
  : `running v${running}, newer than the v${ours} you launched — kept it`;
375
375
  }
376
+
377
+ /**
378
+ * The line under versionNote when the deck kept is the newer one: how to bring
379
+ * the command just typed up to it.
380
+ *
381
+ * The deck knows commands this copy does not — a 3.42 `ccdeck tui` beside a
382
+ * 3.49 deck read `tui` as an unknown option — and cannot answer for it, so the
383
+ * copy says how it is updated. `command` is that install's own line
384
+ * (upgradeCommand). Empty unless ours is the older one.
385
+ */
386
+ export function catchUpNote(running, ours, command) {
387
+ if (typeof command !== "string" || command === "" || typeof running !== "string" || running === "") return "";
388
+ return olderVersion(ours, running) ? `to use v${running} in this terminal: \`${command}\`` : "";
389
+ }
@@ -42,26 +42,44 @@ export function pickEncoding(acceptEncoding, ext) {
42
42
  return null;
43
43
  }
44
44
 
45
- /** Compressed bytes, made once per file, build and encoding. The key carries the
46
- * file's mtime, so a rebuild is a new entry rather than a stale one; the set of
47
- * files is the dist folder's, so the cache is as big as the build and no bigger.
48
- * Quality 9 rather than 11: the first request after a build pays for it, and 11
49
- * costs seconds there for a percent or two. */
45
+ /** Compressed bytes shared across requests. Rebuilds can leave many old hashed
46
+ * files behind, so bound the total rather than assuming paths never change.
47
+ * LRU keeps frequently requested assets hot; oversized files are served but
48
+ * not retained. Small zlib results otherwise keep a full 16 KiB backing
49
+ * allocation per file, so copy them into an exactly-sized buffer. */
50
+ const MAX_ENCODED_BYTES = 8 * 1024 * 1024;
51
+ const MAX_ENCODED_ENTRIES = 1024;
50
52
  const encodedCache = new Map();
53
+ let encodedBytes = 0;
51
54
 
52
55
  export function encodedBody(filePath, mtimeMs, buf, encoding) {
53
56
  const key = `${encoding}\0${mtimeMs}\0${filePath}`;
54
- let out = encodedCache.get(key);
55
- if (!out) {
56
- out = encoding === "br"
57
- ? brotliCompressSync(buf, {
58
- params: {
59
- [constants.BROTLI_PARAM_QUALITY]: 9,
60
- [constants.BROTLI_PARAM_SIZE_HINT]: buf.length,
61
- },
62
- })
63
- : gzipSync(buf, { level: 6 });
64
- encodedCache.set(key, out);
57
+ const cached = encodedCache.get(key);
58
+ if (cached) {
59
+ encodedCache.delete(key);
60
+ encodedCache.set(key, cached);
61
+ return cached;
65
62
  }
63
+ let out = encoding === "br"
64
+ ? brotliCompressSync(buf, {
65
+ params: {
66
+ [constants.BROTLI_PARAM_QUALITY]: 9,
67
+ [constants.BROTLI_PARAM_SIZE_HINT]: buf.length,
68
+ },
69
+ })
70
+ : gzipSync(buf, { level: 6 });
71
+ if (out.buffer.byteLength !== out.length) {
72
+ const compact = Buffer.allocUnsafeSlow(out.length);
73
+ out.copy(compact);
74
+ out = compact;
75
+ }
76
+ if (out.length > MAX_ENCODED_BYTES) return out;
77
+ while (encodedCache.size && (encodedBytes + out.length > MAX_ENCODED_BYTES || encodedCache.size >= MAX_ENCODED_ENTRIES)) {
78
+ const oldest = encodedCache.keys().next().value;
79
+ encodedBytes -= encodedCache.get(oldest).length;
80
+ encodedCache.delete(oldest);
81
+ }
82
+ encodedCache.set(key, out);
83
+ encodedBytes += out.length;
66
84
  return out;
67
85
  }
@@ -0,0 +1,189 @@
1
+ // The deck updating the terminal's ccdeck on its own.
2
+ //
3
+ // terminal-cli.mjs finds the ccdeck a terminal on this machine starts and says
4
+ // when it is older than the deck. Saying it was not enough: the desktop app, an
5
+ // npx run and a global npm install each update only their own copy, and the
6
+ // one a terminal types stayed at the version it was installed at — a 3.42
7
+ // `ccdeck` beside a 3.49 deck, answering `ccdeck tui` with "unknown option". A
8
+ // copy that old cannot learn to update itself, but the deck can replace it, with
9
+ // the `npm i -g` its own Update now runs (npm-upgrade.mjs), aimed at the global
10
+ // prefix that copy lives in.
11
+ //
12
+ // Only where the command a person would type does the same thing: a global npm
13
+ // install of `ccdeck`, in a prefix this user can write, that is not the deck's
14
+ // own copy (its own update path has that one), under the switch the deck's own
15
+ // unattended update obeys (`autoUpdate`), and never with
16
+ // AGENTS_DECK_NO_INSTALL=1. Everything else — a root-owned prefix, pnpm, yarn or
17
+ // bun, a retired name, a checkout — keeps the command in About and runs nothing.
18
+ //
19
+ // Nothing of the deck's restarts, so this does not wait for an idle moment the
20
+ // way auto-update.mjs does: lifecycle.mjs asks once a minute, after the boot
21
+ // grace.
22
+ import { readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
23
+ import { dirname, join } from "node:path";
24
+ import { AWAY_RECHECK_MS, AWAY_RETRY_MS } from "./auto-update.mjs";
25
+ import { hostPackage, installedName, PUBLISHED_NAME, upgradeCommand, upgradeName } from "./install-layout.mjs";
26
+ import { runInstall, upgradeBlock, upgradeSpec } from "./npm-upgrade.mjs";
27
+ import { isOlder } from "./self-update.mjs";
28
+ import { terminalCli } from "./terminal-cli.mjs";
29
+
30
+ /**
31
+ * Why the deck leaves the terminal's copy to the person, or null when it may
32
+ * update it — before the filesystem is asked (upgradeBlock). Pure, so the
33
+ * policy reads as one expression, as upgradeBlockedReason does for the deck's
34
+ * own copy.
35
+ */
36
+ export function terminalUpdateBlockedReason({ optedOut, enabled, prefix, name, own }) {
37
+ if (optedOut) return "opted_out";
38
+ if (!enabled) return "off";
39
+ // pnpm, yarn, bun or a link made by hand: `npm i -g` would put a second copy
40
+ // somewhere else and leave this one where it is.
41
+ if (!prefix) return "not_npm";
42
+ // A retired name is fixed by a removal as well as an install
43
+ // (upgradeCommand), and that is the person's to run.
44
+ if (name !== PUBLISHED_NAME) return "retired_name";
45
+ if (own) return "own_copy";
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * Whether to start an install for `key` — one copy against one deck version —
51
+ * given the last one this process started. Pure.
52
+ *
53
+ * A finished install is not repeated for the same key: when npm's latest is
54
+ * still older than the deck (a desktop build ahead of the registry), installing
55
+ * it again every half hour would change nothing. A failed one is tried again
56
+ * after AWAY_RETRY_MS, as the deck's own unattended update is.
57
+ */
58
+ export function terminalUpdateDue({ key, last, now, retryMs = AWAY_RETRY_MS }) {
59
+ if (last?.key !== key) return true;
60
+ if (last.state !== "failed") return false;
61
+ // A clock that moved backwards counts as time elapsed, as in awayUpdateStep.
62
+ return !(now >= last.at && now - last.at < retryMs);
63
+ }
64
+
65
+ // Every deck on a machine sees the same terminal copy — the app's beside one
66
+ // started from a checkout, say — and two `npm i -g` into one prefix at once can
67
+ // leave it half written. The first takes this file in the global node_modules
68
+ // the copy sits in (npm passes over dot-files there), and the others leave that
69
+ // tick alone. One left by a deck that died is taken over once it is older than
70
+ // an install can last: npm-upgrade.mjs's five minutes, and one more.
71
+ const LOCK = ".ccdeck-terminal-update.lock";
72
+ const LOCK_STALE_MS = 6 * 60_000;
73
+
74
+ /**
75
+ * Take the install lock in `dir`. Returns the call that gives it back, or null
76
+ * while another deck holds it. A directory the lock cannot be written to is no
77
+ * refusal: whether npm may write there is upgradeBlock's question, answered
78
+ * already.
79
+ */
80
+ export function takeInstallLock(dir, now = Date.now()) {
81
+ const file = join(dir, LOCK);
82
+ const release = () => { try { unlinkSync(file); } catch { /* gone already */ } };
83
+ for (let tries = 0; tries < 2; tries++) {
84
+ try {
85
+ writeFileSync(file, String(now), { flag: "wx" });
86
+ return release;
87
+ } catch (e) {
88
+ if (e?.code !== "EEXIST") return () => {};
89
+ let at = NaN;
90
+ try { at = Number(readFileSync(file, "utf8")); } catch { /* released meanwhile: try again */ }
91
+ if (Number.isFinite(at) && now >= at && now - at < LOCK_STALE_MS) return null;
92
+ release();
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ // The install this process last started for the terminal's copy:
99
+ // { key, state: "running" | "done" | "failed", error, at }.
100
+ let _last = null;
101
+ // The filesystem half of the refusal, kept per copy for AWAY_RECHECK_MS: on
102
+ // Windows upgradeBlock proves a directory writable by creating a file in it,
103
+ // and /api/version asks on every poll.
104
+ let _onDisk = null;
105
+
106
+ /** Forget both, for tests. */
107
+ export function resetTerminalCliUpdate() {
108
+ _last = null;
109
+ _onDisk = null;
110
+ }
111
+
112
+ function real(dir) {
113
+ try { return realpathSync(dir); } catch { return dir; }
114
+ }
115
+
116
+ /** Whether `root` is the copy this deck runs out of. */
117
+ function ownCopy(root, pkgRoot) {
118
+ if (!pkgRoot) return false;
119
+ const own = hostPackage(pkgRoot, installedName(pkgRoot))?.root ?? pkgRoot;
120
+ return real(root) === real(own);
121
+ }
122
+
123
+ function blockedOnDisk(root, now, block) {
124
+ if (_onDisk?.root === root && now >= _onDisk.at && now - _onDisk.at < AWAY_RECHECK_MS) return _onDisk.reason;
125
+ const reason = block(root, { ownCopy: false });
126
+ _onDisk = { root, reason, at: now };
127
+ return reason;
128
+ }
129
+
130
+ /** The terminal's copy when it is older than `running`, its key, and why the
131
+ * deck would leave it alone (null when it would not). */
132
+ function look({ running, pkgRoot, enabled, now, block = upgradeBlock, ...opts }) {
133
+ const cli = terminalCli(opts);
134
+ if (!cli || !isOlder(cli.version, running)) return null;
135
+ const reason = terminalUpdateBlockedReason({
136
+ optedOut: process.env.AGENTS_DECK_NO_INSTALL === "1",
137
+ enabled,
138
+ prefix: cli.prefix,
139
+ name: upgradeName(cli.root),
140
+ own: ownCopy(cli.root, pkgRoot),
141
+ }) ?? blockedOnDisk(cli.root, now, block);
142
+ return { cli, key: `${cli.root}>${running}`, reason };
143
+ }
144
+
145
+ /**
146
+ * What /api/version says about the terminal's ccdeck: its version, the line
147
+ * that updates it for that install's shape (upgradeCommand), and what the deck
148
+ * is doing about it — `auto` is "pending" (it will, within the boot grace and a
149
+ * minute), "running", "failed" with npm's own `error`, or null when the copy is
150
+ * left to the person. Null unless it is older than `running`: the deck's own
151
+ * copy, an up-to-date one and a newer one need nothing said.
152
+ */
153
+ export function terminalCliState({ running, pkgRoot, enabled, now = Date.now(), ...opts } = {}) {
154
+ const seen = look({ running, pkgRoot, enabled, now, ...opts });
155
+ if (!seen) return null;
156
+ const out = { version: seen.cli.version, command: upgradeCommand(seen.cli.root), auto: null, error: null };
157
+ if (_last?.key === seen.key) {
158
+ if (_last.state === "running") out.auto = "running";
159
+ else if (_last.state === "failed") Object.assign(out, { auto: "failed", error: _last.error });
160
+ // Done and still older: npm had nothing newer, and the command is all
161
+ // that is left to say.
162
+ return out;
163
+ }
164
+ if (!seen.reason) out.auto = "pending";
165
+ return out;
166
+ }
167
+
168
+ /**
169
+ * Start `npm i -g --prefix <its prefix> ccdeck@latest` for the terminal's copy
170
+ * when it is due and no other deck is installing it. True when an install
171
+ * started. `install` and `lock` are runInstall and takeInstallLock, parameters
172
+ * so a test can see the spec without npm or a prefix on disk.
173
+ */
174
+ export function updateTerminalCli({
175
+ running, pkgRoot, enabled, now = Date.now(), install = runInstall, lock = takeInstallLock, ...opts
176
+ } = {}) {
177
+ if (_last?.state === "running") return false;
178
+ const seen = look({ running, pkgRoot, enabled, now, ...opts });
179
+ if (!seen || seen.reason || !terminalUpdateDue({ key: seen.key, last: _last, now })) return false;
180
+ const release = lock(dirname(seen.cli.root), now);
181
+ if (!release) return false;
182
+ const { key } = seen;
183
+ _last = { key, state: "running", error: null, at: now };
184
+ const spec = upgradeSpec(PUBLISHED_NAME, opts.platform, undefined, seen.cli.prefix);
185
+ return install(spec, (state, error) => {
186
+ _last = { key, state, error: error ?? null, at: Date.now() };
187
+ release();
188
+ });
189
+ }
@@ -0,0 +1,93 @@
1
+ // The ccdeck a terminal on this machine starts. Whether it is older than the
2
+ // deck answering, and what the deck does about it, is terminal-cli-update.mjs.
3
+ //
4
+ // The desktop app, an npx run and a global npm install each update on their
5
+ // own, so the command a terminal starts can be left behind by the deck it
6
+ // talks to. A 3.42 `ccdeck` beside a 3.49 deck read `ccdeck tui` as an unknown
7
+ // option and opened the browser: it has no `tui`, sends the deck nothing, and
8
+ // cannot be taught one after the fact. The deck can say so instead, on every
9
+ // platform (#2294 said it on Windows only, from the desktop shell).
10
+ //
11
+ // READ, NEVER RUN. The first `ccdeck` on PATH is followed to the package that
12
+ // owns it and that manifest is read; nothing is spawned. Anything that cannot
13
+ // be identified as an installed ccdeck — an .exe ahead of the npm shim on
14
+ // Windows, a wrapper script, a version manager's shim — answers null, and the
15
+ // app says nothing rather than guess.
16
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
17
+ import { posix, win32 } from "node:path";
18
+
19
+ // The names ccdeck has been published under; every one of them ships the
20
+ // `ccdeck` command.
21
+ const NAMES = new Set(["ccdeck", "agents-deck", "agent-dag"]);
22
+ const VERSION = /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;
23
+
24
+ function manifest(file, read) {
25
+ try { return JSON.parse(read(file, "utf8")); } catch { return undefined; }
26
+ }
27
+
28
+ const ours = (pkg) => NAMES.has(pkg?.name) && typeof pkg.version === "string" && VERSION.test(pkg.version);
29
+
30
+ /** The npm shim PowerShell finds first, read through the package npm put beside it. */
31
+ function windowsCli({ env, exists, read }) {
32
+ // Windows environment names are case-insensitive, but injected maps are not.
33
+ const pathKey = Object.keys(env).find(key => key.toLowerCase() === "path");
34
+ const folders = typeof env[pathKey] === "string" ? env[pathKey].split(";") : [];
35
+ for (const segment of folders) {
36
+ const folder = segment.trim().replace(/^"(.*)"$/, "$1");
37
+ if (!folder) continue;
38
+ // A different executable earlier on PATH cannot safely be identified as
39
+ // the npm CLI. Stop here rather than report a later, shadowed npm install.
40
+ if (exists(win32.join(folder, "ccdeck.exe"))) return null;
41
+ if (!exists(win32.join(folder, "ccdeck.ps1")) && !exists(win32.join(folder, "ccdeck.cmd"))) continue;
42
+ const root = win32.join(folder, "node_modules", "ccdeck");
43
+ const pkg = manifest(win32.join(root, "package.json"), read);
44
+ // npm's shims sit in the global prefix itself on Windows.
45
+ return ours(pkg) ? { root, version: pkg.version, prefix: folder } : null;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /** The first `ccdeck` on PATH, followed through npm's symlink to its package. */
51
+ function unixCli({ env, exists, read, realpath }) {
52
+ const folders = typeof env.PATH === "string" ? env.PATH.split(":") : [];
53
+ for (const folder of folders) {
54
+ if (!folder) continue;
55
+ const bin = posix.join(folder, "ccdeck");
56
+ if (!exists(bin)) continue;
57
+ // Only the first one counts: it is the one a terminal runs, and an npm
58
+ // install behind it is a version nobody types.
59
+ let file;
60
+ try { file = realpath(bin); } catch { return null; }
61
+ // <prefix>/lib/node_modules/ccdeck/bin/agent-dag.js: the manifest is a
62
+ // level or two above the file. The first one met is the owner, ours or not.
63
+ let dir = posix.dirname(file);
64
+ for (let up = 0; up < 3; up++) {
65
+ const pkg = manifest(posix.join(dir, "package.json"), read);
66
+ if (pkg !== undefined) return ours(pkg) ? { root: dir, version: pkg.version, prefix: npmPrefix(dir, read) } : null;
67
+ dir = posix.dirname(dir);
68
+ }
69
+ return null;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** The npm global prefix a package root sits in — `<prefix>/lib/node_modules/<name>`
75
+ * — or null for any other layout: pnpm, yarn and bun keep their globals
76
+ * elsewhere, and a project's own node_modules has a package around it, as a
77
+ * global prefix's `lib` never does (install-layout.mjs, frozenNameInstall). */
78
+ function npmPrefix(root, read) {
79
+ const modules = posix.dirname(root);
80
+ const lib = posix.dirname(modules);
81
+ if (posix.basename(modules) !== "node_modules" || posix.basename(lib) !== "lib") return null;
82
+ if (manifest(posix.join(lib, "package.json"), read) !== undefined) return null;
83
+ return posix.dirname(lib);
84
+ }
85
+
86
+ /** The package root, version and npm global prefix (null when it is not npm's)
87
+ * of the ccdeck a terminal starts, or null when there is none or it cannot be
88
+ * identified. */
89
+ export function terminalCli({
90
+ env = process.env, platform = process.platform, exists = existsSync, read = readFileSync, realpath = realpathSync,
91
+ } = {}) {
92
+ return platform === "win32" ? windowsCli({ env, exists, read }) : unixCli({ env, exists, read, realpath });
93
+ }
@@ -42,6 +42,8 @@ export function createWireCapture({ host, port, onExport, onResponse, onIssue, o
42
42
  stream.partial = data.partialSuccess ?? null;
43
43
  }
44
44
  }
45
+ // An empty subarray still owns the entire consumed gRPC message.
46
+ if (stream[key].length === 0) stream[key] = Buffer.alloc(0);
45
47
  }
46
48
  function finishResponse(stream, at) {
47
49
  if (!stream.eventId) return;
@@ -120,6 +122,9 @@ export function createWireCapture({ host, port, onExport, onResponse, onIssue, o
120
122
  throw new Error('connection_closed');
121
123
  }
122
124
  }
125
+ // Keep the HPACK/sequence state for idle connections, without retaining
126
+ // the backing allocation of a frame that was consumed completely.
127
+ if (d.buffer.length === 0) d.buffer = Buffer.alloc(0);
123
128
  let buffered = flow.out.buffer.length + flow.in.buffer.length;
124
129
  for (const stream of flow.streams.values()) buffered += (stream.request?.length ?? 0) + (stream.response?.length ?? 0);
125
130
  if (buffered > LIMIT * 4) throw new Error('stream_limit');
@@ -223,6 +228,7 @@ export function createWireCapture({ host, port, onExport, onResponse, onIssue, o
223
228
  else tcp(pending.subarray(16, 16 + size), at);
224
229
  pending = pending.subarray(size + 16);
225
230
  }
231
+ if (pending.length === 0) pending = Buffer.alloc(0);
226
232
  },
227
233
  close() { pending = Buffer.alloc(0); flows.clear(); },
228
234
  };