pi-chrome-search 0.1.0 → 2.0.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.
Files changed (62) hide show
  1. package/README.md +37 -76
  2. package/assets/anchor.html +2 -2
  3. package/package.json +4 -1
  4. package/src/cdp/bytes.ts +14 -14
  5. package/src/cdp/client.ts +687 -0
  6. package/src/cdp/page.ts +716 -0
  7. package/src/cdp/readiness.ts +119 -0
  8. package/src/cdp/shared.ts +70 -0
  9. package/src/cdp/types.ts +30 -1
  10. package/src/cli/doctor.ts +14 -17
  11. package/src/commands/focus.ts +2 -2
  12. package/src/config/defaults.ts +158 -0
  13. package/src/config/doc.ts +180 -0
  14. package/src/config/env.ts +58 -0
  15. package/src/config/index.ts +10 -0
  16. package/src/config/load.ts +40 -0
  17. package/src/config/schema.ts +264 -0
  18. package/src/engines/duckduckgo.ts +7 -10
  19. package/src/engines/google.ts +11 -21
  20. package/src/engines/images.ts +1 -1
  21. package/src/engines/index.ts +5 -13
  22. package/src/engines/types.ts +29 -6
  23. package/src/engines/yandex.ts +11 -18
  24. package/src/extract/claims.ts +1 -1
  25. package/src/extract/compact.ts +29 -3
  26. package/src/extract/goto.ts +124 -2
  27. package/src/extract/text.ts +43 -0
  28. package/src/index.ts +52 -80
  29. package/src/runtime/artifacts.ts +6 -11
  30. package/src/runtime/attention.ts +2 -2
  31. package/src/runtime/budget.ts +142 -0
  32. package/src/runtime/cache.ts +1 -3
  33. package/src/runtime/doctor.ts +17 -43
  34. package/src/runtime/error-codes.ts +19 -8
  35. package/src/runtime/errors-doc.ts +45 -0
  36. package/src/runtime/limiter.ts +33 -221
  37. package/src/runtime/log.ts +2 -2
  38. package/src/runtime/panel.ts +30 -4
  39. package/src/runtime/types.ts +2 -17
  40. package/src/{cdp/discovery.ts → session/discover.ts} +3 -3
  41. package/src/session/index.ts +34 -0
  42. package/src/session/lock.ts +346 -0
  43. package/src/{cdp → session}/page-lock.ts +12 -13
  44. package/src/session/session.ts +684 -0
  45. package/src/session/tabs.ts +277 -0
  46. package/src/tools/image_search.ts +21 -7
  47. package/src/tools/index.ts +18 -7
  48. package/src/tools/surface.ts +97 -0
  49. package/src/tools/types.ts +2 -5
  50. package/src/tools/web_doctor.ts +2 -2
  51. package/src/tools/web_read.ts +159 -114
  52. package/src/tools/web_research.ts +33 -207
  53. package/src/tools/web_search.ts +208 -419
  54. package/src/version.ts +12 -3
  55. package/src/cdp/browser.ts +0 -1286
  56. package/src/cdp/session.ts +0 -1446
  57. package/src/config.ts +0 -651
  58. package/src/reflex/classifier.ts +0 -1578
  59. package/src/reflex/index.ts +0 -172
  60. package/src/reflex/policy.ts +0 -792
  61. package/src/reflex/rules.ts +0 -557
  62. package/src/reflex/types.ts +0 -117
@@ -15,9 +15,9 @@
15
15
  * raise is reported and ignored.
16
16
  */
17
17
 
18
- import type { AwaitingAllowInfo } from "../cdp/browser.ts";
18
+ import type { AwaitingAllowInfo } from "../session/index.ts";
19
19
  import { raiseBrowserWindow, type RaiseOptions, type RaiseResult } from "../cdp/raise.ts";
20
- import type { Config } from "../config.ts";
20
+ import type { Config } from "../config/index.ts";
21
21
  import { notifyDesktop, type NotifyOptions, type NotifyResult } from "./notify.ts";
22
22
 
