litmus-cli 1.5.0-beta.3 → 1.5.0-beta.5

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 (57) hide show
  1. package/dist/commands/connect.d.ts.map +1 -1
  2. package/dist/commands/connect.js +187 -40
  3. package/dist/commands/connect.js.map +1 -1
  4. package/dist/lib/api.d.ts.map +1 -1
  5. package/dist/lib/api.js +4 -1
  6. package/dist/lib/api.js.map +1 -1
  7. package/dist/lib/capture-storage-error.d.ts +9 -0
  8. package/dist/lib/capture-storage-error.d.ts.map +1 -0
  9. package/dist/lib/capture-storage-error.js +17 -0
  10. package/dist/lib/capture-storage-error.js.map +1 -0
  11. package/dist/lib/editor-foreground.d.ts +9 -1
  12. package/dist/lib/editor-foreground.d.ts.map +1 -1
  13. package/dist/lib/editor-foreground.js +15 -0
  14. package/dist/lib/editor-foreground.js.map +1 -1
  15. package/dist/lib/hosted-capture.d.ts.map +1 -1
  16. package/dist/lib/hosted-capture.js +36 -10
  17. package/dist/lib/hosted-capture.js.map +1 -1
  18. package/dist/lib/installed-tools.d.ts +3 -0
  19. package/dist/lib/installed-tools.d.ts.map +1 -1
  20. package/dist/lib/installed-tools.js +31 -18
  21. package/dist/lib/installed-tools.js.map +1 -1
  22. package/dist/lib/launcher-cleanup-journal.d.ts +44 -0
  23. package/dist/lib/launcher-cleanup-journal.d.ts.map +1 -0
  24. package/dist/lib/launcher-cleanup-journal.js +196 -0
  25. package/dist/lib/launcher-cleanup-journal.js.map +1 -0
  26. package/dist/lib/launcher-inventory-cache.d.ts +44 -0
  27. package/dist/lib/launcher-inventory-cache.d.ts.map +1 -0
  28. package/dist/lib/launcher-inventory-cache.js +126 -0
  29. package/dist/lib/launcher-inventory-cache.js.map +1 -0
  30. package/dist/lib/launcher-preparation-cache.d.ts +46 -0
  31. package/dist/lib/launcher-preparation-cache.d.ts.map +1 -0
  32. package/dist/lib/launcher-preparation-cache.js +131 -0
  33. package/dist/lib/launcher-preparation-cache.js.map +1 -0
  34. package/dist/lib/portal-launcher-background.d.ts +2 -0
  35. package/dist/lib/portal-launcher-background.d.ts.map +1 -1
  36. package/dist/lib/portal-launcher-background.js.map +1 -1
  37. package/dist/lib/portal-launcher.d.ts +40 -5
  38. package/dist/lib/portal-launcher.d.ts.map +1 -1
  39. package/dist/lib/portal-launcher.js +347 -75
  40. package/dist/lib/portal-launcher.js.map +1 -1
  41. package/dist/lib/prepared-editor.d.ts.map +1 -1
  42. package/dist/lib/prepared-editor.js +20 -5
  43. package/dist/lib/prepared-editor.js.map +1 -1
  44. package/dist/lib/ssh-config-file.d.ts +13 -2
  45. package/dist/lib/ssh-config-file.d.ts.map +1 -1
  46. package/dist/lib/ssh-config-file.js +32 -27
  47. package/dist/lib/ssh-config-file.js.map +1 -1
  48. package/dist/lib/tool-installation-watcher.d.ts +20 -0
  49. package/dist/lib/tool-installation-watcher.d.ts.map +1 -0
  50. package/dist/lib/tool-installation-watcher.js +112 -0
  51. package/dist/lib/tool-installation-watcher.js.map +1 -0
  52. package/dist/lib/tracker.d.ts.map +1 -1
  53. package/dist/lib/tracker.js +13 -2
  54. package/dist/lib/tracker.js.map +1 -1
  55. package/dist/program.js +9 -2
  56. package/dist/program.js.map +1 -1
  57. package/package.json +1 -1
@@ -1,12 +1,14 @@
1
1
  /** Candidate-scoped, outbound-only launcher. No localhost listener or arbitrary commands. */
