litmus-cli 1.5.0-beta.1 → 1.5.0-beta.11

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 (151) hide show
  1. package/README.md +26 -4
  2. package/dist/commands/connect.d.ts +23 -0
  3. package/dist/commands/connect.d.ts.map +1 -1
  4. package/dist/commands/connect.js +267 -50
  5. package/dist/commands/connect.js.map +1 -1
  6. package/dist/commands/doctor.d.ts +1 -1
  7. package/dist/commands/doctor.d.ts.map +1 -1
  8. package/dist/commands/doctor.js +16 -4
  9. package/dist/commands/doctor.js.map +1 -1
  10. package/dist/commands/init.d.ts.map +1 -1
  11. package/dist/commands/init.js +25 -6
  12. package/dist/commands/init.js.map +1 -1
  13. package/dist/commands/pause.d.ts.map +1 -1
  14. package/dist/commands/pause.js +12 -2
  15. package/dist/commands/pause.js.map +1 -1
  16. package/dist/cursor-session/extension.cjs +12 -3
  17. package/dist/cursor-session/package.json +3 -3
  18. package/dist/cursor-session/session.cjs +29 -6
  19. package/dist/index.js +10 -232
  20. package/dist/index.js.map +1 -1
  21. package/dist/lib/ai-tracking.d.ts +4 -0
  22. package/dist/lib/ai-tracking.d.ts.map +1 -1
  23. package/dist/lib/ai-tracking.js +68 -0
  24. package/dist/lib/ai-tracking.js.map +1 -1
  25. package/dist/lib/api.d.ts +2 -0
  26. package/dist/lib/api.d.ts.map +1 -1
  27. package/dist/lib/api.js +33 -8
  28. package/dist/lib/api.js.map +1 -1
  29. package/dist/lib/capture-notice-ping.d.ts +7 -27
  30. package/dist/lib/capture-notice-ping.d.ts.map +1 -1
  31. package/dist/lib/capture-notice-ping.js +10 -42
  32. package/dist/lib/capture-notice-ping.js.map +1 -1
  33. package/dist/lib/capture-nudge.d.ts +5 -7
  34. package/dist/lib/capture-nudge.d.ts.map +1 -1
  35. package/dist/lib/capture-nudge.js +19 -35
  36. package/dist/lib/capture-nudge.js.map +1 -1
  37. package/dist/lib/capture-selftest.d.ts +11 -0
  38. package/dist/lib/capture-selftest.d.ts.map +1 -1
  39. package/dist/lib/capture-selftest.js +44 -5
  40. package/dist/lib/capture-selftest.js.map +1 -1
  41. package/dist/lib/capture-startup-diagnostics.d.ts +15 -0
  42. package/dist/lib/capture-startup-diagnostics.d.ts.map +1 -0
  43. package/dist/lib/capture-startup-diagnostics.js +134 -0
  44. package/dist/lib/capture-startup-diagnostics.js.map +1 -0
  45. package/dist/lib/capture-storage-error.d.ts +10 -0
  46. package/dist/lib/capture-storage-error.d.ts.map +1 -0
  47. package/dist/lib/capture-storage-error.js +18 -0
  48. package/dist/lib/capture-storage-error.js.map +1 -0
  49. package/dist/lib/codex-capture-health.d.ts +21 -0
  50. package/dist/lib/codex-capture-health.d.ts.map +1 -0
  51. package/dist/lib/codex-capture-health.js +82 -0
  52. package/dist/lib/codex-capture-health.js.map +1 -0
  53. package/dist/lib/cursor-session.d.ts +4 -0
  54. package/dist/lib/cursor-session.d.ts.map +1 -1
  55. package/dist/lib/cursor-session.js +26 -10
  56. package/dist/lib/cursor-session.js.map +1 -1
  57. package/dist/lib/editor-foreground.d.ts +9 -1
  58. package/dist/lib/editor-foreground.d.ts.map +1 -1
  59. package/dist/lib/editor-foreground.js +15 -0
  60. package/dist/lib/editor-foreground.js.map +1 -1
  61. package/dist/lib/environment-checks.d.ts +1 -3
  62. package/dist/lib/environment-checks.d.ts.map +1 -1
  63. package/dist/lib/environment-checks.js +2 -16
  64. package/dist/lib/environment-checks.js.map +1 -1
  65. package/dist/lib/errors.d.ts +2 -0
  66. package/dist/lib/errors.d.ts.map +1 -1
  67. package/dist/lib/errors.js +7 -0
  68. package/dist/lib/errors.js.map +1 -1
  69. package/dist/lib/file-monitor.d.ts +18 -0
  70. package/dist/lib/file-monitor.d.ts.map +1 -0
  71. package/dist/lib/file-monitor.js +87 -0
  72. package/dist/lib/file-monitor.js.map +1 -0
  73. package/dist/lib/hook-logger.cjs +76 -11
  74. package/dist/lib/hosted-capture.d.ts +4 -2
  75. package/dist/lib/hosted-capture.d.ts.map +1 -1
  76. package/dist/lib/hosted-capture.js +121 -26
  77. package/dist/lib/hosted-capture.js.map +1 -1
  78. package/dist/lib/hosted-watcher.js +9 -1
  79. package/dist/lib/hosted-watcher.js.map +1 -1
  80. package/dist/lib/init-location.d.ts +4 -0
  81. package/dist/lib/init-location.d.ts.map +1 -0
  82. package/dist/lib/init-location.js +36 -0
  83. package/dist/lib/init-location.js.map +1 -0
  84. package/dist/lib/installed-tools.d.ts +3 -0
  85. package/dist/lib/installed-tools.d.ts.map +1 -1
  86. package/dist/lib/installed-tools.js +31 -18
  87. package/dist/lib/installed-tools.js.map +1 -1
  88. package/dist/lib/launcher-cleanup-journal.d.ts +44 -0
  89. package/dist/lib/launcher-cleanup-journal.d.ts.map +1 -0
  90. package/dist/lib/launcher-cleanup-journal.js +196 -0
  91. package/dist/lib/launcher-cleanup-journal.js.map +1 -0
  92. package/dist/lib/launcher-inventory-cache.d.ts +44 -0
  93. package/dist/lib/launcher-inventory-cache.d.ts.map +1 -0
  94. package/dist/lib/launcher-inventory-cache.js +126 -0
  95. package/dist/lib/launcher-inventory-cache.js.map +1 -0
  96. package/dist/lib/launcher-preparation-cache.d.ts +46 -0
  97. package/dist/lib/launcher-preparation-cache.d.ts.map +1 -0
  98. package/dist/lib/launcher-preparation-cache.js +131 -0
  99. package/dist/lib/launcher-preparation-cache.js.map +1 -0
  100. package/dist/lib/mac-notifier.d.ts +4 -0
  101. package/dist/lib/mac-notifier.d.ts.map +1 -0
  102. package/dist/lib/mac-notifier.js +72 -0
  103. package/dist/lib/mac-notifier.js.map +1 -0
  104. package/dist/lib/node-version.d.ts +8 -0
  105. package/dist/lib/node-version.d.ts.map +1 -0
  106. package/dist/lib/node-version.js +23 -0
  107. package/dist/lib/node-version.js.map +1 -0
  108. package/dist/lib/notify.d.ts +4 -5
  109. package/dist/lib/notify.d.ts.map +1 -1
  110. package/dist/lib/notify.js +24 -25
  111. package/dist/lib/notify.js.map +1 -1
  112. package/dist/lib/portal-launcher-background.d.ts +2 -0
  113. package/dist/lib/portal-launcher-background.d.ts.map +1 -1
  114. package/dist/lib/portal-launcher-background.js.map +1 -1
  115. package/dist/lib/portal-launcher.d.ts +44 -5
  116. package/dist/lib/portal-launcher.d.ts.map +1 -1
  117. package/dist/lib/portal-launcher.js +425 -77
  118. package/dist/lib/portal-launcher.js.map +1 -1
  119. package/dist/lib/prepared-editor.d.ts.map +1 -1
  120. package/dist/lib/prepared-editor.js +20 -5
  121. package/dist/lib/prepared-editor.js.map +1 -1
  122. package/dist/lib/session-over.d.ts +2 -0
  123. package/dist/lib/session-over.d.ts.map +1 -1
  124. package/dist/lib/session-over.js +71 -12
  125. package/dist/lib/session-over.js.map +1 -1
  126. package/dist/lib/ssh-config-file.d.ts +13 -2
  127. package/dist/lib/ssh-config-file.d.ts.map +1 -1
  128. package/dist/lib/ssh-config-file.js +32 -27
  129. package/dist/lib/ssh-config-file.js.map +1 -1
  130. package/dist/lib/tool-installation-watcher.d.ts +20 -0
  131. package/dist/lib/tool-installation-watcher.d.ts.map +1 -0
  132. package/dist/lib/tool-installation-watcher.js +112 -0
  133. package/dist/lib/tool-installation-watcher.js.map +1 -0
  134. package/dist/lib/tracker.d.ts +1 -0
  135. package/dist/lib/tracker.d.ts.map +1 -1
  136. package/dist/lib/tracker.js +29 -4
  137. package/dist/lib/tracker.js.map +1 -1
  138. package/dist/lib/watcher.js +152 -101
  139. package/dist/lib/watcher.js.map +1 -1
  140. package/dist/lib/workspace-start-wait.d.ts +3 -1
  141. package/dist/lib/workspace-start-wait.d.ts.map +1 -1
  142. package/dist/lib/workspace-start-wait.js +36 -1
  143. package/dist/lib/workspace-start-wait.js.map +1 -1
  144. package/dist/notification-assets/litmus.icns +0 -0
  145. package/dist/notification-assets/litmus.png +0 -0
  146. package/dist/notification-assets/notifier.js +12 -0
  147. package/dist/program.d.ts +2 -0
  148. package/dist/program.d.ts.map +1 -0
  149. package/dist/program.js +244 -0
  150. package/dist/program.js.map +1 -0
  151. package/package.json +5 -5
