litmus-cli 1.5.2-beta.9 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/commands/connect.d.ts.map +1 -1
  2. package/dist/commands/connect.js +109 -233
  3. package/dist/commands/connect.js.map +1 -1
  4. package/dist/commands/doctor.d.ts.map +1 -1
  5. package/dist/commands/doctor.js +2 -7
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/commands/submit.d.ts.map +1 -1
  8. package/dist/commands/submit.js +1 -4
  9. package/dist/commands/submit.js.map +1 -1
  10. package/dist/cursor-session/package.json +1 -1
  11. package/dist/cursor-session/session.cjs +12 -12
  12. package/dist/lib/ai-tracking.d.ts +1 -2
  13. package/dist/lib/ai-tracking.d.ts.map +1 -1
  14. package/dist/lib/ai-tracking.js +8 -26
  15. package/dist/lib/ai-tracking.js.map +1 -1
  16. package/dist/lib/api.d.ts +2 -1
  17. package/dist/lib/api.d.ts.map +1 -1
  18. package/dist/lib/api.js +10 -5
  19. package/dist/lib/api.js.map +1 -1
  20. package/dist/lib/backfill-tools.d.ts.map +1 -1
  21. package/dist/lib/backfill-tools.js +0 -6
  22. package/dist/lib/backfill-tools.js.map +1 -1
  23. package/dist/lib/backfill.d.ts.map +1 -1
  24. package/dist/lib/backfill.js +0 -3
  25. package/dist/lib/backfill.js.map +1 -1
  26. package/dist/lib/backlog-flush.d.ts.map +1 -1
  27. package/dist/lib/backlog-flush.js +0 -3
  28. package/dist/lib/backlog-flush.js.map +1 -1
  29. package/dist/lib/capture-network.d.ts +2 -0
  30. package/dist/lib/capture-network.d.ts.map +1 -1
  31. package/dist/lib/capture-network.js +7 -0
  32. package/dist/lib/capture-network.js.map +1 -1
  33. package/dist/lib/capture-selftest.d.ts +0 -9
  34. package/dist/lib/capture-selftest.d.ts.map +1 -1
  35. package/dist/lib/capture-selftest.js +2 -4
  36. package/dist/lib/capture-selftest.js.map +1 -1
  37. package/dist/lib/connect-skills.d.ts.map +1 -1
  38. package/dist/lib/connect-skills.js +38 -48
  39. package/dist/lib/connect-skills.js.map +1 -1
  40. package/dist/lib/cursor-session.d.ts +0 -1
  41. package/dist/lib/cursor-session.d.ts.map +1 -1
  42. package/dist/lib/cursor-session.js +1 -1
  43. package/dist/lib/cursor-session.js.map +1 -1
  44. package/dist/lib/hook-logger.cjs +0 -16
  45. package/dist/lib/hosted-capture.d.ts.map +1 -1
  46. package/dist/lib/hosted-capture.js +21 -18
  47. package/dist/lib/hosted-capture.js.map +1 -1
  48. package/dist/lib/hosted-transcripts.d.ts.map +1 -1
  49. package/dist/lib/hosted-transcripts.js +0 -4
  50. package/dist/lib/hosted-transcripts.js.map +1 -1
  51. package/dist/lib/hosted-watcher.js +0 -5
  52. package/dist/lib/hosted-watcher.js.map +1 -1
  53. package/dist/lib/launcher-cleanup-journal.d.ts +0 -34
  54. package/dist/lib/launcher-cleanup-journal.d.ts.map +1 -1
  55. package/dist/lib/launcher-cleanup-journal.js +1 -75
  56. package/dist/lib/launcher-cleanup-journal.js.map +1 -1
  57. package/dist/lib/portal-launcher.d.ts +3 -46
  58. package/dist/lib/portal-launcher.d.ts.map +1 -1
  59. package/dist/lib/portal-launcher.js +42 -465
  60. package/dist/lib/portal-launcher.js.map +1 -1
  61. package/dist/lib/schemas.d.ts +0 -1
  62. package/dist/lib/schemas.d.ts.map +1 -1
  63. package/dist/lib/schemas.js +0 -1
  64. package/dist/lib/schemas.js.map +1 -1
  65. package/dist/lib/skill-import.d.ts +4 -4
  66. package/dist/lib/skill-import.js +4 -4
  67. package/dist/lib/snapshot-capture.d.ts +24 -0
  68. package/dist/lib/snapshot-capture.d.ts.map +1 -0
  69. package/dist/lib/snapshot-capture.js +90 -0
  70. package/dist/lib/snapshot-capture.js.map +1 -0
  71. package/dist/lib/snapshot-guardian.d.ts +2 -0
  72. package/dist/lib/snapshot-guardian.d.ts.map +1 -0
  73. package/dist/lib/snapshot-guardian.js +31 -0
  74. package/dist/lib/snapshot-guardian.js.map +1 -0
  75. package/dist/lib/snapshot-worker.d.ts +2 -0
  76. package/dist/lib/snapshot-worker.d.ts.map +1 -0
  77. package/dist/lib/snapshot-worker.js +98 -0
  78. package/dist/lib/snapshot-worker.js.map +1 -0
  79. package/dist/lib/ssh-config-file.d.ts +1 -1
  80. package/dist/lib/ssh-config-file.d.ts.map +1 -1
  81. package/dist/lib/ssh-config-file.js +3 -37
  82. package/dist/lib/ssh-config-file.js.map +1 -1
  83. package/dist/lib/watcher.js +78 -139
  84. package/dist/lib/watcher.js.map +1 -1
  85. package/dist/lib/zip.d.ts.map +1 -1
  86. package/dist/lib/zip.js +1 -2
  87. package/dist/lib/zip.js.map +1 -1
  88. package/package.json +1 -1
  89. package/dist/lib/isolated-host-policy.d.ts +0 -4
  90. package/dist/lib/isolated-host-policy.d.ts.map +0 -1
  91. package/dist/lib/isolated-host-policy.js +0 -17
  92. package/dist/lib/isolated-host-policy.js.map +0 -1
