ccdeck 3.46.0 → 3.48.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 (68) hide show
  1. package/README.md +99 -46
  2. package/bin/cli/commands.js +17 -9
  3. package/bin/cli/help.js +9 -4
  4. package/bin/cli/second-start.js +4 -2
  5. package/bin/cli/startup.js +26 -2
  6. package/bin/cli/tui.js +544 -0
  7. package/bin/deck.js +32 -1
  8. package/dist/web/assets/{BrowserWatchModal-CoX9FIUE.js → BrowserWatchModal-DuopT2Oa.js} +1 -1
  9. package/dist/web/assets/IntegrationModal-CszT-tts.js +7 -0
  10. package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-Cn3WvPUG.js} +1 -1
  11. package/dist/web/assets/TrafficRadar-DZA8XSi7.js +8 -0
  12. package/dist/web/assets/UsageHistoryModal-MgZJLXbF.js +1 -0
  13. package/dist/web/assets/app-DjlHxWHg.css +1 -0
  14. package/dist/web/assets/app-F1xryJpn.js +321 -0
  15. package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
  16. package/dist/web/assets/{index-DmENqVdt.js → index-BK9avF1k.js} +1 -1
  17. package/dist/web/index.html +3 -3
  18. package/package.json +1 -1
  19. package/release-notes.json +58 -2
  20. package/src/server/args.mjs +1 -0
  21. package/src/server/ccusage-install.mjs +58 -1
  22. package/src/server/ccusage-registry.mjs +289 -0
  23. package/src/server/ccusage-runner.mjs +9 -2
  24. package/src/server/claude-accounts.mjs +21 -0
  25. package/src/server/claude-login.mjs +21 -3
  26. package/src/server/claude-settings-catalog.d.mts +37 -0
  27. package/src/server/claude-settings-catalog.mjs +169 -0
  28. package/src/server/claude-settings-docs.mjs +109 -0
  29. package/src/server/claude-settings-index.json +251 -0
  30. package/src/server/claude-settings-routes.mjs +46 -0
  31. package/src/server/claude-settings.mjs +406 -0
  32. package/src/server/cli-arrival.mjs +64 -0
  33. package/src/server/cli-lines.mjs +46 -0
  34. package/src/server/gpu-metrics.mjs +78 -0
  35. package/src/server/index.mjs +18 -2
  36. package/src/server/integrations/jira-move.mjs +239 -0
  37. package/src/server/integrations/jira.mjs +30 -8
  38. package/src/server/integrations/proxy.mjs +14 -6
  39. package/src/server/integrations/routes.mjs +25 -9
  40. package/src/server/quota-close-watch.mjs +81 -0
  41. package/src/server/quota-closes.mjs +181 -0
  42. package/src/server/quota-history.mjs +8 -1
  43. package/src/server/quota-shape.mjs +12 -0
  44. package/src/server/quota.mjs +28 -1
  45. package/src/server/request-gates.mjs +3 -1
  46. package/src/server/system-metrics.mjs +4 -0
  47. package/src/server/term.mjs +14 -5
  48. package/src/server/tool-audit-operations.mjs +30 -10
  49. package/src/server/tool-audit-report.mjs +79 -7
  50. package/src/server/tool-audit-routes.mjs +1 -1
  51. package/src/server/tool-audit-skills.mjs +8 -3
  52. package/src/server/tool-audit.mjs +55 -5
  53. package/src/server/traffic-radar-capture.mjs +3 -3
  54. package/src/server/traffic-radar-config.mjs +10 -3
  55. package/src/server/traffic-radar-monitor.mjs +8 -5
  56. package/src/server/traffic-radar-permission.mjs +162 -0
  57. package/src/server/traffic-radar-platform.mjs +9 -3
  58. package/src/server/traffic-radar-routes.mjs +8 -18
  59. package/src/server/traffic-radar-service.mjs +76 -92
  60. package/src/server/tui-screen.mjs +110 -0
  61. package/src/server/tui-view.mjs +1072 -0
  62. package/src/server/usage-routes.mjs +14 -2
  63. package/src/server/way-back.mjs +27 -0
  64. package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
  65. package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
  66. package/dist/web/assets/UsageHistoryModal-Bd-JRAa4.js +0 -1
  67. package/dist/web/assets/app-BlRY6EME.css +0 -1
  68. package/dist/web/assets/app-DhGvSH7o.js +0 -319
