agent-dag 3.22.0 → 3.22.3

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 (70) hide show
  1. package/README.md +6 -477
  2. package/package.json +14 -48
  3. package/shim.js +107 -0
  4. package/LICENSE +0 -661
  5. package/LICENSING.md +0 -82
  6. package/THIRD_PARTY_NOTICES.md +0 -395
  7. package/bin/agent-dag.js +0 -626
  8. package/bin/deck.js +0 -1805
  9. package/dist/web/assets/index-3FWd7g_W.css +0 -1
  10. package/dist/web/assets/index-BOwtoP02.js +0 -266
  11. package/dist/web/index.html +0 -49
  12. package/hook/hook.js +0 -542
  13. package/release-notes.json +0 -392
  14. package/src/server/activity.mjs +0 -52
  15. package/src/server/agent-activity.mjs +0 -522
  16. package/src/server/args.mjs +0 -183
  17. package/src/server/auto-update.mjs +0 -79
  18. package/src/server/block-notify.mjs +0 -173
  19. package/src/server/boot-deadline.mjs +0 -127
  20. package/src/server/brand.mjs +0 -16
  21. package/src/server/browser-history.mjs +0 -497
  22. package/src/server/browser-presence.mjs +0 -211
  23. package/src/server/browser-profiles.mjs +0 -279
  24. package/src/server/browser-react.mjs +0 -284
  25. package/src/server/browser-watch-store.mjs +0 -350
  26. package/src/server/browser-watch.mjs +0 -905
  27. package/src/server/ccusage.mjs +0 -1168
  28. package/src/server/claude-accounts.mjs +0 -951
  29. package/src/server/claude-dir.mjs +0 -213
  30. package/src/server/codex-auth.mjs +0 -388
  31. package/src/server/codex-dir.mjs +0 -171
  32. package/src/server/codex-quota.mjs +0 -449
  33. package/src/server/codex-usage.mjs +0 -512
  34. package/src/server/cswap-admin.mjs +0 -1562
  35. package/src/server/cswap-auto.mjs +0 -658
  36. package/src/server/cswap-install.mjs +0 -641
  37. package/src/server/deck-home.mjs +0 -243
  38. package/src/server/deck-prefs.mjs +0 -301
  39. package/src/server/deck-probe.mjs +0 -111
  40. package/src/server/detach.mjs +0 -244
  41. package/src/server/exec.mjs +0 -996
  42. package/src/server/global-install.mjs +0 -67
  43. package/src/server/hwmonitor.mjs +0 -56
  44. package/src/server/index.mjs +0 -6043
  45. package/src/server/installer.mjs +0 -912
  46. package/src/server/invoked-as.mjs +0 -144
  47. package/src/server/lan-about.mjs +0 -119
  48. package/src/server/lan-engine.mjs +0 -952
  49. package/src/server/lan-reach.mjs +0 -256
  50. package/src/server/lan-socket.mjs +0 -682
  51. package/src/server/lan-sync.mjs +0 -941
  52. package/src/server/lhm-parse.mjs +0 -91
  53. package/src/server/log-tail.mjs +0 -139
  54. package/src/server/log-writer.mjs +0 -322
  55. package/src/server/login-service.mjs +0 -473
  56. package/src/server/macmon.mjs +0 -310
  57. package/src/server/npx.mjs +0 -264
  58. package/src/server/open-url.mjs +0 -242
  59. package/src/server/presence.mjs +0 -40
  60. package/src/server/quota.mjs +0 -792
  61. package/src/server/relay-guard.mjs +0 -507
  62. package/src/server/reset-label.mjs +0 -78
  63. package/src/server/retire-sound-hook.mjs +0 -349
  64. package/src/server/running-deck.mjs +0 -234
  65. package/src/server/self-update.mjs +0 -1380
  66. package/src/server/stop-deck.mjs +0 -171
  67. package/src/server/supervisor.mjs +0 -392
  68. package/src/server/system-metrics.mjs +0 -1825
  69. package/src/server/term.mjs +0 -686
  70. package/src/server/uv-bootstrap.mjs +0 -337
