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