package/bin/cli/tui.js ADDED
@@ -0,0 +1,544 @@
1
+ // `ccdeck tui`: the deck's accounts and the sessions waiting on you, on one
2
+ // screen that stays up, for somebody who reached the machine over SSH.
3
+ //
4
+ // The one-shot commands (commands.js) answer and leave. This keeps the answer
5
+ // on screen and lets the next question be a key: move to an account, Enter
6
+ // switches to it, b selects what Auto-switch would pick, a turns Auto-switch on
7
+ // or off. It is a CLIENT of the running deck, as they are, and asks it through
8
+ // their own helpers — so a switch from here takes the deck's route, its store
9
+ // lock and its refusals, and a deck that is alive but silent is never switched
10
+ // behind. With no deck it reads claude-swap's store, as `ccdeck accounts` does,
11
+ // and offers to start one.
12
+ //
13
+ // What it does not do: start, attach to, resume or stop an agent. That is the
14
+ // Command Panel's, and a second way of doing it here would be a second set of
15
+ // rules to keep in step.
16
+ //
17
+ // The view and the keys are pure (src/server/tui-view.mjs) and the painting is
18
+ // a row diff over the alternate screen (src/server/tui-screen.mjs). This file is
19
+ // the rest: the readings, on a timer each, the effects a key asks for, and the
20
+ // terminal handed back on every way out — q, a signal, a closed connection, a
21
+ // throw.
22
+ import { spawn } from "node:child_process";
23
+ import { join } from "node:path";
24
+ import { emitKeypressEvents } from "node:readline";
25
+ import {
26
+ EXIT, ask, autoRules, deckTrouble, load, rosterTrouble, silentDecks, switchHere, switchThroughDeck,
27
+ } from "./commands.js";
28
+ import { oneLine } from "../../src/server/cli-lines.mjs";
29
+ import { stripAnsi } from "../../src/server/term.mjs";
30
+ import { COMMAND, PKG_ROOT } from "./package.js";
31
+ import { G, LINKS, P, PROFILE, UNICODE } from "./screen.js";
32
+
33
+ /** How often each reading is taken while the screen is up. The sessions are
34
+ * the ones a person is waiting to see change; the roster is the deck's own
35
+ * cached read, which its panel polls about as often. */
36
+ export const POLL_MS = Object.freeze({ sessions: 3_000, auto: 10_000, roster: 15_000, find: 5_000 });
37
+
38
+ /** How long a deck started from here is waited for before saying it did not
39
+ * come up. A first run installs hooks and claude-swap before it listens. */
40
+ export const START_WAIT_MS = 90_000;
41
+
42
+ /**
43
+ * Run the screen until q, resolving to the exit code. `deps` replaces the
44
+ * terminal, the clock and the deck for a test: `input`, `output`, `now`,
45
+ * `source` (see deckSource), `tone`, `g`, `unicode`, `profile`, `links`,
46
+ * `tickMs`.
47
+ */
48
+ export async function runTui(flags, out, deps = {}) {
49
+ const input = deps.input ?? process.stdin;
50
+ const output = deps.output ?? process.stdout;
51
+ if (out.json) {
52
+ return out.fail(EXIT.USAGE, "interactive_only", [
53
+ `\`${COMMAND} tui\` is a screen for a person ${G.dash} \`${COMMAND} accounts --json\` and \`${COMMAND} sessions --json\` are the ones for a script`,
54
+ ]);
55
+ }
56
+ if (!input.isTTY || !output.isTTY) {
57
+ return out.fail(EXIT.USAGE, "not_a_terminal", [
58
+ `\`${COMMAND} tui\` needs a terminal at both ends ${G.dash} \`${COMMAND} accounts\` and \`${COMMAND} sessions\` print the same thing once`,
59
+ ]);
60
+ }
61
+ const view = await load("src/server/tui-view.mjs");
62
+ const { createScreen } = await load("src/server/tui-screen.mjs");
63
+ const { accountName, bestAccount } = await load("src/server/account-pick.mjs");
64
+ const port = flags.port != null ? Number(flags.port) : null;
65
+ const src = deps.source ?? deckSource(port);
66
+ const look = {
67
+ tone: deps.tone ?? P, g: deps.g ?? G, unicode: deps.unicode ?? UNICODE, profile: deps.profile ?? PROFILE, links: deps.links ?? LINKS,
68
+ };
69
+ const g = look.g;
70
+ const clock = deps.now ?? Date.now;
71
+
72
+ // The deck is looked for before the screen is taken, so a `--port` nobody
73
+ // listens on is answered on the command line, the way the commands answer it.
74
+ let deck = await src.find();
75
+ if (!deck && port != null) {
76
+ return out.fail(EXIT.NO_DECK, "no_deck", `no deck is listening on ${port} ${G.dash} \`${COMMAND} status\` lists them`);
77
+ }
78
+
79
+ let state = { ...view.initialState(), deck: deck ? { port: deck.port, version: deck.version ?? null } : null };
80
+ const last = { roster: 0, auto: 0, sessions: 0, signin: 0, find: clock() };
81
+ const inflight = new Set();
82
+ const screen = createScreen(s => output.write(s));
83
+ let done = null;
84
+
85
+ const set = (patch) => { state = { ...state, ...patch }; };
86
+ const tell = (tone, text) => set({ notice: view.note(tone, text, clock()) });
87
+ const size = () => ({
88
+ columns: Number.isInteger(output.columns) && output.columns > 0 ? output.columns : 80,
89
+ rows: Number.isInteger(output.rows) && output.rows > 0 ? output.rows : 24,
90
+ });
91
+ const render = () => {
92
+ if (done) return;
93
+ const frame = view.tuiFrame(state, { ...size(), ...look, now: clock() });
94
+ if (frame.top !== state.top) set({ top: frame.top });
95
+ screen.paint(frame.lines, frame.run);
96
+ };
97
+
98
+ /** One reading at a time of each kind: a slow deck answers late, not twice.
99
+ * Timed from when it was asked, so a reading that finds the deck gone can
100
+ * make the next one due at once (`lost`). */
101
+ const once = (kind, work) => async (...args) => {
102
+ if (inflight.has(kind)) return;
103
+ inflight.add(kind);
104
+ last[kind] = clock();
105
+ try { await work(...args); } catch (e) {
106
+ if (READINGS[kind]) tell("err", `could not read ${READINGS[kind]} ${g.dash} ${e?.message ?? e}`);
107
+ } finally {
108
+ inflight.delete(kind);
109
+ render();
110
+ }
111
+ };
112
+
113
+ /** The deck stopped answering: back to looking for one, and to the store
114
+ * in the meantime. */
115
+ const lost = () => {
116
+ deck = null;
117
+ set({ deck: null, auto: null, sessions: null });
118
+ // A sign-in lives in the deck; one that stopped answering took it along.
119
+ if (view.signinRunning(state.signin)) {
120
+ state = view.withLogin(state, { state: "failed", error: "the deck stopped answering, and the sign-in ended with it", local: true });
121
+ }
122
+ last.find = 0;
123
+ last.roster = 0;
124
+ };
125
+
126
+ const readRoster = once("roster", async (force = false) => {
127
+ if (deck) {
128
+ const r = await src.ask(deck, { path: force ? "/api/claude-accounts?refresh=1" : "/api/claude-accounts" });
129
+ if (r.ok && r.body) {
130
+ state = view.withRoster(state, r.body, r.body.ok ? null : [].concat(rosterTrouble(r.body)));
131
+ set({ source: "deck", silent: [], readAt: clock() });
132
+ } else if (r.status === 0) lost();
133
+ else tell("err", deckTrouble(deck, r));
134
+ return;
135
+ }
136
+ const silent = await src.silent();
137
+ const roster = await src.localRoster();
138
+ state = view.withRoster(state, roster, roster?.ok ? null : [].concat(rosterTrouble(roster)));
139
+ set({ source: "local", silent });
140
+ });
141
+
142
+ const readAuto = once("auto", async () => {
143
+ if (!deck) return;
144
+ const r = await src.ask(deck, { path: "/api/cswap-auto" });
145
+ if (r.ok && r.body && typeof r.body === "object") set({ auto: r.body, readAt: clock() });
146
+ else if (r.status === 0) lost();
147
+ else set({ auto: null });
148
+ });
149
+
150
+ const readSessions = once("sessions", async () => {
151
+ if (!deck) return;
152
+ const r = await src.ask(deck, { path: "/api/sessions", timeoutMs: 3_000 });
153
+ if (r.ok && Array.isArray(r.body?.sessions)) {
154
+ set({ sessions: r.body.sessions, skew: typeof r.body.now === "number" ? r.body.now - clock() : 0, readAt: clock() });
155
+ } else if (r.status === 0) lost();
156
+ });
157
+
158
+ // Where the deck's sign-in is, while the page is up and the deck has one —
159
+ // never before the start was answered, when "idle" would only mean "not yet".
160
+ const readSignin = once("signin", async () => {
161
+ if (!deck || !state.signin?.login) return;
162
+ const r = await src.ask(deck, { path: "/api/claude-accounts/login" });
163
+ if (r.ok && typeof r.body?.state === "string" && view.signinRunning(state.signin)) {
164
+ state = view.withLogin(state, r.body);
165
+ } else if (r.status === 0) lost();
166
+ });
167
+
168
+ const readAll = (force) => Promise.all([readRoster(force), readAuto(), readSessions()]);
169
+
170
+ const lookForDeck = once("find", async () => {
171
+ const found = await src.find();
172
+ if (!found) return;
173
+ deck = found;
174
+ set({ deck: { port: found.port, version: found.version ?? null }, silent: [] });
175
+ readAll(true);
176
+ });
177
+
178
+ // ── what a key asks for ──────────────────────────────────────────────────
179
+
180
+ async function doSwitch(row) {
181
+ // A deck that came up since the last look owns the switch now.
182
+ if (!deck) {
183
+ const found = await src.find();
184
+ if (found) {
185
+ deck = found;
186
+ set({ deck: { port: found.port, version: found.version ?? null } });
187
+ } else {
188
+ const silent = await src.silent();
189
+ if (silent.length) {
190
+ set({ silent });
191
+ tell("err", `the deck on ${silent.map(d => d.port).join(", ")} is running but did not answer ${g.dash} not switching behind its back`);
192
+ return;
193
+ }
194
+ }
195
+ }
196
+ set({ busy: { text: `switching to ${accountName(row)}`, since: clock() }, notice: null });
197
+ render();
198
+ const result = deck ? await src.switchDeck(deck, row.num) : await src.switchHere(row.num);
199
+ set({ busy: null });
200
+ if (!result.ok && result.reason === "deck_timeout") {
201
+ tell("warn", `the deck has not finished switching to ${accountName(row)} ${g.dash} it may still land`);
202
+ } else if (!result.ok && result.reason === "login_expired") {
203
+ tell("err", `${accountName(row)}'s login expired ${g.dash} switching to it would sign every running session out`);
204
+ } else if (!result.ok) {
205
+ const why = result.reason === "no_cswap" ? `claude-swap is not installed`
206
+ : result.reason === "timeout" ? `claude-swap took too long to answer`
207
+ : result.output ? String(result.output).trim().split("\n").pop()
208
+ : result.reason ?? "the switch failed";
209
+ tell("err", `could not switch to ${accountName(row)} ${g.dash} ${why}`);
210
+ } else {
211
+ // Who follows the switch: every running Claude session, from its next
212
+ // message — the whole effect, and nowhere else on screen (? says when).
213
+ const live = Array.isArray(state.sessions)
214
+ ? state.sessions.filter(s => s.provider !== "codex" && s.state !== "ended").length
215
+ : 0;
216
+ const follows = live > 0
217
+ ? ` ${g.bullet} ${live} Claude session${live === 1 ? " moves" : "s move"} with it`
218
+ : "";
219
+ tell("ok", `switched to ${accountName(row)}${follows}`);
220
+ }
221
+ await readRoster(true);
222
+ }
223
+
224
+ async function doBest() {
225
+ const rows = state.roster?.ok ? state.roster.accounts : [];
226
+ const best = bestAccount(rows, await src.rules(deck, rows));
227
+ if (best.none) return tell("err", `no account can take the login ${g.dash} every one is disabled or needs a fresh sign-in`);
228
+ // What to do first, then why: the notice is one row, and at 80 columns
229
+ // its end is what a long email cuts off.
230
+ if (best.already) {
231
+ state = view.selectSlot(state, best.already.num);
232
+ return tell("ok", `already on ${KEPT[best.rule] ?? KEPT["most-room"]}: ${accountName(best.already)}`);
233
+ }
234
+ state = view.selectSlot(state, best.account.num);
235
+ tell("info", `enter switches to ${accountName(best.account)} ${g.dash} ${PICKED[best.rule] ?? PICKED["most-room"]}`);
236
+ }
237
+
238
+ async function doAuto(enabled) {
239
+ if (!deck) return;
240
+ set({ busy: { text: `turning Auto-switch ${enabled ? "on" : "off"}`, since: clock() }, notice: null });
241
+ render();
242
+ const r = await src.ask(deck, { method: "POST", path: "/api/cswap-auto", body: { action: "enable", enabled } });
243
+ set({ busy: null });
244
+ if (r.ok && r.body?.ok !== false) tell("ok", `Auto-switch ${enabled ? "on" : "off"}`);
245
+ else tell("err", `could not turn Auto-switch ${enabled ? "on" : "off"} ${g.dash} ${r.body?.reason ?? (r.status ? `the deck answered ${r.status}` : r.reason ?? "no reply")}`);
246
+ last.auto = 0;
247
+ await readAuto();
248
+ }
249
+
250
+ // ── adding an account, through the deck's sign-in ───────────────────────
251
+
252
+ const ADMIN = "/api/claude-accounts/admin";
253
+ /** Why the deck would not start a sign-in, when it said so by name. */
254
+ const START_REFUSED = {
255
+ already_running: "another sign-in is saving an account right now — try again in a moment",
256
+ bad_email: "the deck would not sign in with that address",
257
+ no_url: "the claude CLI did not print a sign-in link",
258
+ };
259
+
260
+ /** Why the deck would not take a code, when it said so by name and gave no
261
+ * sentence of its own. */
262
+ const CODE_REFUSED = {
263
+ not_prompted: "the claude CLI has not asked for a code yet — paste it once the page shows one",
264
+ not_waiting: "the deck is no longer waiting for a code",
265
+ };
266
+ // Which start is the latest: a page closed while the deck was still starting
267
+ // its sign-in is cancelled again once the deck answers, unless a newer one
268
+ // has the deck by then.
269
+ let attempt = 0;
270
+
271
+ async function doSigninStart() {
272
+ if (!deck || !state.signin) return;
273
+ const mine = ++attempt;
274
+ const { email } = state.signin;
275
+ set({ signin: { ...state.signin, started: true, login: null, code: "", sending: false, lastLive: "link" }, notice: null });
276
+ render();
277
+ // The deck answers once the CLI has printed its link, or has died trying.
278
+ const r = await src.ask(deck, { method: "POST", path: ADMIN, body: email ? { action: "login", email } : { action: "login" }, timeoutMs: 30_000 });
279
+ const body = r.body && typeof r.body === "object" ? r.body : null;
280
+ if (mine !== attempt || !view.signinRunning(state.signin)) {
281
+ // The cancel sent when the page closed can have found nothing to cancel
282
+ // yet, and the CLI would sit on its five minutes.
283
+ if (mine === attempt && deck && body?.state === "awaiting_code") {
284
+ src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 15_000 }).catch(() => {});
285
+ }
286
+ return;
287
+ }
288
+ if (r.ok && body?.ok !== false && typeof body?.state === "string") {
289
+ state = view.withLogin(state, body);
290
+ } else {
291
+ const why = body?.detail ?? (body?.reason ? START_REFUSED[body.reason] ?? body.error ?? body.reason : null)
292
+ ?? (r.status === 0 ? `the deck did not answer (${r.reason ?? "no reply"})` : deckTrouble(deck, r));
293
+ // `local`: the deck holds no sign-in of ours to let go of — only for a
294
+ // missing link did it start one, and fail it.
295
+ state = view.withLogin(state, { state: "failed", error: why, url: null, step: null, local: body?.reason !== "no_url" });
296
+ }
297
+ last.signin = clock();
298
+ }
299
+
300
+ async function doSigninCode(code) {
301
+ if (!deck || !state.signin) return;
302
+ // Answered when the CLI took it and the account is saved, or asked again —
303
+ // a minute at the most for the CLI, and the store's lock on top of it.
304
+ const r = await src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-code", code }, timeoutMs: 150_000 });
305
+ if (!state.signin?.started) return;
306
+ // The code is not kept, whatever the answer: a wrong one is copied again.
307
+ set({ signin: { ...state.signin, code: "", sending: false } });
308
+ const body = r.body && typeof r.body === "object" ? r.body : null;
309
+ if (body?.reason === "empty_code") return;
310
+ const why = () => body?.error ?? CODE_REFUSED[body?.reason] ?? body?.reason ?? deckTrouble(deck, r);
311
+ // A refusal names its reason even when the deck wrote no sentence for it:
312
+ // a code sent before the CLI asked for one would otherwise just vanish.
313
+ if (typeof body?.state === "string" && (body.ok !== false || body.state !== "idle")) {
314
+ state = view.withLogin(state, body.ok === false ? { ...body, error: why() } : body);
315
+ } else if (r.status === 0) lost();
316
+ else state = view.withLogin(state, { ...state.signin.login, error: why() });
317
+ last.signin = 0;
318
+ }
319
+
320
+ /** Let go of the deck's sign-in, and say so when the account in use did not
321
+ * go back — the one outcome the person must not miss. */
322
+ async function doSigninCancel({ quiet = false } = {}) {
323
+ if (!deck) return;
324
+ const r = await src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 15_000 });
325
+ const a = r.body?.activeAccount;
326
+ if (r.body?.restored === false) {
327
+ const who = a?.email || (a?.num != null ? `account ${a.num}` : null);
328
+ tell("warn", who ? `this machine is now signed in as ${who} ${g.dash} the account you were using could not be put back`
329
+ : `the account you were using could not be put back ${g.dash} check which one is in use`);
330
+ } else if (!quiet) tell("info", "sign-in cancelled");
331
+ await readRoster(true);
332
+ }
333
+
334
+ async function doSigninDone(account) {
335
+ await readRoster(true);
336
+ if (account?.num != null) state = view.selectSlot(state, Number(account.num));
337
+ if (account?.email) tell("ok", `${account.added === false ? "signed in again" : "added"}: ${account.email}`);
338
+ }
339
+
340
+ async function doStart() {
341
+ set({ starting: true, busy: { text: "starting the deck", since: clock() }, notice: null });
342
+ render();
343
+ let launcher;
344
+ try {
345
+ launcher = src.startDeck();
346
+ } catch (e) {
347
+ set({ starting: false, busy: null });
348
+ return tell("err", `could not start the deck ${g.dash} ${e?.message ?? e}`);
349
+ }
350
+ // The launcher stays until the deck answers and leaves with an error when
351
+ // it will not — a UI that was never built, a port it cannot have — so its
352
+ // last line is the reason, said at once rather than after the wait.
353
+ let failed = null;
354
+ launcher?.exited?.then(r => { if (r && r.code !== 0) failed = r; });
355
+ const until = clock() + START_WAIT_MS;
356
+ while (!done && clock() < until && !failed) {
357
+ await src.wait(1_000);
358
+ const found = await src.find();
359
+ if (found) {
360
+ deck = found;
361
+ set({ deck: { port: found.port, version: found.version ?? null }, starting: false, busy: null, silent: [] });
362
+ tell("ok", `the deck is running on ${found.port}`);
363
+ await readAll(true);
364
+ return;
365
+ }
366
+ }
367
+ set({ starting: false, busy: null });
368
+ if (done) return;
369
+ if (failed?.said) tell("err", `the deck did not start ${g.dash} ${failed.said}`);
370
+ else tell("err", `the deck did not come up ${g.dash} \`${COMMAND} --logs\` shows what it wrote`);
371
+ }
372
+
373
+ const effects = {
374
+ switch: (e) => doSwitch(e.account),
375
+ best: () => doBest(),
376
+ auto: (e) => doAuto(e.enabled),
377
+ refresh: () => readAll(true),
378
+ start: () => doStart(),
379
+ "signin-start": () => doSigninStart(),
380
+ "signin-code": (e) => doSigninCode(e.code),
381
+ "signin-cancel": (e) => doSigninCancel(e),
382
+ "signin-done": (e) => doSigninDone(e.account),
383
+ };
384
+
385
+ return new Promise(resolve => {
386
+ const wasRaw = input.isRaw === true;
387
+ let timer = null;
388
+ const finish = (code = EXIT.OK) => {
389
+ if (done) return;
390
+ done = { code };
391
+ clearInterval(timer);
392
+ input.off("keypress", onKey);
393
+ output.off?.("resize", onResize);
394
+ output.off?.("error", onGone);
395
+ for (const sig of SIGNALS) process.off(sig, onSignal);
396
+ process.off("exit", onExit);
397
+ process.off("uncaughtException", onCrash);
398
+ process.off("unhandledRejection", onCrash);
399
+ // The keys stop being read before the mode goes back. On Windows, raw
400
+ // mode ended while they were still read left the PowerShell that ran us
401
+ // dead behind us: not one more line ran, and an SSH session closed.
402
+ input.pause();
403
+ try { input.setRawMode?.(wasRaw); } catch { /* the terminal went away */ }
404
+ screen.leave();
405
+ resolve(code);
406
+ };
407
+ // Every way out hands the terminal back: a signal (the SSH connection
408
+ // closing is a SIGHUP), the process ending under us, and a throw — which
409
+ // is printed after the screen is left, or the alternate screen would take
410
+ // the only account of it away with it.
411
+ // Out, with the deck's sign-in let go of first when this screen started
412
+ // one: left running, `claude auth login` would hold the next attempt for
413
+ // the rest of its five minutes. Not one refused before it began — the deck
414
+ // has only the sign-in somebody else is running then.
415
+ let leaving = false;
416
+ const leave = (code) => {
417
+ if (done || leaving) return;
418
+ const si = state.signin;
419
+ if (!deck || !si?.started || si.login?.state === "done" || si.login?.local) return finish(code);
420
+ leaving = true;
421
+ set({ busy: { text: "cancelling the sign-in", since: clock() } });
422
+ render();
423
+ const cancel = src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 3_000 }).catch(() => null);
424
+ Promise.race([cancel, src.wait(3_500)]).then(() => finish(code));
425
+ };
426
+ const onSignal = () => leave(EXIT.OK);
427
+ const onExit = () => screen.leave();
428
+ const onGone = () => finish(EXIT.FAILED);
429
+ const onCrash = (e) => {
430
+ finish(EXIT.FAILED);
431
+ process.stderr.write(`${COMMAND} tui: ${e?.stack ?? e}\n`);
432
+ };
433
+ const onResize = () => { screen.invalidate(); render(); };
434
+ function onKey(str, key) {
435
+ if (done || leaving) return;
436
+ const { state: next, effect } = view.tuiKey(state, str, key ?? {}, { now: clock(), g });
437
+ state = next;
438
+ if (effect?.type === "quit") return leave(EXIT.OK);
439
+ if (effect?.type === "redraw") screen.invalidate();
440
+ else if (effect && effects[effect.type]) {
441
+ Promise.resolve(effects[effect.type](effect)).catch(e => tell("err", String(e?.message ?? e))).finally(render);
442
+ }
443
+ render();
444
+ }
445
+ // The timer that keeps the screen current: the readings when they are due,
446
+ // and a repaint for the clock — the ages and the resets move, and a
447
+ // spinner while something is under way.
448
+ const tick = () => {
449
+ if (done) return;
450
+ const now = clock();
451
+ if (!deck) {
452
+ if (!state.starting && now - last.find >= POLL_MS.find) lookForDeck();
453
+ if (now - last.roster >= POLL_MS.roster * 2) readRoster(false);
454
+ } else {
455
+ if (now - last.sessions >= POLL_MS.sessions) readSessions();
456
+ if (now - last.auto >= POLL_MS.auto) readAuto();
457
+ if (now - last.roster >= POLL_MS.roster) readRoster(false);
458
+ if (view.signinRunning(state.signin) && now - last.signin >= view.signinPollMs(state.signin)) readSignin();
459
+ }
460
+ render();
461
+ };
462
+
463
+ emitKeypressEvents(input);
464
+ try { input.setRawMode?.(true); } catch { /* not a terminal after all: the keys still arrive */ }
465
+ input.resume();
466
+ input.on("keypress", onKey);
467
+ output.on?.("resize", onResize);
468
+ output.on?.("error", onGone);
469
+ for (const sig of SIGNALS) process.on(sig, onSignal);
470
+ process.on("exit", onExit);
471
+ process.on("uncaughtException", onCrash);
472
+ process.on("unhandledRejection", onCrash);
473
+ screen.enter();
474
+ render();
475
+ readAll(true);
476
+ timer = setInterval(tick, deps.tickMs ?? 100);
477
+ });
478
+ }
479
+
480
+ /** Why b went where it went, and where it stayed — `switch --best`'s rules
481
+ * (account-pick.mjs bestAccount), in the fewer words one row has room for. */
482
+ const PICKED = Object.freeze({ "most-room": "the most room", home: "your home account", "weekly-reset": "the soonest weekly reset" });
483
+ const KEPT = Object.freeze({
484
+ "most-room": "the account with the most room",
485
+ home: "your home account",
486
+ rules: "the account Auto-switch's rules keep",
487
+ });
488
+
489
+ /** What each reading is called when it fails; looking for a deck that is not
490
+ * there is not a failure. */
491
+ const READINGS = Object.freeze({ roster: "the accounts", auto: "Auto-switch", sessions: "the sessions" });
492
+
493
+ // SIGHUP is a closed SSH connection, and on Windows a closed console window;
494
+ // SIGBREAK is Windows' Ctrl+Break.
495
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", ...(process.platform === "win32" ? ["SIGBREAK"] : [])];
496
+
497
+ /**
498
+ * Where the screen's answers come from: the running deck through the commands'
499
+ * own helpers, and — with none — claude-swap's store in this process.
500
+ */
501
+ export function deckSource(port) {
502
+ return {
503
+ find: async () => {
504
+ const { findDeck } = await load("src/server/deck-client.mjs");
505
+ return findDeck({ port });
506
+ },
507
+ silent: () => silentDecks(port).catch(() => []),
508
+ ask: (deck, opts) => ask(deck, opts),
509
+ localRoster: async () => {
510
+ const { fetchClaudeAccounts } = await load("src/server/claude-accounts.mjs");
511
+ return fetchClaudeAccounts({ force: true });
512
+ },
513
+ switchDeck: (deck, num) => switchThroughDeck(deck, num),
514
+ switchHere: (num) => switchHere(num),
515
+ rules: (deck, accounts) => autoRules(deck, accounts),
516
+ // The bare start, as typed: it detaches itself and its launcher leaves
517
+ // once the deck is up. Never a browser — over SSH there is none to open,
518
+ // and at a desk the person asked for this screen, not a tab. `exited` is
519
+ // the launcher's code and the last line it printed, which on a failure is
520
+ // the reason.
521
+ startDeck: () => {
522
+ const child = spawn(process.execPath, [join(PKG_ROOT, "bin", "agent-dag.js"), "--no-open"], {
523
+ stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true,
524
+ env: { ...process.env, NO_COLOR: "1" },
525
+ });
526
+ let tail = "";
527
+ const keep = (d) => { tail = (tail + String(d)).slice(-4_000); };
528
+ child.stdout.on("data", keep);
529
+ child.stderr.on("data", keep);
530
+ const exited = new Promise(resolve => {
531
+ child.on("error", e => resolve({ code: -1, said: e.message }));
532
+ child.on("exit", code => {
533
+ const lines = tail.split(/\r?\n/).map(l => oneLine(stripAnsi(l))).filter(Boolean);
534
+ resolve({ code, said: lines.at(-1) ?? "" });
535
+ });
536
+ });
537
+ child.unref();
538
+ child.stdout.unref?.();
539
+ child.stderr.unref?.();
540
+ return { exited };
541
+ },
542
+ wait: (ms) => new Promise(r => setTimeout(r, ms)),
543
+ };
544
+ }
package/bin/deck.js CHANGED
@@ -15,6 +15,7 @@ import { pathToFileURL } from "node:url";
15
15
  import { existsSync } from "node:fs";
