overvues 0.0.1 → 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 (78) hide show
  1. package/README.md +58 -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 +28 -7
  78. package/cli.js +0 -2
package/dist/picker.js ADDED
@@ -0,0 +1,863 @@
1
+ /**
2
+ * Interactive environment + session picker for `tiller`.
3
+ *
4
+ * Two-level navigation:
5
+ * 1. Pick an environment (shows status: running/stopped)
6
+ * 2. Pick a session on that environment
7
+ *
8
+ * If the selected environment is stopped, starts it and waits for a session.
9
+ * Uses raw stdin + ANSI escape codes — no external dependencies.
10
+ */
11
+ import { spawnSync } from "node:child_process";
12
+ import { HubClient } from "./hub-client.js";
13
+ import { ansi, ESC } from "./ansi.js";
14
+ import { CLI } from "./identity.js";
15
+ const autoStartedEnvSlugs = new Set();
16
+ export function envDisplayLabel(env, includeDistinctSlug = false) {
17
+ const normalized = typeof env.displayName === "string"
18
+ ? env.displayName
19
+ .replace(/[\p{Cc}\p{Cf}]/gu, " ")
20
+ .replace(/\s+/gu, " ")
21
+ .trim()
22
+ : "";
23
+ const codePoints = Array.from(normalized);
24
+ const displayName = codePoints.length > 80
25
+ ? `${codePoints.slice(0, 79).join("")}…`
26
+ : normalized;
27
+ const primary = displayName || env.slug;
28
+ return includeDistinctSlug && primary !== env.slug
29
+ ? `${primary} (slug: ${env.slug})`
30
+ : primary;
31
+ }
32
+ function pickerLog(message) {
33
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${message}\n`);
34
+ }
35
+ // ── Status helpers ───────────────────────────────────────────────────
36
+ function statusIcon(status) {
37
+ switch (status) {
38
+ case "running":
39
+ return `${ansi.green}\u25cf${ansi.reset}`;
40
+ case "creating":
41
+ case "starting":
42
+ case "saving":
43
+ case "created":
44
+ case "waiting":
45
+ return `${ansi.yellow}\u25cf${ansi.reset}`;
46
+ case "deleting":
47
+ case "stopping":
48
+ return `${ansi.yellow}\u25cb${ansi.reset}`;
49
+ case "stopped":
50
+ case "destroyed":
51
+ return `${ansi.dim}\u25cb${ansi.reset}`;
52
+ case "failed":
53
+ return `${ansi.red}\u2715${ansi.reset}`;
54
+ case "unknown":
55
+ return `${ansi.yellow}?${ansi.reset}`;
56
+ default:
57
+ return `${ansi.dim}?${ansi.reset}`;
58
+ }
59
+ }
60
+ function backendBadge(backend) {
61
+ return backend === "host"
62
+ ? `${ansi.cyan}[machine]${ansi.reset}`
63
+ : `${ansi.blue}[cloudflare]${ansi.reset}`;
64
+ }
65
+ function harnessPresentation(env) {
66
+ const presentation = env.harnessPresentation;
67
+ if (!presentation
68
+ || typeof presentation.modelLabel !== "string"
69
+ || typeof presentation.credentialRequirement !== "string"
70
+ || typeof presentation.providerKind !== "string"
71
+ || typeof presentation.providerLabel !== "string") {
72
+ return null;
73
+ }
74
+ return presentation;
75
+ }
76
+ export function authLabel(env) {
77
+ if (env.harness === "codex") {
78
+ if (env.codexAuthMode === "subscription")
79
+ return "subscription";
80
+ if (env.codexAuthMode === "api-key")
81
+ return "api key";
82
+ return null;
83
+ }
84
+ if (env.harness === "opencode") {
85
+ const requirement = harnessPresentation(env)?.credentialRequirement;
86
+ if (requirement === "workers-ai")
87
+ return "workers ai";
88
+ if (requirement === "openai-api-key")
89
+ return "openai api key";
90
+ if (requirement === "anthropic-api-key")
91
+ return "anthropic api key";
92
+ return null;
93
+ }
94
+ if (env.resolvedAuthMode === "subscription")
95
+ return "claude subscription";
96
+ if (env.resolvedAuthMode === "api")
97
+ return "anthropic api key";
98
+ return null;
99
+ }
100
+ export function authBadge(env) {
101
+ const label = authLabel(env);
102
+ if (!label)
103
+ return "";
104
+ const color = env.harness === "opencode"
105
+ && harnessPresentation(env)?.providerKind === "cloudflare-workers-ai"
106
+ ? ansi.cyan
107
+ : label.includes("subscription")
108
+ ? ansi.green
109
+ : ansi.yellow;
110
+ return `${color}[${label}]${ansi.reset}`;
111
+ }
112
+ export function authDetailLabel(env) {
113
+ if (env.harness === "codex") {
114
+ if (!env.codexAuthMode)
115
+ return null;
116
+ return env.codexAuthMode === "subscription" ? "Subscription" : "API key";
117
+ }
118
+ if (env.harness === "opencode") {
119
+ const presentation = harnessPresentation(env);
120
+ if (!presentation)
121
+ return null;
122
+ return `${presentation.providerLabel} · ${presentation.modelLabel}`;
123
+ }
124
+ if (!env.resolvedAuthMode)
125
+ return null;
126
+ const mode = env.resolvedAuthMode === "subscription" ? "Claude subscription" : "Anthropic API key";
127
+ return mode;
128
+ }
129
+ function timeAgo(dateStr) {
130
+ const diff = Math.max(0, Date.now() - new Date(dateStr).getTime());
131
+ const secs = Math.floor(diff / 1000);
132
+ if (secs < 60)
133
+ return `${secs}s ago`;
134
+ const mins = Math.floor(secs / 60);
135
+ if (mins < 60)
136
+ return `${mins}m ago`;
137
+ const hours = Math.floor(mins / 60);
138
+ if (hours < 24)
139
+ return `${hours}h ago`;
140
+ const days = Math.floor(hours / 24);
141
+ return `${days}d ago`;
142
+ }
143
+ function statusRank(status) {
144
+ switch (status) {
145
+ case "running":
146
+ return 0;
147
+ case "creating":
148
+ case "starting":
149
+ case "saving":
150
+ case "created":
151
+ case "waiting":
152
+ return 1;
153
+ case "deleting":
154
+ case "unknown":
155
+ return 2;
156
+ case "failed":
157
+ return 3;
158
+ case "stopping":
159
+ return 4;
160
+ case "stopped":
161
+ case "destroyed":
162
+ return 5;
163
+ default:
164
+ return 6;
165
+ }
166
+ }
167
+ function normalizeRepoUrl(repoUrl) {
168
+ return repoUrl.trim().replace(/\.git$/, "").replace(/\/+$/, "").toLowerCase();
169
+ }
170
+ function detectCurrentRepoUrl() {
171
+ try {
172
+ const result = spawnSync("git", ["remote", "get-url", "origin"], {
173
+ stdio: ["ignore", "pipe", "ignore"],
174
+ timeout: 3000,
175
+ });
176
+ if (result.status === 0 && result.stdout) {
177
+ return normalizeRepoUrl(result.stdout.toString().trim());
178
+ }
179
+ }
180
+ catch { /* not in a git repo */ }
181
+ return null;
182
+ }
183
+ function repoLabel(repoUrl) {
184
+ try {
185
+ const url = new URL(repoUrl);
186
+ return `${url.hostname}${url.pathname.replace(/\.git$/, "")}`;
187
+ }
188
+ catch {
189
+ return repoUrl;
190
+ }
191
+ }
192
+ function truncate(value, max = 72) {
193
+ return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
194
+ }
195
+ function normalizeStatus(status) {
196
+ switch (status) {
197
+ case "running":
198
+ case "creating":
199
+ case "starting":
200
+ case "saving":
201
+ case "stopping":
202
+ case "stopped":
203
+ case "deleting":
204
+ case "destroyed":
205
+ case "failed":
206
+ case "created":
207
+ case "waiting":
208
+ case "unknown":
209
+ return status;
210
+ default:
211
+ return "unknown";
212
+ }
213
+ }
214
+ // ── Fetch helpers ────────────────────────────────────────────────────
215
+ async function fetchEnvs(hubUrl, headers) {
216
+ const res = await fetch(`${hubUrl}/api/envs`, { headers });
217
+ if (!res.ok)
218
+ throw new Error(`Failed to fetch envs: ${res.status}`);
219
+ return res.json();
220
+ }
221
+ async function fetchSessions(hubUrl, headers) {
222
+ const res = await fetch(`${hubUrl}/api/sessions`, { headers });
223
+ if (!res.ok)
224
+ throw new Error(`Failed to fetch sessions: ${res.status}`);
225
+ return res.json();
226
+ }
227
+ async function fetchEnv(hubUrl, slug, headers) {
228
+ const res = await fetch(`${hubUrl}/api/envs/${slug}`, { headers });
229
+ if (res.status === 404)
230
+ return null;
231
+ if (!res.ok)
232
+ throw new Error(`Failed to fetch env ${slug}: ${res.status}`);
233
+ return res.json();
234
+ }
235
+ async function startEnv(hubUrl, slug, headers) {
236
+ const res = await fetch(`${hubUrl}/api/envs/${slug}/start`, {
237
+ method: "POST",
238
+ headers,
239
+ });
240
+ if (!res.ok)
241
+ throw new Error(`Failed to start env: ${res.status}`);
242
+ }
243
+ async function stopEnv(hubUrl, slug, headers) {
244
+ const res = await fetch(`${hubUrl}/api/envs/${slug}/stop`, {
245
+ method: "POST",
246
+ headers,
247
+ });
248
+ if (!res.ok && res.status !== 404)
249
+ throw new Error(`Failed to stop env: ${res.status}`);
250
+ }
251
+ async function deleteEnv(hubUrl, slug, headers) {
252
+ const res = await fetch(`${hubUrl}/api/envs/${slug}`, {
253
+ method: "DELETE",
254
+ headers,
255
+ });
256
+ if (!res.ok && res.status !== 404)
257
+ throw new Error(`Failed to delete env: ${res.status}`);
258
+ }
259
+ async function fetchRepos(hubUrl, headers) {
260
+ const res = await fetch(`${hubUrl}/api/repos`, { headers });
261
+ if (!res.ok)
262
+ throw new Error(`Failed to fetch repos: ${res.status}`);
263
+ return offeredRepos(await res.json());
264
+ }
265
+ /**
266
+ * The projects the picker offers. A program that connects only to Overvues Dev hubs (the
267
+ * `overvues` build, which has already checked the hub reports that kind) never offers a GitHub
268
+ * project: that hub refuses them. The `tiller` build offers whatever the hub lists.
269
+ */
270
+ export function offeredRepos(repos, identity = CLI) {
271
+ if (identity.hubKinds.includes("tiller"))
272
+ return [...repos];
273
+ return repos.filter((repo) => repo.scmModel !== "github");
274
+ }
275
+ async function createEnv(hubUrl, headers, params) {
276
+ const res = await fetch(`${hubUrl}/api/envs`, {
277
+ method: "POST",
278
+ headers: { ...headers, "Content-Type": "application/json" },
279
+ body: JSON.stringify(params),
280
+ });
281
+ if (!res.ok) {
282
+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
283
+ throw new Error(body.error ?? `Failed to create env: ${res.status}`);
284
+ }
285
+ return res.json();
286
+ }
287
+ // ── Correlate sessions to envs ───────────────────────────────────────
288
+ function sessionsForEnv(env, sessions) {
289
+ return sessions.filter((s) => {
290
+ if (!s.active || s.ended_at)
291
+ return false;
292
+ try {
293
+ const meta = JSON.parse(s.metadata || "{}");
294
+ if (meta.envSlug)
295
+ return meta.envSlug === env.slug;
296
+ if (meta.runnerId && env.runnerId)
297
+ return meta.runnerId === env.runnerId;
298
+ if (meta.repoId)
299
+ return meta.repoId === env.repoId;
300
+ }
301
+ catch { /* ignore */ }
302
+ return false;
303
+ });
304
+ }
305
+ // ── Raw key reader ───────────────────────────────────────────────────
306
+ // Uses an input queue so rapid keystrokes between readKey() calls are
307
+ // not dropped. When data arrives and a caller is waiting, it resolves
308
+ // immediately; otherwise the keystrokes are buffered for the next call.
309
+ const keyBuffer = [];
310
+ let keyWaiter = null;
311
+ function parseKey(str) {
312
+ if (str === `${ESC}[A`)
313
+ return "up";
314
+ if (str === `${ESC}[B`)
315
+ return "down";
316
+ if (str === "\r" || str === "\n")
317
+ return "enter";
318
+ if (str === "q" || str === "Q")
319
+ return "quit";
320
+ if (str === "b" || str === "B")
321
+ return "back";
322
+ if (str === "s" || str === "S")
323
+ return "toggle-start-stop";
324
+ if (str === "d" || str === "D")
325
+ return "delete";
326
+ if (str === "n" || str === "N")
327
+ return "new";
328
+ if (str === "\x03")
329
+ return "ctrl-c";
330
+ return str;
331
+ }
332
+ function createKeyListener() {
333
+ return (data) => {
334
+ const key = parseKey(data.toString());
335
+ if (keyWaiter) {
336
+ const resolve = keyWaiter;
337
+ keyWaiter = null;
338
+ resolve(key);
339
+ }
340
+ else {
341
+ keyBuffer.push(key);
342
+ }
343
+ };
344
+ }
345
+ function clearKeyState() {
346
+ keyBuffer.length = 0;
347
+ keyWaiter = null;
348
+ }
349
+ function readKey() {
350
+ if (keyBuffer.length > 0) {
351
+ return Promise.resolve(keyBuffer.shift());
352
+ }
353
+ return new Promise((resolve) => {
354
+ keyWaiter = resolve;
355
+ });
356
+ }
357
+ // ── Render a selectable list ─────────────────────────────────────────
358
+ function renderList(title, items, selectedIndex, footer, detailLines = [], skippable) {
359
+ let output = `${ansi.eraseLine}${ansi.bold}${title}${ansi.reset}\n`;
360
+ for (let i = 0; i < items.length; i++) {
361
+ if (skippable?.has(i)) {
362
+ output += `${ansi.eraseLine}${items[i]}\n`;
363
+ }
364
+ else if (i === selectedIndex) {
365
+ output += `${ansi.eraseLine} ${ansi.inverse} ${items[i]} ${ansi.reset}\n`;
366
+ }
367
+ else {
368
+ output += `${ansi.eraseLine} ${items[i]}\n`;
369
+ }
370
+ }
371
+ if (detailLines.length > 0) {
372
+ output += `${ansi.eraseLine}\n${ansi.bold}${ansi.magenta}Details${ansi.reset}\n`;
373
+ for (const line of detailLines) {
374
+ output += `${ansi.eraseLine} ${line}\n`;
375
+ }
376
+ }
377
+ output += `${ansi.eraseLine}\n${ansi.dim}${footer}${ansi.reset}`;
378
+ process.stderr.write(`${ansi.clearScreen}${output}`);
379
+ }
380
+ function nextSelectable(from, dir, count, skippable) {
381
+ if (!skippable || skippable.size === 0)
382
+ return (from + dir + count) % count;
383
+ let pos = from;
384
+ for (let i = 0; i < count; i++) {
385
+ pos = (pos + dir + count) % count;
386
+ if (!skippable.has(pos))
387
+ return pos;
388
+ }
389
+ return from;
390
+ }
391
+ function firstSelectable(count, skippable) {
392
+ for (let i = 0; i < count; i++) {
393
+ if (!skippable?.has(i))
394
+ return i;
395
+ }
396
+ return 0;
397
+ }
398
+ async function selectFromList(title, items, footer, renderDetails, options) {
399
+ if (items.length === 0)
400
+ return { kind: "back" };
401
+ const skip = options?.skippable;
402
+ let selected = firstSelectable(items.length, skip);
403
+ const render = () => renderList(title, items, selected, footer, renderDetails?.(selected) ?? [], skip);
404
+ render();
405
+ while (true) {
406
+ const key = await readKey();
407
+ switch (key) {
408
+ case "up":
409
+ selected = nextSelectable(selected, -1, items.length, skip);
410
+ render();
411
+ break;
412
+ case "down":
413
+ selected = nextSelectable(selected, 1, items.length, skip);
414
+ render();
415
+ break;
416
+ case "enter":
417
+ return { kind: "select", index: selected };
418
+ case "back":
419
+ return { kind: "back" };
420
+ case "toggle-start-stop":
421
+ if (options?.allowToggleStartStop) {
422
+ return { kind: "toggle-start-stop", index: selected };
423
+ }
424
+ break;
425
+ case "delete":
426
+ if (options?.allowDelete) {
427
+ return { kind: "delete", index: selected };
428
+ }
429
+ break;
430
+ case "new":
431
+ if (options?.allowNew) {
432
+ return { kind: "new", index: selected };
433
+ }
434
+ break;
435
+ case "quit":
436
+ case "ctrl-c":
437
+ return { kind: "quit" };
438
+ }
439
+ }
440
+ }
441
+ function summarizeSession(session) {
442
+ let meta = {};
443
+ try {
444
+ meta = JSON.parse(session.metadata || "{}");
445
+ }
446
+ catch {
447
+ meta = {};
448
+ }
449
+ return {
450
+ session,
451
+ cwdLabel: meta.cwd || "",
452
+ ago: timeAgo(session.updated_at),
453
+ };
454
+ }
455
+ function envDetailLines(env) {
456
+ const status = normalizeStatus(env.status);
457
+ let action = "Press s to start";
458
+ if (status === "running")
459
+ action = "Press s to stop";
460
+ else if (status === "creating" || status === "starting" || status === "created")
461
+ action = "Press s to stop";
462
+ else if (status === "saving" || status === "stopping" || status === "deleting")
463
+ action = "Waiting for stop to finish";
464
+ else if (status === "failed")
465
+ action = "Press s to retry start";
466
+ const lines = [
467
+ `${ansi.bold}Name:${ansi.reset} ${envDisplayLabel(env)}`,
468
+ `${ansi.bold}Repo:${ansi.reset} ${truncate(repoLabel(env.repoUrl))}`,
469
+ `${ansi.bold}Execution backend:${ansi.reset} ${env.backend === "host" ? "Your machine" : "Cloudflare"}`,
470
+ ];
471
+ const auth = authDetailLabel(env);
472
+ if (auth) {
473
+ lines.push(`${ansi.bold}Auth:${ansi.reset} ${auth}`);
474
+ }
475
+ lines.push(`${ansi.bold}Status:${ansi.reset} ${status}`, `${ansi.bold}Slug:${ansi.reset} ${env.slug}`, `${ansi.bold}Action:${ansi.reset} ${action}`);
476
+ if (env.bootMessage) {
477
+ lines.push(`${ansi.bold}Boot:${ansi.reset} ${truncate(env.bootMessage)}`);
478
+ }
479
+ return lines;
480
+ }
481
+ function sessionDetailLines(summary) {
482
+ const lines = [
483
+ `${ansi.bold}Tag:${ansi.reset} ${summary.session.tag}`,
484
+ `${ansi.bold}Updated:${ansi.reset} ${summary.ago}`,
485
+ `${ansi.bold}Session:${ansi.reset} ${summary.session.id}`,
486
+ ];
487
+ if (summary.cwdLabel) {
488
+ lines.push(`${ansi.bold}Cwd:${ansi.reset} ${truncate(summary.cwdLabel)}`);
489
+ }
490
+ return lines;
491
+ }
492
+ // ── Boot-wait flow ───────────────────────────────────────────────────
493
+ async function waitForSession(hubUrl, env, headers, opts = {}) {
494
+ const label = envDisplayLabel(env, true);
495
+ if (opts.skipStart) {
496
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.cyan}${label}${ansi.reset} is starting, waiting for session...\n`);
497
+ }
498
+ else {
499
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} Starting ${ansi.cyan}${label}${ansi.reset}...\n`);
500
+ await startEnv(hubUrl, env.slug, headers);
501
+ autoStartedEnvSlugs.add(env.slug);
502
+ }
503
+ // Connect WS to receive boot progress
504
+ const hub = new HubClient({ hubUrl, cfAccessHeaders: headers });
505
+ hub.on("env-status-changed", (_slug, _status, message) => {
506
+ if (message) {
507
+ process.stderr.write(`${ansi.eraseLine}${ansi.dim}${CLI.logTag} ${message}${ansi.reset}\n`);
508
+ }
509
+ });
510
+ hub.connect();
511
+ // Poll for sessions until one appears on this env
512
+ const POLL_INTERVAL = 2000;
513
+ const MAX_WAIT = 300_000; // 5 minutes
514
+ const start = Date.now();
515
+ try {
516
+ while (Date.now() - start < MAX_WAIT) {
517
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL));
518
+ const sessions = await fetchSessions(hubUrl, headers);
519
+ const matching = sessionsForEnv(env, sessions);
520
+ if (matching.length > 0) {
521
+ process.stderr.write(`${ansi.eraseLine}${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.green}Session ready.${ansi.reset}\n`);
522
+ return matching[0];
523
+ }
524
+ }
525
+ process.stderr.write(`\n${ansi.red}${CLI.logTag} Timed out waiting for session.${ansi.reset}\n`);
526
+ return null;
527
+ }
528
+ finally {
529
+ hub.close();
530
+ }
531
+ }
532
+ function shouldStartEnv(status) {
533
+ return status === "stopped" || status === "destroyed" || status === "failed" || status === "unknown";
534
+ }
535
+ function canStopEnv(status) {
536
+ return status === "running" || status === "creating" || status === "starting" || status === "created" || status === "waiting";
537
+ }
538
+ async function waitForEnvStatus(hubUrl, slug, headers, isComplete, timeoutMs = 30_000) {
539
+ const startedAt = Date.now();
540
+ while (Date.now() - startedAt < timeoutMs) {
541
+ const env = await fetchEnv(hubUrl, slug, headers);
542
+ const status = normalizeStatus(env?.status);
543
+ if (isComplete(status))
544
+ return status;
545
+ await new Promise((r) => setTimeout(r, 1000));
546
+ }
547
+ return null;
548
+ }
549
+ async function toggleEnvLifecycle(hubUrl, env, headers) {
550
+ const label = envDisplayLabel(env, true);
551
+ if (shouldStartEnv(env.status || "unknown")) {
552
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} Starting ${ansi.cyan}${label}${ansi.reset}...\n`);
553
+ await startEnv(hubUrl, env.slug, headers);
554
+ autoStartedEnvSlugs.add(env.slug);
555
+ await waitForSession(hubUrl, { ...env, status: "starting" }, headers, { skipStart: true });
556
+ return "refresh";
557
+ }
558
+ if (env.status === "starting" || env.status === "created") {
559
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} Stopping ${ansi.cyan}${label}${ansi.reset}...\n`);
560
+ await stopEnv(hubUrl, env.slug, headers);
561
+ autoStartedEnvSlugs.delete(env.slug);
562
+ const status = await waitForEnvStatus(hubUrl, env.slug, headers, (nextStatus) => nextStatus === "stopped" || nextStatus === "failed");
563
+ if (status) {
564
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.cyan}${label}${ansi.reset} is ${status}.\n`);
565
+ }
566
+ return "refresh";
567
+ }
568
+ if (canStopEnv(env.status)) {
569
+ process.stderr.write(`\n${ansi.bold}${CLI.logTag}${ansi.reset} Stopping ${ansi.cyan}${label}${ansi.reset}...\n`);
570
+ await stopEnv(hubUrl, env.slug, headers);
571
+ autoStartedEnvSlugs.delete(env.slug);
572
+ const status = await waitForEnvStatus(hubUrl, env.slug, headers, (nextStatus) => nextStatus === "stopped" || nextStatus === "failed");
573
+ if (status) {
574
+ process.stderr.write(`${ansi.bold}${CLI.logTag}${ansi.reset} ${ansi.cyan}${label}${ansi.reset} is ${status}.\n`);
575
+ }
576
+ return "refresh";
577
+ }
578
+ process.stderr.write(`\n${ansi.yellow}${CLI.logTag} No lifecycle action available for ${label}.${ansi.reset}\n`);
579
+ await new Promise((r) => setTimeout(r, 800));
580
+ return "refresh";
581
+ }
582
+ export async function shutdownAutoStartedLocalEnvs(hubUrl, headers) {
583
+ if (autoStartedEnvSlugs.size === 0)
584
+ return;
585
+ for (const slug of [...autoStartedEnvSlugs]) {
586
+ pickerLog(`Stopping env ${ansi.cyan}${slug}${ansi.reset}...`);
587
+ try {
588
+ await stopEnv(hubUrl, slug, headers);
589
+ pickerLog(`Stopped env ${ansi.cyan}${slug}${ansi.reset}.`);
590
+ }
591
+ catch (error) {
592
+ pickerLog(`${ansi.yellow}Failed to stop env ${slug}: ${error instanceof Error ? error.message : String(error)}${ansi.reset}`);
593
+ }
594
+ finally {
595
+ autoStartedEnvSlugs.delete(slug);
596
+ }
597
+ }
598
+ }
599
+ // ── Main picker entry point ──────────────────────────────────────────
600
+ export async function pickAndConnect(hubUrl, cfHeaders) {
601
+ // Set raw mode for interactive selection
602
+ const wasTTY = process.stdin.isTTY;
603
+ clearKeyState();
604
+ const onKeyData = createKeyListener();
605
+ if (wasTTY)
606
+ process.stdin.setRawMode(true);
607
+ process.stdin.resume();
608
+ process.stdin.on("data", onKeyData);
609
+ process.stderr.write(ansi.hideCursor);
610
+ try {
611
+ return await pickerLoop(hubUrl, cfHeaders);
612
+ }
613
+ finally {
614
+ process.stdin.removeListener("data", onKeyData);
615
+ clearKeyState();
616
+ process.stderr.write(ansi.showCursor);
617
+ if (wasTTY)
618
+ process.stdin.setRawMode(false);
619
+ process.stdin.pause();
620
+ }
621
+ }
622
+ // ── Prompt helpers (used by create/delete flows) ────────────────────
623
+ function promptLine(question) {
624
+ return new Promise((resolve) => {
625
+ process.stderr.write(ansi.showCursor);
626
+ process.stderr.write(`${question} `);
627
+ // Temporarily exit raw mode for readline-style input
628
+ if (process.stdin.isTTY)
629
+ process.stdin.setRawMode(false);
630
+ let buf = "";
631
+ const onData = (data) => {
632
+ const str = data.toString();
633
+ if (str.includes("\n") || str.includes("\r")) {
634
+ process.stdin.removeListener("data", onData);
635
+ if (process.stdin.isTTY)
636
+ process.stdin.setRawMode(true);
637
+ process.stderr.write(ansi.hideCursor);
638
+ resolve(buf.trim());
639
+ }
640
+ else {
641
+ buf += str;
642
+ process.stderr.write(str);
643
+ }
644
+ };
645
+ process.stdin.on("data", onData);
646
+ });
647
+ }
648
+ async function promptConfirm(question) {
649
+ const answer = await promptLine(`${question} [y/N]`);
650
+ return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
651
+ }
652
+ // ── Create environment flow ─────────────────────────────────────────
653
+ async function runCreateEnvFlow(hubUrl, headers, repo) {
654
+ // Pick model
655
+ const modelChoice = await selectFromList("Select model", [" Claude Code", " Codex", " OpenCode"], "\u2191\u2193 navigate enter select b back");
656
+ if (modelChoice.kind !== "select")
657
+ return;
658
+ const harness = modelChoice.index === 1
659
+ ? "codex"
660
+ : modelChoice.index === 2
661
+ ? "opencode"
662
+ : "claude-code";
663
+ try {
664
+ const env = await createEnv(hubUrl, headers, {
665
+ repoId: repo.repoId,
666
+ harness,
667
+ });
668
+ pickerLog(`Created ${ansi.cyan}${envDisplayLabel(env, true)}${ansi.reset}.`);
669
+ }
670
+ catch (error) {
671
+ pickerLog(`${ansi.red}${error instanceof Error ? error.message : String(error)}${ansi.reset}`);
672
+ }
673
+ await new Promise((r) => setTimeout(r, 800));
674
+ }
675
+ // ── Main picker loop ────────────────────────────────────────────────
676
+ async function pickerLoop(hubUrl, cfHeaders) {
677
+ while (true) {
678
+ // Fetch envs, sessions, and repos in parallel
679
+ const [rawEnvs, sessions, repos] = await Promise.all([
680
+ fetchEnvs(hubUrl, cfHeaders),
681
+ fetchSessions(hubUrl, cfHeaders),
682
+ fetchRepos(hubUrl, cfHeaders),
683
+ ]);
684
+ // Sort envs: running first, then by creation date
685
+ const envs = [...rawEnvs].sort((a, b) => {
686
+ const rankDelta = statusRank(normalizeStatus(a.status)) - statusRank(normalizeStatus(b.status));
687
+ if (rankDelta !== 0)
688
+ return rankDelta;
689
+ return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
690
+ });
691
+ if (envs.length === 0) {
692
+ if (repos.length === 0) {
693
+ process.stderr.write(`\n${ansi.yellow}${CLI.logTag} No environments or repos found.${ansi.reset}\n`);
694
+ return null;
695
+ }
696
+ // No envs but repos exist — let user pick a repo to create an env on
697
+ const repoItems = repos.map((r) => ` ${repoLabel(r.repoUrl)}`);
698
+ process.stderr.write(`\n${ansi.yellow}${CLI.logTag} No environments found. Select a repo to create one.${ansi.reset}\n`);
699
+ const repoChoice = await selectFromList("Select repo", repoItems, "\u2191\u2193 navigate enter select q quit");
700
+ if (repoChoice.kind === "select") {
701
+ await runCreateEnvFlow(hubUrl, cfHeaders, repos[repoChoice.index]);
702
+ }
703
+ else {
704
+ return null;
705
+ }
706
+ continue;
707
+ }
708
+ // Detect current repo from cwd
709
+ const cwdRepoUrl = detectCurrentRepoUrl();
710
+ // Group envs by repo
711
+ const repoMap = new Map();
712
+ for (const repo of repos) {
713
+ repoMap.set(repo.repoId, repo);
714
+ }
715
+ const groups = new Map();
716
+ for (const env of envs) {
717
+ if (!groups.has(env.repoId))
718
+ groups.set(env.repoId, []);
719
+ groups.get(env.repoId).push(env);
720
+ }
721
+ // Sort groups: current repo first, then by best env status
722
+ const sortedGroups = [...groups.entries()].sort(([aRepoId, aEnvs], [bRepoId, bEnvs]) => {
723
+ const aUrl = repoMap.get(aRepoId)?.repoUrl ?? aEnvs[0]?.repoUrl ?? aRepoId;
724
+ const bUrl = repoMap.get(bRepoId)?.repoUrl ?? bEnvs[0]?.repoUrl ?? bRepoId;
725
+ const aIsCurrent = cwdRepoUrl ? normalizeRepoUrl(aUrl) === cwdRepoUrl : false;
726
+ const bIsCurrent = cwdRepoUrl ? normalizeRepoUrl(bUrl) === cwdRepoUrl : false;
727
+ if (aIsCurrent !== bIsCurrent)
728
+ return aIsCurrent ? -1 : 1;
729
+ const aMin = Math.min(...aEnvs.map((e) => statusRank(normalizeStatus(e.status))));
730
+ const bMin = Math.min(...bEnvs.map((e) => statusRank(normalizeStatus(e.status))));
731
+ return aMin - bMin;
732
+ });
733
+ // Build grouped display list
734
+ const items = [];
735
+ const skippable = new Set();
736
+ const indexToEnv = new Map();
737
+ for (const [repoId, groupEnvs] of sortedGroups) {
738
+ const repo = repoMap.get(repoId);
739
+ const repoUrl = repo?.repoUrl ?? groupEnvs[0]?.repoUrl ?? repoId;
740
+ const isCurrent = cwdRepoUrl ? normalizeRepoUrl(repoUrl) === cwdRepoUrl : false;
741
+ if (isCurrent) {
742
+ // Box around current repo header
743
+ const rl = repoLabel(repoUrl);
744
+ const innerText = ` ${rl} \u00b7 current repo `;
745
+ const w = innerText.length;
746
+ const topIdx = items.length;
747
+ items.push(` ${ansi.cyan}\u250c${"\u2500".repeat(w)}\u2510${ansi.reset}`);
748
+ skippable.add(topIdx);
749
+ const midIdx = items.length;
750
+ items.push(` ${ansi.cyan}\u2502${ansi.reset} ${ansi.bold}${rl}${ansi.reset} ${ansi.dim}\u00b7 current repo${ansi.reset} ${ansi.cyan}\u2502${ansi.reset}`);
751
+ skippable.add(midIdx);
752
+ const botIdx = items.length;
753
+ items.push(` ${ansi.cyan}\u2514${"\u2500".repeat(w)}\u2518${ansi.reset}`);
754
+ skippable.add(botIdx);
755
+ }
756
+ else {
757
+ const headerIdx = items.length;
758
+ items.push(`\n ${ansi.bold}${repoLabel(repoUrl)}${ansi.reset}`);
759
+ skippable.add(headerIdx);
760
+ }
761
+ for (const env of groupEnvs) {
762
+ const idx = items.length;
763
+ const statusLabel = normalizeStatus(env.status);
764
+ const auth = authBadge(env);
765
+ const authPart = auth ? ` ${auth}` : "";
766
+ items.push(`${statusIcon(statusLabel)} ${envDisplayLabel(env, true)} ${backendBadge(env.backend)}${authPart} ${ansi.dim}(${statusLabel})${ansi.reset}`);
767
+ indexToEnv.set(idx, env);
768
+ }
769
+ }
770
+ const envChoice = await selectFromList("Environments", items, "\u2191\u2193 navigate enter attach s start/stop d delete n new q quit", (selectedIndex) => {
771
+ const env = indexToEnv.get(selectedIndex);
772
+ return env ? envDetailLines(env) : [];
773
+ }, { allowToggleStartStop: true, allowDelete: true, allowNew: true, skippable });
774
+ if (envChoice.kind === "quit" || envChoice.kind === "back")
775
+ return null;
776
+ if (envChoice.kind === "new") {
777
+ const nearEnv = indexToEnv.get(envChoice.index);
778
+ if (nearEnv) {
779
+ const repo = repoMap.get(nearEnv.repoId);
780
+ if (repo) {
781
+ await runCreateEnvFlow(hubUrl, cfHeaders, repo);
782
+ }
783
+ else {
784
+ pickerLog(`${ansi.red}Repository metadata is unavailable for ${repoLabel(nearEnv.repoUrl)}.${ansi.reset}`);
785
+ await new Promise((r) => setTimeout(r, 800));
786
+ }
787
+ }
788
+ continue;
789
+ }
790
+ if (envChoice.kind === "delete") {
791
+ const env = indexToEnv.get(envChoice.index);
792
+ if (env) {
793
+ const label = envDisplayLabel(env, true);
794
+ const canDelete = env.status === "stopped" || env.status === "destroyed" || env.status === "failed";
795
+ if (!canDelete) {
796
+ process.stderr.write(`\n${ansi.yellow}${CLI.logTag} Stop ${label} before deleting.${ansi.reset}\n`);
797
+ await new Promise((r) => setTimeout(r, 800));
798
+ }
799
+ else if (await promptConfirm(`Delete environment ${ansi.cyan}${label}${ansi.reset}?`)) {
800
+ try {
801
+ await deleteEnv(hubUrl, env.slug, cfHeaders);
802
+ pickerLog(`Deleted ${ansi.cyan}${label}${ansi.reset}.`);
803
+ }
804
+ catch (error) {
805
+ pickerLog(`${ansi.red}${error instanceof Error ? error.message : String(error)}${ansi.reset}`);
806
+ }
807
+ await new Promise((r) => setTimeout(r, 500));
808
+ }
809
+ }
810
+ continue;
811
+ }
812
+ const selectedEnv = indexToEnv.get(envChoice.index);
813
+ if (!selectedEnv)
814
+ continue;
815
+ if (envChoice.kind === "toggle-start-stop") {
816
+ await toggleEnvLifecycle(hubUrl, selectedEnv, cfHeaders);
817
+ continue;
818
+ }
819
+ const envSessions = sessionsForEnv(selectedEnv, sessions);
820
+ // If env is stopped, start it and wait
821
+ if (shouldStartEnv(selectedEnv.status || "unknown")) {
822
+ const session = await waitForSession(hubUrl, selectedEnv, cfHeaders);
823
+ if (session) {
824
+ return { session, env: selectedEnv };
825
+ }
826
+ continue;
827
+ }
828
+ // If env is already starting, wait for session without re-issuing start
829
+ if (selectedEnv.status === "starting" || selectedEnv.status === "created") {
830
+ const session = await waitForSession(hubUrl, selectedEnv, cfHeaders, { skipStart: true });
831
+ if (session) {
832
+ return { session, env: selectedEnv };
833
+ }
834
+ continue;
835
+ }
836
+ // Running env — auto-attach if single session, otherwise pick
837
+ if (envSessions.length === 0) {
838
+ process.stderr.write(`\n${ansi.yellow}${CLI.logTag} No active sessions on ${envDisplayLabel(selectedEnv, true)}.${ansi.reset}\n`);
839
+ await new Promise((r) => setTimeout(r, 500));
840
+ continue;
841
+ }
842
+ if (envSessions.length === 1) {
843
+ return { session: envSessions[0], env: selectedEnv };
844
+ }
845
+ // Multiple sessions — show session picker
846
+ const sessionSummaries = envSessions
847
+ .map((s) => summarizeSession(s))
848
+ .sort((a, b) => new Date(b.session.updated_at).getTime() - new Date(a.session.updated_at).getTime());
849
+ const sessionItems = sessionSummaries.map((summary) => {
850
+ const activeIcon = summary.session.active ? `${ansi.green}\u25cf${ansi.reset}` : `${ansi.dim}\u25cb${ansi.reset}`;
851
+ return `${activeIcon} ${summary.session.tag} ${ansi.dim}${summary.cwdLabel} ${summary.ago}${ansi.reset}`;
852
+ });
853
+ const sessionChoice = await selectFromList(`Sessions on ${envDisplayLabel(selectedEnv, true)}`, sessionItems, "\u2191\u2193 navigate enter select b back q/Ctrl+C quit", (selectedIndex) => {
854
+ const session = sessionSummaries[selectedIndex];
855
+ return session ? sessionDetailLines(session) : [];
856
+ });
857
+ if (sessionChoice.kind === "quit")
858
+ return null;
859
+ if (sessionChoice.kind !== "select")
860
+ continue;
861
+ return { session: sessionSummaries[sessionChoice.index].session, env: selectedEnv };
862
+ }
863
+ }