@abhishek944/pi-web-access 0.0.0-stage → 0.1.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 (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
@@ -0,0 +1,29 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { getWebSearchConfigPath } from "./utils.ts";
3
+
4
+ const CONFIG_PATH = getWebSearchConfigPath();
5
+
6
+ type FeatureConfig = { image?: { enabled?: unknown } };
7
+
8
+ function loadFeatureConfig(): FeatureConfig {
9
+ if (!existsSync(CONFIG_PATH)) return {};
10
+ try {
11
+ const raw: unknown = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
12
+ return raw && typeof raw === "object" ? raw as FeatureConfig : {};
13
+ } catch (err) {
14
+ const message = err instanceof Error ? err.message : String(err);
15
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
16
+ }
17
+ }
18
+
19
+ export function isImageEnabled(): boolean {
20
+ return loadFeatureConfig().image?.enabled !== false;
21
+ }
22
+
23
+ export function canAttachImages(): boolean {
24
+ try {
25
+ return isImageEnabled();
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
@@ -0,0 +1,147 @@
1
+ import { normalizeProxyUrl } from "./utils.ts";
2
+
3
+ export interface FetchContentParams {
4
+ url?: unknown;
5
+ urls?: unknown;
6
+ forceClone?: unknown;
7
+ prompt?: unknown;
8
+ timestamp?: unknown;
9
+ frames?: unknown;
10
+ model?: unknown;
11
+ mode?: unknown;
12
+ answerModel?: unknown;
13
+ fields?: unknown;
14
+ auth?: unknown;
15
+ proxy?: unknown;
16
+ redirects?: unknown;
17
+ }
18
+
19
+ export interface NormalizedFetchContentParams {
20
+ urlList: string[];
21
+ /** Parameter-level validation problems collected during normalization
22
+ * instead of throwing, so callers can report them together with their own
23
+ * checks in a single round-trip. */
24
+ problems: string[];
25
+ options: {
26
+ forceClone?: boolean;
27
+ prompt?: string;
28
+ timestamp?: string;
29
+ frames?: number;
30
+ model?: string;
31
+ mode?: "readable" | "raw" | "answer" | "extract";
32
+ answerModel?: string;
33
+ auth?: true | string;
34
+ proxy?: string;
35
+ redirects?: "same-origin";
36
+ };
37
+ }
38
+
39
+ /** Lists the parameter names that actually arrived, for error diagnostics:
40
+ * dropped tool-call arguments (provider issue) show up as missing keys here,
41
+ * malformed ones as present keys with unusable values. */
42
+ export function describeReceivedParams(params: FetchContentParams): string {
43
+ const keys = Object.keys(params);
44
+ return keys.length > 0 ? keys.join(", ") : "none";
45
+ }
46
+
47
+ export function normalizeFetchContentParams(params: FetchContentParams): NormalizedFetchContentParams {
48
+ const problems: string[] = [];
49
+ const normalizedUrls = uniqueUrls(normalizeUrlArray(params.urls));
50
+ const urlList = normalizedUrls.length > 0 ? normalizedUrls : normalizeSingleUrl(params.url);
51
+ const prompt = normalizeOptionalString(params.prompt);
52
+ const timestamp = normalizeOptionalString(params.timestamp);
53
+ const frames = normalizeOptionalFrameCount(params.frames);
54
+
55
+ const shouldIncludeFrames = frames !== undefined && (timestamp !== undefined || frames > 1);
56
+
57
+ const forceClone = typeof params.forceClone === "boolean" ? params.forceClone : undefined;
58
+ const model = normalizeOptionalString(params.model);
59
+ const mode = normalizeMode(params.mode, problems);
60
+ const answerModel = normalizeOptionalString(params.answerModel);
61
+ const auth = normalizeAuth(params.auth, problems);
62
+ const proxy = normalizeProxy(params.proxy, problems);
63
+ const redirects = normalizeRedirects(params.redirects, problems);
64
+
65
+ return {
66
+ urlList,
67
+ problems,
68
+ options: {
69
+ ...(forceClone !== undefined ? { forceClone } : {}),
70
+ ...(prompt !== undefined ? { prompt } : {}),
71
+ ...(timestamp !== undefined ? { timestamp } : {}),
72
+ ...(shouldIncludeFrames ? { frames } : {}),
73
+ ...(model !== undefined ? { model } : {}),
74
+ ...(mode !== undefined ? { mode } : {}),
75
+ ...(answerModel !== undefined ? { answerModel } : {}),
76
+ ...(auth !== undefined ? { auth } : {}),
77
+ ...(proxy !== undefined ? { proxy } : {}),
78
+ ...(redirects !== undefined ? { redirects } : {}),
79
+ },
80
+ };
81
+ }
82
+
83
+ function normalizeUrlArray(value: unknown): string[] {
84
+ if (!Array.isArray(value)) return [];
85
+ return value.flatMap(normalizeSingleUrl);
86
+ }
87
+
88
+ function normalizeSingleUrl(value: unknown): string[] {
89
+ if (typeof value !== "string") return [];
90
+ const trimmed = value.trim();
91
+ return trimmed ? [trimmed] : [];
92
+ }
93
+
94
+ function normalizeOptionalString(value: unknown): string | undefined {
95
+ if (typeof value !== "string") return undefined;
96
+ const trimmed = value.trim();
97
+ return trimmed || undefined;
98
+ }
99
+
100
+ function normalizeMode(value: unknown, problems: string[]): "readable" | "raw" | "answer" | "extract" | undefined {
101
+ if (value === undefined) return undefined;
102
+ if (value === "readable" || value === "raw" || value === "answer" || value === "extract") return value;
103
+ problems.push('mode must be "readable", "raw", "answer", or "extract"');
104
+ return undefined;
105
+ }
106
+
107
+ function normalizeRedirects(value: unknown, problems: string[]): "same-origin" | undefined {
108
+ if (value === undefined) return undefined;
109
+ if (value === "same-origin") return value;
110
+ problems.push('redirects must be "same-origin"');
111
+ return undefined;
112
+ }
113
+
114
+ function normalizeAuth(value: unknown, problems: string[]): true | string | undefined {
115
+ if (value === undefined || value === false) return undefined;
116
+ if (value === true) return true;
117
+ if (typeof value === "string") {
118
+ const trimmed = value.trim();
119
+ if (trimmed) return trimmed;
120
+ }
121
+ problems.push("auth must be a profile name, true, or false");
122
+ return undefined;
123
+ }
124
+
125
+ function normalizeProxy(value: unknown, problems: string[]): string | undefined {
126
+ if (value === undefined || value === false) return undefined;
127
+ if (value === null) {
128
+ problems.push("proxy must be an http(s) or socks proxy URL string");
129
+ return undefined;
130
+ }
131
+ try {
132
+ const normalized = normalizeProxyUrl(value, "proxy");
133
+ return normalized ?? "";
134
+ } catch (err) {
135
+ problems.push(err instanceof Error ? err.message : String(err));
136
+ return undefined;
137
+ }
138
+ }
139
+
140
+ function normalizeOptionalFrameCount(value: unknown): number | undefined {
141
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 12) return undefined;
142
+ return value;
143
+ }
144
+
145
+ function uniqueUrls(urls: string[]): string[] {
146
+ return [...new Set(urls)];
147
+ }
@@ -0,0 +1,347 @@
1
+ // fetch_content mode "extract": typed values read from a fetched page by Cloudflare's Clairic model.
2
+ import type { JsonValue } from "@earendil-works/pi-ai";
3
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
4
+ import { redactCredential } from "./credential-source.ts";
5
+ import { fetchWithCredentialRedirects, isRecord } from "./utils.ts";
6
+
7
+ const MAX_FIELDS = 16;
8
+ const MAX_PAGE_CHARS = 200_000;
9
+ // Measured on the extraction fixtures: no wrong value reached 0.80, so lower confidence is shown only as a guess.
10
+ const EXTRACT_THRESHOLD = 0.8;
11
+ const TIMEOUT_MS = 30_000;
12
+ const DURATION_UNITS = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
13
+
14
+ type ItemType = "text" | "number" | "date";
15
+ interface FieldSpec {
16
+ type: "text" | "number" | "date" | "time" | "datetime" | "duration" | "list";
17
+ integer?: true;
18
+ unit?: string;
19
+ items?: ItemType;
20
+ instructions?: string;
21
+ }
22
+
23
+ export type FieldResult =
24
+ | { status: "extracted"; value: JsonValue; confidence: number; line?: string }
25
+ | { status: "uncertain"; guess: JsonValue; confidence?: number; line?: string; notFound?: true }
26
+ | { status: "null" };
27
+
28
+ export type PageExtraction =
29
+ | { fields: Record<string, FieldResult>; cut: boolean }
30
+ | { error: string };
31
+
32
+ export function parseExtractFields(fields: unknown): Record<string, FieldSpec> {
33
+ if (!isRecord(fields)) throw new Error("fields must be an object mapping names to types");
34
+ const entries = Object.entries(fields);
35
+ if (entries.length === 0 || entries.length > MAX_FIELDS) throw new Error(`fields must list 1 to ${MAX_FIELDS} fields`);
36
+ // No prototype, so a field named "__proto__" or "constructor" is an ordinary key.
37
+ const specs: Record<string, FieldSpec> = Object.create(null);
38
+ for (const [name, raw] of entries) {
39
+ if (!/^[A-Za-z0-9_]{1,64}$/.test(name)) throw new Error(`field name "${name}" must be 1 to 64 letters, digits, or underscores`);
40
+ if (typeof raw !== "string") throw new Error(`field ${name} must be a string such as "number" or "date: when it ships"`);
41
+ const colon = raw.indexOf(":");
42
+ const type = (colon === -1 ? raw : raw.slice(0, colon)).trim();
43
+ const instructions = colon === -1 ? "" : raw.slice(colon + 1).trim();
44
+ const [base, sub, extra] = type.split(".");
45
+ let spec: FieldSpec | undefined;
46
+ if (sub === undefined && ["text", "number", "date", "time", "datetime", "duration"].includes(base)) spec = { type: base as FieldSpec["type"] };
47
+ else if (sub === undefined && base === "integer") spec = { type: "number", integer: true };
48
+ else if (sub === undefined && base === "list") spec = { type: "list", items: "text" };
49
+ else if (base === "duration" && DURATION_UNITS.includes(sub)) spec = { type: "duration", unit: sub };
50
+ else if (base === "list" && (sub === "number" || sub === "date")) spec = { type: "list", items: sub };
51
+ if (!spec || extra !== undefined) {
52
+ throw new Error(`field ${name} has unknown type "${type}"; use text, number, integer, date, time, datetime, duration, duration.<${DURATION_UNITS.join("|")}>, list, list.number, or list.date`);
53
+ }
54
+ specs[name] = instructions ? { ...spec, instructions } : spec;
55
+ }
56
+ return specs;
57
+ }
58
+
59
+ function realDate(text: string): boolean {
60
+ const [year, month, day] = text.split("-").map(Number);
61
+ const date = new Date(Date.UTC(year, month - 1, day));
62
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
63
+ }
64
+
65
+ function realTime(text: string): boolean {
66
+ const [hours, minutes, seconds = 0] = text.split(":").map(Number);
67
+ return hours <= 23 && minutes <= 59 && seconds <= 59;
68
+ }
69
+
70
+ /** Whether the value has the field's type; dates and times must also exist on the calendar and clock. */
71
+ function matchesType(spec: FieldSpec, value: unknown): boolean {
72
+ switch (spec.type) {
73
+ case "text": return typeof value === "string" && value.trim() !== "";
74
+ case "number": return typeof value === "number" && Number.isFinite(value) && (!spec.integer || Number.isInteger(value));
75
+ case "duration": return typeof value === "number" && Number.isFinite(value) && value >= 0;
76
+ case "date": return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && realDate(value);
77
+ case "time": return typeof value === "string" && /^\d{2}:\d{2}(:\d{2})?$/.test(value) && realTime(value);
78
+ case "datetime": {
79
+ const match = typeof value === "string" ? /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-](\d{2}:\d{2}))?$/.exec(value) : null;
80
+ return match !== null && realDate(match[1]) && realTime(match[2]) && (match[3] === undefined || realTime(match[3]));
81
+ }
82
+ case "list": return Array.isArray(value) && value.every((item) => matchesType({ type: spec.items! }, item));
83
+ }
84
+ }
85
+
86
+ function fieldResult(spec: FieldSpec, answer: unknown): FieldResult {
87
+ if (!isRecord(answer)) throw new Error("the response is invalid: a field answer is missing");
88
+ // Clairic may send only p_null when nothing was found.
89
+ // The answer was parsed from Clairic's JSON response, so its value is JSON.
90
+ const { value = null, confidence: rawConfidence } = answer as { value?: JsonValue; confidence?: unknown };
91
+ // A null value is Clairic's "not on the page" verdict; the guess it still sends then is a fallback, not evidence.
92
+ if (value === null) return { status: "null" };
93
+ const confidence = typeof rawConfidence === "number" && rawConfidence >= 0 && rawConfidence <= 1 ? rawConfidence : undefined;
94
+ if (confidence !== undefined && confidence >= EXTRACT_THRESHOLD && matchesType(spec, value)) return { status: "extracted", value, confidence };
95
+ return { status: "uncertain", guess: value, ...(confidence !== undefined ? { confidence } : {}) };
96
+ }
97
+
98
+ const MAX_LINE_CHARS = 200;
99
+ // A link target longer than this is kept as text.
100
+ const MAX_LINK_TARGET_CHARS = 2_048;
101
+ // Thousands separators seen on pages: comma, period, space, no-break and narrow no-break space, apostrophe.
102
+ const SEPARATORS = new Set([",", ".", " ", " ", " ", "'"]);
103
+ const isDigit = (char: string | undefined) => char !== undefined && char >= "0" && char <= "9";
104
+
105
+ /** A line reduced for comparison, with the raw index each of its UTF-16 units came from. */
106
+ interface Comparable { text: string; map: number[] }
107
+
108
+ // For each "(" on the line, the index of its ")" when it closes within the link bound. One pass with a stack.
109
+ function closingParens(line: string): Map<number, number> {
110
+ const close = new Map<number, number>();
111
+ const open: number[] = [];
112
+ for (let i = 0; i < line.length; i++) {
113
+ if (line[i] === "(") open.push(i);
114
+ else if (line[i] === ")" && open.length) {
115
+ const start = open.pop()!;
116
+ if (i - start <= MAX_LINK_TARGET_CHARS) close.set(start, i);
117
+ }
118
+ }
119
+ return close;
120
+ }
121
+
122
+ /**
123
+ * One pass over the text: NFKC, lowercase, markdown backslash escapes removed (Turndown writes `my\_package`,
124
+ * `\[beta\]`), curly quotes and dashes made plain, `* _ \` [ ]` dropped, whitespace collapsed. With `visible`, a
125
+ * link or image target `](…)` (nested parentheses and a quoted title included) is skipped, leaving the text a reader sees.
126
+ * The same steps run on the value, so matching only ever gets looser on the page side.
127
+ */
128
+ function comparable(raw: string, visible: boolean): Comparable {
129
+ const close = visible ? closingParens(raw) : undefined;
130
+ let text = "";
131
+ const map: number[] = [];
132
+ let space = false;
133
+ const emit = (chars: string, at: number) => {
134
+ // A character whose NFKC form is much longer (U+FDFA is 18 characters) stays as it is, on both sides.
135
+ const folded = chars.normalize("NFKC");
136
+ for (const char of folded.length > 4 * chars.length ? chars : folded) {
137
+ const plain = /[‘’‚‛′]/.test(char) ? "'" : /[“”„‟″]/.test(char) ? '"' : /[‐-―]/.test(char) ? "-" : char;
138
+ if (/[*_`[\]]/.test(plain)) continue;
139
+ if (/\s/.test(plain)) {
140
+ if (text && !space) { text += " "; map.push(at); space = true; }
141
+ continue;
142
+ }
143
+ const lower = plain.toLowerCase();
144
+ text += lower;
145
+ if (lower) space = false;
146
+ for (let unit = 0; unit < lower.length; unit++) map.push(at);
147
+ }
148
+ };
149
+ for (let i = 0; i < raw.length;) {
150
+ if (raw[i] === "\\" && i + 1 < raw.length && /[!-/:-@[-`{-~]/.test(raw[i + 1])) {
151
+ emit(raw[i + 1], i + 1);
152
+ i += 2;
153
+ continue;
154
+ }
155
+ const target = close && raw[i] === "]" && raw[i + 1] === "(" ? close.get(i + 1) : undefined;
156
+ if (target !== undefined) {
157
+ i = target + 1;
158
+ continue;
159
+ }
160
+ // A character with its combining marks normalizes as one unit, so "e" + U+0301 meets "é".
161
+ let next = i + String.fromCodePoint(raw.codePointAt(i)!).length;
162
+ while (next < raw.length && /\p{M}/u.test(String.fromCodePoint(raw.codePointAt(next)!))) next += raw.codePointAt(next)! > 0xffff ? 2 : 1;
163
+ emit(raw.slice(i, next), i);
164
+ i = next;
165
+ }
166
+ if (space) { text = text.slice(0, -1); map.pop(); }
167
+ return { text, map };
168
+ }
169
+
170
+ interface PageLines { lines: string[]; forms: Comparable[][]; whole: string[] }
171
+
172
+ function indexLines(page: string): PageLines {
173
+ const lines = page.split("\n");
174
+ // Without "](" there is no link target to skip, so both forms are the same.
175
+ const forms = lines.map((line) => { const visible = comparable(line, true); return [visible, line.includes("](") ? comparable(line, false) : visible]; });
176
+ // Both forms of every line joined, for a value that wraps onto the next line.
177
+ const whole = [0, 1].map((form) => forms.map((pair) => pair[form].text).filter(Boolean).join(" "));
178
+ return { lines, forms, whole };
179
+ }
180
+
181
+ /** The line, or a window of it that holds raw[start, end), at most MAX_LINE_CHARS including ellipses. */
182
+ function cite(line: string, start: number, end: number): string {
183
+ if (line.length <= MAX_LINE_CHARS) return line.replace(/\s+/g, " ").trim();
184
+ const size = MAX_LINE_CHARS - 2;
185
+ const from = Math.max(0, Math.min(line.length - size, end - start >= size ? start : start - Math.floor((size - (end - start)) / 2)));
186
+ return `${from > 0 ? "…" : ""}${line.slice(from, from + size).replace(/\s+/g, " ").trim()}${from + size < line.length ? "…" : ""}`;
187
+ }
188
+
189
+ /** undefined: not on the page; null: on the page with no single line to cite, or nothing comparable in the value. */
190
+ function locateText(value: string, page: PageLines): string | null | undefined {
191
+ const wanted = comparable(value, false).text;
192
+ if (!wanted) return null;
193
+ for (const [index, pair] of page.forms.entries()) {
194
+ for (const form of pair) {
195
+ const at = form.text.indexOf(wanted);
196
+ if (at !== -1) return cite(page.lines[index], form.map[at], form.map[at + wanted.length - 1] + 1);
197
+ }
198
+ }
199
+ return page.whole.some((text) => text.includes(wanted)) ? null : undefined;
200
+ }
201
+
202
+ // The values a digit run with separators can mean: "1.299" is 1.299 or 1299, "1.299,00" is 1299, "5.3.1" is nothing.
203
+ function readings(groups: string[], separators: string[]): number[] {
204
+ const thousands = (parts: string[]) => parts.slice(1).every((part) => part.length === 3);
205
+ const values: number[] = [];
206
+ if (thousands(groups)) values.push(Number(groups.join("")));
207
+ const decimal = separators.at(-1);
208
+ if ((decimal === "." || decimal === ",") && separators.slice(0, -1).every((separator) => separator !== decimal) && thousands(groups.slice(0, -1))) {
209
+ values.push(Number(`${groups.slice(0, -1).join("")}.${groups.at(-1)}`));
210
+ }
211
+ return values;
212
+ }
213
+
214
+ /** The first line holding the whole number, sign included: 299 is not in "1 299", and -42 is not "42". */
215
+ function locateNumber(value: number, lines: string[]): string | undefined {
216
+ for (const line of lines) {
217
+ for (let i = 0; i < line.length;) {
218
+ if (!isDigit(line[i])) { i++; continue; }
219
+ const groups: string[] = [];
220
+ const separators: string[] = [];
221
+ let end = i;
222
+ for (;;) {
223
+ const from = end;
224
+ while (isDigit(line[end])) end++;
225
+ groups.push(line.slice(from, end));
226
+ if (!SEPARATORS.has(line[end]) || !isDigit(line[end + 1])) break;
227
+ separators.push(line[end]);
228
+ end++;
229
+ }
230
+ // A minus, optionally before a currency sign, that does not join two words or numbers ("2026-11", "a-1").
231
+ let sign = i - 1;
232
+ if (/[$€£¥]/.test(line[sign] ?? "")) sign--;
233
+ const negative = (line[sign] === "-" || line[sign] === "−") && !/[\p{L}\p{N}]/u.test(line[sign - 1] ?? "");
234
+ if (readings(groups, separators).some((reading) => (negative ? -reading : reading) === value)) return cite(line, negative ? sign : i, end);
235
+ i = end;
236
+ }
237
+ }
238
+ return undefined;
239
+ }
240
+
241
+ /**
242
+ * Adds the page line a text or number value was found on (dates, times and durations are rewritten by Clairic, so
243
+ * they have none). A number match only cites; it never changes the status.
244
+ */
245
+ function withPageLine(spec: FieldSpec, result: FieldResult, page: () => PageLines): FieldResult {
246
+ if (result.status === "null") return result;
247
+ const value = result.status === "extracted" ? result.value : result.guess;
248
+ if (spec.type === "number" && typeof value === "number") {
249
+ const line = locateNumber(value, page().lines);
250
+ return line ? { ...result, line } : result;
251
+ }
252
+ if (spec.type !== "text" || typeof value !== "string") return result;
253
+ const line = locateText(value, page());
254
+ if (line) return { ...result, line };
255
+ // Text that is not on the page was not read from it, however confident the model is.
256
+ if (line === undefined && result.status === "extracted") return { status: "uncertain", guess: result.value, confidence: result.confidence, notFound: true };
257
+ return result;
258
+ }
259
+
260
+ /**
261
+ * Clairic is not in Pi's model catalog, so it is called directly with Pi's `cloudflare-workers-ai` credential.
262
+ * When Pi has an AI Gateway id (`CLOUDFLARE_GATEWAY_ID`), the request goes through that gateway.
263
+ */
264
+ async function runClairic(body: string, modelRegistry: Pick<ModelRegistry, "getProviderAuth"> | undefined, signal: AbortSignal): Promise<Record<string, unknown>> {
265
+ if (!modelRegistry) throw new Error("extract mode runs only inside Pi");
266
+ if (typeof modelRegistry.getProviderAuth !== "function") throw new Error("this Pi version cannot supply the Cloudflare credential; update Pi");
267
+ const credential = await modelRegistry.getProviderAuth("cloudflare-workers-ai");
268
+ const apiKey = credential?.auth.apiKey;
269
+ const accountId = credential?.env?.CLOUDFLARE_ACCOUNT_ID;
270
+ if (!apiKey || !accountId) throw new Error("Cloudflare Workers AI is not set up in Pi; set CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID");
271
+ const gatewayId = (await modelRegistry.getProviderAuth("cloudflare-ai-gateway"))?.env?.CLOUDFLARE_GATEWAY_ID ?? process.env.CLOUDFLARE_GATEWAY_ID;
272
+ let parsed: unknown;
273
+ try {
274
+ const response = await fetchWithCredentialRedirects(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/@cf/cloudflare/clairic`, {
275
+ method: "POST",
276
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...(gatewayId ? { "cf-aig-gateway-id": gatewayId } : {}) },
277
+ body,
278
+ signal,
279
+ }, ["Authorization"]);
280
+ const text = await response.text();
281
+ if (!response.ok) {
282
+ // Redact before cutting, so a key straddling the cut can't leave a partial copy behind.
283
+ const detail = redactCredential(text, apiKey).trim().slice(0, 200);
284
+ throw new Error(`Cloudflare Workers AI returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
285
+ }
286
+ try {
287
+ parsed = JSON.parse(text);
288
+ } catch {
289
+ throw new Error("the response is invalid: it is not JSON");
290
+ }
291
+ } catch (err) {
292
+ throw new Error(redactCredential(err instanceof Error ? err.message : String(err), apiKey));
293
+ }
294
+ if (!isRecord(parsed) || parsed.success !== true || !isRecord(parsed.result)) throw new Error("Cloudflare Workers AI reported an unsuccessful response");
295
+ return parsed.result;
296
+ }
297
+
298
+ /** Provider failures, including Cloudflare not being set up in Pi, become `{ error }`; a caller abort is rethrown. */
299
+ export async function extractPageFields(
300
+ page: string,
301
+ fields: Record<string, FieldSpec>,
302
+ context: { modelRegistry?: Pick<ModelRegistry, "getProviderAuth"> },
303
+ signal?: AbortSignal,
304
+ referenceDate = new Date().toISOString().slice(0, 10),
305
+ ): Promise<PageExtraction> {
306
+ const cut = page.length > MAX_PAGE_CHARS;
307
+ const state = cut ? page.slice(0, MAX_PAGE_CHARS) : page;
308
+ const body = JSON.stringify({
309
+ model: "clairic",
310
+ state,
311
+ fields,
312
+ reference_date: referenceDate,
313
+ });
314
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
315
+ try {
316
+ const result = await runClairic(body, context.modelRegistry, signal ? AbortSignal.any([signal, timeout]) : timeout);
317
+ const answers = result.answers;
318
+ if (!isRecord(answers)) throw new Error("the response is invalid: answers are missing");
319
+ let lines: PageLines | undefined;
320
+ const page = () => lines ??= indexLines(state);
321
+ const results = Object.fromEntries(Object.entries(fields).map(([name, spec]) => [name, withPageLine(spec, fieldResult(spec, Object.hasOwn(answers, name) ? answers[name] : undefined), page)]));
322
+ return { fields: results, cut: cut || result.truncated === true };
323
+ } catch (err) {
324
+ signal?.throwIfAborted();
325
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
326
+ return { error: err instanceof Error ? err.message : String(err) };
327
+ }
328
+ }
329
+
330
+ const MAX_SHOWN_VALUE_CHARS = 1_000;
331
+ // One long value must not push the other fields and pages out of the text the model sees.
332
+ const shown = (value: unknown) => {
333
+ const text = typeof value === "string" ? value : JSON.stringify(value);
334
+ return text.length > MAX_SHOWN_VALUE_CHARS ? `${text.slice(0, MAX_SHOWN_VALUE_CHARS)}… [${text.length} characters; the rest is in the stored page]` : text;
335
+ };
336
+
337
+ export function formatPageExtraction(extraction: PageExtraction): string {
338
+ if ("error" in extraction) return `Extraction failed: ${extraction.error}\n`;
339
+ const lines = Object.entries(extraction.fields).map(([name, result]) => {
340
+ const from = result.status !== "null" && result.line ? ` from "${result.line}"` : "";
341
+ if (result.status === "extracted") return `${name}: ${shown(result.value)} (${result.confidence.toFixed(2)})${from}`;
342
+ if (result.status === "uncertain") return `${name}: uncertain (guess ${shown(result.guess)}${result.confidence !== undefined ? `, ${result.confidence.toFixed(2)}` : ""}${result.notFound ? "; not found on the page" : ""})${from}`;
343
+ return `${name}: not on the page`;
344
+ });
345
+ if (extraction.cut) lines.push(`(Only the first part of the page was read; it is longer than the model accepts.)`);
346
+ return `${lines.join("\n")}\n`;
347
+ }