16
16
  import { RESTART_CODE, UPGRADE_CODE, dieWithParent, signalExitAction } from "../src/server/supervisor.mjs";
17
17
  import { parseArgs, startPort, wantsCli } from "../src/server/args.mjs";
18
+ import { watchForClis } from "../src/server/cli-arrival.mjs";
18
19
  import { unregisteredDetail } from "../src/server/pulse-line.mjs";
19
20
  import { PRODUCT } from "../src/server/brand.mjs";
20
21
  // A leaf — fs, path and claude-dir.mjs, nothing else — so it is imported here
@@ -36,7 +37,9 @@ import {
36
37
  G, P, fileLink, onHangup, printBanner, showCursor, step, takeCursor, tty, write,
37
38
  } from "./cli/screen.js";
38
39
  // The once-per-session work and the rows that report it.
39
- import { reportReady, reportRestarted, reportStartup, respawnHooks, startupWork } from "./cli/startup.js";
40
+ import {
41
+ reportClaudeArrived, reportReady, reportRestarted, reportStartup, respawnHooks, startupWork,
42
+ } from "./cli/startup.js";
40
43
  import { restartLatch } from "./cli/restart.js";
41
44
  import { startPulse } from "./cli/pulse.js";
42
45
  import { settleSecondStart } from "./cli/second-start.js";