@@ -36,14 +36,13 @@ export function reportLauncherTiming(backendUrl, token, stage, elapsedMs, extra
36
36
  method: "POST", redirect: "error", signal: AbortSignal.timeout(3000),
37
37
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
38
38
  body: JSON.stringify({
39
- stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001), event_at_ms: Date.now(),
39
+ stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001),
40
40
  temperature: extra.temperature ?? "unknown",
41
41
  os: process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : process.platform === "linux" ? "linux" : "unknown",
42
42
  app_version: CLI_VERSION,
43
43
  ...(extra.tool ? { tool: extra.tool } : {}), ...(extra.outcome ? { outcome: extra.outcome } : {}),
44
44
  ...(extra.sessionId ? { session_id: extra.sessionId } : {}), ...(extra.requestId ? { request_id: extra.requestId } : {}),
45
45
  ...(extra.readinessPath ? { readiness_path: extra.readinessPath } : {}),
46
- ...(extra.cleanupTarget ? { cleanup_target: extra.cleanupTarget } : {}),
47
46
  }),
48
47
  }).catch(() => { });
49
48
  }
@@ -132,255 +131,6 @@ const closeTerminalScript = `on run argv
132
131
  return "not_found"
133
132
  end tell
134
133
  end run`;
135
- const closeEditorWindowScript = `on run argv
136
- set assessmentAlias to item 1 of argv
137
- set closedCount to 0
138
- set inspectionFailed to false
139
- tell application "System Events"
140
- repeat with processName in {"Code", "Cursor"}
141
- if exists process processName then
142
- tell process processName
143
- repeat with candidateWindow in windows
144
- set ownedWindow to false
145
- try
146
- if my editorTextOwnsAlias(name of candidateWindow as text, assessmentAlias) then set ownedWindow to true
147
- end try
148
- if not ownedWindow then
149
- try
150
- repeat with candidateElement in entire contents of candidateWindow
151
- set labels to {}
152
- try
153
- set end of labels to value of candidateElement as text
154
- end try
155
- try
156
- set end of labels to description of candidateElement as text
157
- end try
158
- try
159
- set end of labels to name of candidateElement as text
160
- end try
161
- repeat with candidateLabel in labels
162
- if my editorTextOwnsAlias(candidateLabel as text, assessmentAlias) then
163
- set ownedWindow to true
164
- exit repeat
165
- end if
166
- end repeat
167
- if ownedWindow then exit repeat
168
- end repeat
169
- on error
170
- set inspectionFailed to true
171
- end try
172
- end if
173
- if ownedWindow then
174
- -- A disconnected VS Code-family window can cover itself with a
175
- -- modal alert. Dismiss only the alert that belongs to this exact
176
- -- assessment alias before closing the same native window.
177
- try
178
- repeat with candidateElement in entire contents of candidateWindow
179
- if role of candidateElement is "AXButton" then
180
- set buttonLabel to ""
181
- try
182
- set buttonLabel to name of candidateElement as text
183
- end try
184
- if buttonLabel is "Close Remote" then
185
- perform action "AXPress" of candidateElement
186
- delay 0.2
187
- exit repeat
188
- end if
189
- end if
190
- end repeat
191
- end try
192
- try
193
- perform action "AXClose" of candidateWindow
194
- on error
195
- return "retry"
196
- end try
197
- delay 0.2
198
- try
199
- if visible of candidateWindow then return "retry"
200
- end try
201
- set closedCount to closedCount + 1
202
- end if
203
- end repeat
204
- end tell
205
- end if
206
- end repeat
207
- end tell
208
- if closedCount > 0 then return "closed"
209
- if inspectionFailed then return "retry"
210
- return "not_found"
211
- end run
212
-
213
- on editorTextOwnsAlias(candidateText, assessmentAlias)
214
- set remoteMarker to "SSH: " & assessmentAlias
215
- if candidateText is remoteMarker then return true
216
- if candidateText ends with remoteMarker then return true
217
- if candidateText contains (remoteMarker & "]") then return true
218
- if candidateText contains (remoteMarker & " —") then return true
219
- if candidateText contains ("connection to \\"" & assessmentAlias & "\\"") then return true
220
- return false
221
- end editorTextOwnsAlias`;
222
- const closeClaudeWindowScript = `on run argv
223
- set assessmentAlias to item 1 of argv
224
- set assessmentWorkspace to "workspace · " & assessmentAlias
225
- set closedCount to 0
226
- tell application "System Events"
227
- if not (exists process "Claude") then return "not_found"
228
- tell process "Claude"
229
- repeat 20 times
230
- set inspectedWindow to false
231
- set matchingWindow to missing value
232
- set sessionMenuButton to missing value
233
- set pendingConfirmationCancel to missing value
234
- repeat with candidateWindow in windows
235
- set inAssessmentWorkspace to false
236
- set hasPendingConfirmationHeading to false
237
- set hasPendingConfirmationAlias to false
238
- try
239
- set windowContents to entire contents of candidateWindow
240
- set inspectedWindow to true
241
- repeat with candidateElement in windowContents
242
- try
243
- set candidateRole to role of candidateElement as text
244
- set candidateValue to ""
245
- set candidateDescription to ""
246
- set candidateName to ""
247
- try
248
- set candidateValue to value of candidateElement as text
249
- end try
250
- try
251
- set candidateDescription to description of candidateElement as text
252
- end try
253
- try
254
- set candidateName to name of candidateElement as text
255
- end try
256
- if candidateRole is "AXHeading" then
257
- if candidateValue is "Use this SSH connection?" or candidateValue is "Trust this workspace?" or candidateDescription is "Use this SSH connection?" or candidateDescription is "Trust this workspace?" or candidateName is "Use this SSH connection?" or candidateName is "Trust this workspace?" then
258
- set hasPendingConfirmationHeading to true
259
- end if
260
- if candidateValue is assessmentAlias or candidateValue is assessmentWorkspace or candidateDescription is assessmentAlias or candidateDescription is assessmentWorkspace or candidateName is assessmentAlias or candidateName is assessmentWorkspace then
261
- set inAssessmentWorkspace to true
262
- set matchingWindow to candidateWindow
263
- else if inAssessmentWorkspace then
264
- exit repeat
265
- end if
266
- else if inAssessmentWorkspace and candidateRole is "AXPopUpButton" then
267
- if candidateDescription starts with "More options for " or candidateName starts with "More options for " then
268
- set sessionMenuButton to candidateElement
269
- exit repeat
270
- end if
271
- end if
272
- -- Claude can leave its assessment-scoped SSH confirmation over
273
- -- an otherwise unrelated main window. Dismiss only a dialog
274
- -- that exposes this exact alias; never close the whole window
275
- -- merely because the pending handoff is visible.
276
- if candidateValue is assessmentAlias or candidateValue is "on " & assessmentAlias or candidateValue is "on " & assessmentAlias then
277
- set hasPendingConfirmationAlias to true
278
- else if hasPendingConfirmationHeading and hasPendingConfirmationAlias and candidateRole is "AXButton" then
279
- if candidateValue is "Cancel" or candidateDescription is "Cancel" or candidateName is "Cancel" then
280
- set pendingConfirmationCancel to candidateElement
281
- exit repeat
282
- end if
283
- end if
284
- -- Older Claude builds exposed the alias as a bare value rather
285
- -- than a workspace heading. Preserve that exact-match fallback.
286
- if matchingWindow is missing value and candidateValue is assessmentAlias then
287
- set matchingWindow to candidateWindow
288
- end if
289
- end try
290
- end repeat
291
- end try
292
- if pendingConfirmationCancel is not missing value then exit repeat
293
- if sessionMenuButton is not missing value then exit repeat
294
- end repeat
295
- if pendingConfirmationCancel is not missing value then
296
- try
297
- perform action "AXPress" of pendingConfirmationCancel
298
- delay 0.25
299
- set closedCount to closedCount + 1
300
- -- Re-scan until the exact alias is gone. A duplicate handoff can
301
- -- stack more than one confirmation dialog for the same workspace.
302
- on error
303
- return "retry"
304
- end try
305
- else if matchingWindow is missing value then
306
- if closedCount > 0 then return "closed"
307
- if (count of windows) is 0 then return "not_found"
308
- if not inspectedWindow then return "retry"
309
- return "not_found"
310
- else if sessionMenuButton is not missing value then
311
- try
312
- perform action "AXPress" of sessionMenuButton
313
- delay 0.1
314
- set archiveItem to missing value
315
- repeat with menuElement in entire contents of matchingWindow
316
- try
317
- set menuValue to value of menuElement as text
318
- set menuDescription to ""
319
- set menuName to ""
320
- try
321
- set menuDescription to description of menuElement as text
322
- end try
323
- try
324
- set menuName to name of menuElement as text
325
- end try
326
- if menuValue is "Archive" or menuDescription is "Archive" or menuName is "Archive" then
327
- set archiveItem to menuElement
328
- exit repeat
329
- end if
330
- end try
331
- end repeat
332
- if archiveItem is missing value then return "retry"
333
- perform action "AXPress" of archiveItem
334
- delay 0.25
335
- set closedCount to closedCount + 1
336
- -- Keep archiving until the exact assessment workspace contains no
337
- -- sessions. Other workspace groups and chats are never inspected.
338
- on error
339
- return "retry"
340
- end try
341
- else
342
- try
343
- perform action "AXClose" of matchingWindow
344
- on error
345
- return "retry"
346
- end try
347
- delay 0.25
348
- set closedCount to closedCount + 1
349
- end if
350
- end repeat
351
- -- A close request that leaves the exact alias visible is not verified.
352
- return "retry"
353
- end tell
354
- end tell
355
- end run`;
356
- /**
357
- * Testable semantic model of the ownership gate used by the native Claude
358
- * cleanup script. The runtime still uses System Events, but both paths require
359
- * the confirmation heading, exact assessment alias and Cancel button to occur
360
- * in the same window and in that order.
361
- */
362
- export function ownedClaudePendingDialogCancel(alias, windows) {
363
- if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
364
- return null;
365
- const headings = new Set(["Use this SSH connection?", "Trust this workspace?"]);
366
- const aliases = new Set([alias, `on ${alias}`, `on ${alias}`]);
367
- for (let window = 0; window < windows.length; window++) {
368
- let heading = false;
369
- let exactAlias = false;
370
- for (let element = 0; element < windows[window].length; element++) {
371
- const candidate = windows[window][element];
372
- const labels = [candidate.value, candidate.description, candidate.name];
373
- if (candidate.role === "AXHeading" && labels.some(label => label && headings.has(label)))
374
- heading = true;
375
- if (labels.some(label => label && aliases.has(label)))
376
- exactAlias = true;
377
- if (heading && exactAlias && candidate.role === "AXButton" && labels.includes("Cancel")) {
378
- return { window, element };
379
- }
380
- }
381
- }
382
- return null;
383
- }
384
134
  /** Foreground the live, assessment-scoped Terminal session before opening another shell. */
