@alexwkleung/reika 0.9.0 → 0.10.0

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.
@@ -10,7 +10,9 @@ import { expandPastedUrls, planPastedUrls } from '../agent/pastedurls.js';
10
10
  import { matchSkill, shouldAutoInject, shouldConfirmInject } from '../skills/skillmatch.js';
11
11
  import { imageReader } from '../ocr/select.js';
12
12
  import { autoApproves } from '../approval.js';
13
- import { toolLabel } from '../ui/format.js';
13
+ import { budgetWarning } from '../context/bundlesize.js';
14
+ import { formatElapsed, toolLabel } from '../ui/format.js';
15
+ import { stripTerminalControls } from '../ui/termtext.js';
14
16
  import { debugLog, processSessionStem } from '../debug.js';
15
17
  import { callMcpTool, findMcpCommand, parseMcpArgs } from '../mcp/tools.js';
16
18
  import { askApproval, askConfirm, askQuestion, openTerminalPrompter, } from './headlessprompt.js';
@@ -21,6 +23,8 @@ import { pastedUrlConfirmSpec, skillConfirmSpec } from '../ui/dialogspecs.js';
21
23
  // expansion, skill routing) and the approval policy. Those are deliberately the same modules App
22
24
  // calls, in the same order: a headless run must be the run the TUI would have made, or it is
23
25
  // useless as the debugging instrument the issue asks for.
26
+ // The harness ended the turn itself (a loop, the round cap): not a crash, and not an answer.
27
+ const EXIT_HARNESS_STOP = 2;
24
28
  // The TUI's mid-turn auto-save cadence.
25
29
  const AUTOSAVE_INTERVAL_MS = 3000;
26
30
  // The model-facing text for a prompt, built the way App's submit path builds it: a leading