2
2
  import { fetchSubmissionSaved } from "./api.js";
3
- import { spawn, fork } from "child_process";
3
+ import { execFile, spawn, fork } from "child_process";
4
4
  import { mkdirSync, writeFileSync } from "fs";
5
5
  import os from "os";
6
6
  import path from "path";
7
- import { discoverInstalledTools } from "./installed-tools.js";
7
+ import { discoverInstalledTool, discoverInstalledTools } from "./installed-tools.js";
8
+ import { watchToolInstallations } from "./tool-installation-watcher.js";
8
9
  import { configSetsRemoteCommand } from "./ssh-client.js";
9
10
  import { parsePreparedEditor, parseWorkspaceGeneration } from "./prepared-editor.js";
11
+ import { CLI_VERSION } from "./version.js";
10
12
  class LauncherRefusal extends Error {
11
13
  constructor(status, readinessPending = false, code) {
12
14
  super(`Launcher request refused (${status}). Re-run litmus connect to reconnect.`);
@@ -18,6 +20,34 @@ class LauncherRefusal extends Error {
18
20
  export function permanentLauncherFailure(error) {
19
21
  return error instanceof LauncherRefusal && !error.readinessPending && error.status >= 400 && error.status < 500 && ![408, 429].includes(error.status);
20
22
  }
23
+ export function desktopLaunchOutcome(tool, opened) {
24
+ if (!opened)
25
+ return "failed";
26
+ return tool === "claude"
27
+ ? { status: "action_required", reason: "confirmation_required" }
28
+ : "dispatched";
29
+ }
30
+ /** Fixed-schema best-effort receipt; observation can never delay the launcher. */
31
+ export function reportLauncherTiming(backendUrl, token, stage, elapsedMs, extra = {}) {
32
+ if (!Number.isFinite(elapsedMs) || elapsedMs < 0)
33
+ return;
34
+ try {
35
+ void fetch(`${backendUrl}/workspace/launcher/timings`, {
36
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(3000),
37
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
38
+ body: JSON.stringify({
39
+ stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001),
40
+ temperature: extra.temperature ?? "unknown",
41
+ os: process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : process.platform === "linux" ? "linux" : "unknown",
42
+ app_version: CLI_VERSION,
43
+ ...(extra.tool ? { tool: extra.tool } : {}), ...(extra.outcome ? { outcome: extra.outcome } : {}),
44
+ ...(extra.sessionId ? { session_id: extra.sessionId } : {}), ...(extra.requestId ? { request_id: extra.requestId } : {}),
45
+ ...(extra.readinessPath ? { readiness_path: extra.readinessPath } : {}),
46
+ }),
47
+ }).catch(() => { });
48
+ }
49
+ catch { /* telemetry must not change the candidate flow */ }
50
+ }
21
51
  export function desktopUrl(tool, alias) {
22
52
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
23
53
  throw new Error("Invalid assessment SSH alias");
@@ -42,6 +72,32 @@ export function terminalRemoteCommand(requestId) {
42
72
  // Fixed remote adapter; old images keep their ordinary interactive shell.
43
73
  return `if test -x ${wrapper}; then exec ${wrapper}${requestId ? ` ${requestId}` : ""}; else cd /home/candidate/workspace && exec bash -l; fi`;
44
74
  }
75
+ const focusTerminalScript = `on run argv
76
+ set targetName to (item 1 of argv) & ".command"
77
+ tell application "Terminal"
78
+ repeat with terminalWindow in windows
79
+ repeat with terminalTab in tabs of terminalWindow
80
+ if custom title of terminalTab is targetName and processes of terminalTab contains "ssh" then
81
+ set selected tab of terminalWindow to terminalTab
82
+ set index of terminalWindow to 1
83
+ activate
84
+ return "focused"
85
+ end if
86
+ end repeat
87
+ end repeat
88
+ end tell
89
+ return ""
90
+ end run`;
91
+ /** Foreground the live, assessment-scoped Terminal session before opening another shell. */
92
+ export function focusExistingMacTerminal(alias, execFileFn = execFile) {
93
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
94
+ return Promise.resolve(false);
95
+ return new Promise(resolve => {
96
+ execFileFn("/usr/bin/osascript", ["-e", focusTerminalScript, alias], { timeout: 1500 }, (error, stdout) => {
97
+ resolve(!error && String(stdout).trim() === "focused");
98
+ });
99
+ });
100
+ }
45
101
  export async function openTerminal(alias, terminal, requestId) {
46
102
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
47
103
  return false;
@@ -50,6 +106,8 @@ export async function openTerminal(alias, terminal, requestId) {
50
106
  if (configSetsRemoteCommand(alias))
51
107
  options.push("-o", "RemoteCommand=none");
52
108
  if (process.platform === "darwin") {
109
+ if (await focusExistingMacTerminal(alias))
110
+ return true;
53
111
  const dir = path.join(os.homedir(), ".litmus", "launchers");
54
112
  mkdirSync(dir, { recursive: true, mode: 0o700 });
55
113
  const file = path.join(dir, `${alias}.command`);
@@ -62,11 +120,12 @@ export async function openTerminal(alias, terminal, requestId) {
62
120
  return spawnDetached(terminal, [flag, "ssh", ...options, alias, remote]);
63
121
  }
64
122
  /** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
65
- export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation) {
123
+ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
66
124
  return new Promise(resolve => {
67
125
  let result = "action_required";
68
126
  let prepared = null;
69
127
  let announced = false;
128
+ let remembered = false;
70
129
  const env = { ...process.env, LITMUS_ASSESSMENT_TOKEN: token, LITMUS_PORTAL_LAUNCHER_CHILD: "1" };
71
130
  delete env.LITMUS_LAUNCH_GENERATION;
72
131
  const currentGeneration = parseWorkspaceGeneration(generation);
@@ -88,12 +147,14 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
88
147
  if (value.type === "litmus-connect-result" && value.result === "server_detected") {
89
148
  result = "dispatched";
90
149
  prepared = parsePreparedEditor(value.preparedEditor);
150
+ if (!remembered && prepared?.tool === tool) {
151
+ remembered = true;
152
+ onPrepared?.(prepared);
153
+ }
91
154
  // The child has verified attachment. Reporting/cleanup can finish after
92
155
  // the UI stops saying Launching; neither is part of opening the editor.
93
156
  if (!announced) {
94
157
  announced = true;
95
- if (prepared?.tool === tool)
96
- onPrepared?.(prepared);
97
158
  resolve("dispatched");
98
159
  }
99
160
  }
@@ -102,12 +163,24 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
102
163
  signal?.addEventListener("abort", stop, { once: true });
103
164
  if (signal?.aborted)
104
165
  stop();
166
+ void remoteReady?.then(ready => {
167
+ if (!ready || announced || signal?.aborted)
168
+ return;
169
+ // This event comes from the managed remote extension only after hostd
170
+ // stamps the current assessment generation and exact workspace folder.
171
+ // The child keeps running its compatibility probe and can still populate
172
+ // the prepared-editor cache after the UI stops waiting.
173
+ announced = true;
174
+ result = "dispatched";
175
+ onRemoteReady?.();
176
+ resolve("dispatched");
177
+ });
105
178
  const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
106
179
  const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
107
180
  child.once("error", () => { cleanup(); resolve("action_required"); });
108
181
  child.once("exit", code => {
109
182
  cleanup();
110
- if (!announced && code === 0 && result === "dispatched" && prepared?.tool === tool)
183
+ if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
111
184
  onPrepared?.(prepared);
112
185
  resolve(code === 0 ? result : "action_required");
113
186
  });
@@ -168,6 +241,9 @@ export async function startPortalPreparation(backendUrl, token) {
168
241
  });
169
242
  }
170
243
  export async function runPortalLauncher(options) {
244
+ const launcherStarted = performance.now();
245
+ const timing = options.reportTiming ?? (() => { });
246
+ timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
171
247
  const abort = new AbortController();
172
248
  const stop = () => abort.abort();
173
249
  options.signal?.addEventListener("abort", stop, { once: true });
@@ -176,25 +252,94 @@ export async function runPortalLauncher(options) {
176
252
  process.once("SIGINT", stop);
177
253
  process.once("SIGTERM", stop);
178
254
  let session = null;
179
- let installed = discoverInstalledTools();
180
- let lastDiscovery = Date.now();
181
- let inventory = JSON.stringify(installed);
255
+ let launcherCompletionReported = false;
256
+ const completeLauncher = (outcome) => {
257
+ if (launcherCompletionReported)
258
+ return;
259
+ launcherCompletionReported = true;
260
+ timing("launcher_ready", options.connectStartedAt ? Date.now() - options.connectStartedAt : performance.now() - launcherStarted, { outcome, ...(session ? { sessionId: session.session_id } : {}) });
261
+ };
262
+ const discoverTools = options.discoverTools ?? discoverInstalledTools;
263
+ const discoverTool = options.discoverTool ?? discoverInstalledTool;
264
+ const watchInstallations = options.watchInstallations ?? watchToolInstallations;
265
+ const inventoryReconcileMs = options.inventoryReconcileMs ?? 300000;
266
+ const cachedInventory = options.cachedInventory;
267
+ timing(cachedInventory ? "tool_inventory_cache_hit" : "tool_inventory_cache_miss", performance.now() - launcherStarted);
268
+ let discovered = cachedInventory?.tools ?? [];
269
+ let installed = discovered;
270
+ let inventory = JSON.stringify(discovered);
182
271
  let changedInventory;
183
272
  let inventoryPoll;
184
- // Local discovery stays independent of the idle server long poll.
185
- const discoveryTimer = setInterval(() => {
186
- const next = discoverInstalledTools();
273
+ let nextInventoryReconcile = Date.now() + inventoryReconcileMs;
274
+ let nextPreparationRetry = Date.now() + 30000;
275
+ const queueInventory = (next) => {
187
276
  const signature = JSON.stringify(next);
188
- if (signature !== inventory) {
189
- inventory = signature;
190
- changedInventory = next;
191
- inventoryPoll?.abort();
277
+ if (signature === inventory)
278
+ return false;
279
+ inventory = signature;
280
+ discovered = next;
281
+ changedInventory = next;
282
+ return true;
283
+ };
284
+ const stopInstallationWatch = watchInstallations(tool => {
285
+ let next;
286
+ if (!tool)
287
+ next = discoverTools();
288
+ else {
289
+ const nextByTool = new Map(discovered.map(candidate => [candidate.tool, candidate]));
290
+ const candidate = discoverTool(tool);
291
+ if (candidate)
292
+ nextByTool.set(tool, candidate);
293
+ else
294
+ nextByTool.delete(tool);
295
+ const order = ["vscode", "cursor", "codex", "claude", "ssh"];
296
+ next = [...nextByTool.values()].sort((a, b) => order.indexOf(a.tool) - order.indexOf(b.tool));
192
297
  }
193
- }, 5000);
298
+ if (queueInventory(next))
299
+ inventoryPoll?.abort();
300
+ }, abort.signal);
194
301
  let seenCommandId = null;
302
+ const seenCommands = new Set();
195
303
  let longPoll = false;
196
304
  let readinessSupported = false;
305
+ let preparationInventorySupported = false;
197
306
  let desktopConnectionSetupSupported = false;
307
+ let editorReadinessEventsSupported = false;
308
+ const eventReadyEditors = new Set();
309
+ const readinessWaiters = new Map();
310
+ const acceptEditorReadiness = (tools) => {
311
+ if (!editorReadinessEventsSupported || !Array.isArray(tools))
312
+ return;
313
+ const next = new Set(tools.filter((tool) => tool === "vscode" || tool === "cursor"));
314
+ for (const tool of ["vscode", "cursor"]) {
315
+ if (!next.has(tool)) {
316
+ eventReadyEditors.delete(tool);
317
+ continue;
318
+ }
319
+ eventReadyEditors.add(tool);
320
+ for (const resolve of readinessWaiters.get(tool) ?? [])
321
+ resolve(true);
322
+ readinessWaiters.delete(tool);
323
+ }
324
+ };
325
+ const waitForEditorReadiness = (tool) => {
326
+ if (!editorReadinessEventsSupported || (tool !== "vscode" && tool !== "cursor"))
327
+ return undefined;
328
+ if (eventReadyEditors.has(tool))
329
+ return Promise.resolve(true);
330
+ return new Promise(resolve => {
331
+ const waiters = readinessWaiters.get(tool) ?? new Set();
332
+ waiters.add(resolve);
333
+ readinessWaiters.set(tool, waiters);
334
+ });
335
+ };
336
+ const readyToolsCursor = () => [...eventReadyEditors].sort().join(",") || "-";
337
+ abort.signal.addEventListener("abort", () => {
338
+ for (const waiters of readinessWaiters.values())
339
+ for (const resolve of waiters)
340
+ resolve(false);
341
+ readinessWaiters.clear();
342
+ }, { once: true });
198
343
  const toolIds = () => [...installed.filter(i => !i.unavailable).map(i => i.tool), ...(options.browserAvailable ? ["browser"] : [])];
199
344
  const unavailableTools = () => Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable === "desktop_setup_failed" && !desktopConnectionSetupSupported ? "workspace_not_ready" : i.unavailable]));
200
345
  async function call(route, body, method = "POST", polling = false) {
@@ -221,8 +366,24 @@ export async function runPortalLauncher(options) {
221
366
  }));
222
367
  try {
223
368
  let registered;
369
+ let cacheRejectedForCompatibility = false;
224
370
  try {
225
- registered = await call("/sessions", { tools: [], phase: "connecting" });
371
+ try {
372
+ registered = await call("/sessions", cachedInventory ? {
373
+ tools: cachedInventory.tools.map(tool => tool.tool),
374
+ preparing: cachedInventory.tools.map(tool => tool.tool),
375
+ phase: "connecting", stage: "checking_tools", cached_generation: cachedInventory.generation,
376
+ } : { tools: [], phase: "connecting" });
377
+ }
378
+ catch (error) {
379
+ // CLI and backend deploy independently. An older strict ToolReport
380
+ // rejects cached_generation; retry once with the original contract.
381
+ if (!cachedInventory || !(error instanceof LauncherRefusal) || error.status !== 422)
382
+ throw error;
383
+ cacheRejectedForCompatibility = true;
384
+ options.onInventoryCacheRejected?.();
385
+ registered = await call("/sessions", { tools: [], phase: "connecting" });
386
+ }
226
387
  }
227
388
  catch (error) {
228
389
  if (!(error instanceof LauncherRefusal) || !([404, 405].includes(error.status) || (error.status === 403 && error.code === "launcher_beta_unavailable")))
@@ -234,40 +395,157 @@ export async function runPortalLauncher(options) {
234
395
  return;
235
396
  }
236
397
  session = registered;
398
+ await options.onRegistered?.(registered.workspace_generation);
237
399
  readinessSupported = registered.tool_readiness === true;
400
+ preparationInventorySupported = registered.preparation_inventory === true;
238
401
  desktopConnectionSetupSupported = registered.desktop_connection_setup === true;
239
- if (options.prepareTools && registered.progress_updates) {
240
- await call(`/sessions/${session.session_id}/poll`, { tools: [], phase: "connecting", stage: "checking_tools" }).catch(() => { });
402
+ editorReadinessEventsSupported = registered.editor_readiness_events === true;
403
+ if (cachedInventory && registered.inventory_cache_accepted !== true) {
404
+ discovered = [];
405
+ installed = [];
406
+ inventory = "[]";
407
+ timing("tool_inventory_cache_rejected", performance.now() - launcherStarted, { sessionId: registered.session_id });
408
+ if (!cacheRejectedForCompatibility)
409
+ options.onInventoryCacheRejected?.();
241
410
  }
242
- if (options.prepareTools) {
411
+ discovered = discoverTools();
412
+ installed = discovered;
413
+ inventory = JSON.stringify(discovered);
414
+ // A watcher event may race registration and queue a delta from the cached
415
+ // startup list. The authoritative full scan supersedes that stale delta.
416
+ changedInventory = undefined;
417
+ const inventoryElapsed = performance.now() - launcherStarted;
418
+ timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
419
+ timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
420
+ options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
421
+ const dispatchCommand = (command) => {
422
+ if (seenCommands.has(command.id))
423
+ return;
424
+ const commandReceived = performance.now();
425
+ timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
426
+ // A poll can redeliver an opening command after its response was lost.
427
+ // Record before launching, including while result delivery retries.
428
+ seenCommands.add(command.id);
429
+ seenCommandId = command.id;
430
+ void (async () => {
431
+ let outcome = { status: "failed" };
432
+ if (toolIds().includes(command.tool)) {
433
+ timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
434
+ const remoteReady = waitForEditorReadiness(command.tool);
435
+ try {
436
+ const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
437
+ outcome = typeof launched === "string" ? { status: launched } : launched;
438
+ }
439
+ catch { /* fixed failure */ }
440
+ const openElapsed = performance.now() - commandReceived;
441
+ timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
442
+ }
443
+ if (abort.signal.aborted)
444
+ return;
445
+ // CLI and backend versions roll independently. Older backends accept
446
+ // action_required but forbid the newer bounded reason field; omit it
447
+ // unless registration explicitly advertised that schema extension.
448
+ const reportedOutcome = outcome.reason && registered.confirmation_reasons !== true
449
+ ? { status: outcome.status }
450
+ : outcome;
451
+ // Deliver the same result again after transport errors; never execute
452
+ // the tool again merely because its acknowledgement was lost.
453
+ // Polling owns the session's lifetime. Cap the delay, not attempts:
454
+ // retain the result until acknowledged, permanently refused or stopped.
455
+ for (let attempt = 0; !abort.signal.aborted; attempt++) {
456
+ try {
457
+ await call(`/sessions/${registered.session_id}/results/${command.id}`, reportedOutcome);
458
+ timing("result_acknowledged", performance.now() - commandReceived, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
459
+ return;
460
+ }
461
+ catch (error) {
462
+ if (permanentLauncherFailure(error)) {
463
+ console.error("Launch result could not be delivered. Check the tool before opening it again.");
464
+ return;
465
+ }
466
+ await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
467
+ }
468
+ }
469
+ })();
470
+ };
471
+ const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
472
+ tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
473
+ unavailable: Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable])),
474
+ preparing: preparingTools.filter(i => !i.unavailable).map(i => i.tool),
475
+ phase: "connecting",
476
+ ...(registered.progress_updates ? { stage: "checking_tools" } : {}),
477
+ } : { tools: [], phase: "connecting", ...(registered.progress_updates ? { stage: "checking_tools" } : {}) };
478
+ const prepareInstalledTools = async (preparingTools, readyTools = []) => {
479
+ if (!options.prepareTools)
480
+ return;
481
+ const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
482
+ const ready = new Set(readyTools);
483
+ let reportInFlight;
484
+ let reportRequested = false;
485
+ let preparationEnded = false;
486
+ const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
487
+ const publishPreparation = () => {
488
+ if (!registered.progress_updates || preparationEnded)
489
+ return reportInFlight ?? Promise.resolve();
490
+ reportRequested = true;
491
+ if (!reportInFlight)
492
+ reportInFlight = (async () => {
493
+ while (reportRequested && !preparationEnded) {
494
+ reportRequested = false;
495
+ const query = seenCommandId ? `?seen_command_id=${encodeURIComponent(seenCommandId)}` : "";
496
+ const reply = await call(`/sessions/${session.session_id}/poll${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
497
+ acceptEditorReadiness(reply?.ready_tools);
498
+ if (reply?.command) {
499
+ dispatchCommand(reply.command);
500
+ // Acknowledge receipt promptly; otherwise a slow opener blocks
501
+ // delivery of another ready tool until the lease renewal.
502
+ reportRequested = true;
503
+ }
504
+ }
505
+ })().finally(() => { reportInFlight = undefined; });
506
+ return reportInFlight;
507
+ };
508
+ await publishPreparation();
243
509
  // Preparing a matching editor server may outlast the initial mailbox
244
510
  // lease. Renew as connecting, without claiming readiness or starting time.
245
511
  // Drain any in-flight renewal before the first ready poll, so a delayed
246
512
  // response cannot put a connected laptop back into preparation.
247
- let preparationEnded = false;
248
- let pendingRenewal;
249
513
  let renewalTimer;
250
514
  const renewPreparation = () => {
251
515
  if (preparationEnded || abort.signal.aborted)
252
516
  return;
253
- pendingRenewal = call(`/sessions/${session.session_id}/poll`, {
254
- tools: [], phase: "connecting", ...(registered.progress_updates ? { stage: "checking_tools" } : {}),
255
- }).then(() => { }, () => { }).finally(() => {
517
+ void publishPreparation().finally(() => {
256
518
  if (!preparationEnded && !abort.signal.aborted)
257
519
  renewalTimer = setTimeout(renewPreparation, 15000);
258
520
  });
259
521
  };
260
522
  renewalTimer = setTimeout(renewPreparation, 15000);
261
523
  try {
262
- installed = await options.prepareTools(installed, abort.signal);
524
+ const preparesEntireInventory = preparingTools.length === installed.length
525
+ && preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
526
+ const preparedTools = await options.prepareTools(preparingTools, abort.signal, async (prepared) => {
527
+ installed = installed.map(tool => tool.tool === prepared.tool ? prepared : tool);
528
+ pendingTools.delete(prepared.tool);
529
+ if (prepared.unavailable)
530
+ ready.delete(prepared.tool);
531
+ else
532
+ ready.add(prepared.tool);
533
+ void publishPreparation();
534
+ }, registered.workspace_generation);
535
+ if (preparesEntireInventory)
536
+ installed = preparedTools;
537
+ else {
538
+ const preparedByTool = new Map(preparedTools.map(tool => [tool.tool, tool]));
539
+ installed = installed.map(tool => preparedByTool.get(tool.tool) ?? tool);
540
+ }
263
541
  }
264
542
  finally {
265
- preparationEnded = true;
266
543
  clearTimeout(renewalTimer);
267
- await pendingRenewal;
544
+ await reportInFlight;
545
+ preparationEnded = true;
268
546
  }
269
- }
270
- lastDiscovery = Date.now();
547
+ };
548
+ await prepareInstalledTools(installed);
271
549
  if (abort.signal.aborted)
272
550
  return;
273
551
  let readyAcknowledged = false;
@@ -275,24 +553,43 @@ export async function runPortalLauncher(options) {
275
553
  let readinessDeadline = Date.now() + 120000;
276
554
  let readinessFailures = 0;
277
555
  let failures = 0;
278
- const seenCommands = new Set();
279
556
  while (!abort.signal.aborted) {
280
- if (changedInventory || Date.now() - lastDiscovery >= 30000) {
281
- installed = changedInventory ?? discoverInstalledTools();
557
+ const now = Date.now();
558
+ if (now >= nextInventoryReconcile) {
559
+ queueInventory(discoverTools());
560
+ nextInventoryReconcile = now + inventoryReconcileMs;
561
+ }
562
+ if (changedInventory) {
563
+ const readyTools = toolIds();
564
+ const readySet = new Set(readyTools);
565
+ installed = changedInventory;
282
566
  changedInventory = undefined;
283
- if (options.prepareTools)
284
- installed = await options.prepareTools(installed, abort.signal);
285
- lastDiscovery = Date.now();
567
+ const newlyInstalled = installed.filter(tool => !tool.unavailable && !readySet.has(tool.tool));
568
+ if (newlyInstalled.length)
569
+ await prepareInstalledTools(newlyInstalled, readyTools);
570
+ }
571
+ if (Date.now() >= nextPreparationRetry) {
572
+ const retryable = new Set(installed.filter(tool => tool.unavailable === "workspace_not_ready" || tool.unavailable === "desktop_setup_failed").map(tool => tool.tool));
573
+ if (retryable.size) {
574
+ const readyTools = toolIds();
575
+ installed = installed.map(tool => retryable.has(tool.tool) ? { ...tool, unavailable: undefined } : tool);
576
+ await prepareInstalledTools(installed.filter(tool => retryable.has(tool.tool)), readyTools);
577
+ }
578
+ nextPreparationRetry = Date.now() + 30000;
286
579
  }
287
580
  let command;
288
581
  try {
289
- // End the wait in time for the next installation inventory refresh.
290
- const waitSeconds = Math.min(25, Math.max(1, Math.ceil((30000 - (Date.now() - lastDiscovery)) / 1000)));
582
+ // End the wait in time for the next retry or bounded reconciliation.
583
+ const nextLocalDeadline = Math.min(nextPreparationRetry, nextInventoryReconcile);
584
+ const waitSeconds = Math.min(25, Math.max(1, Math.ceil((nextLocalDeadline - Date.now()) / 1000)));
291
585
  const query = new URLSearchParams({ wait_seconds: String(readyAcknowledged ? waitSeconds : 0) });
292
586
  if (seenCommandId)
293
587
  query.set("seen_command_id", seenCommandId);
588
+ if (editorReadinessEventsSupported)
589
+ query.set("ready_tools_seen", readyToolsCursor());
294
590
  inventoryPoll = new AbortController();
295
591
  const reply = await call(`/sessions/${registered.session_id}/poll?${query}`, { tools: toolIds(), phase: "ready", ...(readinessSupported ? { unavailable: unavailableTools() } : {}) }, "POST", true);
592
+ acceptEditorReadiness(reply.ready_tools);
296
593
  longPoll = reply.long_poll === true;
297
594
  command = reply.command;
298
595
  failures = 0;
@@ -332,49 +629,23 @@ export async function runPortalLauncher(options) {
332
629
  console.log("\nYour tool launcher is ready. Open tools from your assessment page.");
333
630
  console.log(` ${options.pageUrl}`);
334
631
  options.onReady?.();
632
+ completeLauncher("ok");
335
633
  await options.openUrl(options.pageUrl);
336
634
  }
337
- if (command && !seenCommands.has(command.id)) {
338
- // A poll can redeliver an opening command after its response was lost.
339
- // Record before launching, including while result delivery retries.
340
- seenCommands.add(command.id);
341
- seenCommandId = command.id;
342
- void (async () => {
343
- let status = "failed";
344
- if (toolIds().includes(command.tool)) {
345
- try {
346
- status = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}) });
347
- }
348
- catch { /* fixed failure */ }
349
- }
350
- if (abort.signal.aborted)
351
- return;
352
- // Deliver the same result again after transport errors; never execute
353
- // the tool again merely because its acknowledgement was lost.
354
- // Polling owns the session's lifetime. Cap the delay, not attempts:
355
- // retain the result until acknowledged, permanently refused or stopped.
356
- for (let attempt = 0; !abort.signal.aborted; attempt++) {
357
- try {
358
- await call(`/sessions/${registered.session_id}/results/${command.id}`, { status });
359
- return;
360
- }
361
- catch (error) {
362
- if (permanentLauncherFailure(error)) {
363
- console.error("Launch result could not be delivered. Check the tool before opening it again.");
364
- return;
365
- }
366
- await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
367
- }
368
- }
369
- })();
370
- }
635
+ if (command)
636
+ dispatchCommand(command);
371
637
  // Old backends ignore the query parameters. Preserve their polling rate.
372
638
  if (!longPoll)
373
639
  await wait(5000, abort.signal);
374
640
  }
375
641
  }
642
+ catch (error) {
643
+ completeLauncher(error instanceof LauncherRefusal && error.readinessPending ? "timeout" : "failed");
644
+ throw error;
645
+ }
376
646
  finally {
377
- clearInterval(discoveryTimer);
647
+ completeLauncher("cancelled");
648
+ stopInstallationWatch();
378
649
  abort.abort();
379
650
  if (session)
380
651
  await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
@@ -385,8 +656,9 @@ export async function runPortalLauncher(options) {
385
656
  // Only a positive server acknowledgement permits local connection cleanup.
386
657
  if (session && options.onSubmitted) {
387
658
  try {
388
- if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000))
659
+ if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000)) {
389
660
  await options.onSubmitted();
661
+ }
390
662
  }
391
663
  catch { /* Leave settings intact when submission cannot be verified. */ }
392
664
  }