@@ -252,6 +255,13 @@ const wantCodex = wantsCli({ off: flags.noCodex, on: flags.codex, installed: has
252
255
  // with a settings.json the installer refuses to rewrite needs, since that
253
256
  // refusal is fatal at boot on a component they do not use.
254
257
  const wantClaude = wantsCli({ off: flags.noClaude, on: flags.claude, installed: hasClaudeInstalled });
258
+ // A respawn that finds Claude Code where the session's first boot did not:
259
+ // installed while the deck ran, which is the restart src/server/cli-arrival.mjs
260
+ // asks for. The supervisor hands down how the first boot's hooks went, and
261
+ // "off" is "not attempted, no Claude Code". Such a respawn owes everything the
262
+ // first boot skipped for it — the hooks, claude-swap, the ccusage prime — so it
263
+ // runs the first boot's work rather than a respawn's. See reportClaudeArrived.
264
+ const claudeArrived = RESPAWN && wantClaude && process.env.AGENTS_DECK_BOOT_HOOKS === "off";
255
265
  // The Codex tree this deck would tail, spelled the way its discovery record will
256
266
  // spell it — the one field of a start's shape that is not a flag. Resolved here,
257
267
  // with the other three, because the second-start question below is asked of
@@ -429,6 +439,11 @@ if (!RESPAWN) {
429
439
  jobs.cswapQuiet.then(settleCswap);
430
440
  await printBanner();
431
441
  await reportStartup(jobs, { workspace, wantClaude, wantCodex, CODEX_SESSIONS_DIR });
442
+ } else if (claudeArrived) {
443
+ const jobs = startupWork({ wantClaude, installHooks, leftoverCodexHooks });
444
+ handDownSetup(noteSetup({ claude: jobs.hooks, codex: wantCodex }));
445
+ jobs.cswapQuiet.then(settleCswap);
446
+ await reportClaudeArrived(jobs);
432
447
  } else {
433
448
  settleCswap();
434
449
  // What a respawn says about the hooks is what it saw: its own re-install when
@@ -599,6 +614,22 @@ markDeckReady();
599
614
  try { process.send?.({ type: "booted" }); } catch { /* no channel; nothing waiting */ }
600
615
  runHeldRestart();
601
616
 
617
+ // A CLI installed while this deck runs is served from the restart this asks for
618
+ // — see src/server/cli-arrival.mjs. Only under a supervisor, which is the only
619
+ // thing that can bring the deck back.
620
+ if (SUPERVISED) {
621
+ watchForClis({
622
+ clis: [
623
+ { name: "Claude Code", want: wantClaude, off: flags.noClaude, installed: hasClaudeInstalled },
624
+ { name: "Codex", want: wantCodex, off: flags.noCodex, installed: hasCodexInstalled },
625
+ ],
626
+ onArrive: (name) => {
627
+ write(`\n ${P.ok}${G.ok}${P.reset} ${P.muted}${name} found ${G.dash} restarting to serve it${P.reset}\n`);
628
+ requestRestart();
629
+ },
630
+ });
631
+ }
632
+
602
633
  /**
603
634
  * A declaration, not the `const` arrow this was for eight months.
604
635
  *