@@ -99,6 +103,32 @@ export function headlessProfile(config, mode, named) {
99
103
  export function formatTurnFailure(profile, baseURL, message) {
100
104
  return `reika: turn failed (profile "${profile}" at ${baseURL}): ${message}`;
101
105
  }
106
+ // One line closing a run, since headless has no status bar or exit summary. On stderr, so stdout
107
+ // stays the reply; the session path is where the rest of what the TUI shows can be read back.
108
+ export function formatRunSummary(run) {
109
+ const { model, totals, elapsedMs, sessionPath } = run;
110
+ const n = (t) => t.toLocaleString('en-US');
111
+ const approx = totals.estimated ? '~' : '';
112
+ const cached = totals.cachedTokens ? ` (${n(totals.cachedTokens)} cached)` : '';
113
+ // A server that reports no usage leaves zeros, which would read as a measurement.
114
+ const counted = totals.promptTokens > 0 || totals.completionTokens > 0;
115
+ const parts = [
116
+ model,
117
+ ...(counted
118
+ ? [
119
+ `${approx}${n(totals.promptTokens)} tokens in${cached}, ${approx}${n(totals.completionTokens)} out`,
120
+ ]
121
+ : []),
122
+ formatElapsed(Math.floor(elapsedMs / 1000)),
123
+ ...(sessionPath ? [`session ${sessionPath}`] : []),
124
+ ];
125
+ return parts.join(' · ');
126
+ }
127
+ // A reply can carry escape sequences a fetched page smuggled into it, and a terminal obeys them. A
128
+ // pipe gets the model's bytes: stdout is the reply, and a consumer decides what to do with it.
129
+ export function terminalSafeWriter(stream) {
130
+ return text => void stream.write(stream.isTTY ? stripTerminalControls(text) : text);
131
+ }
102
132
  export async function runHeadless(args, io) {
103
133
  const prompt = (args.prompt ?? (await io.readStdin())).trim();
104
134
  if (!prompt) {
@@ -197,6 +227,9 @@ async function runHeadlessTurn(args, io, prompt, controller, prompter) {
197
227
  io.stderr(`reika: ${session.limitsNotice}\n`);
198
228
  if (session.windowNotice)
199
229
  io.stderr(`reika: ${session.windowNotice}\n`);
230
+ const budgetProblem = budgetWarning(bundle, config);
231
+ if (budgetProblem)
232
+ io.stderr(`reika: ${budgetProblem}\n`);
200
233
  if (session.offline)
201
234
  io.stderr('reika: no network — search and fetch_url are off for this run\n');
202
235
  if (session.searchNotice)
@@ -234,6 +267,7 @@ async function runHeadlessTurn(args, io, prompt, controller, prompter) {
234
267
  const onSigint = () => controller.abort();
235
268
  process.once('SIGINT', onSigint);
236
269
  let failed = null;
270
+ const turnStartedAt = Date.now();
237
271
  try {
238
272
  await session.submit(input.modelText, {
239
273
  mode,
@@ -260,6 +294,13 @@ async function runHeadlessTurn(args, io, prompt, controller, prompter) {
260
294
  io.stderr(`reika: save failed: ${e.message}\n`);
261
295
  }
262
296
  }
297
+ const summary = formatRunSummary({
298
+ model: config.model,
299
+ totals: session.totals,
300
+ elapsedMs: Date.now() - turnStartedAt,
301
+ sessionPath: autosave?.savedPath(),
302
+ });
303
+ io.stderr(`reika: ${summary}\n`);
263
304
  if (failed) {
264
305
  debugLog(`headless: turn failed: ${failed.message}`);
265
306
  io.stderr(`${formatTurnFailure(profile, config.baseURL, failed.message)}\n`);
@@ -274,7 +315,16 @@ async function runHeadlessTurn(args, io, prompt, controller, prompter) {
274
315
  io.stderr('reika: interrupted\n');
275
316
  return 130;
276
317
  }
318
+ const closing = closingAssistantMessage(appended);
319
+ if (closing?.role === 'assistant' && closing.harnessStop) {
320
+ // Not printed as the reply: a script reading stdout would take the harness's report for the
321
+ // model's answer. The exit status is what it can branch on.
322
+ io.stderr(`reika: stopped (${closing.harnessStop}): ${closing.content}\n`);
323
+ return EXIT_HARNESS_STOP;
324
+ }
277
325
  const reply = finalReply(appended);
326
+ if (!reply)
327
+ io.stderr('reika: the turn ended without a reply\n');
278
328
  if (!args.json && !args.stream && reply)
279
329
  io.stdout(`${reply}\n`);
280
330
  return reply ? 0 : 1;
@@ -362,6 +412,7 @@ export function createHeadlessAutosave(path, messages, side, meta, onError, inte
362
412
  timer.unref?.();
363
413
  },
364
414
  finish: () => save(false),
415
+ savedPath: () => (written && !failed ? path : null),
365
416
  };
366
417
  }
367
418
  // --stream (#566). Text: the content channel goes to stdout as it arrives and each tool call's
@@ -424,16 +475,24 @@ export function createStreamPrinter(io, json) {
424
475
  finish: endLine,
425
476
  };
426
477
  }
427
- // The last assistant message with content is the answer. A turn that ended on a tool call or an
428
- // empty message has no reply, which the exit status reports.
429
- export function finalReply(messages) {
478
+ // What the turn itself ended on: a subagent's rounds and a compaction note are harness asides.
479
+ function closingAssistantMessage(messages) {
430
480
  for (let i = messages.length - 1; i >= 0; i--) {
431
481
  const m = messages[i];
432
- if (m.role === 'assistant' && m.content?.trim())
433
- return m.content.trim();
482
+ if (m.role === 'assistant' && !m.nested && !m.compactionNote)
483
+ return m;
434
484
  }
435
485
  return null;
436
486
  }
487
+ // The message the turn ended on, and only that one. A turn that ended on a tool call or an empty
488
+ // message has no reply, which the exit status reports: walking further back would return the text
489
+ // a model wrote before an earlier tool call as if it were the answer.
490
+ export function finalReply(messages) {
491
+ const closing = closingAssistantMessage(messages);
492
+ if (closing?.role !== 'assistant' || closing.toolCalls?.length)
493
+ return null;
494
+ return closing.content?.trim() || null;
495
+ }
437
496
  function firstLine(text) {
438
497
  const line = text.split('\n', 1)[0] ?? '';
439
498
  return line.length > 80 ? `${line.slice(0, 77)}…` : line;
@@ -20,7 +20,7 @@ With -p: a prompt starting with /<skill> runs that skill. Approvals follow REIKA
20
20
  (default 'safe'): with no prompt to fall back on, anything 'safe' would have asked about is
21
21
  declined, and 'off' declines every edit and command. ask_user is never offered. With -i each of
22
22
  those is asked instead, as a numbered menu on the terminal. Exit status: 0 on a reply, 1 on an
23
- error, 130 when interrupted.`;
23
+ error, 2 when Reika stopped the turn itself (a loop, the round limit), 130 when interrupted.`;
24
24
  const MODES = new Set(['agent', 'plan', 'vibe', 'minimal', 'grind', 'chat']);
25
25
  // Returns null when the argv holds no headless request, so the caller starts the TUI. --help and
26
26
  // --version count as requests: both answer without starting either front-end. Throws on
@@ -2,6 +2,7 @@ import { openSync, createReadStream, createWriteStream } from 'node:fs';
2
2
  import { createInterface } from 'node:readline';
3
3
  import { APPROVAL_FEEDBACK_INDEX, APPROVAL_OPTIONS } from '../ui/dialogspecs.js';
4
4
  import { toolLabel } from '../ui/format.js';
5
+ import { stripTerminalControls } from '../ui/termtext.js';
5
6
  // Headless dialogs (#872): `reika -p -i` asks what the TUI would have opened a dialog for, as a
6
7
  // numbered menu on the controlling terminal. The terminal, not stdin/stderr: stdin may be the piped
7
8
  // prompt and stderr a log file, and a question written into a log waits for an answer nobody sees.
@@ -55,7 +56,7 @@ export function createPrompter(input, output, signal) {
55
56
  });
56
57
  const write = (text) => {
57
58
  if (!closed)
58
- output.write(text);
59
+ output.write(stripTerminalControls(text));
59
60
  };
60
61
  return {
61
62
  choose: (header, options, defaultIndex) => serial(async () => {
@@ -1,7 +1,7 @@
1
1
  import { jsonrepair } from 'jsonrepair';
2
2
  import { debugLog } from '../debug.js';
3
3
  import { cacheControlFor, promptCacheKeyFor } from './cachehints.js';
4
- import { chatTemplateKwargsFor } from './templatekwargs.js';
4
+ import { chatTemplateKwargsFor, isLocalEngine } from './templatekwargs.js';
5
5
  import { latchesFor, resetEndpointLatches } from './latches.js';
6
6
  import { messagesToChatParams, shapeRejection, toolsToChatTools } from './toolcall.js';
7
7
  import { streamChatCompletion } from './transport.js';
@@ -54,6 +54,13 @@ export async function callModel(opts) {
54
54
  let startedAt = Date.now();
55
55
  let ttftMs;
56
56
  const timing = () => ttftMs == null ? undefined : { ttftMs, totalMs: Date.now() - startedAt };
57
+ let promptProgressLive = false;
58
+ const endPromptProgress = () => {
59
+ if (!promptProgressLive)
60
+ return;
61
+ promptProgressLive = false;
62
+ opts.onPromptProgress?.(undefined);
63
+ };
57
64
  const wantLogprobs = !!opts.logprobs && opts.logprobs > 0 && !latches.logprobs;
58
65
  const wantToolChoice = !!opts.toolChoice && opts.tools.length > 0 && !latches.toolChoice;
59
66
  // A latched-off tool_choice means the tools go too: the caller asked for a round with no calls,
@@ -66,6 +73,8 @@ export async function callModel(opts) {
66
73
  const templateKwargs = latches.chatTemplateKwargs
67
74
  ? undefined
68
75
  : chatTemplateKwargsFor(opts.config.baseURL);
76
+ const wantPromptProgress = !!opts.onPromptProgress && isLocalEngine(opts.config.baseURL) && !latches.promptProgress;
77
+ const wantEngineTimings = !!opts.onEngineTimings && isLocalEngine(opts.config.baseURL) && !latches.timingsPerToken;
69
78
  const body = {
70
79
  model: opts.config.model,
71
80
  messages,
@@ -73,6 +82,8 @@ export async function callModel(opts) {
73
82
  ...(wantToolChoice ? { tool_choice: opts.toolChoice } : {}),
74
83
  stream: true,
75
84
  stream_options: { include_usage: true },
85
+ ...(wantPromptProgress ? { return_progress: true } : {}),
86
+ ...(wantEngineTimings ? { timings_per_token: true } : {}),
76
87
  ...(maxTokens ? { max_tokens: maxTokens } : {}),
77
88
  ...(opts.logitBias && Object.keys(opts.logitBias).length > 0
78
89
  ? { logit_bias: opts.logitBias }
@@ -95,7 +106,16 @@ export async function callModel(opts) {
95
106
  signal: opts.signal,
96
107
  });
97
108
  for await (const chunk of stream) {
98
- received = true;
109
+ // Not `received`: progress is no generated output, so a stream that dies during prefill
110
+ // stays retryable by the degrade ladder below.
111
+ const promptProgress = readPromptProgress(chunk);
112
+ if (promptProgress) {
113
+ promptProgressLive = true;
114
+ opts.onPromptProgress?.(promptProgress);
115
+ }
116
+ else {
117
+ received = true;
118
+ }
99
119
  if (chunk.usage) {
100
120
  // Cache-hit accounting is reported under different field names per provider:
101
121
  // OpenAI nests it in `prompt_tokens_details.cached_tokens`; DeepSeek exposes
@@ -136,6 +156,10 @@ export async function callModel(opts) {
136
156
  if (Object.keys(prompt).length > 0)
137
157
  enginePrompt = prompt;
138
158
  }
159
+ // Zero predicted is still prefill, where the prompt fields are partial.
160
+ if (et && engineTimings && engineTimings.predictedN > 0) {
161
+ opts.onEngineTimings?.(engineTimings, enginePrompt);
162
+ }
139
163
  // Logprobs ride the choice, not the delta, and a chunk can carry them with no delta at all
140
164
  // — so collect before the delta guard. Normalized to SampledToken here (the wire's null
141
165
  // top_logprobs becomes an absent `top`) so nothing downstream handles wire shapes.
@@ -155,11 +179,14 @@ export async function callModel(opts) {
155
179
  // First chunk carrying generated tokens ends prefill. Role-only openers and usage-only
156
180
  // chunks carry no work, so they must not stop the clock early.
157
181
  if (ttftMs == null &&
158
- (delta.content || delta.reasoning_content || delta.reasoning || delta.tool_calls))
182
+ (delta.content || delta.reasoning_content || delta.reasoning || delta.tool_calls)) {
159
183
  ttftMs = Date.now() - startedAt;
184
+ endPromptProgress();
185
+ }
160
186
  if (delta.content) {
161
187
  contentParts.push(delta.content);
162
188
  opts.onContentDelta?.(delta.content);
189
+ opts.onOutputDelta?.(delta.content);
163
190
  }
164
191
  // Field name differs by provider: DeepSeek/Kimi use `reasoning_content`,
165
192
  // OpenRouter normalizes to `reasoning`. Accept either.
@@ -167,6 +194,7 @@ export async function callModel(opts) {
167
194
  if (reasoningChunk) {
168
195
  reasoningParts.push(reasoningChunk);
169
196
  opts.onReasoningDelta?.(reasoningChunk);
197
+ opts.onOutputDelta?.(reasoningChunk);
170
198
  }
171
199
  if (delta.tool_calls) {
172
200
  for (const tc of delta.tool_calls) {
@@ -178,10 +206,14 @@ export async function callModel(opts) {
178
206
  }
179
207
  if (tc.id)
180
208
  acc.id = tc.id;
181
- if (tc.function?.name)
209
+ if (tc.function?.name) {
182
210
  acc.name = tc.function.name;
183
- if (tc.function?.arguments)
211
+ opts.onOutputDelta?.(tc.function.name);
212
+ }
213
+ if (tc.function?.arguments) {
184
214
  acc.args += tc.function.arguments;
215
+ opts.onOutputDelta?.(tc.function.arguments);
216
+ }
185
217
  }
186
218
  }
187
219
  }
@@ -247,6 +279,20 @@ export async function callModel(opts) {
247
279
  req = plain;
248
280
  continue;
249
281
  }
282
+ if (req.return_progress !== undefined && reason.includes('return_progress')) {
283
+ latches.promptProgress = true;
284
+ debugLog(`[reika:debug] return_progress unsupported by backend — retrying without (${reason})\n`);
285
+ const { return_progress: _returnProgress, ...plain } = req;
286
+ req = plain;
287
+ continue;
288
+ }
289
+ if (req.timings_per_token !== undefined && reason.includes('timings_per_token')) {
290
+ latches.timingsPerToken = true;
291
+ debugLog(`[reika:debug] timings_per_token unsupported by backend — retrying without (${reason})\n`);
292
+ const { timings_per_token: _timingsPerToken, ...plain } = req;
293
+ req = plain;
294
+ continue;
295
+ }
250
296
  // Name-keyed like the cache hints: logprobs below latches on any pre-chunk failure, and a
251
297
  // server still loading at startup would otherwise cost the session its reasoning.
252
298
  if (req.chat_template_kwargs !== undefined && reason.includes('chat_template_kwargs')) {
@@ -294,6 +340,9 @@ export async function callModel(opts) {
294
340
  }
295
341
  throw e;
296
342
  }
343
+ finally {
344
+ endPromptProgress();
345
+ }
297
346
  const nativeToolCalls = [];
298
347
  for (const [, acc] of callsByIndex) {
299
348
  const name = sanitizeToolName(acc.name);
@@ -316,6 +365,17 @@ export async function callModel(opts) {
316
365
  ...(sampled.length > 0 ? { sampled } : {}),
317
366
  };
318
367
  }
368
+ // All four or none: a partial object is nothing a percent or an estimate can be built from.
369
+ function readPromptProgress(chunk) {
370
+ const p = chunk.prompt_progress;
371
+ if (typeof p?.total !== 'number' ||
372
+ typeof p.cache !== 'number' ||
373
+ typeof p.processed !== 'number' ||
374
+ typeof p.time_ms !== 'number') {
375
+ return undefined;
376
+ }
377
+ return { total: p.total, cached: p.cache, processed: p.processed, elapsedMs: p.time_ms };
378
+ }
319
379
  // Resolve the final (content, reasoning, toolCalls) from a streamed response. Pure and exported so
320
380
  // the recovery/stripping rules are unit-testable without mocking a stream. Two jobs:
321
381
  // 1. Recover an inline tool call when the model emitted one as text instead of via native
@@ -18,6 +18,8 @@ export function latchesFor(endpoint) {
18
18
  promptCacheKey: false,
19
19
  cacheControl: false,
20
20
  chatTemplateKwargs: false,
21
+ promptProgress: false,
22
+ timingsPerToken: false,
21
23
  assistantPrefill: false,
22
24
  noteOnToolResult: false,
23
25
  };
@@ -199,6 +199,11 @@ const SMALL_PAYLOAD_FLOOR_TOTAL_CHARS = 4096;
199
199
  // motivated this was 505 bytes), and a first result larger than this is a dump, not a definition,
200
200
  // which aging should stay free to collapse.
201
201
  export const TASK_SPEC_PIN_CHARS = 4096;
202
+ // A `gh issue|pr view` opening a turn is a task definition whatever its size, and comments are where
203
+ // an issue's decisions land, so it is pinned whole rather than by its head. 8192 clears 480 of 485
204
+ // saved fetches; 4096 cleared 355.
205
+ export const TASK_SPEC_FETCH_PIN_CHARS = 8192;
206
+ const TASK_SPEC_FETCH_SUMMARY = /^Ran: gh (?:issue|pr) view\b/;
202
207
  // Classify a transport error by the backend's own words; null for anything else — only a
203
208
  // rejection naming its cause may spend a retry. Matched against the whole error string
204
209
  // (`chat/completions failed: 400 … — {raw JSON body}`), whose quotes arrive JSON-escaped, so
@@ -545,8 +550,8 @@ export function findFreshToolBlockStart(history) {
545
550
  // opening call (`/issue`, `/review` both do) the payload holding the task definition is always the
546
551
  // FIRST one sacrificed, which inverts the priority (#227). `verbatim` only exempts a fresh payload
547
552
  // from the char cap and newest-read protection only covers a `read`, so neither reaches a `bash`
548
- // result holding the issue text. Scoped to the turn in progress and capped at TASK_SPEC_PIN_CHARS,
549
- // so the pin costs a bounded few KB and the next turn's own opening result moves it. Deliberately
553
+ // result holding the issue text. Scoped to the turn in progress and capped (TASK_SPEC_PIN_CHARS, or
554
+ // TASK_SPEC_FETCH_PIN_CHARS for a `gh` view), so the pin costs a bounded few KB and the next turn's own opening result moves it. Deliberately
550
555
  // not "the first SMALL payload": the opening call is the spec candidate, and a huge one means this
551
556
  // turn didn't open with a spec fetch at all. Pure + exported for tests and batch aging.
552
557
  // Index of the newest real user message, or -1. "Real" excludes `meta` — a slash-command echo is
@@ -562,16 +567,15 @@ export function lastUserMessageIndex(history) {
562
567
  }
563
568
  return -1;
564
569
  }
565
- export function taskSpecIndex(history) {
570
+ function openingPayloadIndex(history) {
566
571
  for (let u = history.length - 1; u >= 0; u--) {
567
572
  const m = history[u];
568
573
  if (m.role !== 'user' || m.meta || m.harness)
569
574
  continue;
570
575
  for (let i = u + 1; i < history.length; i++) {
571
576
  const t = history[i];
572
- if (t.role !== 'tool' || !t.payload)
573
- continue;
574
- return t.payload.length <= TASK_SPEC_PIN_CHARS ? i : -1;
577
+ if (t.role === 'tool' && t.payload)
578
+ return i;
575
579
  }
576
580
  // This turn has no tool result yet (round 0), so nothing has replaced the spec — keep the
577
581
  // previous turn's pin rather than releasing it the instant the user hits enter. Releasing at
@@ -581,6 +585,24 @@ export function taskSpecIndex(history) {
581
585
  }
582
586
  return -1;
583
587
  }
588
+ function fitsTaskSpecPin(m) {
589
+ if (m.role !== 'tool' || !m.payload)
590
+ return false;
591
+ const cap = TASK_SPEC_FETCH_SUMMARY.test(m.summary)
592
+ ? TASK_SPEC_FETCH_PIN_CHARS
593
+ : TASK_SPEC_PIN_CHARS;
594
+ return m.payload.length <= cap;
595
+ }
596
+ export function taskSpecIndex(history) {
597
+ const i = openingPayloadIndex(history);
598
+ return i >= 0 && fitsTaskSpecPin(history[i]) ? i : -1;
599
+ }
600
+ // The opening payload the pin refused for its size, or -1. Nothing in a payload says it is the
601
+ // task, so a spec fetched some other way cannot be detected; this makes the miss greppable instead.
602
+ export function oversizeOpeningPayloadIndex(history) {
603
+ const i = openingPayloadIndex(history);
604
+ return i >= 0 && !fitsTaskSpecPin(history[i]) ? i : -1;
605
+ }
584
606
  // Per-payload character budget for the fresh tool block, computed to *fit the window*:
585
607
  // take the prompt's char budget (window minus response headroom, converted from tokens
586
608
  // via the learned calibration), subtract everything else in the request, and split what
@@ -636,7 +658,7 @@ function freshPayloadCharCap(systemContent, history, freshFrom, keepReasoningFro
636
658
  // split; whether it goes verbatim or rejoins the split is decided after the budget is known.
637
659
  let protectedChars = 0;
638
660
  // Payload length of the pinned task spec (0 = none). Allocated verbatim ahead of everything
639
- // else — it is already bounded by TASK_SPEC_PIN_CHARS, and losing it is what #227 is about.
661
+ // else — it is already bounded by taskSpecIndex, and losing it is what #227 is about.
640
662
  let specChars = 0;
641
663
  for (let i = 0; i < history.length; i++) {
642
664
  const m = history[i];
@@ -14,12 +14,21 @@ const READY_POLL_MS = 200;
14
14
  // minutes keeps a burst of searches on one warm browser while not holding the memory all session.
15
15
  // The profile lives on disk, so cookies survive the kill and only the process cost is reclaimed.
16
16
  const IDLE_SHUTDOWN_MS = 10 * 60_000;
17
+ // Long enough for a tab another session just opened to leave `about:blank` (#920).
18
+ const BROWSER_CLOSE_SETTLE_MS = 1000;
17
19
  export class ChromeHost {
18
20
  port;
19
21
  binary;
20
22
  profileDir;
21
23
  idleTimer;
22
24
  launching;
25
+ // Armed only by launch: a browser reattached on the port may be one the user started (#920).
26
+ closeBrowserAfterExit = () => {
27
+ spawn(process.execPath, ['-e', buildBrowserCloseScript(this.port)], {
28
+ detached: true,
29
+ stdio: 'ignore',
30
+ }).unref();
31
+ };
23
32
  constructor(opts = {}) {
24
33
  this.port = opts.port ?? DEFAULT_PORT;
25
34
  this.binary = opts.binary;
@@ -163,6 +172,8 @@ export class ChromeHost {
163
172
  // check's tab. macOS only: elsewhere closing the last window quits Chrome.
164
173
  if (hidden)
165
174
  await this.closeStartupWindow();
175
+ process.off('exit', this.closeBrowserAfterExit);
176
+ process.once('exit', this.closeBrowserAfterExit);
166
177
  return;
167
178
  }
168
179
  await sleep(LAUNCH_POLL_MS);
@@ -250,6 +261,7 @@ export class ChromeHost {
250
261
  catch {
251
262
  /* already gone */
252
263
  }
264
+ process.off('exit', this.closeBrowserAfterExit);
253
265
  debugLog('[cdp] browser shut down after idle timeout');
254
266
  }
255
267
  // Every search closes its tab when it answers, and a bot check leaves its tab open on purpose, so
@@ -268,6 +280,32 @@ export class ChromeHost {
268
280
  }
269
281
  }
270
282
  }
283
+ // The idle timer dies with the process that armed it, and an exit hook cannot await the open-tab
284
+ // check, so a detached child does what shutdown() would (#920). It looks twice because another
285
+ // session's new tab is `about:blank` until it navigates, which reads the same as the launch tab.
286
+ // No imports: it runs from `node -e`.
287
+ export function buildBrowserCloseScript(port, settleMs = BROWSER_CLOSE_SETTLE_MS) {
288
+ return [
289
+ `const base = 'http://127.0.0.1:${port}';`,
290
+ 'const get = async path => (await fetch(base + path, { signal: AbortSignal.timeout(1500) })).json();',
291
+ 'const blankPageIds = async () => {',
292
+ " const pages = (await get('/json/list')).filter(t => t.type === 'page');",
293
+ " return pages.every(t => t.url === 'about:blank') ? pages.map(t => t.id).sort().join() : null;",
294
+ '};',
295
+ '(async () => {',
296
+ ' const first = await blankPageIds();',
297
+ ' if (first === null) return;',
298
+ ` await new Promise(resolve => setTimeout(resolve, ${settleMs}));`,
299
+ ' if ((await blankPageIds()) !== first) return;',
300
+ " const { webSocketDebuggerUrl } = await get('/json/version');",
301
+ ' if (!webSocketDebuggerUrl) return;',
302
+ ' const socket = new WebSocket(webSocketDebuggerUrl);',
303
+ " socket.onopen = () => socket.send(JSON.stringify({ id: 1, method: 'Browser.close' }));",
304
+ ' socket.onmessage = socket.onerror = socket.onclose = () => process.exit(0);',
305
+ ' setTimeout(() => process.exit(0), 3000);',
306
+ '})().catch(() => {});',
307
+ ].join('\n');
308
+ }
271
309
  // readyState alone is not enough: it reads `complete` for the document still on screen while the
272
310
  // navigation is in flight, so a fast poll extracts from the *previous* page — in practice the
273
311
  // about:blank a new tab starts on, which looks exactly like a search that found nothing. Probe the
@@ -538,8 +538,24 @@ export function isProvablyReadOnly(command) {
538
538
  // Also read by the sandbox (#163): a pipeline of `gh`/`git` plus these keeps its network allow, since
539
539
  // these are what a model pages remote output through (`gh pr diff | sed -n '1,300p'`).
540
540
  export const INSPECTION_COMMANDS = new Set([...READ_ONLY_COMMANDS, ...INSPECTION_ALSO]);
541
+ // Commands that read nothing. Refused during a withdrawal, a model's `echo hi` confirmed its reading
542
+ // that the shell had broken. Exempt only as the WHOLE command, never by leaving INSPECTION_COMMANDS:
543
+ // `echo ---; cat a.ts` is how a model separates reads, and the sandbox's network allow reads that set.
544
+ const INSPECTION_PROBES = new Set(['echo', 'pwd']);
545
+ // An unquoted glob makes `echo *` a directory listing.
546
+ const UNQUOTED_GLOB_RE = /[*?[]/;
547
+ function isBareProbe(command) {
548
+ const trimmed = command.trim();
549
+ const { raw, masked } = blankHarmlessRedirects(trimmed, maskQuoted(trimmed));
550
+ if (UNQUOTED_GLOB_RE.test(masked))
551
+ return false;
552
+ const segments = splitSegments(raw, masked)
553
+ .map(s => s.trim())
554
+ .filter(s => s && !/^cd\s/.test(s));
555
+ return segments.length > 0 && segments.every(s => INSPECTION_PROBES.has(words(s)[0]));
556
+ }
541
557
  // The LADDER's question: is this the model inspecting rather than working? A superset of the above —
542
558
  // same write/substitution/separator rules, wider set of command names.
543
559
  export function isInspectionEscape(command) {
544
- return classify(command, INSPECTION_COMMANDS);
560
+ return classify(command, INSPECTION_COMMANDS) && !isBareProbe(command);
545
561
  }