@alexwkleung/reika 0.5.0 → 0.7.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.
@@ -1,4 +1,4 @@
1
- import { spawn } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
2
  import { accessSync, constants, mkdirSync } from 'node:fs';
3
3
  import { homedir, platform } from 'node:os';
4
4
  import { join } from 'node:path';
@@ -28,19 +28,38 @@ export class ChromeHost {
28
28
  async newTab() {
29
29
  await this.ensure();
30
30
  this.touch();
31
- const res = await fetch(`http://127.0.0.1:${this.port}/json/new`, { method: 'PUT' });
32
- if (!res.ok)
33
- throw new Error(`could not open a tab (CDP ${res.status})`);
34
- const tab = (await res.json());
35
- if (!tab.webSocketDebuggerUrl || !tab.id)
31
+ // Not `PUT /json/new`: that opens a foreground tab, which activates Chrome and takes focus on
32
+ // every search. A background target in a minimized window of its own never shows, and
33
+ // minimizing or showing one tab's window never moves another search's tab.
34
+ const browser = await openSession(await this.browserWsUrl());
35
+ let targetId;
36
+ try {
37
+ const res = (await browser.call('Target.createTarget', {
38
+ url: 'about:blank',
39
+ newWindow: true,
40
+ background: true,
41
+ windowState: 'minimized',
42
+ }));
43
+ if (res.error)
44
+ throw new Error(`could not open a tab (CDP ${res.error.message ?? 'error'})`);
45
+ targetId = res.result?.targetId;
46
+ }
47
+ finally {
48
+ browser.close();
49
+ }
50
+ if (!targetId)
51
+ throw new Error('CDP returned a tab with no target id');
52
+ const list = (await (await fetch(`http://127.0.0.1:${this.port}/json/list`)).json());
53
+ const tab = list.find(t => t.id === targetId);
54
+ if (!tab?.webSocketDebuggerUrl || !tab.id)
36
55
  throw new Error('CDP returned a tab with no debugger URL');
37
56
  const session = await openSession(tab.webSocketDebuggerUrl);
38
57
  const port = this.port;
39
58
  const touch = () => this.touch();
40
- // The browser works minimized. `open -g` keeps launch from taking focus, but the window it
41
- // makes still sits on the desktop, and one reattached from an earlier session is in whatever
42
- // state it was left — so the state is enforced per tab, not per launch. Only a bot check
43
- // (`show`) is allowed to surface it; see CdpSearchProvider.
59
+ const activate = () => this.activate();
60
+ // The window should already be minimized from creation; this covers a Chrome that predates
61
+ // `windowState` on `Target.createTarget`. Only a bot check (`show`) is allowed to surface it;
62
+ // see CdpSearchProvider.
44
63
  await setWindowState(session, 'minimized');
45
64
  return {
46
65
  async navigate(url) {
@@ -61,9 +80,11 @@ export class ChromeHost {
61
80
  async show() {
62
81
  touch();
63
82
  await setWindowState(session, 'normal');
64
- // Page.bringToFront is the reliable path: the browser is a separate instance on its own
65
- // profile, so macOS app-level activation would raise the user's Chrome instead (#238).
83
+ // Page.bringToFront raises the tab within its own browser, but a browser that never took
84
+ // focus stays behind the active app, so the instance is activated too — by pid, since
85
+ // activating by name would raise the user's own Chrome instead (#238).
66
86
  await session.call('Page.bringToFront').catch(() => undefined);
87
+ await activate();
67
88
  },
68
89
  async hide() {
69
90
  await setWindowState(session, 'minimized');
@@ -119,17 +140,17 @@ export class ChromeHost {
119
140
  '--disable-sync',
120
141
  '--password-store=basic',
121
142
  '--mute-audio',
143
+ // Not `--no-startup-window`: Chrome then ignores Quit from the Dock, and it kept focus no
144
+ // better than a hidden launch does (measured on macOS 26, Chrome 155).
122
145
  'about:blank',
123
146
  ];
124
147
  debugLog(`[cdp] launching ${exe} on port ${this.port}`);
125
148
  // Not headless, deliberately: a fresh headless profile is the shape search engines CAPTCHA.
126
- // macOS `open -g -na` starts a real browser that never takes focus or shows a window, which is
127
- // the same end the headless flag was wanted for without raising the detection surface.
128
- if (platform() === 'darwin' && !this.binary) {
129
- spawn('/usr/bin/open', ['-g', '-na', macAppName() ?? 'Google Chrome', '--args', ...flags], {
130
- detached: true,
131
- stdio: 'ignore',
132
- }).unref();
149
+ // `open -g` alone still let Chrome activate itself when its first window opened, so macOS
150
+ // also launches it hidden (`-j`): a real browser that never takes focus.
151
+ const hidden = platform() === 'darwin' && !this.binary;
152
+ if (hidden) {
153
+ spawn('/usr/bin/open', ['-g', '-j', '-na', macAppName() ?? 'Google Chrome', '--args', ...flags], { detached: true, stdio: 'ignore' }).unref();
133
154
  }
134
155
  else {
135
156
  spawn(exe, flags, { detached: true, stdio: 'ignore' }).unref();
@@ -138,6 +159,10 @@ export class ChromeHost {
138
159
  while (Date.now() < deadline) {
139
160
  if (await this.alive()) {
140
161
  debugLog(`[cdp] browser ready on port ${this.port}`);
162
+ // Searches open their own windows, and the startup one would surface beside the first bot
163
+ // check's tab. macOS only: elsewhere closing the last window quits Chrome.
164
+ if (hidden)
165
+ await this.closeStartupWindow();
141
166
  return;
142
167
  }
143
168
  await sleep(LAUNCH_POLL_MS);
@@ -153,6 +178,54 @@ export class ChromeHost {
153
178
  this.idleTimer = setTimeout(() => void this.shutdown(), IDLE_SHUTDOWN_MS);
154
179
  this.idleTimer.unref?.();
155
180
  }
181
+ async closeStartupWindow() {
182
+ try {
183
+ const res = await fetch(`http://127.0.0.1:${this.port}/json/list`);
184
+ const targets = (await res.json());
185
+ for (const t of targets) {
186
+ if (t.type === 'page' && t.url === 'about:blank' && t.id)
187
+ await fetch(`http://127.0.0.1:${this.port}/json/close/${t.id}`);
188
+ }
189
+ }
190
+ catch {
191
+ /* cosmetic: a leftover blank window never fails a search */
192
+ }
193
+ }
194
+ async browserWsUrl() {
195
+ const res = await fetch(`http://127.0.0.1:${this.port}/json/version`, {
196
+ signal: AbortSignal.timeout(1500),
197
+ });
198
+ const { webSocketDebuggerUrl } = (await res.json());
199
+ if (!webSocketDebuggerUrl)
200
+ throw new Error('CDP reported no browser debugger URL');
201
+ return webSocketDebuggerUrl;
202
+ }
203
+ // The pid comes from CDP because `open` doesn't report the one it launched. Best-effort, and a
204
+ // no-op off macOS: the window is restored either way, activation only saves the user a click.
205
+ async activate() {
206
+ if (platform() !== 'darwin')
207
+ return;
208
+ try {
209
+ const browser = await openSession(await this.browserWsUrl());
210
+ let pid;
211
+ try {
212
+ const res = (await browser.call('SystemInfo.getProcessInfo'));
213
+ pid = res.result?.processInfo?.find(p => p.type === 'browser')?.id;
214
+ }
215
+ finally {
216
+ browser.close();
217
+ }
218
+ if (!Number.isInteger(pid))
219
+ return;
220
+ const script = `ObjC.import('AppKit'); $.NSRunningApplication.runningApplicationWithProcessIdentifier(${pid}).activateWithOptions($.NSApplicationActivateAllWindows)`;
221
+ await new Promise(resolve => {
222
+ execFile('/usr/bin/osascript', ['-l', 'JavaScript', '-e', script], () => resolve());
223
+ });
224
+ }
225
+ catch {
226
+ /* best-effort */
227
+ }
228
+ }
156
229
  async shutdown() {
157
230
  if (this.idleTimer)
158
231
  clearTimeout(this.idleTimer);
@@ -8,6 +8,9 @@ import { SearchUnavailableError } from './types.js';
8
8
  // Bing, so it isn't correlated with the engine most likely to block us next. See #235.
9
9
  const SEARCH_URL = 'https://search.brave.com/search?q=';
10
10
  const OWN_HOSTS = /(^|\.)(brave\.com|search\.brave\.com)$/;
11
+ // Brave ends some result anchors with a date line ("May 8, 2026", "3 days ago"), which the
12
+ // last-line rule below then reported as the result's title.
13
+ export const DATE_LINE = /^(?:(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.? \d{1,2},? \d{4}|\d+ (?:second|minute|hour|day|week|month|year)s? ago)$/i;
11
14
  // Deliberately structure-agnostic: every visible link, filtered and deduped. No result-card
12
15
  // selectors, so a SERP redesign can't silently empty the results the way class-name scraping does.
13
16
  // The snippet walks up from the anchor until a container holds meaningfully more text than the
@@ -24,9 +27,11 @@ function extractionScript(maxResults) {
24
27
  // A result anchor's innerText is "SiteName / breadcrumb › path / actual title" on separate lines.
25
28
  // The last line is the title; the earlier ones are chrome that would otherwise be fed to the model
26
29
  // as part of it. No class names involved, so a redesign degrades this to "whole text", not to junk.
30
+ const dateLine = ${DATE_LINE.toString()};
27
31
  const titleOf = a => {
28
32
  const lines = (a.innerText || '').split('\\n').map(clean).filter(Boolean);
29
- return lines.length ? lines[lines.length - 1] : '';
33
+ const named = lines.filter(l => !dateLine.test(l));
34
+ return named.length ? named[named.length - 1] : '';
30
35
  };
31
36
  // The container repeats the anchor's own text before the description; removing it stops every
32
37
  // snippet from opening with a copy of the title it sits under.
package/dist/session.js CHANGED
@@ -1,4 +1,5 @@
1
- import { loadConfig, resolveProfile, withProbedLimits } from './config.js';
1
+ import { assertRawConfig, loadConfig, resolveProfile, withProbedLimits } from './config.js';
2
+ import { ensureNoteSlot } from './provider/noteslot.js';
2
3
  import { repoMapBudgetFor } from './context/repomap.js';
3
4
  import { needsLimitsProbe, probeModelLimits, } from './provider/modellimits.js';
4
5
  import { bootstrap, refitRepoMap } from './context/bootstrap.js';
@@ -13,6 +14,8 @@ import { detectIdentity, setIdentity } from './ui/identity.js';
13
14
  import { kFormat } from './ui/format.js';
14
15
  import { buildImplementPrompt, isMinimalPrompt, isGrindPrompt, planWritten, turnPromptMode, turnRefines, turnTools, } from './ui/commands.js';
15
16
  export async function createSession(opts) {
17
+ if (opts.config)
18
+ assertRawConfig(opts.config, 'createSession');
16
19
  let cfg = opts.config ?? loadConfig();
17
20
  let profile = opts.profile ?? 'default';
18
21
  // Identity detection runs CONCURRENTLY with bootstrap, not before it. Four git subprocesses cost
@@ -49,6 +52,11 @@ export async function createSession(opts) {
49
52
  const retryWindow = new Set();
50
53
  if (probed && !probed.reached)
51
54
  retryWindow.add(profile);
55
+ // #827: which slot the per-round note takes on this endpoint. Fired here so it overlaps startup,
56
+ // awaited at each submit once the user's message is on screen and before the turn's first request,
57
+ // so it never runs between rounds (a probe there would evict a single-slot server's cache), and
58
+ // asked again at a submit if the server was not up.
59
+ void ensureNoteSlot(resolveProfile(cfg, profile));
52
60
  // No route out → no web tools this session (#392). Checked once, here, because the tool list is
53
61
  // part of the cached prefix; the per-turn latch in the tools covers a drop later.
54
62
  const offline = isOffline();
@@ -146,6 +154,9 @@ export async function createSession(opts) {
146
154
  // vibe) never refines, since its plan phase is a new task even when a plan sits right above.
147
155
  allowRefine: turnRefines(recorded),
148
156
  manualCompact: submit.manualCompact,
157
+ // After the user echo, so the prompt is on screen while a probe runs; still before the
158
+ // turn's first request, never between rounds.
159
+ beforeFirstRequest: () => ensureNoteSlot(resolveProfile(cfg, profile), undefined, signal ?? undefined),
149
160
  // The prompt carries the turn's mode from here on (the loop has no notion of one), so a
150
161
  // saved transcript can say what each turn was.
151
162
  onMessage: raw => {
@@ -239,6 +250,7 @@ export async function createSession(opts) {
239
250
  decodeRate = undefined;
240
251
  genReserve = new GenReserve();
241
252
  changed();
253
+ void ensureNoteSlot(resolveProfile(cfg, name));
242
254
  if (!needsLimitsProbe(next))
243
255
  return Promise.resolve([]);
244
256
  return probeModelLimits(next).then(probe => {