23
23
  export interface AttentionOutcome {
@@ -0,0 +1,142 @@
1
+ /**
2
+ * One deadline per tool call (SPEC S8.1).
3
+ *
4
+ * A call gets a single budget. Every stage derives its own deadline from what is
5
+ * left, so a slow navigation cannot buy extra time for the AI wait and a queued
6
+ * page lock cannot outlive the call. Exhaustion is `E_TIMEOUT` at stage
7
+ * `budget`: that is a different fact from a stage timing out on its own, and the
8
+ * error code says which one happened.
9
+ *
10
+ * The timer is a hard stop for anything that honours its signal (navigation,
11
+ * pacing, `/goto`, the AI wait). The `remainingMs()` check also uses the
12
+ * injected `Clock`, which is what makes the budget testable without real waits
13
+ * and what catches a clock jump that the timer would miss.
14
+ *
15
+ * This module owns no policy: the caller decides which stages to check and how
16
+ * to spend what is left.
17
+ */
18
+
19
+ import type { EngineId } from "../engines/types.ts";
20
+ import type { Stage } from "./error-codes.ts";
21
+ import { fail } from "./errors.ts";
22
+ import type { Clock } from "./types.ts";
23
+
24
+ export interface CallBudget {
25
+ /** Caller signal combined with the budget timer. Pass it to every stage. */
26
+ readonly signal: AbortSignal;
27
+ readonly budgetMs: number;
28
+ /** Clock time spent since the budget was created. */
29
+ elapsedMs(): number;
30
+ /** Clock time left, never negative. */
31
+ remainingMs(): number;
32
+ /** True once the timer fired or the clock says the budget is spent. */
33
+ expired(): boolean;
34
+ /**
35
+ * Throw `E_TIMEOUT` at stage `budget` when nothing is left. Call it before a
36
+ * stage starts, so a stage never begins with a deadline in the past.
37
+ */
38
+ check(stage: Stage, engine?: EngineId): void;
39
+ /** Free the timer. Always call it; a call may end long before the deadline. */
40
+ dispose(): void;
41
+ }
42
+
43
+ export interface CallBudgetOptions {
44
+ clock: Clock;
45
+ budgetMs: number;
46
+ /** The caller's own abort (Ctrl-C / pi cancellation); it wins over the timer. */
47
+ parent?: AbortSignal;
48
+ /** Prefix for the failure message, e.g. `web_search`. */
49
+ label?: string;
50
+ }
51
+
52
+ function budgetExhausted(budgetMs: number, label: string, engine?: EngineId): ReturnType<typeof fail> {
53
+ return fail("E_TIMEOUT", "budget", {
54
+ ...(engine === undefined ? {} : { engine }),
55
+ message: `${label} exhausted its ${budgetMs} ms budget`,
56
+ hint: "retry, or ask for less (a smaller `n`, fewer engines, or `summary:false`)",
57
+ });
58
+ }
59
+
60
+ export function createCallBudget(options: CallBudgetOptions): CallBudget {
61
+ const { clock } = options;
62
+ const budgetMs = options.budgetMs;
63
+ const label = options.label ?? "the call";
64
+ if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
65
+ throw fail("E_CONFIG", "config", {
66
+ message: `${label} budget must be a positive number of milliseconds, got ${String(budgetMs)}`,
67
+ hint: "set search.budgetMs to a positive number of milliseconds",
68
+ });
69
+ }
70
+
71
+ const startedAt = clock.now();
72
+ const controller = new AbortController();
73
+ let fired = false;
74
+
75
+ const fire = (): void => {
76
+ if (fired) return;
77
+ fired = true;
78
+ controller.abort(budgetExhausted(budgetMs, label));
79
+ };
80
+ // `unref` so a completed call never keeps the process alive for its whole
81
+ // budget; `dispose()` clears it in the normal path anyway.
82
+ const timer = setTimeout(fire, budgetMs);
83
+ timer.unref?.();
84
+
85
+ const signal =
86
+ options.parent === undefined ? controller.signal : AbortSignal.any([options.parent, controller.signal]);
87
+
88
+ const elapsedMs = (): number => Math.max(0, clock.now() - startedAt);
89
+ const remainingMs = (): number => Math.max(0, budgetMs - elapsedMs());
90
+ const expired = (): boolean => fired || remainingMs() <= 0;
91
+
92
+ return {
93
+ signal,
94
+ budgetMs,
95
+ elapsedMs,
96
+ remainingMs,
97
+ expired,
98
+ check(stage, engine) {
99
+ if (signal.aborted && options.parent?.aborted === true && !fired) {
100
+ // The caller cancelled; that is E_CANCELLED, not a budget verdict.
101
+ return;
102
+ }
103
+ if (fired || remainingMs() <= 0) {
104
+ // Throw instead of firing the controller here: aborting the signal
105
+ // would race the caller's own error path and lose the artifact the
106
+ // in-flight stage is about to attach.
107
+ throw budgetExhausted(budgetMs, `${label} (${stage})`, engine);
108
+ }
109
+ },
110
+ dispose() {
111
+ clearTimeout(timer);
112
+ },
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Resolve/reject like `promise`, but reject as soon as `signal` aborts.
118
+ *
119
+ * Used for a stage that cannot be cancelled itself (a queued page lock). The
120
+ * losing promise is left to finish; its rejection is swallowed so a late
121
+ * `E_TIMEOUT` cannot surface as an unhandled rejection, and the stage it guards
122
+ * checks the budget again before doing any work.
123
+ */
124
+ export function raceSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
125
+ if (signal === undefined) return promise;
126
+ void promise.catch(() => {});
127
+ if (signal.aborted) return Promise.reject(signal.reason);
128
+ return new Promise<T>((resolve, reject) => {
129
+ const onAbort = (): void => reject(signal.reason);
130
+ signal.addEventListener("abort", onAbort, { once: true });
131
+ promise.then(
132
+ (value) => {
133
+ signal.removeEventListener("abort", onAbort);
134
+ resolve(value);
135
+ },
136
+ (error: unknown) => {
137
+ signal.removeEventListener("abort", onAbort);
138
+ reject(error);
139
+ },
140
+ );
141
+ });
142
+ }
@@ -12,7 +12,7 @@
12
12
  * a 24 h `/goto` resolution is gone at 24 h, not after.
13
13
  */
14
14
 
15
- import type { EngineId, Freshness } from "../engines/types.ts";
15
+ import type { EngineId } from "../engines/types.ts";
16
16
  import { WebSearchError } from "./error-codes.ts";
17
17
  import type { Cache, Clock } from "./types.ts";
18
18
 
@@ -120,7 +120,6 @@ export interface SerpKeyInput {
120
120
  text: string;
121
121
  n: number;
122
122
  page?: number;
123
- freshness?: Freshness;
124
123
  /** Engine UI language (`query.lang`). Part of the key: a lang change changes the SERP. */
125
124
  lang?: string;
126
125
  /** Engine region/country (`query.region`). Same reasoning as `lang`. */
@@ -234,7 +233,6 @@ export function serpKey(q: SerpKeyInput): string {
234
233
  text,
235
234
  q.n,
236
235
  q.page ?? 1,
237
- q.freshness ?? "",
238
236
  q.lang ?? "",
239
237
  q.region ?? "",
240
238
  q.summary,
@@ -21,7 +21,7 @@
21
21
  * never `ok`: the report must not claim an engine works when nothing was
22
22
  * exercised. The extension, the CLI and `/web-doctor` wire
23
23
  * `createEngineProbe`; a caller that does not is told "no probe configured",
24
- * not that the engine is fine. P5 extends `reflex` the same way.
24
+ * not that the engine is fine.
25
25
  *
26
26
  * The report is plain JSON with a fixed key order (no Maps, no class instances)
27
27
  * so `--json` output is diffable and the schema test can validate it. It never
@@ -31,11 +31,10 @@
31
31
 
32
32
  import { readFile, unlink } from "node:fs/promises";
33
33
 
34
- import type { Connector, ConnectorInfo } from "../cdp/browser.ts";
35
- import { defaultLockPath, parseLockRecord, pidAlive } from "../cdp/browser.ts";
36
- import { pageLockFor } from "../cdp/page-lock.ts";
34
+ import { defaultLockPath, pageLockFor, parseLockRecord, pidAlive } from "../session/index.ts";
35
+ import type { Session, SessionInfo } from "../session/index.ts";
37
36
  import type { CdpSource } from "../cdp/types.ts";
38
- import type { Config, FocusPolicy, FollowPolicy, HumanizeMode, Mode, ReflexBackend } from "../config.ts";
37
+ import type { Config, FocusPolicy, FollowPolicy, HumanizeMode } from "../config/index.ts";
39
38
  import type { Engine, EngineId, EngineRegistry, Query, WallKind } from "../engines/types.ts";
40
39
  import { ENGINE_IDS } from "../engines/types.ts";
41
40
  import { ERROR_HINTS, type FailureDetails } from "./error-codes.ts";
@@ -100,7 +99,7 @@ export const DOCTOR_PROBE_QUERY = "pi-chrome-search doctor probe";
100
99
 
101
100
  export interface EngineProbeOptions {
102
101
  config: Config;
103
- connector: Connector;
102
+ connector: Session;
104
103
  registry: EngineRegistry;
105
104
  clock: Clock;
106
105
  /**
@@ -150,9 +149,9 @@ function probeLocale(engine: EngineId, config: Config): Pick<Query, "lang" | "re
150
149
  * `error: { code, stage, hint }` so the report keeps the latency and the verdict
151
150
  * mapper owns the interpretation. A wall detected after a settle timeout is
152
151
  * promoted to `wall` — a captcha page usually fails the adapter's readiness
153
- * marker before `detectWall()` is ever reached. A limiter rejection (daily cap,
154
- * abort) is reported the same way and never navigates: a paced-out probe must
155
- * not burn an unthrottled search on the user's profile.
152
+ * marker before `detectWall()` is ever reached. A limiter rejection (an abort or
153
+ * a pacing deadline) is reported the same way and never navigates: a paced-out
154
+ * probe must not burn an unthrottled search on the user's profile.
156
155
  *
157
156
  * One writer per engine tab: the probe navigates the same tab `web_search`
158
157
  * extracts from, so it takes the tools' FIFO page lock for that engine. A
@@ -169,7 +168,7 @@ export function createEngineProbe(options: EngineProbeOptions): EngineProbe {
169
168
  try {
170
169
  await options.limiter.acquire(id);
171
170
  } catch (error) {
172
- const details = toFailure(error, { code: "E_RATE_LIMITED", stage: "navigate" });
171
+ const details = toFailure(error, { code: "E_TIMEOUT", stage: "navigate" });
173
172
  return {
174
173
  ms: elapsed(),
175
174
  results: 0,
@@ -229,7 +228,7 @@ export function createEngineProbe(options: EngineProbeOptions): EngineProbe {
229
228
  export interface DoctorDeps {
230
229
  config: Config;
231
230
  configPath: string;
232
- connector?: Connector;
231
+ connector?: Session;
233
232
  /**
234
233
  * P11: the CLI's Allow-attention coordinator. Its outcome (wait duration,
235
234
  * notification adapter, raise adapter) is rendered next to the verdict; the
@@ -265,7 +264,6 @@ export interface DoctorExtensionInfo {
265
264
 
266
265
  export interface DoctorConfigInfo {
267
266
  path: string;
268
- mode: Mode;
269
267
  focus: FocusPolicy;
270
268
  humanize: HumanizeMode;
271
269
  /** P10: the anchor panel and the follow-focus policy, so a report explains the window. */
@@ -331,16 +329,6 @@ export interface DoctorEngine {
331
329
  probe?: EngineProbeResult;
332
330
  }
333
331
 
334
- export interface DoctorReflexInfo {
335
- enabled: boolean;
336
- /** P14: the offline page gate can be on while the rest of the reflex is off. */
337
- pageGate: boolean;
338
- backend: ReflexBackend;
339
- localOnly: boolean;
340
- /** `disabled` when reflex is off; `unavailable` until P5 injects a classifier probe. */
341
- classifier: "disabled" | "unavailable";
342
- }
343
-
344
332
  export interface DoctorReport {
345
333
  schemaVersion: 1;
346
334
  generatedAt: string;
@@ -350,7 +338,6 @@ export interface DoctorReport {
350
338
  cache: DoctorCacheInfo | null;
351
339
  artifacts: DoctorArtifactsInfo | null;
352
340
  engines: DoctorEngine[];
353
- reflex: DoctorReflexInfo;
354
341
  verdict: DoctorVerdict;
355
342
  }
356
343
 
@@ -387,7 +374,7 @@ async function readLockRecord(path: string): Promise<ParsedLock | null> {
387
374
  }
388
375
  }
389
376
 
390
- function lockPathOf(connector: Connector | undefined, env: NodeJS.ProcessEnv): string {
377
+ function lockPathOf(connector: Session | undefined, env: NodeJS.ProcessEnv): string {
391
378
  if (connector !== undefined) {
392
379
  try {
393
380
  return connector.lockPath();
@@ -398,7 +385,7 @@ function lockPathOf(connector: Connector | undefined, env: NodeJS.ProcessEnv): s
398
385
  return defaultLockPath(env);
399
386
  }
400
387
 
401
- async function collectLock(connector: Connector | undefined, env: NodeJS.ProcessEnv): Promise<DoctorLock> {
388
+ async function collectLock(connector: Session | undefined, env: NodeJS.ProcessEnv): Promise<DoctorLock> {
402
389
  const path = lockPathOf(connector, env);
403
390
  const record = await readLockRecord(path);
404
391
  if (record === null) return { locked: false, path, owner: "none" };
@@ -447,7 +434,7 @@ export interface DoctorFixOptions {
447
434
  connectGraceMs?: number;
448
435
  }
449
436
 
450
- function isConnected(connector: Connector | undefined): boolean {
437
+ function isConnected(connector: Session | undefined): boolean {
451
438
  if (connector === undefined) return false;
452
439
  try {
453
440
  return connector.isConnected();
@@ -465,7 +452,7 @@ type ConnectOutcome = { ok: true; late: boolean } | { ok: false; code: string };
465
452
  * the original code.
466
453
  */
467
454
  async function boundedConnect(
468
- connector: Connector,
455
+ connector: Session,
469
456
  config: Config,
470
457
  options: DoctorFixOptions = {},
471
458
  ): Promise<ConnectOutcome> {
@@ -643,7 +630,7 @@ function failedCdp(status: CdpStatus, details: FailureDetails, lock: DoctorLock)
643
630
  };
644
631
  }
645
632
 
646
- function endpointOf(info: ConnectorInfo): DoctorEndpoint {
633
+ function endpointOf(info: SessionInfo): DoctorEndpoint {
647
634
  return {
648
635
  port: nonNegativeInt(info.endpoint.port),
649
636
  wsUrl: safeText(info.endpoint.wsUrl, "ws://127.0.0.1"),
@@ -683,7 +670,7 @@ async function collectCdp(deps: DoctorDeps): Promise<DoctorCdp> {
683
670
  }
684
671
  }
685
672
 
686
- let info: ConnectorInfo | null;
673
+ let info: SessionInfo | null;
687
674
  try {
688
675
  info = connector.info();
689
676
  } catch (error) {
@@ -1020,7 +1007,6 @@ export async function buildDoctorReport(
1020
1007
  },
1021
1008
  config: {
1022
1009
  path: deps.configPath,
1023
- mode: deps.config.mode,
1024
1010
  focus: deps.config.window.focus,
1025
1011
  humanize: deps.config.humanize,
1026
1012
  panel: deps.config.window.panel,
@@ -1032,13 +1018,6 @@ export async function buildDoctorReport(
1032
1018
  cache,
1033
1019
  artifacts,
1034
1020
  engines,
1035
- reflex: {
1036
- enabled: deps.config.reflex.enabled,
1037
- pageGate: deps.config.reflex.pageGate,
1038
- backend: deps.config.reflex.backend,
1039
- localOnly: deps.config.reflex.localOnly,
1040
- classifier: deps.config.reflex.enabled ? "unavailable" : "disabled",
1041
- },
1042
1021
  verdict,
1043
1022
  };
1044
1023
  }
@@ -1064,7 +1043,7 @@ export function renderDoctorText(
1064
1043
  lines.push(`${report.extension.name} ${report.extension.version} — doctor (node ${report.extension.node})`);
1065
1044
  lines.push(`generated ${report.generatedAt}`);
1066
1045
  lines.push(
1067
- `config: ${tildify(report.config.path)} (${report.config.mode}, focus=${report.config.focus}, ` +
1046
+ `config: ${tildify(report.config.path)} (focus=${report.config.focus}, ` +
1068
1047
  `humanize=${report.config.humanize}, panel=${report.config.panel ? "on" : "off"}, ` +
1069
1048
  `follow=${report.config.follow}, debug=${report.config.debug ? "on" : "off"})`,
1070
1049
  );
@@ -1119,11 +1098,6 @@ export function renderDoctorText(
1119
1098
  lines.push(` ${engine.id.padEnd(11)} ${engine.verdict}${probe}${note}`);
1120
1099
  }
1121
1100
 
1122
- lines.push(
1123
- `reflex: ${report.reflex.enabled ? "enabled" : "disabled"} (backend=${report.reflex.backend}, ` +
1124
- `localOnly=${report.reflex.localOnly ? "on" : "off"}, pageGate=${report.reflex.pageGate ? "on" : "off"}, ` +
1125
- `classifier=${report.reflex.classifier})`,
1126
- );
1127
1101
  if (attention !== undefined) {
1128
1102
  lines.push(
1129
1103
  `attention: waited ${Math.max(0, Math.round(attention.waitedMs / 1000))}s · ` +
@@ -16,9 +16,9 @@ export type ErrorCode =
16
16
  | "E_TARGET_LOST"
17
17
  | "E_WALL"
18
18
  | "E_EMPTY"
19
+ | "E_EMPTY_PAGE"
19
20
  | "E_PARSE"
20
21
  | "E_TIMEOUT"
21
- | "E_RATE_LIMITED"
22
22
  | "E_BUSY"
23
23
  | "E_BLOCKED_URL"
24
24
  | "E_UNSUPPORTED"
@@ -36,9 +36,9 @@ export const ERROR_CODES = [
36
36
  "E_TARGET_LOST",
37
37
  "E_WALL",
38
38
  "E_EMPTY",
39
+ "E_EMPTY_PAGE",
39
40
  "E_PARSE",
40
41
  "E_TIMEOUT",
41
- "E_RATE_LIMITED",
42
42
  "E_BUSY",
43
43
  "E_BLOCKED_URL",
44
44
  "E_UNSUPPORTED",
@@ -60,7 +60,7 @@ export type Stage =
60
60
  | "resolve"
61
61
  | "render"
62
62
  | "read"
63
- | "reflex";
63
+ | "budget";
64
64
 
65
65
  export const STAGES = [
66
66
  "config",
@@ -72,7 +72,7 @@ export const STAGES = [
72
72
  "resolve",
73
73
  "render",
74
74
  "read",
75
- "reflex",
75
+ "budget",
76
76
  ] as const satisfies readonly Stage[];
77
77
 
78
78
  export interface FailureDetails {
@@ -102,10 +102,12 @@ export const ERROR_HINTS: Record<ErrorCode, string> = {
102
102
  E_CDP_DISCONNECTED: "the CDP socket dropped; retry once — if it repeats, run /web-doctor and check the lock file",
103
103
  E_TARGET_LOST: "the owned tab was closed or navigated away; retry to reopen it",
104
104
  E_WALL: "solve the captcha/consent in the visible browser window, then retry — never automate it",
105
- E_EMPTY: "the engine returned no organic results; rephrase, try another engine, or drop freshness filters",
105
+ E_EMPTY: "the engine returned no organic results; rephrase the query or try another engine",
106
106
  E_PARSE: "a selector canary failed; inspect the artifact directory, run /web-doctor, then patch the adapter",
107
- E_TIMEOUT: "the deadline was exceeded; retry or raise the timeout in config",
108
- E_RATE_LIMITED: "the per-engine gap or daily soft cap is active; wait or use another engine",
107
+ E_EMPTY_PAGE:
108
+ "the document rendered no readable text; the page may be client-side, so open the artifact " +
109
+ "and try another URL (or retry once if the page loads late)",
110
+ E_TIMEOUT: "the deadline was exceeded; retry, or ask for less (a smaller `n` or `maxChars`)",
109
111
  E_BUSY: "another pi session holds ~/.pi/agent/web-search.lock; close it or wait for its heartbeat to expire",
110
112
  E_BLOCKED_URL: "use a public http(s) URL; localhost, private ranges, file: and data: are blocked",
111
113
  E_UNSUPPORTED: "this engine or vertical is not implemented yet; check /web-doctor for per-engine status",
@@ -135,9 +137,9 @@ export const RETRYABLE: Record<ErrorCode, boolean> = {
135
137
  E_TARGET_LOST: true,
136
138
  E_WALL: true,
137
139
  E_EMPTY: true,
140
+ E_EMPTY_PAGE: false,
138
141
  E_PARSE: false,
139
142
  E_TIMEOUT: true,
140
- E_RATE_LIMITED: true,
141
143
  E_BUSY: true,
142
144
  E_BLOCKED_URL: false,
143
145
  E_UNSUPPORTED: false,
@@ -149,6 +151,15 @@ export const RETRYABLE: Record<ErrorCode, boolean> = {
149
151
  E_PDF_UNSUPPORTED: false,
150
152
  };
151
153
 
154
+ /**
155
+ * Codes whose owning phase has not added a dedicated offline test yet (S9.5).
156
+ * Production paths may throw them, but the contract is not proven until the
157
+ * named phase lands its test, so a reservation cannot become a permanent pass.
158
+ * P5 proved `E_EMPTY_PAGE`, `E_NAVIGATION_MISMATCH` and `E_OFFSET_RANGE`; the
159
+ * table stays so a future code can be reserved deliberately, not by omission.
160
+ */
161
+ export const RESERVED_CODES: Partial<Record<ErrorCode, string>> = {};
162
+
152
163
  export class WebSearchError extends Error {
153
164
  readonly details: FailureDetails;
154
165
 
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Documentation data for `docs/errors.md` (S9.5, S13.3 pattern).
3
+ *
4
+ * The page is rendered from the closed taxonomy and the one hint per code, so a
5
+ * new code without a hint, a changed retry flag or a stale action cannot survive
6
+ * `npm run lint`. The README deliberately keeps no copy of this table: it links
7
+ * here instead, and the link is checked by the audit.
8
+ */
9
+
10
+ import { ERROR_CODES, ERROR_HINTS, RETRYABLE } from "./error-codes.ts";
11
+
12
+ function cell(text: string): string {
13
+ return text.replace(/\|/g, "\\|").replace(/\n/g, " ");
14
+ }
15
+
16
+ export function errorDocRows(): string[] {
17
+ return ERROR_CODES.map(
18
+ (code) => `| \`${code}\` | ${RETRYABLE[code] ? "yes" : "no"} | ${cell(ERROR_HINTS[code])} |`,
19
+ );
20
+ }
21
+
22
+ export function renderErrorsDoc(): string {
23
+ return [
24
+ "# Errors",
25
+ "",
26
+ "Generated from `src/runtime/error-codes.ts`; do not hand-edit. `node scripts/gen-errors-doc.mjs",
27
+ "--check` fails when this page drifts from the taxonomy.",
28
+ "",
29
+ "Every failure is a `WebSearchError`: `code`, `stage`, `retryable`, `hint`, and, for page states, an",
30
+ "artifact directory. The hint is the action, shown to the agent and the user verbatim.",
31
+ "",
32
+ "| Code | Retry | Action |",
33
+ "|---|---|---|",
34
+ ...errorDocRows(),
35
+ "",
36
+ "`web_doctor` (or `/web-doctor`) is the first stop for CDP, lock, window and per-engine verdicts:",
37
+ "`node src/cli/doctor.ts --json` prints the same report headlessly. Artifacts:",
38
+ "`~/.pi/agent/web-search/artifacts/<ts>-<engine>-<hash>/` (`page.html`, `page.txt`, `screenshot.jpg`,",
39
+ "`meta.json`). Decisions: `~/.pi/agent/web-search/decisions.jsonl`.",
40
+ "",
41
+ "Every code here has an offline test; `RESERVED_CODES` is empty and stays that way unless a future code",
42
+ "is deliberately reserved with a phase and a reason.",
43
+ "",
44
+ ].join("\n");
45
+ }