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