ccdeck 3.29.10 → 3.30.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 (176) hide show
  1. package/README.md +1 -1
  2. package/bin/agent-dag.js +67 -118
  3. package/bin/cli/help.js +67 -0
  4. package/bin/cli/login-item.js +182 -0
  5. package/bin/cli/one-shot.js +254 -0
  6. package/bin/cli/package.js +39 -0
  7. package/bin/cli/pulse.js +98 -0
  8. package/bin/cli/restart.js +179 -0
  9. package/bin/cli/screen.js +166 -0
  10. package/bin/cli/second-start.js +120 -0
  11. package/bin/cli/startup.js +459 -0
  12. package/bin/cli/uninstall.js +169 -0
  13. package/bin/deck.js +112 -1559
  14. package/dist/web/assets/BrowserWatchModal-DP3YMtEi.js +1 -0
  15. package/dist/web/assets/UsageHistoryModal-CcdPVXAw.js +1 -0
  16. package/dist/web/assets/index-3vS6A0vt.css +1 -0
  17. package/dist/web/assets/index-BVTWHDta.js +298 -0
  18. package/dist/web/index.html +2 -2
  19. package/hook/hook.js +15 -14
  20. package/package.json +1 -1
  21. package/release-notes.json +28 -0
  22. package/src/server/account-projects.mjs +25 -11
  23. package/src/server/account-routes.mjs +254 -0
  24. package/src/server/activity.mjs +3 -3
  25. package/src/server/append-budget.mjs +185 -0
  26. package/src/server/append-failures.mjs +147 -0
  27. package/src/server/args.mjs +37 -5
  28. package/src/server/atomic-write.mjs +300 -0
  29. package/src/server/block-notify.mjs +0 -5
  30. package/src/server/boot-lock.mjs +1 -1
  31. package/src/server/brand.mjs +7 -6
  32. package/src/server/browser-react.mjs +10 -2
  33. package/src/server/browser-watch-decks.mjs +146 -0
  34. package/src/server/browser-watch-feed.mjs +69 -0
  35. package/src/server/browser-watch-log.mjs +173 -0
  36. package/src/server/browser-watch-mtime.mjs +18 -0
  37. package/src/server/browser-watch-relay.mjs +112 -0
  38. package/src/server/browser-watch-routes.mjs +172 -0
  39. package/src/server/browser-watch-seen.mjs +127 -0
  40. package/src/server/browser-watch-store.mjs +14 -143
  41. package/src/server/browser-watch.mjs +278 -626
  42. package/src/server/canonical-path.mjs +150 -0
  43. package/src/server/ccusage-failure.mjs +64 -0
  44. package/src/server/ccusage-install.mjs +459 -0
  45. package/src/server/ccusage-runner.mjs +271 -0
  46. package/src/server/ccusage.mjs +21 -756
  47. package/src/server/claude-accounts.mjs +220 -464
  48. package/src/server/claude-collector.mjs +189 -0
  49. package/src/server/claude-dir.mjs +2 -2
  50. package/src/server/claude-identity.mjs +5 -4
  51. package/src/server/claude-reset-credits.mjs +130 -0
  52. package/src/server/claude-verdicts.mjs +174 -0
  53. package/src/server/clear-route.mjs +191 -0
  54. package/src/server/codex-auth.mjs +4 -4
  55. package/src/server/codex-dir.mjs +52 -8
  56. package/src/server/codex-enrichment.mjs +310 -0
  57. package/src/server/codex-quota.mjs +5 -3
  58. package/src/server/codex-translate.mjs +407 -0
  59. package/src/server/codex-usage.mjs +8 -5
  60. package/src/server/codex-watch.mjs +496 -0
  61. package/src/server/cswap-auto-loop.mjs +342 -0
  62. package/src/server/cswap-auto-readers.mjs +303 -0
  63. package/src/server/cswap-auto.mjs +51 -609
  64. package/src/server/cswap-install.mjs +69 -265
  65. package/src/server/cswap-layout.mjs +242 -0
  66. package/src/server/deck-home.mjs +1 -1
  67. package/src/server/deck-prefs.mjs +51 -184
  68. package/src/server/deck-scope.mjs +52 -0
  69. package/src/server/desktop-update-routes.mjs +75 -0
  70. package/src/server/detach.mjs +78 -0
  71. package/src/server/discovery.mjs +298 -0
  72. package/src/server/event-log.mjs +328 -0
  73. package/src/server/event-pipeline.mjs +235 -0
  74. package/src/server/event-ring.mjs +214 -0
  75. package/src/server/event-routes.mjs +352 -0
  76. package/src/server/event-sink.mjs +26 -0
  77. package/src/server/exec-children.mjs +128 -0
  78. package/src/server/exec-not-found.mjs +213 -0
  79. package/src/server/exec-output.mjs +23 -0
  80. package/src/server/exec-spec.mjs +341 -0
  81. package/src/server/exec.mjs +74 -661
  82. package/src/server/health-route.mjs +42 -0
  83. package/src/server/hook-challenge.mjs +37 -0
  84. package/src/server/http-io.mjs +104 -0
  85. package/src/server/index.mjs +172 -7620
  86. package/src/server/install-layout.mjs +506 -0
  87. package/src/server/installer.mjs +79 -608
  88. package/src/server/jsonl-chunks.mjs +139 -0
  89. package/src/server/lan-accounts.mjs +27 -0
  90. package/src/server/lan-beacon.mjs +457 -0
  91. package/src/server/lan-call.mjs +239 -0
  92. package/src/server/lan-copies.mjs +270 -0
  93. package/src/server/lan-deck.mjs +583 -0
  94. package/src/server/lan-dials.mjs +161 -0
  95. package/src/server/lan-engine.mjs +475 -1024
  96. package/src/server/lan-hearing.mjs +49 -0
  97. package/src/server/lan-inbound.mjs +100 -0
  98. package/src/server/lan-invite-offer.mjs +77 -0
  99. package/src/server/lan-invite.mjs +207 -0
  100. package/src/server/lan-lines.mjs +73 -0
  101. package/src/server/lan-manifest.mjs +74 -0
  102. package/src/server/lan-reach.mjs +82 -69
  103. package/src/server/lan-requests.mjs +249 -0
  104. package/src/server/lan-round-record.mjs +45 -0
  105. package/src/server/lan-round-timer.mjs +62 -0
  106. package/src/server/lan-routes.mjs +143 -0
  107. package/src/server/lan-serve.mjs +112 -0
  108. package/src/server/lan-socket.mjs +243 -925
  109. package/src/server/lan-sync.mjs +58 -1026
  110. package/src/server/lan-tailnet-poll.mjs +57 -0
  111. package/src/server/lan-turns.mjs +80 -0
  112. package/src/server/lan-wire.mjs +620 -0
  113. package/src/server/lifecycle.mjs +421 -0
  114. package/src/server/listen.mjs +110 -0
  115. package/src/server/live-decks.mjs +138 -0
  116. package/src/server/load-average.mjs +32 -0
  117. package/src/server/log-election.mjs +235 -0
  118. package/src/server/log-replay.mjs +374 -0
  119. package/src/server/log-writer.mjs +72 -557
  120. package/src/server/login-service.mjs +3 -2
  121. package/src/server/macmon.mjs +1 -1
  122. package/src/server/memory-files.mjs +163 -0
  123. package/src/server/memory-metrics.mjs +178 -0
  124. package/src/server/metrics-history.mjs +94 -0
  125. package/src/server/metrics-run.mjs +100 -0
  126. package/src/server/music-routes.mjs +134 -0
  127. package/src/server/network-metrics.mjs +5 -3
  128. package/src/server/network-sampler.mjs +256 -0
  129. package/src/server/npm-latest.mjs +385 -0
  130. package/src/server/npm-upgrade.mjs +352 -0
  131. package/src/server/npx.mjs +41 -7
  132. package/src/server/output-watch.mjs +5 -4
  133. package/src/server/pinned-build.mjs +108 -0
  134. package/src/server/prefs-path.mjs +14 -0
  135. package/src/server/prefs-refusal.mjs +77 -0
  136. package/src/server/prefs-routes.mjs +76 -0
  137. package/src/server/prefs-set-aside.mjs +86 -0
  138. package/src/server/prefs-state.mjs +51 -0
  139. package/src/server/process-command.mjs +104 -0
  140. package/src/server/process-list.mjs +547 -0
  141. package/src/server/pulse-line.mjs +132 -0
  142. package/src/server/purge-key.mjs +7 -7
  143. package/src/server/quota-cli.mjs +174 -0
  144. package/src/server/quota-oauth.mjs +190 -0
  145. package/src/server/quota-shape.mjs +229 -0
  146. package/src/server/quota-store-resets.mjs +206 -0
  147. package/src/server/quota.mjs +123 -509
  148. package/src/server/relay-guard.mjs +3 -3
  149. package/src/server/request-gates.mjs +441 -0
  150. package/src/server/restart-note.mjs +180 -0
  151. package/src/server/retire-sound-hook.mjs +3 -3
  152. package/src/server/ring-bounds.mjs +215 -0
  153. package/src/server/running-deck.mjs +1 -1
  154. package/src/server/running-version.mjs +24 -0
  155. package/src/server/self-update.mjs +39 -1371
  156. package/src/server/session-enrichment.mjs +622 -0
  157. package/src/server/session-read-gate.mjs +49 -0
  158. package/src/server/session-tracking.mjs +242 -0
  159. package/src/server/sse-clients.mjs +222 -0
  160. package/src/server/stale-discovery.mjs +30 -0
  161. package/src/server/static-serve.mjs +81 -0
  162. package/src/server/supervisor.mjs +73 -12
  163. package/src/server/system-metrics.mjs +169 -1935
  164. package/src/server/term.mjs +11 -249
  165. package/src/server/thermal-metrics.mjs +520 -0
  166. package/src/server/thermal-sampler.mjs +204 -0
  167. package/src/server/token-redact.mjs +123 -0
  168. package/src/server/transcript-gate.mjs +107 -0
  169. package/src/server/transcript-scan.mjs +563 -0
  170. package/src/server/usage-routes.mjs +93 -0
  171. package/src/server/uv-bootstrap.mjs +1 -1
  172. package/src/server/wordmark.mjs +127 -0
  173. package/dist/web/assets/BrowserWatchModal-CMn28FHb.js +0 -1
  174. package/dist/web/assets/UsageHistoryModal-C-sPhsKT.js +0 -1
  175. package/dist/web/assets/index-C1YFI9f4.js +0 -298
  176. package/dist/web/assets/index-Ck2RAla3.css +0 -1
