overvues 0.0.0-stage → 0.4.10

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 (77) hide show
  1. package/README.md +60 -2
  2. package/dist/ansi.js +24 -0
  3. package/dist/attach-client.js +586 -0
  4. package/dist/auth-connect-browser.js +112 -0
  5. package/dist/auth-connect.js +306 -0
  6. package/dist/browser-bootstrap.js +190 -0
  7. package/dist/browser-loopback.js +289 -0
  8. package/dist/build-identity.js +6 -0
  9. package/dist/codex-reviewer-apparmor.json +4 -0
  10. package/dist/codex-reviewer-seccomp.json +1238 -0
  11. package/dist/codex-runtime-protocol.js +1 -0
  12. package/dist/codex-subscription.js +53 -0
  13. package/dist/config.js +297 -0
  14. package/dist/connect-comparison-code.js +26 -0
  15. package/dist/development-runner.js +109 -0
  16. package/dist/dns-doctor.js +390 -0
  17. package/dist/docker-names.js +47 -0
  18. package/dist/doctor.js +114 -0
  19. package/dist/gadget-job.js +804 -0
  20. package/dist/health-check.js +112 -0
  21. package/dist/help.js +71 -0
  22. package/dist/host-auth.js +22 -0
  23. package/dist/host-diagnostics.js +20 -0
  24. package/dist/host-runtime-identity.js +39 -0
  25. package/dist/host-runtime-metadata.js +56 -0
  26. package/dist/host-service.js +377 -0
  27. package/dist/host-stack.js +484 -0
  28. package/dist/host-supervisor.js +237 -0
  29. package/dist/host-update.js +387 -0
  30. package/dist/hub-address.js +100 -0
  31. package/dist/hub-client.js +459 -0
  32. package/dist/hub-kind.js +88 -0
  33. package/dist/identity.js +73 -0
  34. package/dist/index.js +185 -0
  35. package/dist/init.js +295 -0
  36. package/dist/isolated-run-cache.js +116 -0
  37. package/dist/local-stack.js +685 -0
  38. package/dist/machine-capacity.js +128 -0
  39. package/dist/managed-runner-image.js +13 -0
  40. package/dist/os-acted-record.js +49 -0
  41. package/dist/os-adapter.js +8190 -0
  42. package/dist/os-command.js +292 -0
  43. package/dist/os-handoff.js +274 -0
  44. package/dist/os-keychain.js +247 -0
  45. package/dist/os-machine.js +818 -0
  46. package/dist/os-owner.js +61 -0
  47. package/dist/os-private-file.js +98 -0
  48. package/dist/os-protocol.js +468 -0
  49. package/dist/os-session-store.js +133 -0
  50. package/dist/os-status.js +102 -0
  51. package/dist/picker.js +863 -0
  52. package/dist/portable-workspace-capability.js +60 -0
  53. package/dist/project-environment-capability.js +62 -0
  54. package/dist/project-environment.js +28 -0
  55. package/dist/project-preparation.js +134 -0
  56. package/dist/readiness.js +28 -0
  57. package/dist/redaction.js +27 -0
  58. package/dist/reviewer-isolation-capability.js +61 -0
  59. package/dist/runner-api-auth.js +80 -0
  60. package/dist/runner-command-fence.js +536 -0
  61. package/dist/runner-inspection.js +57 -0
  62. package/dist/runner-inventory.js +587 -0
  63. package/dist/runner-server.js +2520 -0
  64. package/dist/runner-session.js +470 -0
  65. package/dist/runner-slug-folder.js +39 -0
  66. package/dist/runner-slug.js +40 -0
  67. package/dist/setup.js +139 -0
  68. package/dist/shutdown.js +102 -0
  69. package/dist/splash.js +65 -0
  70. package/dist/staged-workspaces.js +441 -0
  71. package/dist/staging-disk.js +97 -0
  72. package/dist/terminal-lane.js +339 -0
  73. package/dist/terminal-recovery.js +502 -0
  74. package/licenses/capnweb.txt +23 -0
  75. package/licenses/moby-profiles.txt +212 -0
  76. package/licenses/ws.txt +22 -0
  77. package/package.json +30 -4
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # overvues
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `overvues` connects your computer to your Overvues Dev hub. Once it is connected, the hub can
4
+ build, preview and deploy your apps on this computer, and send them to Overvues as you.
5
+
6
+ You need Node.js 22 or newer and Docker (Docker Desktop on a Mac).
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ npm install -g overvues
12
+ ```
13
+
14
+ ## Use
15
+
16
+ 1. **Connect this computer to your hub.**
17
+
18
+ ```sh
19
+ overvues host setup --hub-url https://<your hub's address>
20
+ ```
21
+
22
+ Your browser opens on the hub. Check that the code it shows matches the one in your terminal,
23
+ and approve. `overvues` then asks the hub which runner image to use (the hub names it by its
24
+ digest, so this computer runs exactly that image and no other), downloads it with Docker, and
25
+ keeps running in the background, also after a restart.
26
+
27
+ 2. **Sign this computer in to Overvues.**
28
+
29
+ ```sh
30
+ overvues os connect
31
+ ```
32
+
33
+ Your browser opens Overvues. Press Continue there. The sign-in lasts 30 days; run this again
34
+ before then. `overvues os status` shows whether this computer is signed in, and until when.
35
+
36
+ 3. **Check that everything works.**
37
+
38
+ ```sh
39
+ overvues doctor
40
+ ```
41
+
42
+ It says what is missing and how to fix it.
43
+
44
+ 4. **Keep it up to date.**
45
+
46
+ ```sh
47
+ npm install -g overvues
48
+ overvues host update
49
+ ```
50
+
51
+ `overvues host update` moves this computer to the runner image your hub names now. Your hub
52
+ is updated for you; run this after it has been.
53
+
54
+ `overvues --help` lists every command.
55
+
56
+ ## Next to `tiller`
57
+
58
+ `overvues` is the same program as `tiller` under its own name. It keeps its own settings
59
+ (`~/.config/overvues`), its own background service, its own Docker containers and its own
60
+ keychain entry, so both can be installed on one computer, each connected to its own hub. It
61
+ connects only to Overvues Dev hubs.
package/dist/ansi.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Shared ANSI escape-code helpers used by the picker and attach client.
3
+ */
4
+ const ESC = "\x1b";
5
+ const CSI = `${ESC}[`;
6
+ export const ansi = {
7
+ clearScreen: `${CSI}2J${CSI}H`,
8
+ cursorUp: (n) => `${CSI}${n}A`,
9
+ cursorDown: (n) => `${CSI}${n}B`,
10
+ eraseLine: `${CSI}2K\r`,
11
+ hideCursor: `${CSI}?25l`,
12
+ showCursor: `${CSI}?25h`,
13
+ bold: `${CSI}1m`,
14
+ dim: `${CSI}2m`,
15
+ blue: `${CSI}34m`,
16
+ green: `${CSI}32m`,
17
+ yellow: `${CSI}33m`,
18
+ cyan: `${CSI}36m`,
19
+ magenta: `${CSI}35m`,
20
+ red: `${CSI}31m`,
21
+ reset: `${CSI}0m`,
22
+ inverse: `${CSI}7m`,
23
+ };
24
+ export { ESC, CSI };
@@ -0,0 +1,586 @@
1
+ /**
2
+ * `tiller` — connect to a remote Claude Code session via the hub
3
+ * WebSocket and display terminal output in a real terminal.
4
+ *
5
+ * - Live terminal output via stdout (native scrolling, native selection)
6
+ * - Inline permission prompts (a/s/d)
7
+ * - stdin forwarded as user-input messages
8
+ * - Ctrl+C → exit tiller
9
+ * - Ctrl+B → detach back to the picker
10
+ * - Ctrl+] → send abort to the remote session
11
+ * - Does NOT send session-end on detach (session keeps running)
12
+ */
13
+ import { HubClient, } from "./hub-client.js";
14
+ import { HUB_URL, hubControlHeaders, } from "./config.js";
15
+ import { ansi } from "./ansi.js";
16
+ import { authLabel, envDisplayLabel, pickAndConnect } from "./picker.js";
17
+ import { CliTerminalRecovery, readJsonResponseWithinLimit, writeStdoutWithBackpressure, } from "./terminal-recovery.js";
18
+ import { CLI } from "./identity.js";
19
+ const TERMINAL_ACK_TIMEOUT_MS = 1000;
20
+ const TERMINAL_WARNING_COOLDOWN_MS = 2000;
21
+ function tillerLog(msg) {
22
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${msg}\n`);
23
+ }
24
+ function showAttachControls() {
25
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.dim}Controls:${ansi.reset} ` +
26
+ `${ansi.cyan}Ctrl+B${ansi.reset} back to picker ` +
27
+ `${ansi.cyan}Ctrl+]${ansi.reset} abort remote ` +
28
+ `${ansi.cyan}Ctrl+C${ansi.reset} exit ${CLI.command}\n`);
29
+ }
30
+ export class TerminalAckTracker {
31
+ sessionId;
32
+ clientId;
33
+ pendingInputs = new Map();
34
+ pendingControls = new Map();
35
+ warningActive = false;
36
+ failureWarnedAt = null;
37
+ dropWarnedAt = null;
38
+ constructor(sessionId, clientId) {
39
+ this.sessionId = sessionId;
40
+ this.clientId = clientId;
41
+ }
42
+ trackInput(inputSeq) {
43
+ const timer = setTimeout(() => {
44
+ // Delete on timeout so a never-acked seq (e.g. across a dropped socket)
45
+ // can't grow the map forever or suppress future warnings.
46
+ this.pendingInputs.delete(inputSeq);
47
+ this.warnOnce("Terminal input is delayed; waiting for the remote session.");
48
+ this.resetWarningIfIdle();
49
+ }, TERMINAL_ACK_TIMEOUT_MS);
50
+ this.pendingInputs.set(inputSeq, timer);
51
+ }
52
+ trackControl(controlSeq, action) {
53
+ const timer = setTimeout(() => {
54
+ this.pendingControls.delete(controlSeq);
55
+ this.warnOnce(action === "resize"
56
+ ? "Terminal resize acknowledgement is delayed; terminal input may still work."
57
+ : "Terminal abort is delayed; waiting for the remote session.");
58
+ this.resetWarningIfIdle();
59
+ }, TERMINAL_ACK_TIMEOUT_MS);
60
+ this.pendingControls.set(controlSeq, { action, timer });
61
+ }
62
+ handleInputAck(ack) {
63
+ if (ack.sessionId !== this.sessionId || ack.clientId !== this.clientId)
64
+ return;
65
+ const timer = this.pendingInputs.get(ack.inputSeq);
66
+ if (!timer)
67
+ return;
68
+ clearTimeout(timer);
69
+ this.pendingInputs.delete(ack.inputSeq);
70
+ if (ack.ok) {
71
+ this.failureWarnedAt = null;
72
+ }
73
+ else {
74
+ this.warnFailure(`Terminal input failed: ${ack.error ?? "remote session rejected input"}`);
75
+ }
76
+ this.resetWarningIfIdle();
77
+ }
78
+ handleControlAck(ack) {
79
+ if (ack.sessionId !== this.sessionId || ack.clientId !== this.clientId)
80
+ return;
81
+ const pending = this.pendingControls.get(ack.controlSeq);
82
+ if (!pending)
83
+ return;
84
+ clearTimeout(pending.timer);
85
+ this.pendingControls.delete(ack.controlSeq);
86
+ if (ack.ok) {
87
+ this.failureWarnedAt = null;
88
+ }
89
+ else {
90
+ this.warnFailure(`Terminal ${pending.action} failed: ${ack.error ?? "remote session rejected control"}`);
91
+ }
92
+ this.resetWarningIfIdle();
93
+ }
94
+ warnSendFailed(what) {
95
+ const now = Date.now();
96
+ if (this.dropWarnedAt != null && now - this.dropWarnedAt < TERMINAL_WARNING_COOLDOWN_MS)
97
+ return;
98
+ this.dropWarnedAt = now;
99
+ tillerLog(`${ansi.yellow}Not connected — ${what} dropped.${ansi.reset}`);
100
+ }
101
+ clear() {
102
+ for (const timer of this.pendingInputs.values()) {
103
+ clearTimeout(timer);
104
+ }
105
+ for (const pending of this.pendingControls.values()) {
106
+ clearTimeout(pending.timer);
107
+ }
108
+ this.pendingInputs.clear();
109
+ this.pendingControls.clear();
110
+ this.warningActive = false;
111
+ this.failureWarnedAt = null;
112
+ }
113
+ warnOnce(message) {
114
+ if (this.warningActive)
115
+ return;
116
+ this.warningActive = true;
117
+ tillerLog(`${ansi.yellow}${message}${ansi.reset}`);
118
+ }
119
+ resetWarningIfIdle() {
120
+ if (this.pendingInputs.size === 0 && this.pendingControls.size === 0) {
121
+ this.warningActive = false;
122
+ }
123
+ }
124
+ // Coalesce failed-ACK logs on a cooldown rather than on empty pending maps:
125
+ // in a no-owner window each failed ACK drains the map immediately, so a
126
+ // drain-based reset would still print one line per keypress.
127
+ warnFailure(message) {
128
+ const now = Date.now();
129
+ if (this.failureWarnedAt != null && now - this.failureWarnedAt < TERMINAL_WARNING_COOLDOWN_MS)
130
+ return;
131
+ this.failureWarnedAt = now;
132
+ tillerLog(`${ansi.red}${message}${ansi.reset}`);
133
+ }
134
+ }
135
+ // ── REST helpers ─────────────────────────────────────────────────────
136
+ export function parseTerminalHistoryMessage(message, sessionId) {
137
+ if (typeof message !== "object" ||
138
+ message === null ||
139
+ !("id" in message) ||
140
+ typeof message.id !== "string" ||
141
+ message.id.length === 0 ||
142
+ !("session_id" in message) ||
143
+ message.session_id !== sessionId ||
144
+ !("content" in message) ||
145
+ typeof message.content !== "string" ||
146
+ !("seq" in message) ||
147
+ !Number.isInteger(message.seq) ||
148
+ message.seq < 1 ||
149
+ !("local_id" in message) ||
150
+ (message.local_id !== null && typeof message.local_id !== "string") ||
151
+ !("created_at" in message) ||
152
+ typeof message.created_at !== "string") {
153
+ throw new Error("Invalid terminal history response");
154
+ }
155
+ let content;
156
+ try {
157
+ content = JSON.parse(message.content);
158
+ }
159
+ catch {
160
+ throw new Error("Invalid terminal history response");
161
+ }
162
+ const localId = message.local_id;
163
+ return {
164
+ id: message.id,
165
+ sessionId,
166
+ seq: message.seq,
167
+ content,
168
+ ...(typeof localId === "string"
169
+ ? { localId }
170
+ : {}),
171
+ };
172
+ }
173
+ async function fetchMessages(hubUrl, sessionId, headers, opts) {
174
+ const params = new URLSearchParams();
175
+ if (opts.limit)
176
+ params.set("limit", String(opts.limit));
177
+ if (opts.afterSeq != null)
178
+ params.set("after_seq", String(opts.afterSeq));
179
+ const qs = params.toString() ? `?${params}` : "";
180
+ const res = await fetch(`${hubUrl}/api/sessions/${sessionId}/messages${qs}`, {
181
+ headers,
182
+ signal: opts.signal,
183
+ });
184
+ if (!res.ok)
185
+ throw new Error(`Failed to fetch messages: ${res.status}`);
186
+ const payload = await readJsonResponseWithinLimit(res, opts.maxBytes, opts.onBytes);
187
+ if (!Array.isArray(payload))
188
+ throw new Error("Invalid terminal history response");
189
+ return payload.map((message) => parseTerminalHistoryMessage(message, sessionId));
190
+ }
191
+ async function fetchPendingPermissions(hubUrl, sessionId, headers) {
192
+ const res = await fetch(`${hubUrl}/api/sessions/${sessionId}/permissions`, { headers });
193
+ if (!res.ok)
194
+ throw new Error(`Failed to fetch permissions: ${res.status}`);
195
+ return res.json();
196
+ }
197
+ async function resolvePermission(hubUrl, sessionId, permId, status, allowForSession, headers) {
198
+ const res = await fetch(`${hubUrl}/api/sessions/${sessionId}/permissions/${permId}`, {
199
+ method: "POST",
200
+ headers: { "Content-Type": "application/json", ...headers },
201
+ body: JSON.stringify({ status, allow_for_session: allowForSession }),
202
+ });
203
+ if (!res.ok)
204
+ throw new Error(`Failed to resolve permission: ${res.status}`);
205
+ }
206
+ // ── Attach logic ─────────────────────────────────────────────────────
207
+ async function attachToSession(session, env, hubUrl, headers, opts) {
208
+ const resolvedAuthLabel = authLabel(env);
209
+ const authSuffix = resolvedAuthLabel ? ` ${ansi.dim}(${resolvedAuthLabel})${ansi.reset}` : "";
210
+ tillerLog(`Attaching to ${ansi.cyan}${session.tag}${ansi.reset} on ${ansi.cyan}${envDisplayLabel(env, true)}${ansi.reset}${authSuffix}`);
211
+ let replayedTerminalOutput = false;
212
+ let detached = false;
213
+ let recoveryState = "recovering";
214
+ let recoveryFaultReported = false;
215
+ let recoveryFallbackAttempted = false;
216
+ let recoveryFallbackPending = false;
217
+ let hubForRecovery = null;
218
+ let terminalWriteBarrier = Promise.resolve();
219
+ let inputBuffer = "";
220
+ let inputTimer = null;
221
+ void opts.history; // Cold reconstruction is intentionally bounded to one 200-message tail.
222
+ function discardInputBuffer() {
223
+ if (inputTimer)
224
+ clearTimeout(inputTimer);
225
+ inputTimer = null;
226
+ inputBuffer = "";
227
+ }
228
+ const writeTerminal = async (data) => {
229
+ const write = writeStdoutWithBackpressure(data);
230
+ terminalWriteBarrier = write.then(() => undefined, () => undefined);
231
+ await write;
232
+ };
233
+ let recovery;
234
+ function createRecovery() {
235
+ let controller;
236
+ controller = new CliTerminalRecovery({
237
+ sessionId: session.id,
238
+ fetchPage: async (request) => fetchMessages(hubUrl, session.id, headers, request),
239
+ write: async (message) => {
240
+ const content = message.content;
241
+ if (content?.type === "terminal-output" && typeof content.data === "string" && content.data) {
242
+ replayedTerminalOutput = true;
243
+ await writeTerminal(content.data);
244
+ }
245
+ },
246
+ onSequenceComplete: (seq) => hubForRecovery?.markMessageComplete(seq),
247
+ onStateChange: (state, fault) => {
248
+ recoveryState = state;
249
+ if (state !== "ready")
250
+ discardInputBuffer();
251
+ if (state === "fault" &&
252
+ (fault === "overflow" || fault === "deadline") &&
253
+ !recoveryFallbackAttempted &&
254
+ !detached) {
255
+ recoveryFallbackAttempted = true;
256
+ recoveryFallbackPending = true;
257
+ recoveryState = "recovering";
258
+ controller.dispose();
259
+ void restartFromRecentOutput(controller);
260
+ return;
261
+ }
262
+ if (state === "ready" && recoveryFallbackPending) {
263
+ recoveryFallbackPending = false;
264
+ tillerLog(`${ansi.yellow}Showing recent output; older missed output was skipped.${ansi.reset}`);
265
+ }
266
+ if (state === "fault" && !recoveryFaultReported) {
267
+ recoveryFaultReported = true;
268
+ tillerLog(`${ansi.red}Terminal recovery stopped (${fault ?? "unknown"}); reattach to retry.${ansi.reset}`);
269
+ }
270
+ },
271
+ });
272
+ return controller;
273
+ }
274
+ async function restartFromRecentOutput(failed) {
275
+ try {
276
+ await terminalWriteBarrier;
277
+ if (detached || recovery !== failed)
278
+ return;
279
+ await writeTerminal("\x1b[2J\x1b[H");
280
+ if (detached || recovery !== failed)
281
+ return;
282
+ recovery = createRecovery();
283
+ await recovery.startCold();
284
+ }
285
+ catch {
286
+ if (detached)
287
+ return;
288
+ recoveryFallbackPending = false;
289
+ recoveryState = "fault";
290
+ if (!recoveryFaultReported) {
291
+ recoveryFaultReported = true;
292
+ tillerLog(`${ansi.red}Terminal recovery stopped (recent output fallback failed); reattach to retry.${ansi.reset}`);
293
+ }
294
+ }
295
+ }
296
+ recovery = createRecovery();
297
+ tillerLog("Replaying recent output...");
298
+ void recovery.startCold();
299
+ // 3. Check for pending permissions
300
+ let pendingPermission = null;
301
+ void fetchPendingPermissions(hubUrl, session.id, headers)
302
+ .then((perms) => {
303
+ if (detached)
304
+ return;
305
+ const pending = perms.filter((permission) => permission.status === "pending");
306
+ if (pending.length > 0) {
307
+ pendingPermission = pending[0];
308
+ showPermissionPrompt(pendingPermission);
309
+ }
310
+ })
311
+ .catch(() => undefined);
312
+ // 4. Connect WebSocket
313
+ const hub = new HubClient({ hubUrl, cfAccessHeaders: headers });
314
+ hubForRecovery = hub;
315
+ hub.markMessageComplete?.(recovery.lastSeq);
316
+ hub.setSessionId(session.id, { lifecycle: "viewer" });
317
+ const clientId = crypto.randomUUID();
318
+ const ackTracker = new TerminalAckTracker(session.id, clientId);
319
+ let inputSeq = 0;
320
+ let controlSeq = 0;
321
+ hub.on("connected", () => {
322
+ sendTerminalResize(process.stdout.columns, process.stdout.rows);
323
+ recovery.recover();
324
+ });
325
+ hub.on("error", (err) => {
326
+ tillerLog(`${ansi.red}Hub error: ${err.message}${ansi.reset}`);
327
+ });
328
+ hub.on("capabilities", () => {
329
+ sendTerminalResize(process.stdout.columns, process.stdout.rows);
330
+ });
331
+ hub.on("disconnected", () => {
332
+ // ACKs are live-only; anything in flight when the socket drops will never
333
+ // be acked, so clear pending state instead of leaking timers and warnings.
334
+ ackTracker.clear();
335
+ });
336
+ hub.on("terminal-input-ack", (ack) => {
337
+ ackTracker.handleInputAck(ack);
338
+ });
339
+ hub.on("terminal-control-ack", (ack) => {
340
+ ackTracker.handleControlAck(ack);
341
+ });
342
+ // 5. Handle incoming messages
343
+ hub.on("message-received", (msg) => {
344
+ if (typeof msg.id !== "string" ||
345
+ typeof msg.sessionId !== "string" ||
346
+ typeof msg.seq !== "number")
347
+ return;
348
+ recovery.acceptLive({
349
+ id: msg.id,
350
+ sessionId: msg.sessionId,
351
+ seq: msg.seq,
352
+ content: msg.content,
353
+ ...(typeof msg.localId === "string" ? { localId: msg.localId } : {}),
354
+ });
355
+ });
356
+ hub.on("permission-created", (perm) => {
357
+ const p = perm;
358
+ if (p.session_id === session.id && p.status === "pending") {
359
+ pendingPermission = p;
360
+ showPermissionPrompt(p);
361
+ }
362
+ });
363
+ hub.on("permission-resolved", (perm) => {
364
+ const p = perm;
365
+ if (p.session_id === session.id) {
366
+ if (pendingPermission && pendingPermission.id === p.id) {
367
+ pendingPermission = null;
368
+ tillerLog(`${ansi.dim}Permission ${p.status}.${ansi.reset}`);
369
+ }
370
+ }
371
+ });
372
+ hub.on("session-deleted", (deletedId) => {
373
+ if (deletedId === session.id) {
374
+ tillerLog(`${ansi.red}Session ended by remote.${ansi.reset}`);
375
+ detach("picker");
376
+ }
377
+ });
378
+ hub.connect();
379
+ // 6. Setup stdin handling with input batching
380
+ const INPUT_BATCH_MS = 2; // Minimal batch window — coalesces pastes without delaying keystrokes
381
+ let detachDisposition = "exit";
382
+ let onDetach;
383
+ const done = new Promise((r) => { onDetach = r; });
384
+ const attachStartedAt = Date.now();
385
+ let userInputPrimed = false;
386
+ if (process.stdin.isTTY) {
387
+ process.stdin.setRawMode(true);
388
+ }
389
+ process.stdin.resume();
390
+ // Forward terminal resize events to remote PTY
391
+ const onResize = () => {
392
+ if (!detached) {
393
+ sendTerminalResize(process.stdout.columns, process.stdout.rows);
394
+ }
395
+ };
396
+ process.stdout.on("resize", onResize);
397
+ if (!replayedTerminalOutput) {
398
+ tillerLog(`${ansi.green}Connected.${ansi.reset}`);
399
+ showAttachControls();
400
+ }
401
+ function shouldIgnoreInitialTerminalResponse(str) {
402
+ if (userInputPrimed)
403
+ return false;
404
+ if (Date.now() - attachStartedAt > 1500)
405
+ return false;
406
+ return /^\x1b\[(\?|>)[0-9;]+c$/.test(str);
407
+ }
408
+ // Terminal input/control is fast-lane-only: live sends never queue, and
409
+ // there is deliberately no durable fallback — durable raw input would be
410
+ // queued during a disconnect and replayed stale into the PTY on reconnect.
411
+ function sendTerminalInput(data) {
412
+ if (!hub.supportsTerminalFastLane()) {
413
+ ackTracker.warnSendFailed("terminal input");
414
+ return false;
415
+ }
416
+ inputSeq += 1;
417
+ const sent = hub.sendTerminalInput(session.id, clientId, inputSeq, data, { cols: process.stdout.columns || 120, rows: process.stdout.rows || 40 });
418
+ if (sent)
419
+ ackTracker.trackInput(inputSeq);
420
+ else
421
+ ackTracker.warnSendFailed("terminal input");
422
+ return sent;
423
+ }
424
+ function sendTerminalResize(cols, rows) {
425
+ // Dropped resizes self-heal: the latest size is re-sent when
426
+ // capabilities arrive on (re)connect.
427
+ if (!hub.supportsTerminalFastLane())
428
+ return false;
429
+ controlSeq += 1;
430
+ const sent = hub.sendTerminalControl(session.id, clientId, controlSeq, "resize", { cols, rows }, { claim: true });
431
+ if (sent)
432
+ ackTracker.trackControl(controlSeq, "resize");
433
+ return sent;
434
+ }
435
+ function sendTerminalAbort() {
436
+ if (!hub.supportsTerminalFastLane()) {
437
+ ackTracker.warnSendFailed("abort");
438
+ return false;
439
+ }
440
+ controlSeq += 1;
441
+ const sent = hub.sendTerminalControl(session.id, clientId, controlSeq, "abort");
442
+ if (sent)
443
+ ackTracker.trackControl(controlSeq, "abort");
444
+ else
445
+ ackTracker.warnSendFailed("abort");
446
+ return sent;
447
+ }
448
+ function flushInputBuffer() {
449
+ if (inputTimer) {
450
+ clearTimeout(inputTimer);
451
+ inputTimer = null;
452
+ }
453
+ if (inputBuffer.length === 0)
454
+ return;
455
+ if (detached || recoveryState !== "ready") {
456
+ inputBuffer = "";
457
+ return;
458
+ }
459
+ const data = inputBuffer;
460
+ inputBuffer = "";
461
+ const normalized = data.replace(/\n/g, "\r");
462
+ sendTerminalInput(normalized);
463
+ }
464
+ const onData = (data) => {
465
+ if (detached)
466
+ return;
467
+ const str = data.toString();
468
+ if (shouldIgnoreInitialTerminalResponse(str)) {
469
+ return;
470
+ }
471
+ // Single Ctrl+C → detach and exit tiller
472
+ if (str === "\x03") {
473
+ tillerLog("Ctrl+C — exiting");
474
+ detach("exit");
475
+ return;
476
+ }
477
+ // Ctrl+B → detach back to picker
478
+ if (str === "\x02") {
479
+ tillerLog(`${ansi.dim}Ctrl+B — back to picker.${ansi.reset}`);
480
+ detach("picker");
481
+ return;
482
+ }
483
+ // Ctrl+] → send abort to remote session
484
+ if (str === "\x1d") {
485
+ discardInputBuffer();
486
+ if (sendTerminalAbort()) {
487
+ tillerLog(`${ansi.dim}Sent abort to remote session.${ansi.reset}`);
488
+ }
489
+ return;
490
+ }
491
+ // Permission pending — handle a/s/d keys
492
+ if (pendingPermission) {
493
+ const key = str.toLowerCase();
494
+ if (key === "a" || key === "s" || key === "d") {
495
+ const perm = pendingPermission;
496
+ pendingPermission = null;
497
+ const statusMap = { a: "allowed", s: "allowed", d: "denied" };
498
+ const allowForSession = key === "s";
499
+ resolvePermission(hubUrl, session.id, perm.id, statusMap[key], allowForSession, headers).catch((err) => tillerLog(`${ansi.red}Failed to resolve permission: ${err instanceof Error ? err.message : String(err)}${ansi.reset}`));
500
+ return;
501
+ }
502
+ }
503
+ if (recoveryState !== "ready") {
504
+ if (recoveryState === "fault" && !recoveryFaultReported) {
505
+ recoveryFaultReported = true;
506
+ tillerLog(`${ansi.red}Terminal recovery is incomplete; reattach before sending input.${ansi.reset}`);
507
+ }
508
+ return;
509
+ }
510
+ userInputPrimed = true;
511
+ // Batch input: collect keystrokes for INPUT_BATCH_MS before sending
512
+ inputBuffer += str;
513
+ if (!inputTimer) {
514
+ inputTimer = setTimeout(flushInputBuffer, INPUT_BATCH_MS);
515
+ }
516
+ };
517
+ // Discard any startup-buffered bytes, then attach the listener
518
+ setImmediate(() => {
519
+ process.stdin.on("data", onData);
520
+ });
521
+ // Wait until detach
522
+ return await done;
523
+ function detach(nextDisposition = "exit") {
524
+ if (detached)
525
+ return;
526
+ detached = true;
527
+ detachDisposition = nextDisposition;
528
+ // Detach is a hard boundary: pending ordinary input must not leak through.
529
+ discardInputBuffer();
530
+ // Remove listeners
531
+ process.stdin.removeListener("data", onData);
532
+ process.stdout.removeListener("resize", onResize);
533
+ // Restore terminal
534
+ if (process.stdin.isTTY) {
535
+ process.stdin.setRawMode(false);
536
+ }
537
+ process.stdin.pause();
538
+ // Do NOT send session-end — session keeps running
539
+ // Just close the WebSocket connection
540
+ ackTracker.clear();
541
+ hub.sendTerminalDetach?.(session.id, clientId);
542
+ hub.close();
543
+ recovery.dispose();
544
+ onDetach(detachDisposition);
545
+ }
546
+ }
547
+ function showPermissionPrompt(perm) {
548
+ let toolInput = "";
549
+ try {
550
+ const input = JSON.parse(perm.tool_input);
551
+ if (input.command) {
552
+ toolInput = `$ ${input.command}`;
553
+ }
554
+ else {
555
+ toolInput = JSON.stringify(input).slice(0, 120);
556
+ }
557
+ }
558
+ catch {
559
+ toolInput = perm.tool_input.slice(0, 120);
560
+ }
561
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.yellow}Permission: ${perm.tool_name}${ansi.reset}` +
562
+ (toolInput ? ` wants to run: ${ansi.cyan}${toolInput}${ansi.reset}` : "") +
563
+ `\n${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.dim}[a]llow / [s]ession-allow / [d]eny?${ansi.reset}\n`);
564
+ }
565
+ // ── CLI entry point ──────────────────────────────────────────────────
566
+ export async function runAttach(args) {
567
+ // Auth is already validated by the entry point in index.ts
568
+ // Parse attach-specific args
569
+ const opts = {};
570
+ for (const arg of args) {
571
+ if (arg === "--history")
572
+ opts.history = true;
573
+ }
574
+ tillerLog(`Connecting to ${ansi.cyan}${HUB_URL}${ansi.reset}`);
575
+ while (true) {
576
+ const result = await pickAndConnect(HUB_URL, hubControlHeaders);
577
+ if (!result) {
578
+ tillerLog("No session selected.");
579
+ return;
580
+ }
581
+ const disposition = await attachToSession(result.session, result.env, HUB_URL, hubControlHeaders, opts);
582
+ if (disposition === "exit") {
583
+ return;
584
+ }
585
+ }
586
+ }