@@ -1,658 +0,0 @@
1
- // Auto-switch controls: read and write claude-swap's autoswitch settings and
2
- // run a tick on a schedule.
3
- //
4
- // The engine is claude-swap's own — `cswap auto --once` evaluates one tick and
5
- // exits, honouring the cooldown, quarantine and poll-budget state it keeps in
6
- // its own files. Running that on an interval gets the same behaviour as the
7
- // long-lived `cswap auto` loop while leaving all the decisions with the tool
8
- // that owns them: nothing here decides when to switch, only when to ask.
9
- //
10
- // A tick can move the user's live Claude account, so it is off unless turned
11
- // on and the setting survives restarts.
12
- import { run } from "./exec.mjs";
13
- import { cswapBin } from "./cswap-install.mjs";
14
- import { invalidateClaudeAccountsCache } from "./claude-accounts.mjs";
15
- import { invalidateQuotaCache } from "./quota.mjs";
16
- import { readFile, writeFile, mkdir } from "node:fs/promises";
17
- import { join } from "node:path";
18
- import { homedir } from "node:os";
19
-
20
- const STATE_DIR = join(homedir(), ".agents-deck");
21
- const STATE_PATH = join(STATE_DIR, "cswap-auto.json");
22
-
23
- const TICK_TIMEOUT_MS = 120_000; // a tick can refresh a token and switch
24
- const MIN_INTERVAL_S = 15; // claude-swap's own floor
25
-
26
- // Only these may be written, and only with a value of the right shape. The
27
- // value reaches an exec argument, and `cswap config set` will happily store
28
- // whatever it is handed.
29
- const SETTINGS = {
30
- "autoswitch.threshold": { type: "number", min: 50, max: 99.9 },
31
- "autoswitch.intervalSeconds": { type: "number", min: 15, max: 3600 },
32
- "autoswitch.cooldownSeconds": { type: "number", min: 0, max: 86400 },
33
- "autoswitch.hysteresisPct": { type: "number", min: 0, max: 50 },
34
- "autoswitch.model": { type: "model" },
35
- };
36
-
37
- // ── one reading at a time ──────────────────────────────────────────────────
38
-
39
- /**
40
- * #616: /api/cswap-auto is a GET with no cache, no dedupe and no throttle, and
41
- * autoStatus() runs BOTH of this module's readers on every one of them — so the
42
- * number of children was exactly twice the number of requests.
43
- *
44
- * Measured on macOS with claude-swap installed, counting real children through a
45
- * PATH shim: one autoStatus() is 2 children (`cswap config` and `ps -Ao args=`)
46
- * and about 190ms warm; two back-to-back calls are 4; twenty-five concurrent
47
- * readers produced 50 — twenty-five Python interpreters and twenty-five `ps` —
48
- * and took 1.3 to 1.9s between them against 190ms for one, so the cost per
49
- * reader grows rather than holds. With the guard below the same twenty-five are
50
- * 2 children and 190ms, which is one reader's worth.
51
- *
52
- * On Windows the process-table half is `Get-CimInstance Win32_Process` through
53
- * PowerShell, carrying an 8s deadline of its own, which is the same order of
54
- * cost as the Get-Process #544 measured at about six seconds; and where cswap is
55
- * not on PATH each call also re-pays cswapBin()'s probe, which memoizes only
56
- * success and which `candidates` expands to four spellings there, two of them
57
- * launched through cmd.exe.
58
- *
59
- * Two callers reach these without an attacker anywhere: AccountsPanel polls the
60
- * route every 15s per open tab, and runTick asks externalAutoRunning() again
61
- * before every tick. And it is a GET, so it passes isTrustedRead for any local
62
- * client that sends neither Origin nor Sec-Fetch-Site — curl, a shell script, a
63
- * sandboxed agent.
64
- *
65
- * The fix is #544's, at the route that sweep did not reach: a minimum gap plus
66
- * one shared in-flight promise per reader. There is no MAX_OUTSTANDING beside it
67
- * the way ccusage.mjs has one, and there does not need to be — ccusage keys its
68
- * cache by date range, so a flood of distinct ranges can never share a run,
69
- * while each reader here asks exactly one question and every caller of it can
70
- * therefore join the same child.
71
- *
72
- * What is NOT shared is the window, because the two halves are not the same
73
- * question. See CONFIG_MIN_GAP_MS and EXTERNAL_MIN_GAP_MS.
74
- */
75
-
76
- /**
77
- * `cswap config` — the settings map, which is also what the panel DISPLAYS.
78
- *
79
- * The deck is not its only writer: `cswap config set` typed in a terminal
80
- * changes it behind the deck's back, and the panel is where the user would
81
- * expect to see that. So this window has to stay well under AccountsPanel's
82
- * 15s poll, or an edit made outside the deck waits for the window AND the poll.
83
- * Three seconds does not delay a single tab by one frame — its polls are five
84
- * gaps apart — while a burst of requests and two tabs whose polls land within
85
- * three seconds of each other collapse onto one child.
86
- */
87
- const CONFIG_MIN_GAP_MS = 3_000;
88
-
89
- /**
90
- * The process table — the expensive half, and the one whose answer changes
91
- * least: it is a boolean about whether the user has their own `cswap auto`
92
- * running, and nobody starts one between two fifteen-second polls.
93
- *
94
- * Ten seconds is chosen against the two scheduled callers rather than against
95
- * the cost: AccountsPanel's poll is 15s and MIN_INTERVAL_S — claude-swap's own
96
- * floor, and the smallest tick interval SETTINGS will accept — is also 15, so a
97
- * gap below both means neither of them is ever handed a reading older than its
98
- * own period. The deck's tick still decides on a fresh process table, and the
99
- * panel still shows one; what disappears is the second, third and twenty-fifth
100
- * copy taken in the same ten seconds.
101
- *
102
- * Worst case for a caller in a loop is now 20 `cswap config` and 6 process-table
103
- * children a minute, whatever it asks for, against a pair per request before.
104
- */
105
- const EXTERNAL_MIN_GAP_MS = 10_000;
106
-
107
- const _config = { last: null, inFlight: null };
108
- const _external = { last: null, inFlight: null };
109
-
110
- /**
111
- * One reading of `read`, shared by everyone who asks inside `gapMs`.
112
- *
113
- * Only a real reading is remembered, which is what `value != null` means here:
114
- * readCswapConfig spells its failure `null` — autoStatus reports
115
- * `ok: config != null`, so holding one for three seconds would turn a single
116
- * hiccup into a panel that renders itself as broken for longer than the hiccup
117
- * lasted — and externalAutoRunning has no failure spelling at all, answering
118
- * `false` for a process table it could not read because that is the same answer
119
- * as an empty one and is the safe one either way. The in-flight share still
120
- * applies to a failing read, so a burst arriving during one is a single failing
121
- * child rather than a burst of them.
122
- *
123
- * `slot.inFlight === mine` on both hops is claude-accounts.mjs's guard and is
124
- * here for its reason: invalidateCswapAutoCache drops `inFlight` so the next
125
- * caller starts a read that knows the settings moved, and a read from BEFORE the
126
- * write must neither store its answer under the new state nor clear the new
127
- * read's promise on its way out.
128
- *
129
- * The reading is not keyed by platform even though externalAutoRunning branches
130
- * on one. A process does not change platform; the two test files that flip
131
- * `process.platform` to reach the other half from this one call
132
- * invalidateCswapAutoCache between cases.
133
- */
134
- function throttled(slot, gapMs, read) {
135
- const now = Date.now();
136
- if (slot.last && now - slot.last.at < gapMs) return Promise.resolve(slot.last.value);
137
- if (slot.inFlight) return slot.inFlight;
138
- const mine = read()
139
- .then(value => {
140
- if (value != null && slot.inFlight === mine) slot.last = { at: Date.now(), value };
141
- return value;
142
- })
143
- .finally(() => { if (slot.inFlight === mine) slot.inFlight = null; });
144
- slot.inFlight = mine;
145
- return mine;
146
- }
147
-
148
- /**
149
- * Forget both readings, because the deck has just changed what they would say.
150
- *
151
- * The one caller is setCswapConfig. There is no `?refresh=1` on /api/cswap-auto
152
- * and no force argument through autoStatus, because the panel's explicit-refresh
153
- * path is not a query parameter: every auto-switch control is a POST followed by
154
- * `load(true)`, which re-fetches this route. Dropping the reading inside the
155
- * write is what makes that reload show what was written rather than the map read
156
- * a moment before it — the same disagreement between an optimistic value and the
157
- * next read that #584 was.
158
- *
159
- * The process-table reading goes with it. A settings write does not start
160
- * anybody's `cswap auto`, so this is not correctness for that half — it is that
161
- * one function which forgets everything this module is holding cannot be called
162
- * half-right, and the cost is at most one extra `ps` on a path the user reached
163
- * by clicking. It is also what the tests reset between cases.
164
- */
165
- export function invalidateCswapAutoCache() {
166
- _config.last = _config.inFlight = null;
167
- _external.last = _external.inFlight = null;
168
- }
169
-
170
- // ── settings ───────────────────────────────────────────────────────────────
171
-
172
- /**
173
- * Parse `cswap config` — "key value (default)" per line.
174
- *
175
- * Exported for its test rather than for a caller (#383). The two callers here —
176
- * `autoStatus`, which hands the map straight to the settings panel, and
177
- * `tickInterval`, which takes the poll interval out of it — both reduce the
178
- * parse to something a test cannot see through: the panel takes whatever shape
179
- * it is given, and the interval collapses four fields to one number that is
180
- * clamped anyway. The parse itself is a regex over human-formatted output from a
181
- * separate Python tool, on both line-ending conventions. See
182
- * cswap-auto-readers.test.ts.
183
- *
184
- * One reading at a time and one every CONFIG_MIN_GAP_MS at most; the parse below
185
- * is what a reading is, and admission control is the wrapper. See throttled.
186
- */
187
- export function readCswapConfig() {
188
- return throttled(_config, CONFIG_MIN_GAP_MS, readCswapConfigNow);
189
- }
190
-
191
- async function readCswapConfigNow() {
192
- const r = await run(await cswapBin(), ["config"]);
193
- if (!r.ok) return null;
194
- const out = {};
195
- for (const line of r.stdout.split("\n")) {
196
- const m = line.match(/^(\S+)\s+(.*?)\s*(\(default\))?\s*$/);
197
- if (!m || !m[1].includes(".")) continue;
198
- const raw = m[2].trim();
199
- out[m[1]] = {
200
- value: raw === "(none)" ? null : raw,
201
- isDefault: Boolean(m[3]),
202
- };
203
- }
204
- return out;
205
- }
206
-
207
- /**
208
- * What the model list may be made of before it becomes an argv element.
209
- *
210
- * The character class is the same one this field has always had — a
211
- * comma-separated list of plain model names, bounded at 120 — with the one rule
212
- * #543 wrote down at cswap-admin.mjs's EMAIL_OK added to the front: *"The
213
- * leading-character rule is the same argv-position rule ALIAS_OK now carries."*
214
- *
215
- * This is the THIRD free-text field to reach an argument vector and the first
216
- * one that pass missed, because it lives in a different module. It is not a
217
- * different question. `{ key: "autoswitch.model", value: "-h" }` produced
218
- * `cswap config set autoswitch.model -h`; argparse on the other side reads the
219
- * leading dash as an option rather than as data, prints help, exits 0 — so
220
- * `r.ok` is true and the deck reports a setting saved that was never written,
221
- * after which the panel's optimistic value disagrees with the next read (#584).
222
- *
223
- * Only the first character is constrained, so `claude-3-5-sonnet` and every
224
- * other dash-bearing model name still works. cswap-argv-position.test.ts
225
- * enumerates every field this rule covers, so a fourth cannot be added without
226
- * one.
227
- */
228
- const MODEL_LIST_OK = /^(?!-)[A-Za-z0-9 ,._-]{1,120}$/;
229
-
230
- /** Validate against SETTINGS, then hand to `cswap config set`. */
231
- export async function setCswapConfig(key, value) {
232
- // `Object.hasOwn`, not a bare read. `SETTINGS["constructor"]` is truthy and
233
- // its `.type` is undefined, so a prototype member passed the allowlist and
234
- // fell through to the free-text branch — reaching `cswap config set
235
- // constructor <value>` and skipping the type-specific range check on the way.
236
- // Nothing reachable that way was dangerous; an allowlist that does not hold
237
- // is.
238
- const spec = Object.hasOwn(SETTINGS, key) ? SETTINGS[key] : null;
239
- if (!spec) return { ok: false, reason: "unknown_setting" };
240
-
241
- let str;
242
- if (spec.type === "number") {
243
- const n = Number(value);
244
- if (!Number.isFinite(n) || n < spec.min || n > spec.max) return { ok: false, reason: "out_of_range" };
245
- str = String(n);
246
- } else if (spec.type === "enum") {
247
- if (!spec.values.includes(value)) return { ok: false, reason: "bad_value" };
248
- str = value;
249
- } else {
250
- // Model names: a comma-separated list of plain words, or "all".
251
- str = String(value ?? "").trim();
252
- if (str && !MODEL_LIST_OK.test(str)) return { ok: false, reason: "bad_value" };
253
- }
254
-
255
- const r = await run(await cswapBin(), ["config", "set", key, str]);
256
- // Whatever the CLI said. A write that reported a failure may still have landed
257
- // — and `r.ok` is not proof either way here, which is the whole of #584 — so
258
- // the only safe thing to hold after asking cswap to change a setting is
259
- // nothing. The panel reloads this route immediately afterwards and gets a real
260
- // read; see invalidateCswapAutoCache.
261
- invalidateCswapAutoCache();
262
- // A NEW INTERVAL HAS TO REACH THE TIMER. `tickInterval()` is read once, at
263
- // startLoop, so changing this setting used to update what the panel reports
264
- // and nothing else: set 3600 with auto-switch on and the panel read back an
265
- // hour while the loop kept firing every sixty seconds for the life of the
266
- // process — sixty `cswap auto --once` spawns an hour instead of one, against
267
- // the shared per-account request budget this subsystem exists to protect.
268
- // Lowering it was equally inert.
269
- if (r.ok && key === "autoswitch.intervalSeconds" && _enabled) {
270
- stopLoop();
271
- // startLoop records the ask when one is already in flight, so this can no
272
- // longer be swallowed by the boot's own start — see the note there (#791).
273
- await startLoop();
274
- }
275
- return r.ok ? { ok: true } : { ok: false, reason: "set_failed", detail: (r.stderr || r.stdout).trim().slice(0, 300) };
276
- }
277
-
278
- // ── ticks ──────────────────────────────────────────────────────────────────
279
-
280
- /** Last meaningful event from a `cswap auto --once --json` run. */
281
- function summarise(stdout) {
282
- const events = stdout.split("\n")
283
- .map(l => { try { return JSON.parse(l); } catch { return null; } })
284
- .filter(e => e && typeof e === "object");
285
-
286
- const poll = events.find(e => e.event === "poll") ?? null;
287
- const action = [...events].reverse().find(e => e.event !== "poll" && e.event !== "sleep") ?? null;
288
-
289
- return {
290
- event: action?.event ?? "no-switch",
291
- // Whether the LIVE ACCOUNT MOVED, which is a narrower question than which
292
- // event came last and the only one the caches care about. Taken over every
293
- // event rather than over `action`, so a quarantine or an error emitted after
294
- // the switch cannot hide it; and `dryRun` is checked even though this
295
- // module's ticks never pass `--dry-run`, because the engine emits the same
296
- // `switch` event for a decision it did not carry out, and a false positive
297
- // here throws away readings that cost a subprocess each.
298
- switched: events.some(e => e.event === "switch" && e.dryRun !== true),
299
- reason: action?.reason ?? null,
300
- detail: action?.detail ?? null,
301
- from: action?.from ?? null,
302
- to: action?.to ?? null,
303
- active: poll?.active ?? null,
304
- threshold: poll?.threshold ?? null,
305
- headroom: poll?.headroomPct ?? null,
306
- windows: poll?.windowsPct ?? null,
307
- };
308
- }
309
-
310
- /** Evaluate a tick for real. May switch the active account. */
311
- async function runAutoTick() {
312
- const r = await run(await cswapBin(), ["auto", "--once", "--json"], { timeout: TICK_TIMEOUT_MS });
313
- // A KILLED RUN IS NOT A QUIET ONE. `run`'s timeout path deliberately keeps an
314
- // 8 KB tail of whatever the child managed to print, so `!r.ok && !r.stdout`
315
- // is false for a tick that emitted its `{"event":"poll"}` line and then
316
- // stalled — and the killed run fell through to `ok: true`. The panel then
317
- // showed a healthy `no-switch` every two minutes, forever, while the engine
318
- // did nothing at all: exactly the trap exec.mjs's own header names.
319
- if (r.timedOut) {
320
- return { ok: false, reason: "tick_timeout", detail: `cswap auto --once did not finish within ${TICK_TIMEOUT_MS / 1000}s` };
321
- }
322
- if (!r.ok && !r.stdout) {
323
- return { ok: false, reason: "tick_failed", detail: (r.stderr || "").trim().slice(0, 300) };
324
- }
325
- return { ok: true, ...summarise(r.stdout) };
326
- }
327
-
328
- // ── external engine detection ──────────────────────────────────────────────
329
-
330
- /**
331
- * One command line, as a list of the words a process was actually launched
332
- * with.
333
- *
334
- * The quote characters are separators here, not delimiters, and that is the
335
- * whole point of #552. `Win32_Process.CommandLine` reports what the CREATOR
336
- * wrote, and every launcher on Windows except a human typing at `cmd.exe`
337
- * quotes the executable:
338
- *
339
- * "C:\Users\dorin\.local\bin\cswap.exe" auto
340
- *
341
- * — which is what .NET's `Process.Start` writes, so PowerShell, Windows
342
- * Terminal's default profile, Task Scheduler and an Explorer shortcut all
343
- * produce it. A pattern that wanted whitespace immediately after `cswap.exe`
344
- * saw a `"` there and answered no, for every one of them.
345
- *
346
- * The deck's own spawns are the same shape from the other side: viaCmd in
347
- * src/server/exec.mjs launches a `.cmd` shim as
348
- * `cmd.exe /d /s /c ""C:\…\cswap.cmd" "auto" "--once""`, with the whole line
349
- * wrapped in one more pair of quotes because that is what `cmd /c` wants.
350
- * Treating `"` as a separator takes both apart with no parser and no knowledge
351
- * of which launcher wrote the line — the outer pair, the per-argument pairs and
352
- * the bare case all collapse to the same token list.
353
- *
354
- * What it deliberately does NOT do is respect a quoted path containing spaces:
355
- * `"C:\Program Files\cswap\cswap.exe" auto` splits into three tokens rather than
356
- * two. That costs nothing here — the tail token is still `cswap.exe` followed by
357
- * `auto`, which is the only question asked — and the alternative is a real
358
- * command-line parser for a probe whose wrong answer must never be a crash.
359
- */
360
- export function commandTokens(line) {
361
- return String(line ?? "").split(/["\s]+/).filter(Boolean);
362
- }
363
-
364
- /** The last path component of a token: `C:\bin\cswap.exe` → `cswap.exe`. */
365
- const leaf = (token) => token.split(/[\\/]/).pop() ?? "";
366
-
367
- /** Every spelling of the executable, on every platform. */
368
- const CSWAP_EXE = /^cswap(\.exe|\.cmd|\.bat)?$/i;
369
-
370
- /**
371
- * True when this command line is a long-lived `cswap auto` loop.
372
- *
373
- * The rule, stated over tokens rather than characters: some token IS the cswap
374
- * executable — its last path component, so `/opt/bin/mycswap` and `notcswap`
375
- * are somebody else's program — and the token straight after it is exactly
376
- * `auto`, so `autopilot` and `automate` are not this. `--once` anywhere rules
377
- * the line out: the deck's own ticks carry it, and so does a cron user's.
378
- *
379
- * Pure and exported so the Windows shapes can be checked from a Mac. The
380
- * residual false positive is a line that mentions cswap as an ARGUMENT and then
381
- * `auto` — `myprog --exe cswap auto`. That direction is the safe one: a wrong
382
- * `true` is a deck that stays quiet, while a wrong `false` is two engines moving
383
- * the same live Claude account.
384
- */
385
- export function looksLikeAutoLoop(line) {
386
- if (/--once/i.test(String(line ?? ""))) return false;
387
- const tokens = commandTokens(line);
388
- return tokens.some((token, i) =>
389
- CSWAP_EXE.test(leaf(token)) && String(tokens[i + 1] ?? "").toLowerCase() === "auto");
390
- }
391
-
392
- /**
393
- * True when the user is already running `cswap auto` themselves.
394
- *
395
- * Two engines would not corrupt anything — claude-swap serializes decisions
396
- * under its state lock — but they would double the tick rate against a request
397
- * budget that is already the scarce resource here, and the user would have two
398
- * things switching their account with no single place showing why. So the deck
399
- * reports it and stays out of the way.
400
- *
401
- * Exported for its test rather than for a caller (#383). Its two callers reduce
402
- * it to a boolean on a status object and to a skipped tick, so neither can show
403
- * WHICH command line was matched — and the matching is the whole function. The
404
- * two halves also run completely different commands, `ps` against
405
- * `Get-CimInstance`, so on any one machine only half of it is ever exercised at
406
- * all. See cswap-auto-readers.test.ts, which drives both from either host.
407
- *
408
- * One reading at a time and one every EXTERNAL_MIN_GAP_MS at most — the
409
- * expensive half of #616, and the one both of its callers ask for on a
410
- * fifteen-second timer. See throttled.
411
- */
412
- export function externalAutoRunning() {
413
- return throttled(_external, EXTERNAL_MIN_GAP_MS, externalAutoRunningNow);
414
- }
415
-
416
- async function externalAutoRunningNow() {
417
- // A line is the user's loop if it runs `cswap auto` without --once. Our own
418
- // ticks are --once, and so is a cron user's. See looksLikeAutoLoop.
419
- const isLoop = looksLikeAutoLoop;
420
-
421
- if (process.platform === "win32") {
422
- // No `ps` on Windows, and `tasklist` reports the image name only — every
423
- // Python tool shows up as python.exe, which cannot tell cswap from
424
- // anything else. CIM is the one place the full command line is available.
425
- //
426
- // `Out-String -Width 32767` is not decoration. `-ExpandProperty` emits
427
- // strings, and strings leave PowerShell through its console FORMATTER,
428
- // which hard-wraps at the host buffer width — 80 columns on a redirected
429
- // stdout, which is what a spawned child always has. A real command line
430
- // (`"C:\Users\dorin\AppData\Local\Programs\Python\Python312\Scripts\cswap.exe" auto`)
431
- // is longer than that, so the executable and its subcommand arrived on
432
- // SEPARATE LINES and no per-line match could ever see both. 32767 is the
433
- // maximum length Windows allows a command line, so nothing real can wrap.
434
- const r = await run("powershell.exe", [
435
- "-NoProfile", "-NonInteractive", "-Command",
436
- "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine | Out-String -Width 32767",
437
- ], { timeout: 8_000 });
438
- if (!r.ok) return false; // no PowerShell, or the query was refused
439
- return r.stdout.split("\n").some(isLoop);
440
- }
441
-
442
- // `ps`, not `pgrep -a`: BSD pgrep ignores -a and prints bare PIDs, so a
443
- // command-line match against its output silently never fires.
444
- const r = await run("ps", ["-Ao", "args="], { timeout: 5_000 });
445
- if (!r.stdout.trim()) return false;
446
- return r.stdout.split("\n").some(isLoop);
447
- }
448
-
449
- // ── deck-managed loop ──────────────────────────────────────────────────────
450
-
451
- let _timer = null;
452
- let _lastTick = null;
453
- let _enabled = false;
454
- // Set the instant startLoop is entered and cleared when it settles, because
455
- // `_timer` cannot do that job: it is assigned AFTER an await, and the window in
456
- // between is what #537 was. See startLoop.
457
- let _starting = false;
458
- // The tick in flight, so the interval can skip rather than stack. See tick.
459
- let _ticking = null;
460
-
461
- async function loadState() {
462
- try { return JSON.parse(await readFile(STATE_PATH, "utf8")); } catch { return {}; }
463
- }
464
- async function saveState(state) {
465
- try {
466
- await mkdir(STATE_DIR, { recursive: true });
467
- await writeFile(STATE_PATH, JSON.stringify(state, null, 2));
468
- } catch { /* best-effort */ }
469
- }
470
-
471
- async function tickInterval() {
472
- const cfg = await readCswapConfig();
473
- const raw = Number(cfg?.["autoswitch.intervalSeconds"]?.value);
474
- return Math.max(MIN_INTERVAL_S, Number.isFinite(raw) ? raw : 60) * 1000;
475
- }
476
-
477
- /**
478
- * Everything the deck holds that belongs to ONE Claude account, dropped.
479
- *
480
- * The accounts roster is keyed on whichever account claude-swap says is active,
481
- * and every quota percentage was read for whoever was active when it was
482
- * collected. A switch makes both of them the wrong account's, and neither cache
483
- * has any way to find that out for itself: they are refreshed on timers, by
484
- * panels that were not told.
485
- *
486
- * The two caches decay at very different rates, which is why saying nothing was
487
- * visibly wrong rather than briefly wrong. claude-accounts.mjs holds its roster
488
- * for CACHE_MS = 5s, so the panel flips to the new account almost at once, while
489
- * quota.mjs holds its result for a CACHE_MS of its own = 60s — and `_lastGood`
490
- * outlives even that, coming back under a "stale" label every five seconds until
491
- * the store has something to say about the account the deck moved TO. So for up
492
- * to a minute, and for longer than that in the fallback, two panels on one screen
493
- * described two different accounts, and the wrong one was the big quota bars:
494
- * sitting at the 90% that triggered the switch, for an account nobody is on.
495
- */
496
- function forgetAccountScopedCaches() {
497
- invalidateClaudeAccountsCache();
498
- invalidateQuotaCache();
499
- }
500
-
501
- async function runTick() {
502
- // Re-check each time: the user can start their own loop at any point, and
503
- // the deck should fall silent rather than compete with it.
504
- if (await externalAutoRunning()) {
505
- _lastTick = { at: Date.now(), event: "skipped", reason: "external-engine" };
506
- return;
507
- }
508
- // AND RE-CHECK THE SWITCH ITSELF, after that await. `stopLoop` clears the
509
- // interval and nothing else, so a tick already running went on to move the
510
- // user's live account seconds after the panel had drawn itself as off. The
511
- // await above is not short: ticks are at least fifteen seconds apart against
512
- // a ten-second floor, so every one pays a real process-table read — on
513
- // Windows a PowerShell Get-CimInstance with an eight-second deadline. The
514
- // panel then showed `enabled: false` beside a `lastTick` of
515
- // `{event: "switch", from, to}` stamped after the user turned it off.
516
- if (!_enabled) {
517
- _lastTick = { at: Date.now(), event: "skipped", reason: "disabled" };
518
- return;
519
- }
520
- const result = await runAutoTick();
521
- // Before `_lastTick`, not after. This is the only path in the deck that moves
522
- // the live account without a click behind it, so nothing else is in a position
523
- // to make the call — and `_lastTick` is what /api/cswap-auto reports, so
524
- // dropping the caches first means anything that can see the tick happened is
525
- // already looking at caches that know about it.
526
- //
527
- // Only on a tick that actually switched. A tick is mostly a poll that decides
528
- // to do nothing — cooldown, no candidates, nothing over the threshold — and
529
- // invalidating on those would throw away readings the deck paid a subprocess
530
- // for, every interval, forever.
531
- if (result.switched) forgetAccountScopedCaches();
532
- _lastTick = { at: Date.now(), ...result };
533
- }
534
-
535
- /**
536
- * One tick at a time, whatever the interval is.
537
- *
538
- * The interval floor is 15 seconds (MIN_INTERVAL_S, and SETTINGS allows exactly
539
- * that), while a single tick can legitimately take 8 for externalAutoRunning's
540
- * `Get-CimInstance`/`ps` plus 120 for runAutoTick's own timeout. Nothing capped
541
- * the fan-out, so a slow `cswap auto --once` — one that is refreshing a token
542
- * and switching an account — could have eight copies of itself running against
543
- * each other two minutes later, each with a PowerShell process beside it on
544
- * Windows. `_lastTick` was then written by whichever finished last rather than
545
- * by the most recent tick, so the panel's "last tick" could go backwards.
546
- *
547
- * A skipped tick is not a lost one: the next interval is at most 15 seconds
548
- * away, and the work this schedules is idempotent by design.
549
- */
550
- function tick() {
551
- if (_ticking) return _ticking;
552
- _ticking = runTick().finally(() => { _ticking = null; });
553
- return _ticking;
554
- }
555
-
556
- /**
557
- * Start the deck-managed loop, at most once.
558
- *
559
- * `if (_timer) return` looked like a guard and was not one: `_timer` is assigned
560
- * after `await tickInterval()`, which shells out to `cswap config`, so two
561
- * callers could both be past the check before either had set it. Two ways in
562
- * during that window, both reachable from the UI:
563
- *
564
- * - enable then disable, a few hundred milliseconds apart. The disable set
565
- * `_enabled = false` and called stopLoop, which cleared nothing because
566
- * `_timer` was still null — and then the enable came back and installed the
567
- * interval. autoStatus() reported `enabled: false` and the toggle read off
568
- * while every tick went on running `cswap auto --once`, which switches the
569
- * user's live Claude account. A control that says it is off while it moves
570
- * credentials is the worst shape this bug could take.
571
- *
572
- * - two enables (a double click, or two tabs). Two intervals, only the second
573
- * reachable from `_timer`, so the first could never be cleared again for the
574
- * life of the process.
575
- *
576
- * initCswapAuto is a third way in: index.mjs fires it unawaited while the server
577
- * is already accepting requests.
578
- *
579
- * `_starting` is set before the await, so the guard covers the whole function.
580
- * `_enabled` is re-read after it, because the answer may have changed while this
581
- * was waiting on a subprocess — and a loop that installs itself after the user
582
- * has turned it off is the same defect from the other side.
583
- */
584
- async function startLoop() {
585
- // A start requested while one is already in flight is REMEMBERED, not dropped
586
- // (#791). `initCswapAuto()` is fired unawaited at boot, so this sits inside
587
- // `await tickInterval()` — a `cswap config` spawn, preceded on Windows by
588
- // cswapBin() probing up to four spellings, two of them through cmd.exe, each
589
- // with an 8s deadline — while the panel is already serving. A user setting
590
- // the interval in that window called stopLoop() (no timer yet: a no-op) and
591
- // then startLoop(), which returned here having done nothing; the boot's own
592
- // start then resumed with the interval it had read BEFORE the write and
593
- // installed the timer at the old value. The panel read back the new number
594
- // while the loop kept the old one for the life of the process.
595
- if (_starting) { _restartWanted = true; return; }
596
- if (_timer) return;
597
- _starting = true;
598
- try {
599
- // Loop rather than a single pass: the config may be written again while
600
- // THIS read is in flight, and the answer must be the last one written.
601
- for (;;) {
602
- _restartWanted = false;
603
- const ms = await tickInterval();
604
- if (!_enabled) return; // turned off while we were asking cswap
605
- if (_restartWanted) continue; // the interval changed under this read
606
- _timer = setInterval(() => { tick().catch(() => {}); }, ms);
607
- _timer.unref?.();
608
- break;
609
- }
610
- } finally {
611
- _starting = false;
612
- }
613
- tick().catch(() => {}); // don't make the user wait a full interval for the first one
614
- }
615
-
616
- /** Set when a restart is asked for while `startLoop` is mid-read, so the read
617
- * that is already running takes the new value instead of installing the old
618
- * one. Module-level beside `_starting`, which it exists to answer for. */
619
- let _restartWanted = false;
620
-
621
- function stopLoop() {
622
- if (_timer) { clearInterval(_timer); _timer = null; }
623
- }
624
-
625
- /** Turn the deck-managed loop on or off, persisting the choice. */
626
- export async function setAutoEnabled(enabled) {
627
- _enabled = Boolean(enabled);
628
- await saveState({ ...(await loadState()), enabled: _enabled });
629
- if (_enabled) await startLoop(); else stopLoop();
630
- return { ok: true, enabled: _enabled };
631
- }
632
-
633
- /** Restore the persisted setting at server boot. */
634
- export async function initCswapAuto() {
635
- const state = await loadState();
636
- if (state.enabled) { _enabled = true; await startLoop(); }
637
- }
638
-
639
- export async function autoStatus() {
640
- const [config, external] = await Promise.all([readCswapConfig(), externalAutoRunning()]);
641
- return {
642
- ok: config != null,
643
- enabled: _enabled,
644
- external, // user is running their own `cswap auto`
645
- lastTick: _lastTick,
646
- settings: config ?? {},
647
- };
648
- }
649
-
650
- // ── per-account rotation flag ──────────────────────────────────────────────
651
-
652
- /** Hold an account out of auto-rotation, or return it. */
653
- export async function setAccountEnabled(accountNum, enabled) {
654
- const num = Number(accountNum);
655
- if (!Number.isInteger(num) || num < 1 || num > 999) return { ok: false, reason: "bad_account" };
656
- const r = await run(await cswapBin(), [enabled ? "enable" : "disable", String(num)]);
657
- return r.ok ? { ok: true } : { ok: false, reason: "command_failed", detail: (r.stderr || r.stdout).trim().slice(0, 300) };
658
- }