@@ -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";
4
- import { mkdirSync, writeFileSync } from "fs";
3
+ import { execFile, spawn, fork } from "child_process";
4
+ import { mkdirSync, rmSync, 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,92 @@ 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
+ const closeTerminalScript = `on run argv
92
+ set targetName to (item 1 of argv) & ".command"
93
+ set closedCount to 0
94
+ tell application "Terminal"
95
+ repeat
96
+ set matchingWindowId to missing value
97
+ repeat with terminalWindow in windows
98
+ repeat with terminalTab in tabs of terminalWindow
99
+ if custom title of terminalTab is targetName then
100
+ set matchingWindowId to id of terminalWindow
101
+ exit repeat
102
+ end if
103
+ end repeat
104
+ if matchingWindowId is not missing value then exit repeat
105
+ end repeat
106
+ if matchingWindowId is missing value then exit repeat
107
+ set matchingWindow to first window whose id is matchingWindowId
108
+ -- Terminal does not implement close for tab objects. The launcher
109
+ -- opens its .command file in a dedicated window, so close only that
110
+ -- single-tab window and fail closed if the user has added another tab.
111
+ if (count of tabs of matchingWindow) is not 1 then return "retry"
112
+ set matchingTab to selected tab of matchingWindow
113
+ if processes of matchingTab contains "ssh" then
114
+ do script "exit" in matchingTab
115
+ delay 0.5
116
+ end if
117
+ if processes of matchingTab contains "ssh" then return "retry"
118
+ if (count of tabs of matchingWindow) is not 1 then return "retry"
119
+ close matchingWindow
120
+ delay 0.25
121
+ repeat with remainingWindow in windows
122
+ if id of remainingWindow is matchingWindowId then
123
+ -- Terminal can retain an invisible, zero-tab AppleScript object after
124
+ -- its real native window is gone. That is not a user-visible window.
125
+ if visible of remainingWindow or (count of tabs of remainingWindow) > 0 then return "retry"
126
+ end if
127
+ end repeat
128
+ set closedCount to closedCount + 1
129
+ end repeat
130
+ if closedCount > 0 then return "closed"
131
+ return "not_found"
132
+ end tell
133
+ end run`;
134
+ /** Foreground the live, assessment-scoped Terminal session before opening another shell. */
135
+ export function focusExistingMacTerminal(alias, execFileFn = execFile) {
136
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
137
+ return Promise.resolve(false);
138
+ return new Promise(resolve => {
139
+ execFileFn("/usr/bin/osascript", ["-e", focusTerminalScript, alias], { timeout: 1500 }, (error, stdout) => {
140
+ resolve(!error && String(stdout).trim() === "focused");
141
+ });
142
+ });
143
+ }
144
+ /** Close only the assessment tab that the portal launcher created on macOS. */
145
+ export function closeOwnedMacTerminal(alias, platform = process.platform, execFileFn = execFile) {
146
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
147
+ return Promise.resolve("unsupported");
148
+ return new Promise((resolve, reject) => {
149
+ execFileFn("/usr/bin/osascript", ["-e", closeTerminalScript, alias], { timeout: 2500 }, (error, stdout) => {
150
+ if (error)
151
+ return reject(error);
152
+ const outcome = String(stdout).trim();
153
+ if (outcome === "closed" || outcome === "not_found")
154
+ return resolve(outcome);
155
+ if (outcome === "retry")
156
+ return reject(new Error("The owned assessment Terminal tab is still attached"));
157
+ reject(new Error("Terminal returned an unknown cleanup result"));
158
+ });
159
+ });
160
+ }
45
161
  export async function openTerminal(alias, terminal, requestId) {
46
162
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
47
163
  return false;
@@ -50,6 +166,8 @@ export async function openTerminal(alias, terminal, requestId) {
50
166
  if (configSetsRemoteCommand(alias))
51
167
  options.push("-o", "RemoteCommand=none");
52
168
  if (process.platform === "darwin") {
169
+ if (await focusExistingMacTerminal(alias))
170
+ return true;
53
171
  const dir = path.join(os.homedir(), ".litmus", "launchers");
54
172
  mkdirSync(dir, { recursive: true, mode: 0o700 });
55
173
  const file = path.join(dir, `${alias}.command`);
@@ -61,18 +179,35 @@ export async function openTerminal(alias, terminal, requestId) {
61
179
  const flag = terminal.endsWith("gnome-terminal") ? "--" : "-e";
62
180
  return spawnDetached(terminal, [flag, "ssh", ...options, alias, remote]);
63
181
  }
182
+ /** Remove only the launcher file created for this exact assessment alias. */
183
+ export function removeTerminalLauncher(alias, home = os.homedir()) {
184
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
185
+ return;
186
+ rmSync(path.join(home, ".litmus", "launchers", `${alias}.command`), { force: true });
187
+ }
64
188
  /** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
65
- export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation) {
189
+ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
66
190
  return new Promise(resolve => {
67
191
  let result = "action_required";
68
192
  let prepared = null;
69
193
  let announced = false;
194
+ let remembered = false;
70
195
  const env = { ...process.env, LITMUS_ASSESSMENT_TOKEN: token, LITMUS_PORTAL_LAUNCHER_CHILD: "1" };
71
196
  delete env.LITMUS_LAUNCH_GENERATION;
72
197
  const currentGeneration = parseWorkspaceGeneration(generation);
73
198
  if (currentGeneration)
74
199
  env.LITMUS_LAUNCH_GENERATION = JSON.stringify(currentGeneration);
75
- const child = forkFn(new URL("../index.js", import.meta.url), ["connect", "--ide", tool, "--no-skills"], {
200
+ // The global Agents Window can retain an older SSH environment even after
201
+ // workspace handoff. Keep portal opens in the verified assessment IDE.
202
+ // The portal's long-lived launcher is the one laptop-side process that can
203
+ // arrange teardown for a submission initiated in the browser, by a cron,
204
+ // or from another machine. Install the workspace-scoped companion in the
205
+ // exact native editor window we open. It verifies the terminal status with
206
+ // the assessment token before closing anything and refuses dirty windows.
207
+ const args = ["connect", "--ide", tool, "--no-skills", "--cursor-session-cleanup"];
208
+ if (tool === "cursor")
209
+ args.push("--no-cursor-agent-window");
210
+ const child = forkFn(new URL("../index.js", import.meta.url), args, {
76
211
  execArgv: [], env,
77
212
  stdio: ["ignore", "inherit", "inherit", "ipc"],
78
213
  });
@@ -83,12 +218,14 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
83
218
  if (value.type === "litmus-connect-result" && value.result === "server_detected") {
84
219
  result = "dispatched";
85
220
  prepared = parsePreparedEditor(value.preparedEditor);
221
+ if (!remembered && prepared?.tool === tool) {
222
+ remembered = true;
223
+ onPrepared?.(prepared);
224
+ }
86
225
  // The child has verified attachment. Reporting/cleanup can finish after
87
226
  // the UI stops saying Launching; neither is part of opening the editor.
88
227
  if (!announced) {
89
228
  announced = true;
90
- if (prepared?.tool === tool)
91
- onPrepared?.(prepared);
92
229
  resolve("dispatched");
93
230
  }
94
231
  }
@@ -97,12 +234,24 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
97
234
  signal?.addEventListener("abort", stop, { once: true });
98
235
  if (signal?.aborted)
99
236
  stop();
237
+ void remoteReady?.then(ready => {
238
+ if (!ready || announced || signal?.aborted)
239
+ return;
240
+ // This event comes from the managed remote extension only after hostd
241
+ // stamps the current assessment generation and exact workspace folder.
242
+ // The child keeps running its compatibility probe and can still populate
243
+ // the prepared-editor cache after the UI stops waiting.
244
+ announced = true;
245
+ result = "dispatched";
246
+ onRemoteReady?.();
247
+ resolve("dispatched");
248
+ });
100
249
  const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
101
250
  const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
102
251
  child.once("error", () => { cleanup(); resolve("action_required"); });
103
252
  child.once("exit", code => {
104
253
  cleanup();
105
- if (!announced && code === 0 && result === "dispatched" && prepared?.tool === tool)
254
+ if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
106
255
  onPrepared?.(prepared);
107
256
  resolve(code === 0 ? result : "action_required");
108
257
  });
@@ -163,6 +312,9 @@ export async function startPortalPreparation(backendUrl, token) {
163
312
  });
164
313
  }
165
314
  export async function runPortalLauncher(options) {
315
+ const launcherStarted = performance.now();
316
+ const timing = options.reportTiming ?? (() => { });
317
+ timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
166
318
  const abort = new AbortController();
167
319
  const stop = () => abort.abort();
168
320
  options.signal?.addEventListener("abort", stop, { once: true });
@@ -171,25 +323,94 @@ export async function runPortalLauncher(options) {
171
323
  process.once("SIGINT", stop);
172
324
  process.once("SIGTERM", stop);
173
325
  let session = null;
174
- let installed = discoverInstalledTools();
175
- let lastDiscovery = Date.now();
176
- let inventory = JSON.stringify(installed);
326
+ let launcherCompletionReported = false;
327
+ const completeLauncher = (outcome) => {
328
+ if (launcherCompletionReported)
329
+ return;
330
+ launcherCompletionReported = true;
331
+ timing("launcher_ready", options.connectStartedAt ? Date.now() - options.connectStartedAt : performance.now() - launcherStarted, { outcome, ...(session ? { sessionId: session.session_id } : {}) });
332
+ };
333
+ const discoverTools = options.discoverTools ?? discoverInstalledTools;
334
+ const discoverTool = options.discoverTool ?? discoverInstalledTool;
335
+ const watchInstallations = options.watchInstallations ?? watchToolInstallations;
336
+ const inventoryReconcileMs = options.inventoryReconcileMs ?? 300000;
337
+ const cachedInventory = options.cachedInventory;
338
+ timing(cachedInventory ? "tool_inventory_cache_hit" : "tool_inventory_cache_miss", performance.now() - launcherStarted);
339
+ let discovered = cachedInventory?.tools ?? [];
340
+ let installed = discovered;
341
+ let inventory = JSON.stringify(discovered);
177
342
  let changedInventory;
178
343
  let inventoryPoll;
179
- // Local discovery stays independent of the idle server long poll.
180
- const discoveryTimer = setInterval(() => {
181
- const next = discoverInstalledTools();
344
+ let nextInventoryReconcile = Date.now() + inventoryReconcileMs;
345
+ let nextPreparationRetry = Date.now() + 30000;
346
+ const queueInventory = (next) => {
182
347
  const signature = JSON.stringify(next);
183
- if (signature !== inventory) {
184
- inventory = signature;
185
- changedInventory = next;
186
- inventoryPoll?.abort();
348
+ if (signature === inventory)
349
+ return false;
350
+ inventory = signature;
351
+ discovered = next;
352
+ changedInventory = next;
353
+ return true;
354
+ };
355
+ const stopInstallationWatch = watchInstallations(tool => {
356
+ let next;
357
+ if (!tool)
358
+ next = discoverTools();
359
+ else {
360
+ const nextByTool = new Map(discovered.map(candidate => [candidate.tool, candidate]));
361
+ const candidate = discoverTool(tool);
362
+ if (candidate)
363
+ nextByTool.set(tool, candidate);
364
+ else
365
+ nextByTool.delete(tool);
366
+ const order = ["vscode", "cursor", "codex", "claude", "ssh"];
367
+ next = [...nextByTool.values()].sort((a, b) => order.indexOf(a.tool) - order.indexOf(b.tool));
187
368
  }
188
- }, 5000);
369
+ if (queueInventory(next))
370
+ inventoryPoll?.abort();
371
+ }, abort.signal);
189
372
  let seenCommandId = null;
373
+ const seenCommands = new Set();
190
374
  let longPoll = false;
191
375
  let readinessSupported = false;
376
+ let preparationInventorySupported = false;
192
377
  let desktopConnectionSetupSupported = false;
378
+ let editorReadinessEventsSupported = false;
379
+ const eventReadyEditors = new Set();
380
+ const readinessWaiters = new Map();
381
+ const acceptEditorReadiness = (tools) => {
382
+ if (!editorReadinessEventsSupported || !Array.isArray(tools))
383
+ return;
384
+ const next = new Set(tools.filter((tool) => tool === "vscode" || tool === "cursor"));
385
+ for (const tool of ["vscode", "cursor"]) {
386
+ if (!next.has(tool)) {
387
+ eventReadyEditors.delete(tool);
388
+ continue;
389
+ }
390
+ eventReadyEditors.add(tool);
391
+ for (const resolve of readinessWaiters.get(tool) ?? [])
392
+ resolve(true);
393
+ readinessWaiters.delete(tool);
394
+ }
395
+ };
396
+ const waitForEditorReadiness = (tool) => {
397
+ if (!editorReadinessEventsSupported || (tool !== "vscode" && tool !== "cursor"))
398
+ return undefined;
399
+ if (eventReadyEditors.has(tool))
400
+ return Promise.resolve(true);
401
+ return new Promise(resolve => {
402
+ const waiters = readinessWaiters.get(tool) ?? new Set();
403
+ waiters.add(resolve);
404
+ readinessWaiters.set(tool, waiters);
405
+ });
406
+ };
407
+ const readyToolsCursor = () => [...eventReadyEditors].sort().join(",") || "-";
408
+ abort.signal.addEventListener("abort", () => {
409
+ for (const waiters of readinessWaiters.values())
410
+ for (const resolve of waiters)
411
+ resolve(false);
412
+ readinessWaiters.clear();
413
+ }, { once: true });
193
414
  const toolIds = () => [...installed.filter(i => !i.unavailable).map(i => i.tool), ...(options.browserAvailable ? ["browser"] : [])];
194
415
  const unavailableTools = () => Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable === "desktop_setup_failed" && !desktopConnectionSetupSupported ? "workspace_not_ready" : i.unavailable]));
195
416
  async function call(route, body, method = "POST", polling = false) {
@@ -216,8 +437,24 @@ export async function runPortalLauncher(options) {
216
437
  }));
217
438
  try {
218
439
  let registered;
440
+ let cacheRejectedForCompatibility = false;
219
441
  try {
220
- registered = await call("/sessions", { tools: [], phase: "connecting" });
442
+ try {
443
+ registered = await call("/sessions", cachedInventory ? {
444
+ tools: cachedInventory.tools.map(tool => tool.tool),
445
+ preparing: cachedInventory.tools.map(tool => tool.tool),
446
+ phase: "connecting", stage: "checking_tools", cached_generation: cachedInventory.generation,
447
+ } : { tools: [], phase: "connecting" });
448
+ }
449
+ catch (error) {
450
+ // CLI and backend deploy independently. An older strict ToolReport
451
+ // rejects cached_generation; retry once with the original contract.
452
+ if (!cachedInventory || !(error instanceof LauncherRefusal) || error.status !== 422)
453
+ throw error;
454
+ cacheRejectedForCompatibility = true;
455
+ options.onInventoryCacheRejected?.();
456
+ registered = await call("/sessions", { tools: [], phase: "connecting" });
457
+ }
221
458
  }
222
459
  catch (error) {
223
460
  if (!(error instanceof LauncherRefusal) || !([404, 405].includes(error.status) || (error.status === 403 && error.code === "launcher_beta_unavailable")))
@@ -229,40 +466,157 @@ export async function runPortalLauncher(options) {
229
466
  return;
230
467
  }
231
468
  session = registered;
469
+ await options.onRegistered?.(registered.workspace_generation);
232
470
  readinessSupported = registered.tool_readiness === true;
471
+ preparationInventorySupported = registered.preparation_inventory === true;
233
472
  desktopConnectionSetupSupported = registered.desktop_connection_setup === true;
234
- if (options.prepareTools && registered.progress_updates) {
235
- await call(`/sessions/${session.session_id}/poll`, { tools: [], phase: "connecting", stage: "checking_tools" }).catch(() => { });
473
+ editorReadinessEventsSupported = registered.editor_readiness_events === true;
474
+ if (cachedInventory && registered.inventory_cache_accepted !== true) {
475
+ discovered = [];
476
+ installed = [];
477
+ inventory = "[]";
478
+ timing("tool_inventory_cache_rejected", performance.now() - launcherStarted, { sessionId: registered.session_id });
479
+ if (!cacheRejectedForCompatibility)
480
+ options.onInventoryCacheRejected?.();
236
481
  }
237
- if (options.prepareTools) {
482
+ discovered = discoverTools();
483
+ installed = discovered;
484
+ inventory = JSON.stringify(discovered);
485
+ // A watcher event may race registration and queue a delta from the cached
486
+ // startup list. The authoritative full scan supersedes that stale delta.
487
+ changedInventory = undefined;
488
+ const inventoryElapsed = performance.now() - launcherStarted;
489
+ timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
490
+ timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
491
+ options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
492
+ const dispatchCommand = (command) => {
493
+ if (seenCommands.has(command.id))
494
+ return;
495
+ const commandReceived = performance.now();
496
+ timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
497
+ // A poll can redeliver an opening command after its response was lost.
498
+ // Record before launching, including while result delivery retries.
499
+ seenCommands.add(command.id);
500
+ seenCommandId = command.id;
501
+ void (async () => {
502
+ let outcome = { status: "failed" };
503
+ if (toolIds().includes(command.tool)) {
504
+ timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
505
+ const remoteReady = waitForEditorReadiness(command.tool);
506
+ try {
507
+ const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
508
+ outcome = typeof launched === "string" ? { status: launched } : launched;
509
+ }
510
+ catch { /* fixed failure */ }
511
+ const openElapsed = performance.now() - commandReceived;
512
+ timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
513
+ }
514
+ if (abort.signal.aborted)
515
+ return;
516
+ // CLI and backend versions roll independently. Older backends accept
517
+ // action_required but forbid the newer bounded reason field; omit it
518
+ // unless registration explicitly advertised that schema extension.
519
+ const reportedOutcome = outcome.reason && registered.confirmation_reasons !== true
520
+ ? { status: outcome.status }
521
+ : outcome;
522
+ // Deliver the same result again after transport errors; never execute
523
+ // the tool again merely because its acknowledgement was lost.
524
+ // Polling owns the session's lifetime. Cap the delay, not attempts:
525
+ // retain the result until acknowledged, permanently refused or stopped.
526
+ for (let attempt = 0; !abort.signal.aborted; attempt++) {
527
+ try {
528
+ await call(`/sessions/${registered.session_id}/results/${command.id}`, reportedOutcome);
529
+ timing("result_acknowledged", performance.now() - commandReceived, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
530
+ return;
531
+ }
532
+ catch (error) {
533
+ if (permanentLauncherFailure(error)) {
534
+ console.error("Launch result could not be delivered. Check the tool before opening it again.");
535
+ return;
536
+ }
537
+ await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
538
+ }
539
+ }
540
+ })();
541
+ };
542
+ const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
543
+ tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
544
+ unavailable: Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable])),
545
+ preparing: preparingTools.filter(i => !i.unavailable).map(i => i.tool),
546
+ phase: "connecting",
547
+ ...(registered.progress_updates ? { stage: "checking_tools" } : {}),
548
+ } : { tools: [], phase: "connecting", ...(registered.progress_updates ? { stage: "checking_tools" } : {}) };
549
+ const prepareInstalledTools = async (preparingTools, readyTools = []) => {
550
+ if (!options.prepareTools)
551
+ return;
552
+ const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
553
+ const ready = new Set(readyTools);
554
+ let reportInFlight;
555
+ let reportRequested = false;
556
+ let preparationEnded = false;
557
+ const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
558
+ const publishPreparation = () => {
559
+ if (!registered.progress_updates || preparationEnded)
560
+ return reportInFlight ?? Promise.resolve();
561
+ reportRequested = true;
562
+ if (!reportInFlight)
563
+ reportInFlight = (async () => {
564
+ while (reportRequested && !preparationEnded) {
565
+ reportRequested = false;
566
+ const query = seenCommandId ? `?seen_command_id=${encodeURIComponent(seenCommandId)}` : "";
567
+ const reply = await call(`/sessions/${session.session_id}/poll${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
568
+ acceptEditorReadiness(reply?.ready_tools);
569
+ if (reply?.command) {
570
+ dispatchCommand(reply.command);
571
+ // Acknowledge receipt promptly; otherwise a slow opener blocks
572
+ // delivery of another ready tool until the lease renewal.
573
+ reportRequested = true;
574
+ }
575
+ }
576
+ })().finally(() => { reportInFlight = undefined; });
577
+ return reportInFlight;
578
+ };
579
+ await publishPreparation();
238
580
  // Preparing a matching editor server may outlast the initial mailbox
239
581
  // lease. Renew as connecting, without claiming readiness or starting time.
240
582
  // Drain any in-flight renewal before the first ready poll, so a delayed
241
583
  // response cannot put a connected laptop back into preparation.
242
- let preparationEnded = false;
243
- let pendingRenewal;
244
584
  let renewalTimer;
245
585
  const renewPreparation = () => {
246
586
  if (preparationEnded || abort.signal.aborted)
247
587
  return;
248
- pendingRenewal = call(`/sessions/${session.session_id}/poll`, {
249
- tools: [], phase: "connecting", ...(registered.progress_updates ? { stage: "checking_tools" } : {}),
250
- }).then(() => { }, () => { }).finally(() => {
588
+ void publishPreparation().finally(() => {
251
589
  if (!preparationEnded && !abort.signal.aborted)
252
590
  renewalTimer = setTimeout(renewPreparation, 15000);
253
591
  });
254
592
  };
255
593
  renewalTimer = setTimeout(renewPreparation, 15000);
256
594
  try {
257
- installed = await options.prepareTools(installed, abort.signal);
595
+ const preparesEntireInventory = preparingTools.length === installed.length
596
+ && preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
597
+ const preparedTools = await options.prepareTools(preparingTools, abort.signal, async (prepared) => {
598
+ installed = installed.map(tool => tool.tool === prepared.tool ? prepared : tool);
599
+ pendingTools.delete(prepared.tool);
600
+ if (prepared.unavailable)
601
+ ready.delete(prepared.tool);
602
+ else
603
+ ready.add(prepared.tool);
604
+ void publishPreparation();
605
+ }, registered.workspace_generation);
606
+ if (preparesEntireInventory)
607
+ installed = preparedTools;
608
+ else {
609
+ const preparedByTool = new Map(preparedTools.map(tool => [tool.tool, tool]));
610
+ installed = installed.map(tool => preparedByTool.get(tool.tool) ?? tool);
611
+ }
258
612
  }
259
613
  finally {
260
- preparationEnded = true;
261
614
  clearTimeout(renewalTimer);
262
- await pendingRenewal;
615
+ await reportInFlight;
616
+ preparationEnded = true;
263
617
  }
264
- }
265
- lastDiscovery = Date.now();
618
+ };
619
+ await prepareInstalledTools(installed);
266
620
  if (abort.signal.aborted)
267
621
  return;
268
622
  let readyAcknowledged = false;
@@ -270,24 +624,43 @@ export async function runPortalLauncher(options) {
270
624
  let readinessDeadline = Date.now() + 120000;
271
625
  let readinessFailures = 0;
272
626
  let failures = 0;
273
- const seenCommands = new Set();
274
627
  while (!abort.signal.aborted) {
275
- if (changedInventory || Date.now() - lastDiscovery >= 30000) {
276
- installed = changedInventory ?? discoverInstalledTools();
628
+ const now = Date.now();
629
+ if (now >= nextInventoryReconcile) {
630
+ queueInventory(discoverTools());
631
+ nextInventoryReconcile = now + inventoryReconcileMs;
632
+ }
633
+ if (changedInventory) {
634
+ const readyTools = toolIds();
635
+ const readySet = new Set(readyTools);
636
+ installed = changedInventory;
277
637
  changedInventory = undefined;
278
- if (options.prepareTools)
279
- installed = await options.prepareTools(installed, abort.signal);
280
- lastDiscovery = Date.now();
638
+ const newlyInstalled = installed.filter(tool => !tool.unavailable && !readySet.has(tool.tool));
639
+ if (newlyInstalled.length)
640
+ await prepareInstalledTools(newlyInstalled, readyTools);
641
+ }
642
+ if (Date.now() >= nextPreparationRetry) {
643
+ const retryable = new Set(installed.filter(tool => tool.unavailable === "workspace_not_ready" || tool.unavailable === "desktop_setup_failed").map(tool => tool.tool));
644
+ if (retryable.size) {
645
+ const readyTools = toolIds();
646
+ installed = installed.map(tool => retryable.has(tool.tool) ? { ...tool, unavailable: undefined } : tool);
647
+ await prepareInstalledTools(installed.filter(tool => retryable.has(tool.tool)), readyTools);
648
+ }
649
+ nextPreparationRetry = Date.now() + 30000;
281
650
  }
282
651
  let command;
283
652
  try {
284
- // End the wait in time for the next installation inventory refresh.
285
- const waitSeconds = Math.min(25, Math.max(1, Math.ceil((30000 - (Date.now() - lastDiscovery)) / 1000)));
653
+ // End the wait in time for the next retry or bounded reconciliation.
654
+ const nextLocalDeadline = Math.min(nextPreparationRetry, nextInventoryReconcile);
655
+ const waitSeconds = Math.min(25, Math.max(1, Math.ceil((nextLocalDeadline - Date.now()) / 1000)));
286
656
  const query = new URLSearchParams({ wait_seconds: String(readyAcknowledged ? waitSeconds : 0) });
287
657
  if (seenCommandId)
288
658
  query.set("seen_command_id", seenCommandId);
659
+ if (editorReadinessEventsSupported)
660
+ query.set("ready_tools_seen", readyToolsCursor());
289
661
  inventoryPoll = new AbortController();
290
662
  const reply = await call(`/sessions/${registered.session_id}/poll?${query}`, { tools: toolIds(), phase: "ready", ...(readinessSupported ? { unavailable: unavailableTools() } : {}) }, "POST", true);
663
+ acceptEditorReadiness(reply.ready_tools);
291
664
  longPoll = reply.long_poll === true;
292
665
  command = reply.command;
293
666
  failures = 0;
@@ -327,49 +700,23 @@ export async function runPortalLauncher(options) {
327
700
  console.log("\nYour tool launcher is ready. Open tools from your assessment page.");
328
701
  console.log(` ${options.pageUrl}`);
329
702
  options.onReady?.();
703
+ completeLauncher("ok");
330
704
  await options.openUrl(options.pageUrl);
331
705
  }
332
- if (command && !seenCommands.has(command.id)) {
333
- // A poll can redeliver an opening command after its response was lost.
334
- // Record before launching, including while result delivery retries.
335
- seenCommands.add(command.id);
336
- seenCommandId = command.id;
337
- void (async () => {
338
- let status = "failed";
339
- if (toolIds().includes(command.tool)) {
340
- try {
341
- status = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}) });
342
- }
343
- catch { /* fixed failure */ }
344
- }
345
- if (abort.signal.aborted)
346
- return;
347
- // Deliver the same result again after transport errors; never execute
348
- // the tool again merely because its acknowledgement was lost.
349
- // Polling owns the session's lifetime. Cap the delay, not attempts:
350
- // retain the result until acknowledged, permanently refused or stopped.
351
- for (let attempt = 0; !abort.signal.aborted; attempt++) {
352
- try {
353
- await call(`/sessions/${registered.session_id}/results/${command.id}`, { status });
354
- return;
355
- }
356
- catch (error) {
357
- if (permanentLauncherFailure(error)) {
358
- console.error("Launch result could not be delivered. Check the tool before opening it again.");
359
- return;
360
- }
361
- await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
362
- }
363
- }
364
- })();
365
- }
706
+ if (command)
707
+ dispatchCommand(command);
366
708
  // Old backends ignore the query parameters. Preserve their polling rate.
367
709
  if (!longPoll)
368
710
  await wait(5000, abort.signal);
369
711
  }
370
712
  }
713
+ catch (error) {
714
+ completeLauncher(error instanceof LauncherRefusal && error.readinessPending ? "timeout" : "failed");
715
+ throw error;
716
+ }
371
717
  finally {
372
- clearInterval(discoveryTimer);
718
+ completeLauncher("cancelled");
719
+ stopInstallationWatch();
373
720
  abort.abort();
374
721
  if (session)
375
722
  await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
@@ -380,8 +727,9 @@ export async function runPortalLauncher(options) {
380
727
  // Only a positive server acknowledgement permits local connection cleanup.
381
728
  if (session && options.onSubmitted) {
382
729
  try {
383
- if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000))
730
+ if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000)) {
384
731
  await options.onSubmitted();
732
+ }
385
733
  }
386
734
  catch { /* Leave settings intact when submission cannot be verified. */ }
387
735
  }