@@ -0,0 +1,342 @@
1
+ // The deck-managed auto-switch loop: `cswap auto --once` run on claude-swap's
2
+ // own interval, one tick at a time, and only while the user has it switched on
3
+ // — a choice kept in ~/.agents-deck/cswap-auto.json across restarts.
4
+ //
5
+ // Moved out of cswap-auto.mjs unchanged, with what one tick is (summarise,
6
+ // runAutoTick). cswap-auto.mjs re-exports setAutoEnabled and initCswapAuto,
7
+ // which is where the route and the boot reach them; its settings write asks
8
+ // restartLoop for a new interval, and its status route reports loopEnabled and
9
+ // lastTick.
10
+ import { run } from "./exec.mjs";
11
+ import { failureDetail } from "./exec-output.mjs";
12
+ import { cswapBin } from "./cswap-install.mjs";
13
+ import { externalAutoRunning, readCswapConfig } from "./cswap-auto-readers.mjs";
14
+ import { invalidateClaudeAccountsCache } from "./claude-accounts.mjs";
15
+ import { invalidateQuotaCache } from "./quota.mjs";
16
+ // The one store mutex. A tick is the only thing in the deck that moves the live
17
+ // account with nobody watching, which is why it of all writers must queue.
18
+ import { withStoreLock } from "./store-lock.mjs";
19
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
20
+ import { join } from "node:path";
21
+ import { homedir } from "node:os";
22
+
23
+ const STATE_DIR = join(homedir(), ".agents-deck");
24
+ const STATE_PATH = join(STATE_DIR, "cswap-auto.json");
25
+
26
+ const TICK_TIMEOUT_MS = 120_000; // a tick can refresh a token and switch
27
+ const MIN_INTERVAL_S = 15; // claude-swap's own floor
28
+
29
+ // ── ticks ──────────────────────────────────────────────────────────────────
30
+
31
+ /** Last meaningful event from a `cswap auto --once --json` run. */
32
+ function summarise(stdout) {
33
+ const events = stdout.split("\n")
34
+ .map(l => { try { return JSON.parse(l); } catch { return null; } })
35
+ .filter(e => e && typeof e === "object");
36
+
37
+ const poll = events.find(e => e.event === "poll") ?? null;
38
+ const action = [...events].reverse().find(e => e.event !== "poll" && e.event !== "sleep") ?? null;
39
+
40
+ return {
41
+ event: action?.event ?? "no-switch",
42
+ // Whether the LIVE ACCOUNT MOVED, which is a narrower question than which
43
+ // event came last and the only one the caches care about. Taken over every
44
+ // event rather than over `action`, so a quarantine or an error emitted after
45
+ // the switch cannot hide it; and `dryRun` is checked even though this
46
+ // module's ticks never pass `--dry-run`, because the engine emits the same
47
+ // `switch` event for a decision it did not carry out, and a false positive
48
+ // here throws away readings that cost a subprocess each.
49
+ switched: events.some(e => e.event === "switch" && e.dryRun !== true),
50
+ reason: action?.reason ?? null,
51
+ detail: action?.detail ?? null,
52
+ from: action?.from ?? null,
53
+ to: action?.to ?? null,
54
+ active: poll?.active ?? null,
55
+ threshold: poll?.threshold ?? null,
56
+ headroom: poll?.headroomPct ?? null,
57
+ windows: poll?.windowsPct ?? null,
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Evaluate a tick for real. May switch the active account.
63
+ *
64
+ * UNDER THE STORE MUTEX (#1039). `cswap auto --once` is not a question: it
65
+ * reads sequence.json, decides, and writes it back, which is the unlocked
66
+ * read-modify-write cswap-admin.mjs's header opens by explaining and the reason
67
+ * every mutation there goes through one lock. This one was outside it, and it
68
+ * is the writer least likely to be noticed — nobody presses it. The interval
69
+ * floor is MIN_INTERVAL_S = 15 s (claude-swap's own) and one `cswap add` is
70
+ * allowed sixty, so a tick landing inside a sign-in takes no coincidence at
71
+ * all: whichever write lands second drops the other's record, and the deck
72
+ * reports a rotation that was silently undone, or the account the user has just
73
+ * added is gone.
74
+ *
75
+ * A tick skipped because the lock was busy is not a tick lost — `tick()` already
76
+ * says as much about its own guard: the next interval is at most fifteen
77
+ * seconds away and the work is idempotent by design. Here it is not even
78
+ * skipped, only queued.
79
+ */
80
+ async function runAutoTick() {
81
+ const r = await withStoreLock(async () =>
82
+ run(await cswapBin(), ["auto", "--once", "--json"], { timeout: TICK_TIMEOUT_MS }));
83
+ // A KILLED RUN IS NOT A QUIET ONE. `run`'s timeout path deliberately keeps an
84
+ // 8 KB tail of whatever the child managed to print, so `!r.ok && !r.stdout`
85
+ // is false for a tick that emitted its `{"event":"poll"}` line and then
86
+ // stalled — and the killed run fell through to `ok: true`. The panel then
87
+ // showed a healthy `no-switch` every two minutes, forever, while the engine
88
+ // did nothing at all: exactly the trap exec.mjs's own header names.
89
+ if (r.timedOut) {
90
+ return { ok: false, reason: "tick_timeout", detail: `cswap auto --once did not finish within ${TICK_TIMEOUT_MS / 1000}s` };
91
+ }
92
+ if (!r.ok && !r.stdout) {
93
+ return { ok: false, reason: "tick_failed", detail: failureDetail(r, 300) };
94
+ }
95
+ return { ok: true, ...summarise(r.stdout) };
96
+ }
97
+
98
+ // ── deck-managed loop ──────────────────────────────────────────────────────
99
+
100
+ let _timer = null;
101
+ let _lastTick = null;
102
+ let _enabled = false;
103
+ // Set the instant startLoop is entered and cleared when it settles, because
104
+ // `_timer` cannot do that job: it is assigned AFTER an await, and the window in
105
+ // between is what #537 was. See startLoop.
106
+ let _starting = false;
107
+ /** Set when a restart is asked for while `startLoop` is mid-read, so the read
108
+ * that is already running takes the new value instead of installing the old
109
+ * one. Module-level beside `_starting`, which it exists to answer for. */
110
+ let _restartWanted = false;
111
+ // The tick in flight, so the interval can skip rather than stack. See tick.
112
+ let _ticking = null;
113
+ // What every tick waits for before it runs anything: the launcher's word that
114
+ // the claude-swap it drives is not being installed or upgraded underneath it.
115
+ // Settled by default, so a caller with nothing to wait for — a respawn, a test,
116
+ // the dev server — ticks exactly as before. See initCswapAuto (#1043).
117
+ let _toolQuiet = Promise.resolve();
118
+
119
+ async function loadState() {
120
+ try { return JSON.parse(await readFile(STATE_PATH, "utf8")); } catch { return {}; }
121
+ }
122
+ async function saveState(state) {
123
+ try {
124
+ await mkdir(STATE_DIR, { recursive: true });
125
+ await writeFile(STATE_PATH, JSON.stringify(state, null, 2));
126
+ } catch { /* best-effort */ }
127
+ }
128
+
129
+ async function tickInterval() {
130
+ const cfg = await readCswapConfig();
131
+ const raw = Number(cfg?.["autoswitch.intervalSeconds"]?.value);
132
+ return Math.max(MIN_INTERVAL_S, Number.isFinite(raw) ? raw : 60) * 1000;
133
+ }
134
+
135
+ /**
136
+ * Everything the deck holds that belongs to ONE Claude account, dropped.
137
+ *
138
+ * The accounts roster is keyed on whichever account claude-swap says is active,
139
+ * and every quota percentage was read for whoever was active when it was
140
+ * collected. A switch makes both of them the wrong account's, and neither cache
141
+ * has any way to find that out for itself: they are refreshed on timers, by
142
+ * panels that were not told.
143
+ *
144
+ * The two caches decay at very different rates, which is why saying nothing was
145
+ * visibly wrong rather than briefly wrong. claude-accounts.mjs holds its roster
146
+ * for CACHE_MS = 5s, so the panel flips to the new account almost at once, while
147
+ * quota.mjs holds its result for a CACHE_MS of its own = 60s — and `_lastGood`
148
+ * outlives even that, coming back under a "stale" label every five seconds until
149
+ * the store has something to say about the account the deck moved TO. So for up
150
+ * to a minute, and for longer than that in the fallback, two panels on one screen
151
+ * described two different accounts, and the wrong one was the big quota bars:
152
+ * sitting at the 90% that triggered the switch, for an account nobody is on.
153
+ */
154
+ function forgetAccountScopedCaches() {
155
+ invalidateClaudeAccountsCache();
156
+ invalidateQuotaCache();
157
+ }
158
+
159
+ async function runTick() {
160
+ // NOT WHILE THE TOOL IS BEING SET UP (#1043). A tick is `cswap auto --once`,
161
+ // which moves the user's live Claude credentials, and the boot arms this loop
162
+ // the moment the port binds — while bin/deck.js may still be installing
163
+ // claude-swap, or has just fired an upgrade of it that nothing awaits. It sits
164
+ // here rather than in startLoop so that it holds every tick that could land in
165
+ // that window: the boot's eager one, an interval that comes round during a
166
+ // three-minute install, and one the user starts from the panel meanwhile.
167
+ // Everything below is asked after it, so a switch turned off while this was
168
+ // waiting is seen as off.
169
+ await _toolQuiet;
170
+ // Re-check each time: the user can start their own loop at any point, and
171
+ // the deck should fall silent rather than compete with it.
172
+ if (await externalAutoRunning()) {
173
+ _lastTick = { at: Date.now(), event: "skipped", reason: "external-engine" };
174
+ return;
175
+ }
176
+ // AND RE-CHECK THE SWITCH ITSELF, after that await. `stopLoop` clears the
177
+ // interval and nothing else, so a tick already running went on to move the
178
+ // user's live account seconds after the panel had drawn itself as off. The
179
+ // await above is not short: ticks are at least fifteen seconds apart against
180
+ // a ten-second floor, so every one pays a real process-table read — on
181
+ // Windows a PowerShell Get-CimInstance with an eight-second deadline. The
182
+ // panel then showed `enabled: false` beside a `lastTick` of
183
+ // `{event: "switch", from, to}` stamped after the user turned it off.
184
+ if (!_enabled) {
185
+ _lastTick = { at: Date.now(), event: "skipped", reason: "disabled" };
186
+ return;
187
+ }
188
+ const result = await runAutoTick();
189
+ // Before `_lastTick`, not after. This is the only path in the deck that moves
190
+ // the live account without a click behind it, so nothing else is in a position
191
+ // to make the call — and `_lastTick` is what /api/cswap-auto reports, so
192
+ // dropping the caches first means anything that can see the tick happened is
193
+ // already looking at caches that know about it.
194
+ //
195
+ // Only on a tick that actually switched. A tick is mostly a poll that decides
196
+ // to do nothing — cooldown, no candidates, nothing over the threshold — and
197
+ // invalidating on those would throw away readings the deck paid a subprocess
198
+ // for, every interval, forever.
199
+ if (result.switched) forgetAccountScopedCaches();
200
+ // Record the move for the account-projects report. Only on a real switch, and
201
+ // best effort — the tick must not fail because a log line did not append. The
202
+ // slot is resolved from the store inside recordSwap, so cswap's `to` need not
203
+ // be threaded through here.
204
+ if (result.switched) {
205
+ import("./swap-log.mjs")
206
+ .then(({ recordSwap }) => recordSwap(result.to, "auto"))
207
+ .catch(() => {});
208
+ }
209
+ _lastTick = { at: Date.now(), ...result };
210
+ }
211
+
212
+ /**
213
+ * One tick at a time, whatever the interval is.
214
+ *
215
+ * The interval floor is 15 seconds (MIN_INTERVAL_S, and SETTINGS allows exactly
216
+ * that), while a single tick can legitimately take 8 for externalAutoRunning's
217
+ * `Get-CimInstance`/`ps` plus 120 for runAutoTick's own timeout. Nothing capped
218
+ * the fan-out, so a slow `cswap auto --once` — one that is refreshing a token
219
+ * and switching an account — could have eight copies of itself running against
220
+ * each other two minutes later, each with a PowerShell process beside it on
221
+ * Windows. `_lastTick` was then written by whichever finished last rather than
222
+ * by the most recent tick, so the panel's "last tick" could go backwards.
223
+ *
224
+ * A skipped tick is not a lost one: the next interval is at most 15 seconds
225
+ * away, and the work this schedules is idempotent by design.
226
+ */
227
+ function tick() {
228
+ if (_ticking) return _ticking;
229
+ _ticking = runTick().finally(() => { _ticking = null; });
230
+ return _ticking;
231
+ }
232
+
233
+ /**
234
+ * Start the deck-managed loop, at most once.
235
+ *
236
+ * `if (_timer) return` looked like a guard and was not one: `_timer` is assigned
237
+ * after `await tickInterval()`, which shells out to `cswap config`, so two
238
+ * callers could both be past the check before either had set it. Two ways in
239
+ * during that window, both reachable from the UI:
240
+ *
241
+ * - enable then disable, a few hundred milliseconds apart. The disable set
242
+ * `_enabled = false` and called stopLoop, which cleared nothing because
243
+ * `_timer` was still null — and then the enable came back and installed the
244
+ * interval. autoStatus() reported `enabled: false` and the toggle read off
245
+ * while every tick went on running `cswap auto --once`, which switches the
246
+ * user's live Claude account. A control that says it is off while it moves
247
+ * credentials is the worst shape this bug could take.
248
+ *
249
+ * - two enables (a double click, or two tabs). Two intervals, only the second
250
+ * reachable from `_timer`, so the first could never be cleared again for the
251
+ * life of the process.
252
+ *
253
+ * initCswapAuto is a third way in: index.mjs fires it unawaited while the server
254
+ * is already accepting requests.
255
+ *
256
+ * `_starting` is set before the await, so the guard covers the whole function.
257
+ * `_enabled` is re-read after it, because the answer may have changed while this
258
+ * was waiting on a subprocess — and a loop that installs itself after the user
259
+ * has turned it off is the same defect from the other side.
260
+ */
261
+ async function startLoop() {
262
+ // A start requested while one is already in flight is REMEMBERED, not dropped
263
+ // (#791). `initCswapAuto()` is fired unawaited at boot, so this sits inside
264
+ // `await tickInterval()` — a `cswap config` spawn, preceded on Windows by
265
+ // cswapBin() probing up to four spellings, two of them through cmd.exe, each
266
+ // with an 8s deadline — while the panel is already serving. A user setting
267
+ // the interval in that window called stopLoop() (no timer yet: a no-op) and
268
+ // then startLoop(), which returned here having done nothing; the boot's own
269
+ // start then resumed with the interval it had read BEFORE the write and
270
+ // installed the timer at the old value. The panel read back the new number
271
+ // while the loop kept the old one for the life of the process.
272
+ if (_starting) { _restartWanted = true; return; }
273
+ if (_timer) return;
274
+ _starting = true;
275
+ try {
276
+ // Loop rather than a single pass: the config may be written again while
277
+ // THIS read is in flight, and the answer must be the last one written.
278
+ for (;;) {
279
+ _restartWanted = false;
280
+ const ms = await tickInterval();
281
+ if (!_enabled) return; // turned off while we were asking cswap
282
+ if (_restartWanted) continue; // the interval changed under this read
283
+ _timer = setInterval(() => { tick().catch(() => {}); }, ms);
284
+ _timer.unref?.();
285
+ break;
286
+ }
287
+ } finally {
288
+ _starting = false;
289
+ }
290
+ tick().catch(() => {}); // don't make the user wait a full interval for the first one
291
+ }
292
+
293
+ function stopLoop() {
294
+ if (_timer) { clearInterval(_timer); _timer = null; }
295
+ }
296
+
297
+ /** Put a new interval into effect: the timer goes, and a fresh read of the
298
+ * interval installs the next one. */
299
+ export function restartLoop() {
300
+ stopLoop();
301
+ // startLoop records the ask when one is already in flight, so this can no
302
+ // longer be swallowed by the boot's own start — see the note there (#791).
303
+ return startLoop();
304
+ }
305
+
306
+ /** Whether the user has the loop switched on — the setting, which a new
307
+ * interval and the status route both ask about, rather than whether a timer is
308
+ * installed right now. */
309
+ export function loopEnabled() {
310
+ return _enabled;
311
+ }
312
+
313
+ /** What the most recent tick did, as /api/cswap-auto reports it; null before
314
+ * the first. */
315
+ export function lastTick() {
316
+ return _lastTick;
317
+ }
318
+
319
+ /** Turn the deck-managed loop on or off, persisting the choice. */
320
+ export async function setAutoEnabled(enabled) {
321
+ _enabled = Boolean(enabled);
322
+ await saveState({ ...(await loadState()), enabled: _enabled });
323
+ if (_enabled) await startLoop(); else stopLoop();
324
+ return { ok: true, enabled: _enabled };
325
+ }
326
+
327
+ /**
328
+ * Restore the persisted setting at server boot.
329
+ *
330
+ * `after` is the launcher's promise that claude-swap is quiet: its startup job
331
+ * has settled, and so has any upgrade that job started without waiting for.
332
+ * index.mjs passes on what bin/deck.js hands startServer. With nothing to wait
333
+ * for it is null, and the loop ticks as it always did. A rejection counts as
334
+ * settled, because a job that failed has nothing left running either.
335
+ *
336
+ * The loop still starts here and reads its interval here. Only the ticks wait.
337
+ */
338
+ export async function initCswapAuto({ after = null } = {}) {
339
+ _toolQuiet = Promise.resolve(after).then(() => {}, () => {});
340
+ const state = await loadState();
341
+ if (state.enabled) { _enabled = true; await startLoop(); }
342
+ }
@@ -0,0 +1,303 @@
1
+ // The two readings behind GET /api/cswap-auto — claude-swap's settings map, and
2
+ // whether the user is running a `cswap auto` loop of their own — each shared by
3
+ // everyone who asks inside its window, one child at a time (#616).
4
+ //
5
+ // Moved out of cswap-auto.mjs unchanged, with the rule that tells the user's
6
+ // loop from the deck's own ticks. cswap-auto.mjs asks both on every status
7
+ // read, takes the tick interval out of the settings map, asks about the other
8
+ // engine before every tick, and drops both readings when it writes a setting;
9
+ // it re-exports all five names, which is where the suite reaches them.
10
+ import { run } from "./exec.mjs";
11
+ import { cswapBin } from "./cswap-install.mjs";
12
+
13
+ // ── one reading at a time ──────────────────────────────────────────────────
14
+
15
+ /**
16
+ * #616: /api/cswap-auto is a GET with no cache, no dedupe and no throttle, and
17
+ * autoStatus() runs BOTH of this module's readers on every one of them — so the
18
+ * number of children was exactly twice the number of requests.
19
+ *
20
+ * Measured on macOS with claude-swap installed, counting real children through a
21
+ * PATH shim: one autoStatus() is 2 children (`cswap config` and `ps -Ao args=`)
22
+ * and about 190ms warm; two back-to-back calls are 4; twenty-five concurrent
23
+ * readers produced 50 — twenty-five Python interpreters and twenty-five `ps` —
24
+ * and took 1.3 to 1.9s between them against 190ms for one, so the cost per
25
+ * reader grows rather than holds. With the guard below the same twenty-five are
26
+ * 2 children and 190ms, which is one reader's worth.
27
+ *
28
+ * On Windows the process-table half is `Get-CimInstance Win32_Process` through
29
+ * PowerShell, carrying an 8s deadline of its own, which is the same order of
30
+ * cost as the Get-Process #544 measured at about six seconds; and where cswap is
31
+ * not on PATH each call also re-pays cswapBin()'s probe, which memoizes only
32
+ * success and which `candidates` expands to four spellings there, two of them
33
+ * launched through cmd.exe.
34
+ *
35
+ * Two callers reach these without an attacker anywhere: AccountsPanel polls the
36
+ * route every 15s per open tab, and runTick asks externalAutoRunning() again
37
+ * before every tick. And it is a GET, so it passes isTrustedRead for any local
38
+ * client that sends neither Origin nor Sec-Fetch-Site — curl, a shell script, a
39
+ * sandboxed agent.
40
+ *
41
+ * The fix is #544's, at the route that sweep did not reach: a minimum gap plus
42
+ * one shared in-flight promise per reader. There is no MAX_OUTSTANDING beside it
43
+ * the way ccusage.mjs has one, and there does not need to be — ccusage keys its
44
+ * cache by date range, so a flood of distinct ranges can never share a run,
45
+ * while each reader here asks exactly one question and every caller of it can
46
+ * therefore join the same child.
47
+ *
48
+ * What is NOT shared is the window, because the two halves are not the same
49
+ * question. See CONFIG_MIN_GAP_MS and EXTERNAL_MIN_GAP_MS.
50
+ */
51
+
52
+ /**
53
+ * `cswap config` — the settings map, which is also what the panel DISPLAYS.
54
+ *
55
+ * The deck is not its only writer: `cswap config set` typed in a terminal
56
+ * changes it behind the deck's back, and the panel is where the user would
57
+ * expect to see that. So this window has to stay well under AccountsPanel's
58
+ * 15s poll, or an edit made outside the deck waits for the window AND the poll.
59
+ * Three seconds does not delay a single tab by one frame — its polls are five
60
+ * gaps apart — while a burst of requests and two tabs whose polls land within
61
+ * three seconds of each other collapse onto one child.
62
+ */
63
+ const CONFIG_MIN_GAP_MS = 3_000;
64
+
65
+ /**
66
+ * The process table — the expensive half, and the one whose answer changes
67
+ * least: it is a boolean about whether the user has their own `cswap auto`
68
+ * running, and nobody starts one between two fifteen-second polls.
69
+ *
70
+ * Ten seconds is chosen against the two scheduled callers rather than against
71
+ * the cost: AccountsPanel's poll is 15s and MIN_INTERVAL_S — claude-swap's own
72
+ * floor, and the smallest tick interval SETTINGS will accept — is also 15, so a
73
+ * gap below both means neither of them is ever handed a reading older than its
74
+ * own period. The deck's tick still decides on a fresh process table, and the
75
+ * panel still shows one; what disappears is the second, third and twenty-fifth
76
+ * copy taken in the same ten seconds.
77
+ *
78
+ * Worst case for a caller in a loop is now 20 `cswap config` and 6 process-table
79
+ * children a minute, whatever it asks for, against a pair per request before.
80
+ */
81
+ const EXTERNAL_MIN_GAP_MS = 10_000;
82
+
83
+ const _config = { last: null, inFlight: null };
84
+ const _external = { last: null, inFlight: null };
85
+
86
+ /**
87
+ * One reading of `read`, shared by everyone who asks inside `gapMs`.
88
+ *
89
+ * Only a real reading is remembered, which is what `value != null` means here:
90
+ * readCswapConfig spells its failure `null` — autoStatus reports
91
+ * `ok: config != null`, so holding one for three seconds would turn a single
92
+ * hiccup into a panel that renders itself as broken for longer than the hiccup
93
+ * lasted — and externalAutoRunning has no failure spelling at all, answering
94
+ * `false` for a process table it could not read because that is the same answer
95
+ * as an empty one and is the safe one either way. The in-flight share still
96
+ * applies to a failing read, so a burst arriving during one is a single failing
97
+ * child rather than a burst of them.
98
+ *
99
+ * `slot.inFlight === mine` on both hops is claude-accounts.mjs's guard and is
100
+ * here for its reason: invalidateCswapAutoCache drops `inFlight` so the next
101
+ * caller starts a read that knows the settings moved, and a read from BEFORE the
102
+ * write must neither store its answer under the new state nor clear the new
103
+ * read's promise on its way out.
104
+ *
105
+ * The reading is not keyed by platform even though externalAutoRunning branches
106
+ * on one. A process does not change platform; the two test files that flip
107
+ * `process.platform` to reach the other half from this one call
108
+ * invalidateCswapAutoCache between cases.
109
+ */
110
+ function throttled(slot, gapMs, read) {
111
+ const now = Date.now();
112
+ if (slot.last && now - slot.last.at < gapMs) return Promise.resolve(slot.last.value);
113
+ if (slot.inFlight) return slot.inFlight;
114
+ const mine = read()
115
+ .then(value => {
116
+ if (value != null && slot.inFlight === mine) slot.last = { at: Date.now(), value };
117
+ return value;
118
+ })
119
+ .finally(() => { if (slot.inFlight === mine) slot.inFlight = null; });
120
+ slot.inFlight = mine;
121
+ return mine;
122
+ }
123
+
124
+ /**
125
+ * Forget both readings, because the deck has just changed what they would say.
126
+ *
127
+ * The one caller is setCswapConfig. There is no `?refresh=1` on /api/cswap-auto
128
+ * and no force argument through autoStatus, because the panel's explicit-refresh
129
+ * path is not a query parameter: every auto-switch control is a POST followed by
130
+ * `load(true)`, which re-fetches this route. Dropping the reading inside the
131
+ * write is what makes that reload show what was written rather than the map read
132
+ * a moment before it — the same disagreement between an optimistic value and the
133
+ * next read that #584 was.
134
+ *
135
+ * The process-table reading goes with it. A settings write does not start
136
+ * anybody's `cswap auto`, so this is not correctness for that half — it is that
137
+ * one function which forgets everything this module is holding cannot be called
138
+ * half-right, and the cost is at most one extra `ps` on a path the user reached
139
+ * by clicking. It is also what the tests reset between cases.
140
+ */
141
+ export function invalidateCswapAutoCache() {
142
+ _config.last = _config.inFlight = null;
143
+ _external.last = _external.inFlight = null;
144
+ }
145
+
146
+ // ── settings ───────────────────────────────────────────────────────────────
147
+
148
+ /**
149
+ * Parse `cswap config` — "key value (default)" per line.
150
+ *
151
+ * Exported for its test, not only for its callers (#383). Its two callers in
152
+ * cswap-auto.mjs — `autoStatus`, which hands the map straight to the settings
153
+ * panel, and `tickInterval`, which takes the poll interval out of it — both
154
+ * reduce the parse to something a test cannot see through: the panel takes
155
+ * whatever shape it is given, and the interval collapses four fields to one
156
+ * number that is clamped anyway. The parse itself is a regex over
157
+ * human-formatted output from a separate Python tool, on both line-ending
158
+ * conventions. See cswap-auto-readers.test.ts.
159
+ *
160
+ * One reading at a time and one every CONFIG_MIN_GAP_MS at most; the parse below
161
+ * is what a reading is, and admission control is the wrapper. See throttled.
162
+ */
163
+ export function readCswapConfig() {
164
+ return throttled(_config, CONFIG_MIN_GAP_MS, readCswapConfigNow);
165
+ }
166
+
167
+ async function readCswapConfigNow() {
168
+ const r = await run(await cswapBin(), ["config"]);
169
+ if (!r.ok) return null;
170
+ const out = {};
171
+ for (const line of r.stdout.split("\n")) {
172
+ const m = line.match(/^(\S+)\s+(.*?)\s*(\(default\))?\s*$/);
173
+ if (!m || !m[1].includes(".")) continue;
174
+ const raw = m[2].trim();
175
+ out[m[1]] = {
176
+ value: raw === "(none)" ? null : raw,
177
+ isDefault: Boolean(m[3]),
178
+ };
179
+ }
180
+ return out;
181
+ }
182
+
183
+ // ── external engine detection ──────────────────────────────────────────────
184
+
185
+ /**
186
+ * One command line, as a list of the words a process was actually launched
187
+ * with.
188
+ *
189
+ * The quote characters are separators here, not delimiters, and that is the
190
+ * whole point of #552. `Win32_Process.CommandLine` reports what the CREATOR
191
+ * wrote, and every launcher on Windows except a human typing at `cmd.exe`
192
+ * quotes the executable:
193
+ *
194
+ * "C:\Users\dorin\.local\bin\cswap.exe" auto
195
+ *
196
+ * — which is what .NET's `Process.Start` writes, so PowerShell, Windows
197
+ * Terminal's default profile, Task Scheduler and an Explorer shortcut all
198
+ * produce it. A pattern that wanted whitespace immediately after `cswap.exe`
199
+ * saw a `"` there and answered no, for every one of them.
200
+ *
201
+ * The deck's own spawns are the same shape from the other side: viaCmd in
202
+ * src/server/exec.mjs launches a `.cmd` shim as
203
+ * `cmd.exe /d /s /c ""C:\…\cswap.cmd" "auto" "--once""`, with the whole line
204
+ * wrapped in one more pair of quotes because that is what `cmd /c` wants.
205
+ * Treating `"` as a separator takes both apart with no parser and no knowledge
206
+ * of which launcher wrote the line — the outer pair, the per-argument pairs and
207
+ * the bare case all collapse to the same token list.
208
+ *
209
+ * What it deliberately does NOT do is respect a quoted path containing spaces:
210
+ * `"C:\Program Files\cswap\cswap.exe" auto` splits into three tokens rather than
211
+ * two. That costs nothing here — the tail token is still `cswap.exe` followed by
212
+ * `auto`, which is the only question asked — and the alternative is a real
213
+ * command-line parser for a probe whose wrong answer must never be a crash.
214
+ */
215
+ export function commandTokens(line) {
216
+ return String(line ?? "").split(/["\s]+/).filter(Boolean);
217
+ }
218
+
219
+ /** The last path component of a token: `C:\bin\cswap.exe` → `cswap.exe`. */
220
+ const leaf = (token) => token.split(/[\\/]/).pop() ?? "";
221
+
222
+ /** Every spelling of the executable, on every platform. */
223
+ const CSWAP_EXE = /^cswap(\.exe|\.cmd|\.bat)?$/i;
224
+
225
+ /**
226
+ * True when this command line is a long-lived `cswap auto` loop.
227
+ *
228
+ * The rule, stated over tokens rather than characters: some token IS the cswap
229
+ * executable — its last path component, so `/opt/bin/mycswap` and `notcswap`
230
+ * are somebody else's program — and the token straight after it is exactly
231
+ * `auto`, so `autopilot` and `automate` are not this. `--once` anywhere rules
232
+ * the line out: the deck's own ticks carry it, and so does a cron user's.
233
+ *
234
+ * Pure and exported so the Windows shapes can be checked from a Mac. The
235
+ * residual false positive is a line that mentions cswap as an ARGUMENT and then
236
+ * `auto` — `myprog --exe cswap auto`. That direction is the safe one: a wrong
237
+ * `true` is a deck that stays quiet, while a wrong `false` is two engines moving
238
+ * the same live Claude account.
239
+ */
240
+ export function looksLikeAutoLoop(line) {
241
+ if (/--once/i.test(String(line ?? ""))) return false;
242
+ const tokens = commandTokens(line);
243
+ return tokens.some((token, i) =>
244
+ CSWAP_EXE.test(leaf(token)) && String(tokens[i + 1] ?? "").toLowerCase() === "auto");
245
+ }
246
+
247
+ /**
248
+ * True when the user is already running `cswap auto` themselves.
249
+ *
250
+ * Two engines would not corrupt anything — claude-swap serializes decisions
251
+ * under its state lock — but they would double the tick rate against a request
252
+ * budget that is already the scarce resource here, and the user would have two
253
+ * things switching their account with no single place showing why. So the deck
254
+ * reports it and stays out of the way.
255
+ *
256
+ * Exported for its test, not only for its callers (#383). Its two callers in
257
+ * cswap-auto.mjs reduce it to a boolean on a status object and to a skipped
258
+ * tick, so neither can show WHICH command line was matched — and the matching
259
+ * is the whole function. The two halves also run completely different
260
+ * commands, `ps` against `Get-CimInstance`, so on any one machine only half of
261
+ * it is ever exercised at all. See cswap-auto-readers.test.ts, which drives both
262
+ * from either host.
263
+ *
264
+ * One reading at a time and one every EXTERNAL_MIN_GAP_MS at most — the
265
+ * expensive half of #616, and the one both of its callers ask for on a
266
+ * fifteen-second timer. See throttled.
267
+ */
268
+ export function externalAutoRunning() {
269
+ return throttled(_external, EXTERNAL_MIN_GAP_MS, externalAutoRunningNow);
270
+ }
271
+
272
+ async function externalAutoRunningNow() {
273
+ // A line is the user's loop if it runs `cswap auto` without --once. Our own
274
+ // ticks are --once, and so is a cron user's. See looksLikeAutoLoop.
275
+ const isLoop = looksLikeAutoLoop;
276
+
277
+ if (process.platform === "win32") {
278
+ // No `ps` on Windows, and `tasklist` reports the image name only — every
279
+ // Python tool shows up as python.exe, which cannot tell cswap from
280
+ // anything else. CIM is the one place the full command line is available.
281
+ //
282
+ // `Out-String -Width 32767` is not decoration. `-ExpandProperty` emits
283
+ // strings, and strings leave PowerShell through its console FORMATTER,
284
+ // which hard-wraps at the host buffer width — 80 columns on a redirected
285
+ // stdout, which is what a spawned child always has. A real command line
286
+ // (`"C:\Users\dorin\AppData\Local\Programs\Python\Python312\Scripts\cswap.exe" auto`)
287
+ // is longer than that, so the executable and its subcommand arrived on
288
+ // SEPARATE LINES and no per-line match could ever see both. 32767 is the
289
+ // maximum length Windows allows a command line, so nothing real can wrap.
290
+ const r = await run("powershell.exe", [
291
+ "-NoProfile", "-NonInteractive", "-Command",
292
+ "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine | Out-String -Width 32767",
293
+ ], { timeout: 8_000 });
294
+ if (!r.ok) return false; // no PowerShell, or the query was refused
295
+ return r.stdout.split("\n").some(isLoop);
296
+ }
297
+
298
+ // `ps`, not `pgrep -a`: BSD pgrep ignores -a and prints bare PIDs, so a
299
+ // command-line match against its output silently never fires.
300
+ const r = await run("ps", ["-Ao", "args="], { timeout: 5_000 });
301
+ if (!r.stdout.trim()) return false;
302
+ return r.stdout.split("\n").some(isLoop);
303
+ }