385
135
  export function focusExistingMacTerminal(alias, execFileFn = execFile) {
386
136
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
@@ -408,144 +158,6 @@ export function closeOwnedMacTerminal(alias, platform = process.platform, execFi
408
158
  });
409
159
  });
410
160
  }
411
- /** Close only VS Code-family windows whose accessibility tree names this assessment alias. */
412
- export function closeOwnedMacEditorWindows(alias, platform = process.platform, execFileFn = execFile) {
413
- if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
414
- return Promise.resolve("unsupported");
415
- return new Promise((resolve, reject) => {
416
- execFileFn("/usr/bin/osascript", ["-e", closeEditorWindowScript, alias], { timeout: 5000 }, (error, stdout) => {
417
- if (error)
418
- return reject(error);
419
- const outcome = String(stdout).trim();
420
- if (outcome === "closed" || outcome === "not_found")
421
- return resolve(outcome);
422
- if (outcome === "retry")
423
- return reject(new Error("The owned assessment editor window could not be closed safely"));
424
- reject(new Error("The editor returned an unknown cleanup result"));
425
- });
426
- });
427
- }
428
- /** Close only a Claude window whose accessibility tree still names this assessment alias. */
429
- export function closeOwnedMacClaudeWindow(alias, platform = process.platform, execFileFn = execFile) {
430
- if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
431
- return Promise.resolve("unsupported");
432
- return new Promise((resolve, reject) => {
433
- execFileFn("/usr/bin/osascript", ["-e", closeClaudeWindowScript, alias], { timeout: 10000 }, (error, stdout) => {
434
- if (error)
435
- return reject(error);
436
- const outcome = String(stdout).trim();
437
- if (outcome === "closed" || outcome === "not_found")
438
- return resolve(outcome);
439
- if (outcome === "retry")
440
- return reject(new Error("The owned Claude assessment window could not be closed safely"));
441
- reject(new Error("Claude returned an unknown cleanup result"));
442
- });
443
- });
444
- }
445
- function execFileOutput(command, args, execFileFn) {
446
- return new Promise((resolve, reject) => {
447
- execFileFn(command, args, { timeout: 2500 }, (error, stdout) => error ? reject(error) : resolve(String(stdout).trim()));
448
- });
449
- }
450
- /** Identify Claude's main process strongly enough to reject PID reuse. */
451
- export async function macClaudeProcess(platform = process.platform, execFileFn = execFile) {
452
- if (platform !== "darwin")
453
- return null;
454
- let rawPid;
455
- try {
456
- rawPid = await execFileOutput("/usr/bin/pgrep", ["-x", "Claude"], execFileFn);
457
- }
458
- catch (error) {
459
- // pgrep 1 means no matching process. Any other failure is unknown, and
460
- // must not be mistaken for permission to take ownership of Claude.
461
- if (typeof error === "object" && error && "code" in error && error.code === 1)
462
- return null;
463
- throw error;
464
- }
465
- const pid = Number(rawPid.split(/\s+/)[0]);
466
- if (!Number.isSafeInteger(pid) || pid <= 1)
467
- throw new Error("Claude returned an invalid process identity");
468
- const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
469
- if (!startedAt)
470
- throw new Error("Claude process start time is unavailable");
471
- return { pid, startedAt };
472
- }
473
- /** Identify ChatGPT App's main process strongly enough to reject PID reuse. */
474
- export async function macCodexProcess(appCommand, platform = process.platform, execFileFn = execFile) {
475
- if (platform !== "darwin")
476
- return null;
477
- const application = /(?:^|\/)Codex(?:\.app(?:\/Contents\/MacOS\/Codex)?)?$/.test(appCommand ?? "") ? "Codex" : "ChatGPT";
478
- const executable = application === "Codex"
479
- ? /\/Codex\.app\/Contents\/MacOS\/Codex$/
480
- : /\/ChatGPT\.app\/Contents\/MacOS\/ChatGPT$/;
481
- // macOS truncates this Electron process's comm value for pgrep. Read the
482
- // executable column and accept only the app bundle's main executable.
483
- const processes = await execFileOutput("/bin/ps", ["-axo", "pid=,comm="], execFileFn);
484
- const match = processes.split("\n").map(line => /^\s*(\d+)\s+(.+)$/.exec(line))
485
- .find(row => row && executable.test(row[2]));
486
- if (!match)
487
- return null;
488
- const pid = Number(match[1]);
489
- if (!Number.isSafeInteger(pid) || pid <= 1)
490
- throw new Error(`${application} App returned an invalid process identity`);
491
- const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
492
- if (!startedAt)
493
- throw new Error(`${application} App process start time is unavailable`);
494
- return { pid, startedAt, application };
495
- }
496
- /** Quit Claude only when the still-running process is exactly the one Litmus launched. */
497
- export async function closeOwnedMacClaudeProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
498
- if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
499
- return "unsupported";
500
- const current = await macClaudeProcess(platform, execFileFn);
501
- if (!current)
502
- return "not_found";
503
- if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
504
- return "ownership_changed";
505
- await execFileOutput("/usr/bin/osascript", ["-e", 'tell application "Claude" to quit'], execFileFn);
506
- for (let attempt = 0; attempt < 20; attempt++) {
507
- const remaining = await macClaudeProcess(platform, execFileFn);
508
- if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
509
- return "closed";
510
- await wait(100);
511
- }
512
- throw new Error("The Litmus-launched Claude process did not quit");
513
- }
514
- /** Close the assessment-owned Claude process, or its exact alias window after a restart. */
515
- export async function closeOwnedMacClaudeSession(alias, expected, windowLaunched, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
516
- // Archive the exact assessment workspace first. Quitting a process that
517
- // Litmus launched closes its native window but leaves Claude's persisted
518
- // sessions behind, so they reappear the next time Claude opens.
519
- const windowOutcome = windowLaunched
520
- ? await closeOwnedMacClaudeWindow(alias, platform, execFileFn)
521
- : "not_found";
522
- if (expected) {
523
- const outcome = await closeOwnedMacClaudeProcess(expected, platform, execFileFn, wait);
524
- if (outcome !== "ownership_changed")
525
- return outcome;
526
- }
527
- return windowOutcome;
528
- }
529
- /** Quit ChatGPT App only when the running process is exactly the one Litmus launched. */
530
- export async function closeOwnedMacCodexProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
531
- if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
532
- return "unsupported";
533
- if (expected.application !== "ChatGPT" && expected.application !== "Codex")
534
- return "unsupported";
535
- const current = await macCodexProcess(expected.application, platform, execFileFn);
536
- if (!current)
537
- return "not_found";
538
- if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
539
- return "ownership_changed";
540
- await execFileOutput("/usr/bin/osascript", ["-e", `tell application "${expected.application}" to quit`], execFileFn);
541
- for (let attempt = 0; attempt < 20; attempt++) {
542
- const remaining = await macCodexProcess(expected.application, platform, execFileFn);
543
- if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
544
- return "closed";
545
- await wait(100);
546
- }
547
- throw new Error("The Litmus-launched ChatGPT App process did not quit");
548
- }
549
161
  export async function openTerminal(alias, terminal, requestId) {
550
162
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
551
163
  return false;
@@ -574,7 +186,7 @@ export function removeTerminalLauncher(alias, home = os.homedir()) {
574
186
  rmSync(path.join(home, ".litmus", "launchers", `${alias}.command`), { force: true });
575
187
  }
576
188
  /** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
577
- export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady, onLocalOpened) {
189
+ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
578
190
  return new Promise(resolve => {
579
191
  let result = "action_required";
580
192
  let prepared = null;
@@ -599,9 +211,6 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
599
211
  execArgv: [], env,
600
212
  stdio: ["ignore", "inherit", "inherit", "ipc"],
601
213
  });
602
- // This is the local process boundary. Remote attachment is deliberately
603
- // measured later by the managed readiness event/probe.
604
- child.once("spawn", () => onLocalOpened?.("ok"));
605
214
  child.on("message", message => {
606
215
  if (!message || typeof message !== "object")
607
216
  return;
@@ -639,7 +248,7 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
639
248
  });
640
249
  const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
641
250
  const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
642
- child.once("error", () => { onLocalOpened?.("failed"); cleanup(); resolve("action_required"); });
251
+ child.once("error", () => { cleanup(); resolve("action_required"); });
643
252
  child.once("exit", code => {
644
253
  cleanup();
645
254
  if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
@@ -706,8 +315,6 @@ export async function runPortalLauncher(options) {
706
315
  const launcherStarted = performance.now();
707
316
  const timing = options.reportTiming ?? (() => { });
708
317
  timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
709
- timing("connect_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
710
- timing("detection_started", 0);
711
318
  const abort = new AbortController();
712
319
  const stop = () => abort.abort();
713
320
  options.signal?.addEventListener("abort", stop, { once: true });
@@ -764,7 +371,6 @@ export async function runPortalLauncher(options) {
764
371
  }, abort.signal);
765
372
  let seenCommandId = null;
766
373
  const seenCommands = new Set();
767
- const pendingLaunches = new Set();
768
374
  let longPoll = false;
769
375
  let readinessSupported = false;
770
376
  let preparationInventorySupported = false;
@@ -882,47 +488,28 @@ export async function runPortalLauncher(options) {
882
488
  const inventoryElapsed = performance.now() - launcherStarted;
883
489
  timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
884
490
  timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
885
- timing("detection_completed", inventoryElapsed, { sessionId: registered.session_id });
886
491
  options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
887
492
  const dispatchCommand = (command) => {
888
493
  if (seenCommands.has(command.id))
889
494
  return;
890
495
  const commandReceived = performance.now();
891
496
  timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
892
- timing("launch_requested", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
893
497
  // A poll can redeliver an opening command after its response was lost.
894
498
  // Record before launching, including while result delivery retries.
895
499
  seenCommands.add(command.id);
896
500
  seenCommandId = command.id;
897
- const launchTask = (async () => {
501
+ void (async () => {
898
502
  let outcome = { status: "failed" };
899
503
  if (toolIds().includes(command.tool)) {
900
504
  timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
901
505
  const remoteReady = waitForEditorReadiness(command.tool);
902
506
  try {
903
- let localOpenedReported = false;
904
- const onLocalOpened = (localOutcome = "ok") => {
905
- if (localOpenedReported)
906
- return;
907
- localOpenedReported = true;
908
- timing("local_process_opened", performance.now() - commandReceived, {
909
- tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: localOutcome,
910
- });
911
- };
912
- const launched = await options.launch(command.tool, installed, abort.signal, {
913
- requestId: command.id,
914
- ...(command.generation ? { generation: command.generation } : {}),
915
- ...(remoteReady ? { remoteReady } : {}),
916
- onLocalOpened,
917
- });
507
+ const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
918
508
  outcome = typeof launched === "string" ? { status: launched } : launched;
919
- if (!localOpenedReported && outcome.status === "failed")
920
- onLocalOpened("failed");
921
509
  }
922
510
  catch { /* fixed failure */ }
