litmus-cli 1.5.0-beta.4 → 1.5.0-beta.6
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 +4 -0
- package/dist/commands/connect.d.ts.map +1 -1
- package/dist/commands/connect.js +201 -48
- package/dist/commands/connect.js.map +1 -1
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +8 -2
- package/dist/commands/doctor.js.map +1 -1
- package/dist/cursor-session/extension.cjs +12 -3
- package/dist/cursor-session/package.json +2 -2
- package/dist/cursor-session/session.cjs +19 -6
- package/dist/lib/api.d.ts.map +1 -1
- package/dist/lib/api.js +7 -2
- package/dist/lib/api.js.map +1 -1
- package/dist/lib/capture-startup-diagnostics.d.ts +15 -0
- package/dist/lib/capture-startup-diagnostics.d.ts.map +1 -0
- package/dist/lib/capture-startup-diagnostics.js +134 -0
- package/dist/lib/capture-startup-diagnostics.js.map +1 -0
- package/dist/lib/capture-storage-error.d.ts +10 -0
- package/dist/lib/capture-storage-error.d.ts.map +1 -0
- package/dist/lib/capture-storage-error.js +18 -0
- package/dist/lib/capture-storage-error.js.map +1 -0
- package/dist/lib/cursor-session.js +2 -2
- 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/errors.d.ts +2 -0
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +7 -0
- package/dist/lib/errors.js.map +1 -1
- package/dist/lib/hosted-capture.d.ts.map +1 -1
- package/dist/lib/hosted-capture.js +47 -10
- package/dist/lib/hosted-capture.js.map +1 -1
- package/dist/lib/hosted-watcher.js +9 -1
- package/dist/lib/hosted-watcher.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/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 +42 -5
- package/dist/lib/portal-launcher.d.ts.map +1 -1
- package/dist/lib/portal-launcher.js +339 -86
- 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/session-over.d.ts +2 -0
- package/dist/lib/session-over.d.ts.map +1 -1
- package/dist/lib/session-over.js +71 -12
- package/dist/lib/session-over.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/tracker.d.ts.map +1 -1
- package/dist/lib/tracker.js +25 -2
- package/dist/lib/tracker.js.map +1 -1
- package/dist/lib/watcher.js +5 -0
- package/dist/lib/watcher.js.map +1 -1
- package/dist/program.js +11 -3
- package/dist/program.js.map +1 -1
- 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";
|
|
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,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`);
|
|
@@ -61,12 +119,19 @@ export async function openTerminal(alias, terminal, requestId) {
|
|
|
61
119
|
const flag = terminal.endsWith("gnome-terminal") ? "--" : "-e";
|
|
62
120
|
return spawnDetached(terminal, [flag, "ssh", ...options, alias, remote]);
|
|
63
121
|
}
|
|
122
|
+
/** Remove only the launcher file created for this exact assessment alias. */
|
|
123
|
+
export function removeTerminalLauncher(alias, home = os.homedir()) {
|
|
124
|
+
if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
|
|
125
|
+
return;
|
|
126
|
+
rmSync(path.join(home, ".litmus", "launchers", `${alias}.command`), { force: true });
|
|
127
|
+
}
|
|
64
128
|
/** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
|
|
65
|
-
export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation) {
|
|
129
|
+
export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
|
|
66
130
|
return new Promise(resolve => {
|
|
67
131
|
let result = "action_required";
|
|
68
132
|
let prepared = null;
|
|
69
133
|
let announced = false;
|
|
134
|
+
let remembered = false;
|
|
70
135
|
const env = { ...process.env, LITMUS_ASSESSMENT_TOKEN: token, LITMUS_PORTAL_LAUNCHER_CHILD: "1" };
|
|
71
136
|
delete env.LITMUS_LAUNCH_GENERATION;
|
|
72
137
|
const currentGeneration = parseWorkspaceGeneration(generation);
|
|
@@ -74,7 +139,12 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
|
|
|
74
139
|
env.LITMUS_LAUNCH_GENERATION = JSON.stringify(currentGeneration);
|
|
75
140
|
// The global Agents Window can retain an older SSH environment even after
|
|
76
141
|
// workspace handoff. Keep portal opens in the verified assessment IDE.
|
|
77
|
-
|
|
142
|
+
// The portal's long-lived launcher is the one laptop-side process that can
|
|
143
|
+
// arrange teardown for a submission initiated in the browser, by a cron,
|
|
144
|
+
// or from another machine. Install the workspace-scoped companion in the
|
|
145
|
+
// exact native editor window we open. It verifies the terminal status with
|
|
146
|
+
// the assessment token before closing anything and refuses dirty windows.
|
|
147
|
+
const args = ["connect", "--ide", tool, "--no-skills", "--cursor-session-cleanup"];
|
|
78
148
|
if (tool === "cursor")
|
|
79
149
|
args.push("--no-cursor-agent-window");
|
|
80
150
|
const child = forkFn(new URL("../index.js", import.meta.url), args, {
|
|
@@ -88,12 +158,14 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
|
|
|
88
158
|
if (value.type === "litmus-connect-result" && value.result === "server_detected") {
|
|
89
159
|
result = "dispatched";
|
|
90
160
|
prepared = parsePreparedEditor(value.preparedEditor);
|
|
161
|
+
if (!remembered && prepared?.tool === tool) {
|
|
162
|
+
remembered = true;
|
|
163
|
+
onPrepared?.(prepared);
|
|
164
|
+
}
|
|
91
165
|
// The child has verified attachment. Reporting/cleanup can finish after
|
|
92
166
|
// the UI stops saying Launching; neither is part of opening the editor.
|
|
93
167
|
if (!announced) {
|
|
94
168
|
announced = true;
|
|
95
|
-
if (prepared?.tool === tool)
|
|
96
|
-
onPrepared?.(prepared);
|
|
97
169
|
resolve("dispatched");
|
|
98
170
|
}
|
|
99
171
|
}
|
|
@@ -102,12 +174,24 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
|
|
|
102
174
|
signal?.addEventListener("abort", stop, { once: true });
|
|
103
175
|
if (signal?.aborted)
|
|
104
176
|
stop();
|
|
177
|
+
void remoteReady?.then(ready => {
|
|
178
|
+
if (!ready || announced || signal?.aborted)
|
|
179
|
+
return;
|
|
180
|
+
// This event comes from the managed remote extension only after hostd
|
|
181
|
+
// stamps the current assessment generation and exact workspace folder.
|
|
182
|
+
// The child keeps running its compatibility probe and can still populate
|
|
183
|
+
// the prepared-editor cache after the UI stops waiting.
|
|
184
|
+
announced = true;
|
|
185
|
+
result = "dispatched";
|
|
186
|
+
onRemoteReady?.();
|
|
187
|
+
resolve("dispatched");
|
|
188
|
+
});
|
|
105
189
|
const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
|
|
106
190
|
const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
|
|
107
191
|
child.once("error", () => { cleanup(); resolve("action_required"); });
|
|
108
192
|
child.once("exit", code => {
|
|
109
193
|
cleanup();
|
|
110
|
-
if (!
|
|
194
|
+
if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
|
|
111
195
|
onPrepared?.(prepared);
|
|
112
196
|
resolve(code === 0 ? result : "action_required");
|
|
113
197
|
});
|
|
@@ -168,6 +252,9 @@ export async function startPortalPreparation(backendUrl, token) {
|
|
|
168
252
|
});
|
|
169
253
|
}
|
|
170
254
|
export async function runPortalLauncher(options) {
|
|
255
|
+
const launcherStarted = performance.now();
|
|
256
|
+
const timing = options.reportTiming ?? (() => { });
|
|
257
|
+
timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
|
|
171
258
|
const abort = new AbortController();
|
|
172
259
|
const stop = () => abort.abort();
|
|
173
260
|
options.signal?.addEventListener("abort", stop, { once: true });
|
|
@@ -176,26 +263,94 @@ export async function runPortalLauncher(options) {
|
|
|
176
263
|
process.once("SIGINT", stop);
|
|
177
264
|
process.once("SIGTERM", stop);
|
|
178
265
|
let session = null;
|
|
179
|
-
let
|
|
180
|
-
|
|
181
|
-
|
|
266
|
+
let launcherCompletionReported = false;
|
|
267
|
+
const completeLauncher = (outcome) => {
|
|
268
|
+
if (launcherCompletionReported)
|
|
269
|
+
return;
|
|
270
|
+
launcherCompletionReported = true;
|
|
271
|
+
timing("launcher_ready", options.connectStartedAt ? Date.now() - options.connectStartedAt : performance.now() - launcherStarted, { outcome, ...(session ? { sessionId: session.session_id } : {}) });
|
|
272
|
+
};
|
|
273
|
+
const discoverTools = options.discoverTools ?? discoverInstalledTools;
|
|
274
|
+
const discoverTool = options.discoverTool ?? discoverInstalledTool;
|
|
275
|
+
const watchInstallations = options.watchInstallations ?? watchToolInstallations;
|
|
276
|
+
const inventoryReconcileMs = options.inventoryReconcileMs ?? 300000;
|
|
277
|
+
const cachedInventory = options.cachedInventory;
|
|
278
|
+
timing(cachedInventory ? "tool_inventory_cache_hit" : "tool_inventory_cache_miss", performance.now() - launcherStarted);
|
|
279
|
+
let discovered = cachedInventory?.tools ?? [];
|
|
280
|
+
let installed = discovered;
|
|
281
|
+
let inventory = JSON.stringify(discovered);
|
|
182
282
|
let changedInventory;
|
|
183
283
|
let inventoryPoll;
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
284
|
+
let nextInventoryReconcile = Date.now() + inventoryReconcileMs;
|
|
285
|
+
let nextPreparationRetry = Date.now() + 30000;
|
|
286
|
+
const queueInventory = (next) => {
|
|
187
287
|
const signature = JSON.stringify(next);
|
|
188
|
-
if (signature
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
288
|
+
if (signature === inventory)
|
|
289
|
+
return false;
|
|
290
|
+
inventory = signature;
|
|
291
|
+
discovered = next;
|
|
292
|
+
changedInventory = next;
|
|
293
|
+
return true;
|
|
294
|
+
};
|
|
295
|
+
const stopInstallationWatch = watchInstallations(tool => {
|
|
296
|
+
let next;
|
|
297
|
+
if (!tool)
|
|
298
|
+
next = discoverTools();
|
|
299
|
+
else {
|
|
300
|
+
const nextByTool = new Map(discovered.map(candidate => [candidate.tool, candidate]));
|
|
301
|
+
const candidate = discoverTool(tool);
|
|
302
|
+
if (candidate)
|
|
303
|
+
nextByTool.set(tool, candidate);
|
|
304
|
+
else
|
|
305
|
+
nextByTool.delete(tool);
|
|
306
|
+
const order = ["vscode", "cursor", "codex", "claude", "ssh"];
|
|
307
|
+
next = [...nextByTool.values()].sort((a, b) => order.indexOf(a.tool) - order.indexOf(b.tool));
|
|
192
308
|
}
|
|
193
|
-
|
|
309
|
+
if (queueInventory(next))
|
|
310
|
+
inventoryPoll?.abort();
|
|
311
|
+
}, abort.signal);
|
|
194
312
|
let seenCommandId = null;
|
|
313
|
+
const seenCommands = new Set();
|
|
195
314
|
let longPoll = false;
|
|
196
315
|
let readinessSupported = false;
|
|
197
316
|
let preparationInventorySupported = false;
|
|
198
317
|
let desktopConnectionSetupSupported = false;
|
|
318
|
+
let editorReadinessEventsSupported = false;
|
|
319
|
+
const eventReadyEditors = new Set();
|
|
320
|
+
const readinessWaiters = new Map();
|
|
321
|
+
const acceptEditorReadiness = (tools) => {
|
|
322
|
+
if (!editorReadinessEventsSupported || !Array.isArray(tools))
|
|
323
|
+
return;
|
|
324
|
+
const next = new Set(tools.filter((tool) => tool === "vscode" || tool === "cursor"));
|
|
325
|
+
for (const tool of ["vscode", "cursor"]) {
|
|
326
|
+
if (!next.has(tool)) {
|
|
327
|
+
eventReadyEditors.delete(tool);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
eventReadyEditors.add(tool);
|
|
331
|
+
for (const resolve of readinessWaiters.get(tool) ?? [])
|
|
332
|
+
resolve(true);
|
|
333
|
+
readinessWaiters.delete(tool);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
const waitForEditorReadiness = (tool) => {
|
|
337
|
+
if (!editorReadinessEventsSupported || (tool !== "vscode" && tool !== "cursor"))
|
|
338
|
+
return undefined;
|
|
339
|
+
if (eventReadyEditors.has(tool))
|
|
340
|
+
return Promise.resolve(true);
|
|
341
|
+
return new Promise(resolve => {
|
|
342
|
+
const waiters = readinessWaiters.get(tool) ?? new Set();
|
|
343
|
+
waiters.add(resolve);
|
|
344
|
+
readinessWaiters.set(tool, waiters);
|
|
345
|
+
});
|
|
346
|
+
};
|
|
347
|
+
const readyToolsCursor = () => [...eventReadyEditors].sort().join(",") || "-";
|
|
348
|
+
abort.signal.addEventListener("abort", () => {
|
|
349
|
+
for (const waiters of readinessWaiters.values())
|
|
350
|
+
for (const resolve of waiters)
|
|
351
|
+
resolve(false);
|
|
352
|
+
readinessWaiters.clear();
|
|
353
|
+
}, { once: true });
|
|
199
354
|
const toolIds = () => [...installed.filter(i => !i.unavailable).map(i => i.tool), ...(options.browserAvailable ? ["browser"] : [])];
|
|
200
355
|
const unavailableTools = () => Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable === "desktop_setup_failed" && !desktopConnectionSetupSupported ? "workspace_not_ready" : i.unavailable]));
|
|
201
356
|
async function call(route, body, method = "POST", polling = false) {
|
|
@@ -222,8 +377,24 @@ export async function runPortalLauncher(options) {
|
|
|
222
377
|
}));
|
|
223
378
|
try {
|
|
224
379
|
let registered;
|
|
380
|
+
let cacheRejectedForCompatibility = false;
|
|
225
381
|
try {
|
|
226
|
-
|
|
382
|
+
try {
|
|
383
|
+
registered = await call("/sessions", cachedInventory ? {
|
|
384
|
+
tools: cachedInventory.tools.map(tool => tool.tool),
|
|
385
|
+
preparing: cachedInventory.tools.map(tool => tool.tool),
|
|
386
|
+
phase: "connecting", stage: "checking_tools", cached_generation: cachedInventory.generation,
|
|
387
|
+
} : { tools: [], phase: "connecting" });
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
// CLI and backend deploy independently. An older strict ToolReport
|
|
391
|
+
// rejects cached_generation; retry once with the original contract.
|
|
392
|
+
if (!cachedInventory || !(error instanceof LauncherRefusal) || error.status !== 422)
|
|
393
|
+
throw error;
|
|
394
|
+
cacheRejectedForCompatibility = true;
|
|
395
|
+
options.onInventoryCacheRejected?.();
|
|
396
|
+
registered = await call("/sessions", { tools: [], phase: "connecting" });
|
|
397
|
+
}
|
|
227
398
|
}
|
|
228
399
|
catch (error) {
|
|
229
400
|
if (!(error instanceof LauncherRefusal) || !([404, 405].includes(error.status) || (error.status === 403 && error.code === "launcher_beta_unavailable")))
|
|
@@ -235,9 +406,79 @@ export async function runPortalLauncher(options) {
|
|
|
235
406
|
return;
|
|
236
407
|
}
|
|
237
408
|
session = registered;
|
|
409
|
+
await options.onRegistered?.(registered.workspace_generation);
|
|
238
410
|
readinessSupported = registered.tool_readiness === true;
|
|
239
411
|
preparationInventorySupported = registered.preparation_inventory === true;
|
|
240
412
|
desktopConnectionSetupSupported = registered.desktop_connection_setup === true;
|
|
413
|
+
editorReadinessEventsSupported = registered.editor_readiness_events === true;
|
|
414
|
+
if (cachedInventory && registered.inventory_cache_accepted !== true) {
|
|
415
|
+
discovered = [];
|
|
416
|
+
installed = [];
|
|
417
|
+
inventory = "[]";
|
|
418
|
+
timing("tool_inventory_cache_rejected", performance.now() - launcherStarted, { sessionId: registered.session_id });
|
|
419
|
+
if (!cacheRejectedForCompatibility)
|
|
420
|
+
options.onInventoryCacheRejected?.();
|
|
421
|
+
}
|
|
422
|
+
discovered = discoverTools();
|
|
423
|
+
installed = discovered;
|
|
424
|
+
inventory = JSON.stringify(discovered);
|
|
425
|
+
// A watcher event may race registration and queue a delta from the cached
|
|
426
|
+
// startup list. The authoritative full scan supersedes that stale delta.
|
|
427
|
+
changedInventory = undefined;
|
|
428
|
+
const inventoryElapsed = performance.now() - launcherStarted;
|
|
429
|
+
timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
|
|
430
|
+
timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
|
|
431
|
+
options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
|
|
432
|
+
const dispatchCommand = (command) => {
|
|
433
|
+
if (seenCommands.has(command.id))
|
|
434
|
+
return;
|
|
435
|
+
const commandReceived = performance.now();
|
|
436
|
+
timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
|
|
437
|
+
// A poll can redeliver an opening command after its response was lost.
|
|
438
|
+
// Record before launching, including while result delivery retries.
|
|
439
|
+
seenCommands.add(command.id);
|
|
440
|
+
seenCommandId = command.id;
|
|
441
|
+
void (async () => {
|
|
442
|
+
let outcome = { status: "failed" };
|
|
443
|
+
if (toolIds().includes(command.tool)) {
|
|
444
|
+
timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
|
|
445
|
+
const remoteReady = waitForEditorReadiness(command.tool);
|
|
446
|
+
try {
|
|
447
|
+
const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
|
|
448
|
+
outcome = typeof launched === "string" ? { status: launched } : launched;
|
|
449
|
+
}
|
|
450
|
+
catch { /* fixed failure */ }
|
|
451
|
+
const openElapsed = performance.now() - commandReceived;
|
|
452
|
+
timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
|
|
453
|
+
}
|
|
454
|
+
if (abort.signal.aborted)
|
|
455
|
+
return;
|
|
456
|
+
// CLI and backend versions roll independently. Older backends accept
|
|
457
|
+
// action_required but forbid the newer bounded reason field; omit it
|
|
458
|
+
// unless registration explicitly advertised that schema extension.
|
|
459
|
+
const reportedOutcome = outcome.reason && registered.confirmation_reasons !== true
|
|
460
|
+
? { status: outcome.status }
|
|
461
|
+
: outcome;
|
|
462
|
+
// Deliver the same result again after transport errors; never execute
|
|
463
|
+
// the tool again merely because its acknowledgement was lost.
|
|
464
|
+
// Polling owns the session's lifetime. Cap the delay, not attempts:
|
|
465
|
+
// retain the result until acknowledged, permanently refused or stopped.
|
|
466
|
+
for (let attempt = 0; !abort.signal.aborted; attempt++) {
|
|
467
|
+
try {
|
|
468
|
+
await call(`/sessions/${registered.session_id}/results/${command.id}`, reportedOutcome);
|
|
469
|
+
timing("result_acknowledged", performance.now() - commandReceived, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
if (permanentLauncherFailure(error)) {
|
|
474
|
+
console.error("Launch result could not be delivered. Check the tool before opening it again.");
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
})();
|
|
481
|
+
};
|
|
241
482
|
const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
|
|
242
483
|
tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
|
|
243
484
|
unavailable: Object.fromEntries(installed.filter(i => i.unavailable).map(i => [i.tool, i.unavailable])),
|
|
@@ -248,36 +489,74 @@ export async function runPortalLauncher(options) {
|
|
|
248
489
|
const prepareInstalledTools = async (preparingTools, readyTools = []) => {
|
|
249
490
|
if (!options.prepareTools)
|
|
250
491
|
return;
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
492
|
+
const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
|
|
493
|
+
const ready = new Set(readyTools);
|
|
494
|
+
let reportInFlight;
|
|
495
|
+
let reportRequested = false;
|
|
496
|
+
let preparationEnded = false;
|
|
497
|
+
const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
|
|
498
|
+
const publishPreparation = () => {
|
|
499
|
+
if (!registered.progress_updates || preparationEnded)
|
|
500
|
+
return reportInFlight ?? Promise.resolve();
|
|
501
|
+
reportRequested = true;
|
|
502
|
+
if (!reportInFlight)
|
|
503
|
+
reportInFlight = (async () => {
|
|
504
|
+
while (reportRequested && !preparationEnded) {
|
|
505
|
+
reportRequested = false;
|
|
506
|
+
const query = seenCommandId ? `?seen_command_id=${encodeURIComponent(seenCommandId)}` : "";
|
|
507
|
+
const reply = await call(`/sessions/${session.session_id}/poll${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
|
|
508
|
+
acceptEditorReadiness(reply?.ready_tools);
|
|
509
|
+
if (reply?.command) {
|
|
510
|
+
dispatchCommand(reply.command);
|
|
511
|
+
// Acknowledge receipt promptly; otherwise a slow opener blocks
|
|
512
|
+
// delivery of another ready tool until the lease renewal.
|
|
513
|
+
reportRequested = true;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
})().finally(() => { reportInFlight = undefined; });
|
|
517
|
+
return reportInFlight;
|
|
518
|
+
};
|
|
519
|
+
await publishPreparation();
|
|
254
520
|
// Preparing a matching editor server may outlast the initial mailbox
|
|
255
521
|
// lease. Renew as connecting, without claiming readiness or starting time.
|
|
256
522
|
// Drain any in-flight renewal before the first ready poll, so a delayed
|
|
257
523
|
// response cannot put a connected laptop back into preparation.
|
|
258
|
-
let preparationEnded = false;
|
|
259
|
-
let pendingRenewal;
|
|
260
524
|
let renewalTimer;
|
|
261
525
|
const renewPreparation = () => {
|
|
262
526
|
if (preparationEnded || abort.signal.aborted)
|
|
263
527
|
return;
|
|
264
|
-
|
|
528
|
+
void publishPreparation().finally(() => {
|
|
265
529
|
if (!preparationEnded && !abort.signal.aborted)
|
|
266
530
|
renewalTimer = setTimeout(renewPreparation, 15000);
|
|
267
531
|
});
|
|
268
532
|
};
|
|
269
533
|
renewalTimer = setTimeout(renewPreparation, 15000);
|
|
270
534
|
try {
|
|
271
|
-
|
|
535
|
+
const preparesEntireInventory = preparingTools.length === installed.length
|
|
536
|
+
&& preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
|
|
537
|
+
const preparedTools = await options.prepareTools(preparingTools, abort.signal, async (prepared) => {
|
|
538
|
+
installed = installed.map(tool => tool.tool === prepared.tool ? prepared : tool);
|
|
539
|
+
pendingTools.delete(prepared.tool);
|
|
540
|
+
if (prepared.unavailable)
|
|
541
|
+
ready.delete(prepared.tool);
|
|
542
|
+
else
|
|
543
|
+
ready.add(prepared.tool);
|
|
544
|
+
void publishPreparation();
|
|
545
|
+
}, registered.workspace_generation);
|
|
546
|
+
if (preparesEntireInventory)
|
|
547
|
+
installed = preparedTools;
|
|
548
|
+
else {
|
|
549
|
+
const preparedByTool = new Map(preparedTools.map(tool => [tool.tool, tool]));
|
|
550
|
+
installed = installed.map(tool => preparedByTool.get(tool.tool) ?? tool);
|
|
551
|
+
}
|
|
272
552
|
}
|
|
273
553
|
finally {
|
|
274
|
-
preparationEnded = true;
|
|
275
554
|
clearTimeout(renewalTimer);
|
|
276
|
-
await
|
|
555
|
+
await reportInFlight;
|
|
556
|
+
preparationEnded = true;
|
|
277
557
|
}
|
|
278
558
|
};
|
|
279
559
|
await prepareInstalledTools(installed);
|
|
280
|
-
lastDiscovery = Date.now();
|
|
281
560
|
if (abort.signal.aborted)
|
|
282
561
|
return;
|
|
283
562
|
let readyAcknowledged = false;
|
|
@@ -285,24 +564,11 @@ export async function runPortalLauncher(options) {
|
|
|
285
564
|
let readinessDeadline = Date.now() + 120000;
|
|
286
565
|
let readinessFailures = 0;
|
|
287
566
|
let failures = 0;
|
|
288
|
-
const seenCommands = new Set();
|
|
289
567
|
while (!abort.signal.aborted) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
inventory = signature;
|
|
295
|
-
changedInventory = next;
|
|
296
|
-
}
|
|
297
|
-
else {
|
|
298
|
-
const retryable = new Set(installed.filter(tool => tool.unavailable === "workspace_not_ready" || tool.unavailable === "desktop_setup_failed").map(tool => tool.tool));
|
|
299
|
-
if (retryable.size) {
|
|
300
|
-
const readyTools = toolIds();
|
|
301
|
-
installed = installed.map(tool => retryable.has(tool.tool) ? { ...tool, unavailable: undefined } : tool);
|
|
302
|
-
await prepareInstalledTools(installed.filter(tool => retryable.has(tool.tool)), readyTools);
|
|
303
|
-
}
|
|
304
|
-
lastDiscovery = Date.now();
|
|
305
|
-
}
|
|
568
|
+
const now = Date.now();
|
|
569
|
+
if (now >= nextInventoryReconcile) {
|
|
570
|
+
queueInventory(discoverTools());
|
|
571
|
+
nextInventoryReconcile = now + inventoryReconcileMs;
|
|
306
572
|
}
|
|
307
573
|
if (changedInventory) {
|
|
308
574
|
const readyTools = toolIds();
|
|
@@ -312,17 +578,29 @@ export async function runPortalLauncher(options) {
|
|
|
312
578
|
const newlyInstalled = installed.filter(tool => !tool.unavailable && !readySet.has(tool.tool));
|
|
313
579
|
if (newlyInstalled.length)
|
|
314
580
|
await prepareInstalledTools(newlyInstalled, readyTools);
|
|
315
|
-
|
|
581
|
+
}
|
|
582
|
+
if (Date.now() >= nextPreparationRetry) {
|
|
583
|
+
const retryable = new Set(installed.filter(tool => tool.unavailable === "workspace_not_ready" || tool.unavailable === "desktop_setup_failed").map(tool => tool.tool));
|
|
584
|
+
if (retryable.size) {
|
|
585
|
+
const readyTools = toolIds();
|
|
586
|
+
installed = installed.map(tool => retryable.has(tool.tool) ? { ...tool, unavailable: undefined } : tool);
|
|
587
|
+
await prepareInstalledTools(installed.filter(tool => retryable.has(tool.tool)), readyTools);
|
|
588
|
+
}
|
|
589
|
+
nextPreparationRetry = Date.now() + 30000;
|
|
316
590
|
}
|
|
317
591
|
let command;
|
|
318
592
|
try {
|
|
319
|
-
// End the wait in time for the next
|
|
320
|
-
const
|
|
593
|
+
// End the wait in time for the next retry or bounded reconciliation.
|
|
594
|
+
const nextLocalDeadline = Math.min(nextPreparationRetry, nextInventoryReconcile);
|
|
595
|
+
const waitSeconds = Math.min(25, Math.max(1, Math.ceil((nextLocalDeadline - Date.now()) / 1000)));
|
|
321
596
|
const query = new URLSearchParams({ wait_seconds: String(readyAcknowledged ? waitSeconds : 0) });
|
|
322
597
|
if (seenCommandId)
|
|
323
598
|
query.set("seen_command_id", seenCommandId);
|
|
599
|
+
if (editorReadinessEventsSupported)
|
|
600
|
+
query.set("ready_tools_seen", readyToolsCursor());
|
|
324
601
|
inventoryPoll = new AbortController();
|
|
325
602
|
const reply = await call(`/sessions/${registered.session_id}/poll?${query}`, { tools: toolIds(), phase: "ready", ...(readinessSupported ? { unavailable: unavailableTools() } : {}) }, "POST", true);
|
|
603
|
+
acceptEditorReadiness(reply.ready_tools);
|
|
326
604
|
longPoll = reply.long_poll === true;
|
|
327
605
|
command = reply.command;
|
|
328
606
|
failures = 0;
|
|
@@ -362,49 +640,23 @@ export async function runPortalLauncher(options) {
|
|
|
362
640
|
console.log("\nYour tool launcher is ready. Open tools from your assessment page.");
|
|
363
641
|
console.log(` ${options.pageUrl}`);
|
|
364
642
|
options.onReady?.();
|
|
643
|
+
completeLauncher("ok");
|
|
365
644
|
await options.openUrl(options.pageUrl);
|
|
366
645
|
}
|
|
367
|
-
if (command
|
|
368
|
-
|
|
369
|
-
// Record before launching, including while result delivery retries.
|
|
370
|
-
seenCommands.add(command.id);
|
|
371
|
-
seenCommandId = command.id;
|
|
372
|
-
void (async () => {
|
|
373
|
-
let status = "failed";
|
|
374
|
-
if (toolIds().includes(command.tool)) {
|
|
375
|
-
try {
|
|
376
|
-
status = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}) });
|
|
377
|
-
}
|
|
378
|
-
catch { /* fixed failure */ }
|
|
379
|
-
}
|
|
380
|
-
if (abort.signal.aborted)
|
|
381
|
-
return;
|
|
382
|
-
// Deliver the same result again after transport errors; never execute
|
|
383
|
-
// the tool again merely because its acknowledgement was lost.
|
|
384
|
-
// Polling owns the session's lifetime. Cap the delay, not attempts:
|
|
385
|
-
// retain the result until acknowledged, permanently refused or stopped.
|
|
386
|
-
for (let attempt = 0; !abort.signal.aborted; attempt++) {
|
|
387
|
-
try {
|
|
388
|
-
await call(`/sessions/${registered.session_id}/results/${command.id}`, { status });
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
catch (error) {
|
|
392
|
-
if (permanentLauncherFailure(error)) {
|
|
393
|
-
console.error("Launch result could not be delivered. Check the tool before opening it again.");
|
|
394
|
-
return;
|
|
395
|
-
}
|
|
396
|
-
await wait(Math.min((attempt + 1) * 2000, 10000), abort.signal);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
})();
|
|
400
|
-
}
|
|
646
|
+
if (command)
|
|
647
|
+
dispatchCommand(command);
|
|
401
648
|
// Old backends ignore the query parameters. Preserve their polling rate.
|
|
402
649
|
if (!longPoll)
|
|
403
650
|
await wait(5000, abort.signal);
|
|
404
651
|
}
|
|
405
652
|
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
completeLauncher(error instanceof LauncherRefusal && error.readinessPending ? "timeout" : "failed");
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
406
657
|
finally {
|
|
407
|
-
|
|
658
|
+
completeLauncher("cancelled");
|
|
659
|
+
stopInstallationWatch();
|
|
408
660
|
abort.abort();
|
|
409
661
|
if (session)
|
|
410
662
|
await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
|
|
@@ -415,8 +667,9 @@ export async function runPortalLauncher(options) {
|
|
|
415
667
|
// Only a positive server acknowledgement permits local connection cleanup.
|
|
416
668
|
if (session && options.onSubmitted) {
|
|
417
669
|
try {
|
|
418
|
-
if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000))
|
|
670
|
+
if (await fetchSubmissionSaved(options.backendUrl, options.token, 5000)) {
|
|
419
671
|
await options.onSubmitted();
|
|
672
|
+
}
|
|
420
673
|
}
|
|
421
674
|
catch { /* Leave settings intact when submission cannot be verified. */ }
|
|
422
675
|
}
|