ccdeck 3.82.4 → 4.0.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 (145) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/tui.js +58 -4
  5. package/bin/deck.js +27 -1
  6. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  7. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  10. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  12. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  13. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  14. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  16. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  17. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  18. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  19. package/dist/web/assets/app-40gNTTfq.js +361 -0
  20. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-XIY3yFiN.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  23. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  26. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  27. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  28. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  29. package/dist/web/index.html +16 -6
  30. package/package.json +13 -1
  31. package/release-notes.json +67 -0
  32. package/src/server/account-client.mjs +196 -0
  33. package/src/server/account-connect.mjs +238 -0
  34. package/src/server/account-flag.mjs +106 -0
  35. package/src/server/account-projects.mjs +1 -1
  36. package/src/server/account-service.mjs +532 -0
  37. package/src/server/account-status.mjs +293 -0
  38. package/src/server/account-store.mjs +137 -0
  39. package/src/server/account-sync.mjs +473 -0
  40. package/src/server/account-token-store.mjs +216 -0
  41. package/src/server/account-ui-fields.mjs +126 -0
  42. package/src/server/account-watch.mjs +1 -1
  43. package/src/server/browser-watch-log.mjs +1 -1
  44. package/src/server/browser-watch-store.mjs +1 -1
  45. package/src/server/ccdeck-account-routes.mjs +252 -0
  46. package/src/server/ccusage-install.mjs +2 -2
  47. package/src/server/ccusage-registry.mjs +4 -4
  48. package/src/server/ccusage-session.mjs +11 -0
  49. package/src/server/claude-accounts.mjs +1 -1
  50. package/src/server/claude-recovery.mjs +9 -4
  51. package/src/server/claude-settings-catalog.mjs +6 -6
  52. package/src/server/claude-settings.mjs +1 -1
  53. package/src/server/codex-auto.mjs +1 -1
  54. package/src/server/codex-cost-usage.mjs +7 -2
  55. package/src/server/codex-live-checkpoint.mjs +24 -9
  56. package/src/server/codex-live-engine.mjs +14 -4
  57. package/src/server/codex-live-handoff.mjs +53 -9
  58. package/src/server/codex-names.mjs +49 -0
  59. package/src/server/codex-translate.mjs +1 -1
  60. package/src/server/codex-ultrafast.d.mts +3 -0
  61. package/src/server/codex-ultrafast.mjs +5 -0
  62. package/src/server/codex-watch.mjs +25 -0
  63. package/src/server/command-panel-engine.mjs +300 -0
  64. package/src/server/command-panel-platform.mjs +99 -0
  65. package/src/server/cswap-auto-choice.mjs +1 -1
  66. package/src/server/cswap-auto-loop.mjs +1 -1
  67. package/src/server/cswap-install.mjs +21 -40
  68. package/src/server/deck-home.mjs +6 -0
  69. package/src/server/deck-prefs.mjs +53 -1
  70. package/src/server/detach.mjs +1 -1
  71. package/src/server/engine-download.mjs +277 -0
  72. package/src/server/engine-install.mjs +378 -0
  73. package/src/server/engine-package.mjs +267 -0
  74. package/src/server/event-log.mjs +7 -1
  75. package/src/server/event-pipeline.mjs +29 -1
  76. package/src/server/ghostty-handoff.mjs +81 -0
  77. package/src/server/index.mjs +143 -5
  78. package/src/server/installer.mjs +4 -1
  79. package/src/server/integrations/jira-write-guard.mjs +14 -208
  80. package/src/server/integrations/store.mjs +37 -19
  81. package/src/server/integrations/write-guard.mjs +223 -0
  82. package/src/server/intel-cpu-temperature.mjs +26 -0
  83. package/src/server/lifecycle.mjs +69 -6
  84. package/src/server/log-replay.mjs +4 -0
  85. package/src/server/login-service.mjs +7 -1
  86. package/src/server/macmon.mjs +1 -1
  87. package/src/server/npm-latest.mjs +1 -1
  88. package/src/server/org-telemetry.mjs +1 -1
  89. package/src/server/output-watch.mjs +4 -1
  90. package/src/server/panel-provenance.mjs +390 -0
  91. package/src/server/pinned-build.mjs +14 -0
  92. package/src/server/prefs-refusal.mjs +8 -1
  93. package/src/server/prefs-routes.mjs +60 -11
  94. package/src/server/pro-engine-client.mjs +339 -0
  95. package/src/server/pro-engine-install.mjs +294 -0
  96. package/src/server/pro-engine-terminal.mjs +308 -0
  97. package/src/server/project-discovery.mjs +139 -0
  98. package/src/server/provider-session-name.mjs +58 -0
  99. package/src/server/quota-closes.mjs +1 -1
  100. package/src/server/quota-history.mjs +1 -1
  101. package/src/server/reports.mjs +86 -21
  102. package/src/server/request-gates.mjs +34 -5
  103. package/src/server/restart-note.mjs +1 -1
  104. package/src/server/seed-boundary.mjs +489 -0
  105. package/src/server/session-counts.mjs +244 -0
  106. package/src/server/session-deck-names.mjs +143 -0
  107. package/src/server/session-enrichment.mjs +43 -6
  108. package/src/server/session-name-route.mjs +73 -0
  109. package/src/server/session-summary.mjs +12 -1
  110. package/src/server/session-transcript-routes.mjs +167 -0
  111. package/src/server/swap-log.mjs +1 -1
  112. package/src/server/system-metrics.mjs +57 -0
  113. package/src/server/terminal-bridge.mjs +485 -0
  114. package/src/server/terminal-folder.mjs +61 -0
  115. package/src/server/terminal-js-routes.mjs +752 -0
  116. package/src/server/terminal-routes.mjs +553 -0
  117. package/src/server/terminal-sessions.mjs +759 -0
  118. package/src/server/terminal-socket.mjs +403 -0
  119. package/src/server/terminal-target.mjs +928 -0
  120. package/src/server/thermal-metrics.mjs +13 -9
  121. package/src/server/tmux-control.mjs +1319 -0
  122. package/src/server/tmux-download.mjs +220 -0
  123. package/src/server/tmux.mjs +542 -0
  124. package/src/server/token-redact.mjs +42 -3
  125. package/src/server/tool-audit-report.mjs +44 -6
  126. package/src/server/tool-audit-routes.mjs +12 -1
  127. package/src/server/tool-audit.mjs +42 -8
  128. package/src/server/traffic-radar-monitor.mjs +1 -1
  129. package/src/server/traffic-radar-permission.mjs +1 -1
  130. package/src/server/transcript-gate.mjs +1 -1
  131. package/src/server/transcript-scan.mjs +15 -7
  132. package/src/server/transcript-turns.mjs +154 -0
  133. package/src/server/tui-network.mjs +1 -0
  134. package/src/server/tui-view.mjs +28 -0
  135. package/src/server/utf8-carry.mjs +159 -0
  136. package/src/server/uv-bootstrap.mjs +2 -2
  137. package/src/server/windows-acl.mjs +158 -0
  138. package/src/server/ws-frames.mjs +690 -0
  139. package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
  140. package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
  141. package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
  142. package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
  143. package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
  144. package/dist/web/assets/app-BHxsMz3-.js +0 -358
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
@@ -0,0 +1,308 @@
1
+ // The Command Panel's socket and routes, which the optional local engine
2
+ // runs.
3
+ //
4
+ // terminal-socket.mjs keeps everything the browser touches — the upgrade's
5
+ // gates in their order, the shutdown 503, the ticket and its origin,
6
+ // MAX_TERMINALS, the WebSocket itself — and hands a socket here only once all
7
+ // of that has said yes and the ticket's binding is an engine handle. What
8
+ // happens here is the engine's attach and then the relay: each message the
9
+ // panel sends goes to the engine as it came, and each one the engine sends
10
+ // goes to the panel as it came, in order, one WebSocket message for one
11
+ // message on the stream. The wire is docs/contracts/pro-engine-host-v1.md,
12
+ // "Terminal streams".
13
+ //
14
+ // NOTHING HERE NAMES A PANE. The engine is handed the handle a route got from
15
+ // it and a stream id, and it answers with that id and the panel's own
16
+ // messages. No pid, pane, socket or path crosses, in either direction.
17
+ //
18
+ // THE ROUTES ARE ASKED THE SAME WAY. terminal-routes.mjs keeps the switch, the
19
+ // gates, the body's cap and the ticket store; the engine answers each route's
20
+ // question with the status and body the page reads, and where that carries a
21
+ // ticket, an opaque `handle` the deck mints its ticket over
22
+ // (routeThroughEngine). What the engine could not take is answered as a
23
+ // refusal the page can draw (engineRefusal), never by some other terminal:
24
+ // there is none behind it.
25
+ //
26
+ // Neither terminal-socket.mjs nor terminal-routes.mjs reaches a client from
27
+ // here: the deck builds engineTerminals(client) where it creates the client
28
+ // and passes it to the routes and the upgrade as `engine`.
29
+ import { UNSAFE_FOLDER } from "./pro-engine-install.mjs";
30
+
31
+ /**
32
+ * The refusals the panel's routes answer when the engine cannot take the
33
+ * question, by `code`: `{ ok: false, error, code }`, `error` one short
34
+ * sentence the page may show. 409 is a state of this machine the panel says
35
+ * and stops at; 503 is a moment it waits out, reconnecting; 400 is a request
36
+ * the engine would not read. A failure that may have changed something is
37
+ * none of these: it throws, which is the deck's 500, and is never asked
38
+ * again.
39
+ */
40
+ const REFUSALS = Object.freeze({
41
+ unsupported: [409, "The Command Panel is not available on this platform yet."],
42
+ "not-installed": [409, "The Command Panel's engine is not installed on this machine."],
43
+ "not-verified": [409, "The Command Panel's engine could not be verified, so it was not started."],
44
+ "unsafe-folder": [409, "The Command Panel's engine was not started: other users can change a folder above it."],
45
+ "no-terminal": [409, "The Command Panel's engine here cannot open sessions."],
46
+ failed: [409, "The Command Panel's engine would not start."],
47
+ restarting: [503, "The Command Panel's engine is restarting."],
48
+ busy: [503, "The Command Panel is busy. Try again in a moment."],
49
+ "no-answer": [503, "The Command Panel's engine did not answer in time."],
50
+ "bad-request": [400, "The Command Panel could not read that request."],
51
+ });
52
+
53
+ /** The route answer for refusal `code` (a key of REFUSALS), in the shape the
54
+ * engine's own answers take: `{ status, body }`. */
55
+ export function engineRefusal(code) {
56
+ const known = Object.hasOwn(REFUSALS, code) ? code : "failed";
57
+ const [status, error] = REFUSALS[known];
58
+ return { status, body: { ok: false, error, code: known } };
59
+ }
60
+
61
+ /** How an attach the engine refused is answered: a request it could not read
62
+ * is the deck's own fault (500), a handle it would not redeem is a ticket
63
+ * that was no good (401). Anything else — busy, switched off, no answer in
64
+ * time, the engine gone — is a deck that cannot take the socket now (503). */
65
+ const REFUSED = new Map([["bad_params", 500], ["invalid_handle", 401]]);
66
+
67
+ /** How long a shutdown waits for the engine's own close before the socket is
68
+ * ended anyway: the deck's whole shutdown has a second and a half. */
69
+ export const SHUTDOWN_GRACE_MS = 1_500;
70
+
71
+ /** A relayed socket whose engine has gone away is closed 1011 with no `exit`
72
+ * before it, so its panel reconnects with a new ticket. The reason is the one
73
+ * a failing handler gets in ws-frames, so it says no more than that does. */
74
+ const LOST_REASON = "the server could not handle a message";
75
+
76
+ /** The routes that change something: a launch, an adopt, an open (which may
77
+ * start a wrapper), a claim (which labels a pane) and an end of the sessions
78
+ * on an older session host. Once one may have reached the engine it is
79
+ * never asked again — that could be a second agent, or an end nobody
80
+ * reviewed. */
81
+ const MUTATIONS = new Set(["claim", "open", "adopt", "launch", "endHosts"]);
82
+
83
+ /** A request's errors that say the engine never ran it, whatever the route,
84
+ * and the refusal each is: not serving terminals, too many requests, one
85
+ * that was not well formed, or no engine to send it to yet. */
86
+ const NOT_RUN = new Map([
87
+ ["unavailable", "no-terminal"],
88
+ ["busy", "busy"],
89
+ ["invalid_request", "bad-request"],
90
+ ["bad_params", "bad-request"],
91
+ ["backoff", "restarting"],
92
+ ["disabled", "failed"],
93
+ ]);
94
+
95
+ /** What a read (status, target, hosts) that went unanswered is refused as: the
96
+ * engine went away under it, or it took too long. Asking a read again
97
+ * changes nothing, so the page waits and asks. */
98
+ const READ_LOST = new Map([
99
+ ["timeout", "no-answer"],
100
+ ["exited", "restarting"],
101
+ ["closed", "restarting"],
102
+ ["transport", "restarting"],
103
+ ["heartbeat", "restarting"],
104
+ ["protocol", "restarting"],
105
+ ["startup", "restarting"],
106
+ ["cancellation_failed", "restarting"],
107
+ ["incompatible", "failed"],
108
+ ]);
109
+
110
+ /** What an engine route answers: `status` and `body` for the page, and maybe
111
+ * a `handle` where that body's ticket is, a line for the deck's log, and
112
+ * `fixable` on a status with no tmux the engine can use, which the deck
113
+ * could fetch its own of (terminal-routes.mjs' withOwnTmux). */
114
+ const ANSWER_KEYS = new Set(["status", "body", "handle", "log", "fixable"]);
115
+ const HANDLE = /^[0-9a-f]{64}$/;
116
+
117
+ /**
118
+ * What the deck takes as the optional local engine's terminal, for `client`
119
+ * (pro-engine-client.mjs), built once where the client is created and handed
120
+ * to the routes and the upgrade as `engine`: whether the client is enabled,
121
+ * the attach for an upgrade admitted with an engine ticket
122
+ * (installTerminalUpgrade's `engine`), the route methods
123
+ * (terminal-routes.mjs), and the forget the deck sends once its own tmux has
124
+ * landed.
125
+ */
126
+ export function engineTerminals(client) {
127
+ return Object.freeze({
128
+ get enabled() { return client.enabled === true; },
129
+ attach: (handle, socket) => attachThroughEngine(client, handle, socket),
130
+ route: (method, body) => routeThroughEngine(client, method, body),
131
+ forgetTmux: () => forgetTmuxInEngine(client),
132
+ });
133
+ }
134
+
135
+ /** A tmux the deck fetched has landed: a running engine forgets the miss it
136
+ * remembered, so its next status finds the build. One not running has none,
137
+ * and is asked nothing. Answers once the engine has, and never rejects: a
138
+ * forget that did not reach it leaves the miss it had. */
139
+ function forgetTmuxInEngine(client) {
140
+ if (!client.running) return Promise.resolve();
141
+ return client.request("terminal.forgetTmux", { body: null }).then(() => {}, () => {});
142
+ }
143
+
144
+ /**
145
+ * The engine's answer to one of the panel's routes (`method` is the route's
146
+ * name: status, target, hosts, claim, open, adopt, launch, endHosts), asked as
147
+ * `terminal.<method>` with `{ body }`, the route's parsed question. Answers
148
+ * the checked answer, or the refusal (engineRefusal) for an engine that did
149
+ * not take it:
150
+ *
151
+ * - it would not start: `restarting` while its restart waits out a backoff
152
+ * or it is closing, `no-answer` when starting took too long,
153
+ * `not-verified` for an installation that did not verify, `failed` for
154
+ * anything else;
155
+ * - its hello said it serves no terminal here: `no-terminal`;
156
+ * - it turned the request away before running it (NOT_RUN);
157
+ * - a read it did not answer (READ_LOST).
158
+ *
159
+ * Throws — the deck's own 500, through `guard` — for `internal`, for a
160
+ * mutation that may have reached it and was not answered (MUTATIONS), for any
161
+ * other error, and for an answer that is not one.
162
+ */
163
+ export async function routeThroughEngine(client, method, body) {
164
+ try {
165
+ await client.start();
166
+ } catch (error) {
167
+ return engineRefusal(startRefusal(error?.code));
168
+ }
169
+ const backend = client.capabilities?.terminal?.backend;
170
+ if (!backend || backend === "unavailable") return engineRefusal("no-terminal");
171
+ let answer;
172
+ try {
173
+ answer = await client.request(`terminal.${method}`, { body });
174
+ } catch (error) {
175
+ const code = error?.code;
176
+ if (NOT_RUN.has(code)) return engineRefusal(NOT_RUN.get(code));
177
+ if (!MUTATIONS.has(method) && READ_LOST.has(code)) return engineRefusal(READ_LOST.get(code));
178
+ throw error;
179
+ }
180
+ if (!isAnswer(answer)) throw new Error("The terminal engine's answer was not a route answer.");
181
+ return answer;
182
+ }
183
+
184
+ /** The refusal for a client that would not start, by its error's code. A
185
+ * verification failure has none (pro-engine-install.mjs), but for a folder
186
+ * above the engine that other accounts can change, which says so. */
187
+ function startRefusal(code) {
188
+ if (code === "backoff" || code === "closed") return "restarting";
189
+ if (code === "timeout") return "no-answer";
190
+ if (code === undefined) return "not-verified";
191
+ if (code === UNSAFE_FOLDER) return UNSAFE_FOLDER;
192
+ return "failed";
193
+ }
194
+
195
+ function isAnswer(a) {
196
+ if (!a || typeof a !== "object" || Array.isArray(a) || !Object.keys(a).every((k) => ANSWER_KEYS.has(k))) return false;
197
+ if (!Number.isInteger(a.status) || a.status < 200 || a.status > 599 || !("body" in a)) return false;
198
+ const object = !!a.body && typeof a.body === "object" && !Array.isArray(a.body);
199
+ // A handle stands where the body's ticket is; `fixable` comes with a tmux to answer for.
200
+ if (a.handle !== undefined && (typeof a.handle !== "string" || !HANDLE.test(a.handle) || !object || a.body.ticket !== null)) return false;
201
+ if (a.fixable !== undefined && (typeof a.fixable !== "boolean" || !object || !a.body.tmux || typeof a.body.tmux !== "object")) return false;
202
+ return a.log === undefined || typeof a.log === "string";
203
+ }
204
+
205
+ /**
206
+ * Ask `engine` to attach `handle` for `socket`, whose upgrade is not answered
207
+ * yet. Answers `{ ok: true, start(conn), giveUp() }` once the engine has
208
+ * attached it, or `{ ok: false, status }` with the status to refuse the
209
+ * upgrade with. A socket that goes away before the answer gives the attach up
210
+ * at once, which tells the engine (`close`) and frees its place.
211
+ */
212
+ export async function attachThroughEngine(engine, handle, socket) {
213
+ if (socket.destroyed) return { ok: false, status: 503 };
214
+ const abort = new AbortController();
215
+ const gone = () => abort.abort();
216
+ socket.once("close", gone);
217
+ let stream;
218
+ try {
219
+ stream = await engine.attachTerminal(handle, { signal: abort.signal });
220
+ } catch (error) {
221
+ return { ok: false, status: REFUSED.get(error?.code) ?? 503 };
222
+ } finally {
223
+ socket.off("close", gone);
224
+ }
225
+ return {
226
+ ok: true,
227
+ giveUp: () => stream.close(),
228
+ start: (conn) => {
229
+ try {
230
+ return relay(stream, conn, socket);
231
+ } catch (error) {
232
+ stream.close();
233
+ throw error;
234
+ }
235
+ },
236
+ };
237
+ }
238
+
239
+ /**
240
+ * The relay for one attached stream, in the shape installTerminalUpgrade
241
+ * expects of a bridge: `{ message(m), closed(code, reason), shutdown(reason,
242
+ * text) }`. What the engine sent before the 101 goes down the socket first.
243
+ */
244
+ function relay(stream, conn, socket) {
245
+ // Set by shutdown: the socket is ended once the engine's close has gone
246
+ // down it, or when this runs out, whichever is first.
247
+ let ending = null;
248
+ // Reading stopped for the input window (paused) — never resumed by anything
249
+ // but what paused it, so the socket is not set flowing ahead of its reader.
250
+ let paused = false;
251
+ const end = () => {
252
+ clearTimeout(ending);
253
+ try { socket.end(); } catch { /* already gone */ }
254
+ };
255
+ const resume = () => {
256
+ if (!paused) return;
257
+ paused = false;
258
+ socket.resume();
259
+ };
260
+ const drained = () => stream.flow();
261
+ socket.on("drain", drained);
262
+
263
+ // The stream has ended: what the panel sends now goes nowhere, but its
264
+ // answer to the close still has to be read.
265
+ function finish(code, reason) {
266
+ resume();
267
+ try { conn.close(code, reason); } catch { /* already closing */ }
268
+ if (ending) end();
269
+ }
270
+
271
+ stream.start({
272
+ binary: (bytes) => conn.sendBinary(bytes),
273
+ text: (bytes) => conn.sendText(bytes.toString("utf8")),
274
+ close: (code, reason) => finish(code, reason),
275
+ lost: () => finish(1011, LOST_REASON),
276
+ // bufferedAmount only while the socket waits for 'drain'; the bridge's
277
+ // decisions are all far above Node's own high-water mark.
278
+ buffered: () => (socket.writableNeedDrain ? conn.bufferedAmount : 0),
279
+ resume,
280
+ });
281
+
282
+ return {
283
+ message({ type, data }) {
284
+ if (stream.send(type === "binary" ? "binary" : "text", data)) return;
285
+ // Held for the input window, with everything after it: nothing more is
286
+ // read from the socket until the engine has taken enough.
287
+ paused = true;
288
+ socket.pause();
289
+ },
290
+ closed() {
291
+ clearTimeout(ending);
292
+ socket.off("drain", drained);
293
+ stream.close();
294
+ },
295
+ shutdown(reason = "server-shutdown", text) {
296
+ if (ending) return;
297
+ ending = setTimeout(end, SHUTDOWN_GRACE_MS);
298
+ ending.unref?.();
299
+ let sent = false;
300
+ try { sent = stream.shutdown(reason, text); } catch { /* not a reason the engine can be sent */ }
301
+ if (sent) return;
302
+ // Nothing left to tell it: closed here, as closeOpenTerminals closes a
303
+ // socket with no bridge.
304
+ try { conn.close(reason === "server-shutdown" ? 1001 : 1000, reason); } catch { /* already closing */ }
305
+ end();
306
+ },
307
+ };
308
+ }
@@ -0,0 +1,139 @@
1
+ // New session suggestions: repository folders, not a filesystem browser.
2
+ // Inspect directory entries and Git worktree pointers, never source files,
3
+ // Git configuration or credentials.
4
+ import { constants } from 'node:fs';
5
+ import { access, lstat, open, opendir, realpath } from 'node:fs/promises';
6
+ import { homedir } from 'node:os';
7
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
8
+
9
+ const SKIP = new Set(['node_modules', 'vendor', 'dist', 'build', 'bin', 'obj', '__tests__']);
10
+ const denied = error => error?.code === 'EACCES' || error?.code === 'EPERM';
11
+
12
+ // Git metadata here is a single short line. A stale link, symlink, or ordinary
13
+ // file posing as a .git pointer should not turn discovery into a file reader.
14
+ async function metadataLine(path) {
15
+ if (!(await lstat(path)).isFile()) return '';
16
+ const file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
17
+ try {
18
+ const limit = 8192;
19
+ const stat = await file.stat();
20
+ if (!stat.isFile() || stat.size > limit) return '';
21
+ const buffer = Buffer.alloc(limit + 1);
22
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
23
+ if (bytesRead > limit) return '';
24
+ const line = buffer.toString('utf8', 0, bytesRead).replace(/\r?\n$/, '');
25
+ return /[\r\n\0]/.test(line) ? '' : line;
26
+ } finally {
27
+ await file.close();
28
+ }
29
+ }
30
+
31
+ async function linkedWorktree(admin, project) {
32
+ const common = await metadataLine(join(admin, 'commondir'));
33
+ if (!common || await realpath(resolve(admin, common)) !== await realpath(join(project.cwd, '.git'))) return null;
34
+ const gitdir = await metadataLine(join(admin, 'gitdir'));
35
+ if (!gitdir) return null;
36
+ // Relative pointers are resolved from the directory containing the pointer,
37
+ // just as Git does for worktrees created with --relative-paths.
38
+ const marker = isAbsolute(gitdir) ? gitdir : resolve(admin, gitdir);
39
+ if (basename(marker) !== '.git') return null;
40
+ const cwd = await realpath(dirname(marker));
41
+ if (cwd === project.cwd) return null;
42
+ const pointer = await metadataLine(join(cwd, '.git'));
43
+ if (!pointer.startsWith('gitdir: ')) return null;
44
+ if (await realpath(resolve(cwd, pointer.slice(8))) !== await realpath(admin)) return null;
45
+ await access(cwd, constants.R_OK | constants.X_OK);
46
+ const head = await metadataLine(join(admin, 'HEAD')).catch(() => '');
47
+ const branch = head.startsWith('ref: refs/heads/') ? head.slice(16) : '';
48
+ return {
49
+ cwd,
50
+ name: basename(cwd),
51
+ worktree: { projectCwd: project.cwd, projectName: project.name, ...(branch ? { branch } : {}) },
52
+ };
53
+ }
54
+ export function projectRoots(home = homedir()) {
55
+ return ['Desktop', 'Documents', 'Developer', 'Projects', 'projects', 'repos', 'Code', 'code', 'src', 'workspace']
56
+ .map(name => join(home, name));
57
+ }
58
+
59
+ export async function scanProjectFolders({ roots = projectRoots(), maxDepth = 3, maxDirs = 500,
60
+ maxProjects = 150, maxEntries = 10000, budgetMs = 1500, now = Date.now } = {}) {
61
+ const queue = roots.map(cwd => ({ cwd, depth: 0 })), seen = new Set(), projects = [];
62
+ const deadline = now() + budgetMs;
63
+ let visited = 0, entries = 0, truncated = false;
64
+ for (let at = 0; at < queue.length; at++) {
65
+ if (visited >= maxDirs || projects.length >= maxProjects || entries >= maxEntries || now() >= deadline) { truncated = true; break; }
66
+ const { cwd, depth } = queue[at];
67
+ let canonical;
68
+ try { canonical = await realpath(cwd); } catch (error) { if (denied(error)) truncated = true; continue; }
69
+ if (seen.has(canonical)) continue;
70
+ seen.add(canonical); visited++;
71
+ try {
72
+ const marker = await lstat(join(cwd, '.git')).catch(() => null);
73
+ if (marker) {
74
+ if (marker.isDirectory()) {
75
+ await access(cwd, constants.R_OK | constants.X_OK);
76
+ projects.push({ cwd: canonical, name: basename(canonical) });
77
+ }
78
+ continue;
79
+ }
80
+ if (depth >= maxDepth) continue;
81
+ const directory = await opendir(cwd);
82
+ for await (const entry of directory) {
83
+ if (++entries > maxEntries || now() >= deadline) { truncated = true; break; }
84
+ if (entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.startsWith('.') && !SKIP.has(entry.name)) {
85
+ queue.push({ cwd: join(cwd, entry.name), depth: depth + 1 });
86
+ }
87
+ }
88
+ } catch (error) {
89
+ // Missing conventional folders are normal. A denied folder means the
90
+ // suggestions may be incomplete, without exposing the failing path.
91
+ if (denied(error)) truncated = true;
92
+ }
93
+ }
94
+ const byName = (a, b) => a.name.localeCompare(b.name) || a.cwd.localeCompare(b.cwd);
95
+ projects.sort(byName);
96
+ const worktrees = [];
97
+ const offered = new Set(projects.map(p => p.cwd));
98
+ for (const project of projects) {
99
+ if (projects.length + worktrees.length >= maxProjects || now() >= deadline || entries >= maxEntries) {
100
+ truncated = true;
101
+ break;
102
+ }
103
+ const registrations = join(project.cwd, '.git', 'worktrees');
104
+ try {
105
+ if (!(await lstat(registrations)).isDirectory()) continue;
106
+ for await (const entry of await opendir(registrations)) {
107
+ if (++entries > maxEntries || now() >= deadline || projects.length + worktrees.length >= maxProjects) {
108
+ truncated = true;
109
+ break;
110
+ }
111
+ if (!entry.isDirectory()) continue;
112
+ try {
113
+ const worktree = await linkedWorktree(join(registrations, entry.name), project);
114
+ if (!worktree || offered.has(worktree.cwd)) continue;
115
+ offered.add(worktree.cwd);
116
+ worktrees.push(worktree);
117
+ } catch (error) {
118
+ if (denied(error)) truncated = true;
119
+ }
120
+ }
121
+ } catch (error) {
122
+ if (denied(error)) truncated = true;
123
+ }
124
+ }
125
+ projects.push(...worktrees.sort(byName));
126
+ return { projects, truncated };
127
+ }
128
+
129
+ export function createProjectDiscovery({ scan = scanProjectFolders, now = Date.now, ttlMs = 30000 } = {}) {
130
+ let cached = null, cachedAt = 0, pending = null;
131
+ return () => {
132
+ if (pending) return pending;
133
+ if (cached && now() - cachedAt < ttlMs) return Promise.resolve(cached);
134
+ pending = Promise.resolve().then(scan).then(result => { cached = result; cachedAt = now(); return result; })
135
+ .finally(() => { pending = null; });
136
+ return pending;
137
+ };
138
+ }
139
+ export const discoverProjects = createProjectDiscovery();
@@ -0,0 +1,58 @@
1
+ // Native provider metadata only: never submit a prompt or inject terminal keys.
2
+ // Claude's documented renameSession operation appends a custom-title entry:
3
+ // https://code.claude.com/docs/en/agent-sdk/typescript#renamesession
4
+ import { constants } from 'node:fs';
5
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { claudeConfigDir } from './claude-dir.mjs';
8
+ import { readCodexSelection } from './codex-selection.mjs';
9
+ import { resolveCodexLiveEndpoint, connectCodexLiveRpc } from './codex-live-rpc.mjs';
10
+
11
+ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
12
+ const unavailable = () => { throw Object.assign(new Error('provider_name_not_saved'), { code: 'provider_name_not_saved' }); };
13
+
14
+ export async function renameProviderSession(provider, sessionId, name, options = {}) {
15
+ if (!uuid.test(sessionId) || typeof name !== 'string' || !name.trim()) return unavailable();
16
+ if (provider === 'codex') {
17
+ const selection = await (options.readSelection ?? readCodexSelection)(options);
18
+ const endpoint = await (options.resolveEndpoint ?? resolveCodexLiveEndpoint)(selection.originalHome, options);
19
+ const rpc = await (options.connectRpc ?? connectCodexLiveRpc)(endpoint);
20
+ try {
21
+ const { thread } = await rpc.request('thread/read', { threadId: sessionId, includeTurns: false });
22
+ if (thread?.id !== sessionId) return unavailable();
23
+ await rpc.request('thread/name/set', { threadId: sessionId, name });
24
+ return;
25
+ } finally { rpc.close(); }
26
+ }
27
+ if (provider !== 'claude') return unavailable();
28
+ const root = await realpath(join(claudeConfigDir(options.env, options.home), 'projects'));
29
+ const matches = [];
30
+ // Only immediate project directories; never follow a transcript or project symlink.
31
+ const dirs = await readdir(root, { withFileTypes: true });
32
+ if (dirs.length > 10_000) return unavailable();
33
+ for (const dir of dirs) {
34
+ if (!dir.isDirectory()) continue;
35
+ const parent = join(root, dir.name), path = join(parent, `${sessionId}.jsonl`);
36
+ try {
37
+ if (await realpath(parent) !== parent) continue;
38
+ const info = await lstat(path);
39
+ if (!info.isFile() || info.nlink !== 1) continue;
40
+ matches.push({ path, info });
41
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
42
+ }
43
+ if (matches.length !== 1) return unavailable();
44
+ const { path, info } = matches[0];
45
+ const file = await open(path, constants.O_RDWR | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0));
46
+ try {
47
+ const current = await file.stat();
48
+ if (!current.isFile() || current.dev !== info.dev || current.ino !== info.ino || current.nlink !== 1
49
+ || typeof process.getuid === 'function' && current.uid !== process.getuid()) return unavailable();
50
+ if (current.size > 0) {
51
+ const last = Buffer.alloc(1);
52
+ await file.read(last, 0, 1, current.size - 1);
53
+ if (last[0] !== 10) return unavailable(); // Do not splice into an in-flight JSONL write.
54
+ }
55
+ await file.write(JSON.stringify({ type: 'custom-title', customTitle: name, sessionId }) + '\n');
56
+ await file.sync();
57
+ } finally { await file.close(); }
58
+ }
@@ -171,7 +171,7 @@ export function startQuotaCloses() {
171
171
  return JSON.parse((await readFile(file, "utf8")).replace(/^/, ""));
172
172
  } catch (e) { if (e?.code === "ENOENT") return null; throw e; }
173
173
  },
174
- save: async raw => { await mkdir(dirname(file), { recursive: true }); await writeFileAtomic(file, JSON.stringify(raw)); },
174
+ save: async raw => { await mkdir(dirname(file), { recursive: true, mode: 0o700 }); await writeFileAtomic(file, JSON.stringify(raw)); },
175
175
  });
176
176
  return closes;
177
177
  }
@@ -159,7 +159,7 @@ export function startQuotaHistory() {
159
159
  return JSON.parse((await readFile(file, "utf8")).replace(/^\uFEFF/, ""));
160
160
  } catch (e) { if (e?.code === "ENOENT") return null; throw e; }
161
161
  },
162
- save: async raw => { await mkdir(dirname(file), { recursive: true }); await writeFileAtomic(file, JSON.stringify(raw)); },
162
+ save: async raw => { await mkdir(dirname(file), { recursive: true, mode: 0o700 }); await writeFileAtomic(file, JSON.stringify(raw)); },
163
163
  });
164
164
  }
165
165
  export function noteQuotaHistory(provider, account, reading) {