923
511
  const openElapsed = performance.now() - commandReceived;
924
- const osOpened = outcome.status === "dispatched" || outcome.reason === "confirmation_required";
925
- timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: osOpened ? "ok" : "failed" });
512
+ timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
926
513
  }
927
514
  if (abort.signal.aborted)
928
515
  return;
@@ -951,8 +538,6 @@ export async function runPortalLauncher(options) {
951
538
  }
952
539
  }
953
540
  })();
954
- pendingLaunches.add(launchTask);
955
- void launchTask.then(() => pendingLaunches.delete(launchTask), () => pendingLaunches.delete(launchTask));
956
541
  };
957
542
  const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
958
543
  tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
@@ -964,53 +549,48 @@ export async function runPortalLauncher(options) {
964
549
  const prepareInstalledTools = async (preparingTools, readyTools = []) => {
965
550
  if (!options.prepareTools)
966
551
  return;
967
- const preparationPreference = { tool: null };
968
552
  const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
969
553
  const ready = new Set(readyTools);
554
+ let reportInFlight;
555
+ let reportRequested = false;
970
556
  let preparationEnded = false;
971
557
  const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
972
- const pollPreparation = async (waitSeconds) => {
558
+ const publishPreparation = () => {
973
559
  if (!registered.progress_updates || preparationEnded)
974
- return true;
975
- const query = new URLSearchParams({ wait_seconds: String(waitSeconds) });
976
- if (seenCommandId)
977
- query.set("seen_command_id", seenCommandId);
978
- const reply = await call(`/sessions/${session.session_id}/poll?${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
979
- if (!reply)
980
- return false;
981
- acceptEditorReadiness(reply?.ready_tools);
982
- if (reply?.preferred_tool && pendingTools.has(reply.preferred_tool))
983
- preparationPreference.tool = reply.preferred_tool;
984
- if (reply?.command)
985
- dispatchCommand(reply.command);
986
- return true;
560
+ return reportInFlight ?? Promise.resolve();
561
+ reportRequested = true;
562
+ if (!reportInFlight)
563
+ reportInFlight = (async () => {
564
+ while (reportRequested && !preparationEnded) {
565
+ reportRequested = false;
566
+ const query = seenCommandId ? `?seen_command_id=${encodeURIComponent(seenCommandId)}` : "";
567
+ const reply = await call(`/sessions/${session.session_id}/poll${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
568
+ acceptEditorReadiness(reply?.ready_tools);
569
+ if (reply?.command) {
570
+ dispatchCommand(reply.command);
571
+ // Acknowledge receipt promptly; otherwise a slow opener blocks
572
+ // delivery of another ready tool until the lease renewal.
573
+ reportRequested = true;
574
+ }
575
+ }
576
+ })().finally(() => { reportInFlight = undefined; });
577
+ return reportInFlight;
987
578
  };
988
- await pollPreparation(0);
989
- let preferencePoll;
990
- let preferencePollTimer;
991
- const armPreferencePoll = () => {
992
- if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
579
+ await publishPreparation();
580
+ // Preparing a matching editor server may outlast the initial mailbox
581
+ // lease. Renew as connecting, without claiming readiness or starting time.
582
+ // Drain any in-flight renewal before the first ready poll, so a delayed
583
+ // response cannot put a connected laptop back into preparation.
584
+ let renewalTimer;
585
+ const renewPreparation = () => {
586
+ if (preparationEnded || abort.signal.aborted)
993
587
  return;
994
- preferencePoll = pollPreparation(3);
995
- void preferencePoll.then(succeeded => {
996
- preferencePoll = undefined;
997
- // A legacy backend may ignore wait_seconds and answer immediately.
998
- // Keep that path under the server's 30/minute limit, and back off
999
- // further after a refusal or transport failure.
588
+ void publishPreparation().finally(() => {
1000
589
  if (!preparationEnded && !abort.signal.aborted)
1001
- preferencePollTimer = setTimeout(armPreferencePoll, succeeded ? 100 : 2000);
590
+ renewalTimer = setTimeout(renewPreparation, 15000);
1002
591
  });
1003
592
  };
1004
- armPreferencePoll();
1005
- preparationPreference.refresh = async () => {
1006
- if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
1007
- return;
1008
- const activePoll = preferencePoll;
1009
- if (activePoll)
1010
- await activePoll;
1011
- else
1012
- await pollPreparation(0);
1013
- };
593
+ renewalTimer = setTimeout(renewPreparation, 15000);
1014
594
  try {
1015
595
  const preparesEntireInventory = preparingTools.length === installed.length
1016
596
  && preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
@@ -1021,7 +601,8 @@ export async function runPortalLauncher(options) {
1021
601
  ready.delete(prepared.tool);
1022
602
  else
1023
603
  ready.add(prepared.tool);
1024
- }, registered.workspace_generation, preparationPreference);
604
+ void publishPreparation();
605
+ }, registered.workspace_generation);
1025
606
  if (preparesEntireInventory)
1026
607
  installed = preparedTools;
1027
608
  else {
@@ -1030,10 +611,9 @@ export async function runPortalLauncher(options) {
1030
611
  }
1031
612
  }
1032
613
  finally {
614
+ clearTimeout(renewalTimer);
615
+ await reportInFlight;
1033
616
  preparationEnded = true;
1034
- if (preferencePollTimer)
1035
- clearTimeout(preferencePollTimer);
1036
- await preferencePoll;
1037
617
  }
1038
618
  };
1039
619
  await prepareInstalledTools(installed);
@@ -1138,9 +718,6 @@ export async function runPortalLauncher(options) {
1138
718
  completeLauncher("cancelled");
1139
719
  stopInstallationWatch();
1140
720
  abort.abort();
1141
- // A launch may still be recording the exact app process that Litmus owns.
1142
- // Do not let confirmed-submission cleanup read and delete the journal first.
1143
- await Promise.allSettled([...pendingLaunches]);
1144
721
  if (session)
1145
722
  await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
1146
723
  options.signal?.removeEventListener("abort", stop);