@asterxsk/kiln 0.4.0 → 0.4.2

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 (259) hide show
  1. package/README.md +155 -155
  2. package/agent/AGENTS.md +67 -67
  3. package/agent/README.md +5 -5
  4. package/agent/extensions/ask-user/index.ts +418 -418
  5. package/agent/extensions/ask-user/install.ps1 +27 -27
  6. package/agent/extensions/ask-user/install.sh +24 -24
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/install.ps1 +27 -27
  14. package/agent/extensions/background-terminals/install.sh +24 -24
  15. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  16. package/agent/extensions/background-terminals/output.test.ts +109 -109
  17. package/agent/extensions/background-terminals/package-lock.json +769 -769
  18. package/agent/extensions/background-terminals/package.json +17 -17
  19. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  20. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  21. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  22. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  23. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  24. package/agent/extensions/background-terminals/src/output.ts +84 -84
  25. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  26. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  27. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  28. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  29. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  30. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  31. package/agent/extensions/destructive/README.md +31 -31
  32. package/agent/extensions/destructive/index.ts +88 -88
  33. package/agent/extensions/destructive/install.ps1 +27 -27
  34. package/agent/extensions/destructive/install.sh +24 -24
  35. package/agent/extensions/file-search/index.spec.ts +443 -443
  36. package/agent/extensions/file-search/index.ts +459 -459
  37. package/agent/extensions/file-search/install.ps1 +27 -27
  38. package/agent/extensions/file-search/install.sh +24 -24
  39. package/agent/extensions/file-search/package-lock.json +2253 -2253
  40. package/agent/extensions/file-search/package.json +23 -23
  41. package/agent/extensions/file-search/src/args.ts +122 -122
  42. package/agent/extensions/file-search/src/binaries.ts +422 -422
  43. package/agent/extensions/file-search/src/output.ts +126 -126
  44. package/agent/extensions/file-search/src/process.ts +146 -146
  45. package/agent/extensions/file-search/src/prompt.ts +52 -52
  46. package/agent/extensions/file-search/tsconfig.json +7 -7
  47. package/agent/extensions/goal/README.md +50 -50
  48. package/agent/extensions/goal/index.ts +155 -155
  49. package/agent/extensions/goal/install.ps1 +27 -27
  50. package/agent/extensions/goal/install.sh +24 -24
  51. package/agent/extensions/kiln-update/README.md +38 -25
  52. package/agent/extensions/kiln-update/index.ts +177 -99
  53. package/agent/extensions/modelconf/PLAN.md +915 -915
  54. package/agent/extensions/modelconf/README.md +66 -66
  55. package/agent/extensions/modelconf/index.ts +296 -296
  56. package/agent/extensions/modelconf/install.ps1 +27 -27
  57. package/agent/extensions/modelconf/install.sh +24 -24
  58. package/agent/extensions/modelconf/package-lock.json +1809 -1809
  59. package/agent/extensions/modelconf/package.json +13 -13
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
  61. package/agent/extensions/modelconf/src/glob.ts +13 -13
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -164
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  66. package/agent/extensions/modelconf/tsconfig.json +15 -15
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  68. package/agent/extensions/pi-web-access/LICENSE +21 -21
  69. package/agent/extensions/pi-web-access/README.md +470 -470
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  71. package/agent/extensions/pi-web-access/activity.ts +101 -101
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  73. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  74. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  75. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  76. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  77. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  78. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  79. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  80. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  81. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  82. package/agent/extensions/pi-web-access/exa.ts +526 -526
  83. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  84. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  85. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  86. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  87. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  88. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  89. package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
  90. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  91. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  92. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  93. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  94. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  95. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  96. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  97. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  98. package/agent/extensions/pi-web-access/package.json +64 -64
  99. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  100. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  101. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  102. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  103. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  104. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  105. package/agent/extensions/pi-web-access/search-types.ts +20 -20
  106. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  107. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  108. package/agent/extensions/pi-web-access/storage.ts +521 -521
  109. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  110. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  111. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  112. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  113. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  114. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  115. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  116. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  117. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  118. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  119. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  120. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  121. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  122. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  123. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  124. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  125. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  126. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  127. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  128. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  129. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  130. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  131. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  132. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  133. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  134. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  135. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  136. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  137. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  138. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  139. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  140. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  141. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  142. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  143. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  144. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  145. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  146. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  147. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  148. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  149. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  150. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
  151. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  152. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
  153. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  154. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  155. package/agent/extensions/pi-web-access/utils.ts +451 -451
  156. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  157. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  158. package/agent/extensions/shared/activity-status.ts +31 -31
  159. package/agent/extensions/shared/child-session.test.ts +270 -270
  160. package/agent/extensions/shared/child-session.ts +148 -148
  161. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  162. package/agent/extensions/shared/context-utilization.ts +47 -47
  163. package/agent/extensions/shared/dashboard-state.ts +99 -99
  164. package/agent/extensions/shared/install.ps1 +27 -27
  165. package/agent/extensions/shared/install.sh +24 -24
  166. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  167. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  168. package/agent/extensions/skillsconf/README.md +74 -74
  169. package/agent/extensions/skillsconf/index.ts +92 -92
  170. package/agent/extensions/skillsconf/install.ps1 +27 -27
  171. package/agent/extensions/skillsconf/install.sh +24 -24
  172. package/agent/extensions/skillsconf/package-lock.json +1809 -1809
  173. package/agent/extensions/skillsconf/package.json +18 -18
  174. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
  175. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
  176. package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
  177. package/agent/extensions/skillsconf/src/filter.ts +74 -74
  178. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
  179. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
  180. package/agent/extensions/skillsconf/src/persistence.ts +169 -169
  181. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
  182. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
  183. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
  184. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
  185. package/agent/extensions/skillsconf/tsconfig.json +15 -15
  186. package/agent/extensions/statusline/index.ts +273 -282
  187. package/agent/extensions/statusline/install.ps1 +27 -27
  188. package/agent/extensions/statusline/install.sh +24 -24
  189. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  190. package/agent/extensions/subagents/claude.test.ts +119 -119
  191. package/agent/extensions/subagents/codex.test.ts +102 -102
  192. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  193. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  194. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  195. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  196. package/agent/extensions/subagents/index.ts +779 -779
  197. package/agent/extensions/subagents/install.ps1 +27 -27
  198. package/agent/extensions/subagents/install.sh +24 -24
  199. package/agent/extensions/subagents/manager.test.ts +276 -276
  200. package/agent/extensions/subagents/package-lock.json +2244 -2244
  201. package/agent/extensions/subagents/package.json +19 -19
  202. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  203. package/agent/extensions/subagents/src/backend.ts +73 -73
  204. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  205. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  206. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  207. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  208. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  209. package/agent/extensions/subagents/src/domain.ts +253 -253
  210. package/agent/extensions/subagents/src/format.ts +74 -74
  211. package/agent/extensions/subagents/src/manager.ts +736 -736
  212. package/agent/extensions/subagents/src/prompt.ts +92 -92
  213. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  214. package/agent/extensions/subagents/src/runtime.ts +53 -53
  215. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  216. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  217. package/agent/extensions/subagents/takeover.test.ts +29 -29
  218. package/agent/extensions/subagents/tsconfig.json +7 -7
  219. package/agent/extensions/todo/AGENTS.md +38 -38
  220. package/agent/extensions/todo/LICENSE +21 -21
  221. package/agent/extensions/todo/config.ts +55 -55
  222. package/agent/extensions/todo/index.ts +151 -151
  223. package/agent/extensions/todo/install.ps1 +27 -27
  224. package/agent/extensions/todo/install.sh +24 -24
  225. package/agent/extensions/todo/locales/de.json +17 -17
  226. package/agent/extensions/todo/locales/en.json +15 -15
  227. package/agent/extensions/todo/locales/es.json +17 -17
  228. package/agent/extensions/todo/locales/fr.json +17 -17
  229. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  230. package/agent/extensions/todo/locales/pt.json +17 -17
  231. package/agent/extensions/todo/locales/ru.json +17 -17
  232. package/agent/extensions/todo/locales/uk.json +17 -17
  233. package/agent/extensions/todo/locales/zh.json +17 -17
  234. package/agent/extensions/todo/package-lock.json +3358 -3358
  235. package/agent/extensions/todo/package.json +67 -67
  236. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  237. package/agent/extensions/todo/state/invariants.ts +20 -20
  238. package/agent/extensions/todo/state/replay.ts +38 -38
  239. package/agent/extensions/todo/state/selectors.ts +107 -107
  240. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  241. package/agent/extensions/todo/state/state.ts +18 -18
  242. package/agent/extensions/todo/state/store.ts +82 -82
  243. package/agent/extensions/todo/state/task-graph.ts +57 -57
  244. package/agent/extensions/todo/todo-overlay.ts +200 -200
  245. package/agent/extensions/todo/todo.ts +155 -155
  246. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  247. package/agent/extensions/todo/tool/types.ts +206 -206
  248. package/agent/extensions/todo/view/format.ts +177 -177
  249. package/agent/extensions/trim-context/README.md +54 -54
  250. package/agent/extensions/trim-context/index.ts +487 -487
  251. package/agent/extensions/trim-context/install.ps1 +27 -27
  252. package/agent/extensions/trim-context/install.sh +24 -24
  253. package/agent/keybindings.json +7 -7
  254. package/agent/version.txt +1 -1
  255. package/bin/kiln.js +20 -13
  256. package/package.json +1 -1
  257. package/agent/extensions/taste/index.ts +0 -443
  258. package/agent/extensions/taste/install.ps1 +0 -27
  259. package/agent/extensions/taste/install.sh +0 -24
@@ -1,568 +1,568 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import {
3
- hasCredentialSource,
4
- resolveCredential,
5
- redactCredential,
6
- } from "./credential-source.ts";
7
- import { getWebSearchConfigPath } from "./utils.ts";
8
-
9
- const DEFAULT_API_HOST = "https://www.datalab.to";
10
- const API_PREFIX = "/api/v1";
11
- const DEFAULT_TIMEOUT_MS = 120_000;
12
- const DEFAULT_POLL_INTERVAL_MS = 1_500;
13
- const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
14
- const MAX_ERROR_BODY_BYTES = 300;
15
- const CLEANUP_TIMEOUT_MS = 5_000;
16
- const CONFIG_PATH = getWebSearchConfigPath();
17
-
18
- export type DatalabMode = "fast" | "balanced" | "accurate";
19
- export type DatalabProcessingLocation = "eu" | "us";
20
-
21
- export const DATALAB_MODE_VALUES = new Set<DatalabMode>([
22
- "fast",
23
- "balanced",
24
- "accurate",
25
- ]);
26
- export const DATALAB_LOCATION_VALUES = new Set<DatalabProcessingLocation>([
27
- "eu",
28
- "us",
29
- ]);
30
- export const DEFAULT_DATALAB_MODE: DatalabMode = "balanced";
31
- export const DEFAULT_PROCESSING_LOCATION: DatalabProcessingLocation = "us";
32
- export const DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
33
-
34
- interface DatalabConfig {
35
- datalabApiKey?: unknown;
36
- }
37
-
38
- let cachedConfig: DatalabConfig | null = null;
39
-
40
- function loadConfig(): DatalabConfig {
41
- if (cachedConfig) return cachedConfig;
42
- if (!existsSync(CONFIG_PATH)) {
43
- cachedConfig = {};
44
- return cachedConfig;
45
- }
46
-
47
- const rawText = readFileSync(CONFIG_PATH, "utf-8");
48
- try {
49
- cachedConfig = JSON.parse(rawText) as DatalabConfig;
50
- return cachedConfig;
51
- } catch (err) {
52
- const message = err instanceof Error ? err.message : String(err);
53
- throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
54
- }
55
- }
56
-
57
- function normalizeString(value: unknown): string | null {
58
- if (typeof value !== "string") return null;
59
- const normalized = value.trim();
60
- return normalized.length > 0 ? normalized : null;
61
- }
62
-
63
- function normalizeFileId(value: unknown): string | null {
64
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
65
- return normalizeString(value);
66
- }
67
-
68
- export function isDatalabApiAvailable(): boolean {
69
- return hasCredentialSource({
70
- provider: "Datalab",
71
- configuredValue: loadConfig().datalabApiKey,
72
- environmentValue: process.env.DATALAB_API_KEY,
73
- });
74
- }
75
-
76
- export async function getDatalabApiKey(
77
- signal?: AbortSignal,
78
- ): Promise<string | null> {
79
- return resolveCredential({
80
- provider: "Datalab",
81
- configuredValue: loadConfig().datalabApiKey,
82
- environmentValue: process.env.DATALAB_API_KEY,
83
- signal,
84
- });
85
- }
86
-
87
- export function getDatalabApiBase(): string {
88
- const normalized = normalizeString(process.env.DATALAB_API_BASE)?.replace(
89
- /\/+$/,
90
- "",
91
- );
92
- return normalized || `${DEFAULT_API_HOST}${API_PREFIX}`;
93
- }
94
-
95
- /**
96
- * Resolve the processing region. US storage and processing is the default;
97
- * set `DATALAB_PROCESSING_LOCATION=eu` to use EU data residency at Datalab's
98
- * documented 1.25× usage rate. Only `eu` and `us` are supported by the API.
99
- * Config errors are thrown with a `Failed to parse` prefix so the
100
- * extraction fallback chain treats them as fatal, mirroring how malformed
101
- * web-search config is handled elsewhere.
102
- */
103
- export function getDatalabProcessingLocation(): DatalabProcessingLocation {
104
- const value =
105
- normalizeString(process.env.DATALAB_PROCESSING_LOCATION) ??
106
- DEFAULT_PROCESSING_LOCATION;
107
- const normalized = value.toLowerCase() as DatalabProcessingLocation;
108
- if (!DATALAB_LOCATION_VALUES.has(normalized)) {
109
- throw new Error(
110
- `Failed to parse DATALAB_PROCESSING_LOCATION: expected "eu" or "us", got "${value}"`,
111
- );
112
- }
113
- return normalized;
114
- }
115
-
116
- export function normalizeDatalabMode(value: unknown): DatalabMode {
117
- const raw = normalizeString(value);
118
- if (!raw) return DEFAULT_DATALAB_MODE;
119
- const normalized = raw.toLowerCase() as DatalabMode;
120
- if (DATALAB_MODE_VALUES.has(normalized)) return normalized;
121
- throw new Error(
122
- `Failed to parse datalab mode: expected "fast", "balanced", or "accurate", got "${value}"`,
123
- );
124
- }
125
-
126
- export interface DatalabPDFExtractOptions {
127
- maxPages: number;
128
- title: string;
129
- signal?: AbortSignal;
130
- timeoutMs?: number;
131
- mode?: DatalabMode;
132
- processingLocation?: DatalabProcessingLocation;
133
- }
134
-
135
- export interface DatalabPDFExtractResult {
136
- markdown: string;
137
- pages: number;
138
- parseQualityScore?: number;
139
- }
140
-
141
- interface DatalabUploadRequest {
142
- file_id?: unknown;
143
- upload_url?: unknown;
144
- reference?: unknown;
145
- }
146
-
147
- interface DatalabConfirmResponse {
148
- file_id?: unknown;
149
- reference?: unknown;
150
- }
151
-
152
- interface DatalabConversionState {
153
- status?: unknown;
154
- success?: unknown;
155
- request_check_url?: unknown;
156
- markdown?: unknown;
157
- page_count?: unknown;
158
- parse_quality_score?: unknown;
159
- error?: unknown;
160
- }
161
-
162
- /**
163
- * Convert a PDF buffer to Markdown through the Datalab hosted API.
164
- *
165
- * Datalab converts documents with a dedicated extraction engine (Marker),
166
- * which preserves tables, multi-column reading order, headings, and math
167
- * where the local `unpdf` fallback only produces flattened text. Conversion
168
- * is deterministic (no LLM transcription drift), and `accurate` mode handles
169
- * scanned pages. Completed responses may include a `parse_quality_score` (0–5)
170
- * for quality gating. Billing is per processed page; the free tier includes a
171
- * monthly credit (see README) so light use costs nothing.
172
- *
173
- * The flow is:
174
- * 1. request a presigned upload URL for the selected processing region,
175
- * 2. PUT the PDF bytes directly to storage,
176
- * 3. confirm the upload to obtain a `datalab://` reference,
177
- * 4. submit the conversion with that reference, then
178
- * 5. poll the returned `request_check_url` until `complete` or `failed`.
179
- *
180
- * The processing region is fixed at the upload step (US by default; set
181
- * `DATALAB_PROCESSING_LOCATION=eu` for EU data residency). The convert step
182
- * deliberately omits `processing_location` because the API rejects multipart form data that
183
- * carries it; the server processes the file from the storage region it was
184
- * uploaded to. The uploaded file is deleted best-effort after conversion.
185
- * The caller's signal and a shared deadline bound the whole exchange.
186
- */
187
- export async function extractPDFViaDatalab(
188
- buffer: ArrayBuffer,
189
- options: DatalabPDFExtractOptions,
190
- ): Promise<DatalabPDFExtractResult> {
191
- options.signal?.throwIfAborted();
192
- const apiKey = await getDatalabApiKey(options.signal);
193
- options.signal?.throwIfAborted();
194
- if (!apiKey) {
195
- throw new Error(
196
- "Datalab PDF conversion requires a configured Datalab API key",
197
- );
198
- }
199
-
200
- const mode = options.mode ?? normalizeDatalabMode(process.env.DATALAB_MODE);
201
- const processingLocation =
202
- options.processingLocation ?? getDatalabProcessingLocation();
203
- const timeoutMs =
204
- typeof options.timeoutMs === "number" &&
205
- Number.isFinite(options.timeoutMs) &&
206
- options.timeoutMs > 0
207
- ? Math.floor(options.timeoutMs)
208
- : DEFAULT_TIMEOUT_MS;
209
- const deadline = Date.now() + timeoutMs;
210
-
211
- const upload = await requestUploadUrl({
212
- apiKey,
213
- title: options.title,
214
- processingLocation,
215
- signal: options.signal,
216
- deadline,
217
- });
218
- if (typeof upload.upload_url !== "string" || !upload.upload_url) {
219
- throw new Error("Datalab PDF conversion failed: missing upload_url");
220
- }
221
- const uploadFileId = normalizeFileId(upload.file_id);
222
- if (!uploadFileId) {
223
- throw new Error("Datalab PDF conversion failed: missing file_id");
224
- }
225
-
226
- let fileId = uploadFileId;
227
- let reference = normalizeString(upload.reference);
228
-
229
- try {
230
- const put = await fetchDatalab(
231
- upload.upload_url,
232
- {
233
- method: "PUT",
234
- headers: { "content-type": "application/pdf" },
235
- body: new Blob([buffer], { type: "application/pdf" }),
236
- signal: withTimeout(options.signal, remaining(deadline)),
237
- },
238
- apiKey,
239
- );
240
- if (!put.ok) {
241
- throw new Error(
242
- `Datalab PDF upload failed: HTTP ${put.status} ${put.statusText}`,
243
- );
244
- }
245
-
246
- const confirmed = await confirmUpload(
247
- apiKey,
248
- String(fileId),
249
- options.signal,
250
- deadline,
251
- );
252
- fileId = normalizeFileId(confirmed.file_id) ?? fileId;
253
- reference = normalizeString(confirmed.reference) ?? reference;
254
- if (!reference) {
255
- throw new Error("Datalab PDF conversion failed: missing file reference");
256
- }
257
-
258
- const form = new FormData();
259
- form.append("file_url", reference);
260
- form.append("output_format", "markdown");
261
- form.append("mode", mode);
262
- form.append("max_pages", String(options.maxPages));
263
- form.append("paginate", "true");
264
-
265
- // The conversion itself must NOT repeat processing_location: the API
266
- // rejects multipart form data carrying processing_location (HTTP 403).
267
- // The region was already fixed when the presigned upload was issued for
268
- // storage in the selected region, so the server processes the file
269
- // wherever it was stored (US by default; use the env override for EU).
270
-
271
- const submit = await fetchDatalab(
272
- `${getDatalabApiBase()}/convert`,
273
- {
274
- method: "POST",
275
- headers: { "x-api-key": apiKey },
276
- body: form,
277
- signal: withTimeout(options.signal, remaining(deadline)),
278
- },
279
- apiKey,
280
- );
281
- const state = await readJsonResponse(submit, apiKey);
282
-
283
- // The submit response is an acceptance ack ({ success: true,
284
- // request_check_url }) with no status field and no markdown; only the
285
- // polled result carries a status. Key on status, never on success.
286
- if (state.status === "complete") return toResult(state);
287
- if (state.status === "failed") {
288
- throw new Error(
289
- `Datalab PDF conversion failed: ${state.error ?? "unknown error"}`,
290
- );
291
- }
292
-
293
- const checkUrl = normalizeCheckUrl(state.request_check_url);
294
- while (Date.now() < deadline) {
295
- await sleep(
296
- Math.min(DEFAULT_POLL_INTERVAL_MS, remaining(deadline)),
297
- options.signal,
298
- );
299
- if (Date.now() >= deadline) break;
300
- const poll = await fetchDatalab(
301
- checkUrl,
302
- {
303
- method: "GET",
304
- headers: { "x-api-key": apiKey },
305
- signal: withTimeout(options.signal, remaining(deadline)),
306
- },
307
- apiKey,
308
- );
309
- const next = await readJsonResponse(poll, apiKey);
310
- if (next.status === "complete") return toResult(next);
311
- if (next.status === "failed") {
312
- throw new Error(
313
- `Datalab PDF conversion failed: ${next.error ?? "unknown error"}`,
314
- );
315
- }
316
- }
317
-
318
- throw new Error("Datalab PDF conversion timed out");
319
- } finally {
320
- // File deletion is best-effort. Do not extend a caller's timeout or
321
- // cancellation while waiting for a remote cleanup request.
322
- void deleteDatalabFile(apiKey, fileId);
323
- }
324
- }
325
-
326
- async function requestUploadUrl(options: {
327
- apiKey: string;
328
- title: string;
329
- processingLocation: DatalabProcessingLocation;
330
- signal: AbortSignal | undefined;
331
- deadline: number;
332
- }): Promise<DatalabUploadRequest> {
333
- const { apiKey, title, processingLocation, signal, deadline } = options;
334
- const response = await fetchDatalab(
335
- `${getDatalabApiBase()}/files/upload`,
336
- {
337
- method: "POST",
338
- headers: {
339
- "x-api-key": apiKey,
340
- "content-type": "application/json",
341
- },
342
- body: JSON.stringify({
343
- filename: `${datalabFilename(title)}.pdf`,
344
- content_type: "application/pdf",
345
- processing_location: processingLocation,
346
- }),
347
- signal: withTimeout(signal, remaining(deadline)),
348
- },
349
- apiKey,
350
- );
351
- return readJsonResponse(response, apiKey);
352
- }
353
-
354
- async function confirmUpload(
355
- apiKey: string,
356
- fileId: string,
357
- signal: AbortSignal | undefined,
358
- deadline: number,
359
- ): Promise<DatalabConfirmResponse> {
360
- const response = await fetchDatalab(
361
- `${getDatalabApiBase()}/files/${encodeURIComponent(fileId)}/confirm`,
362
- {
363
- method: "GET",
364
- headers: { "x-api-key": apiKey },
365
- signal: withTimeout(signal, remaining(deadline)),
366
- },
367
- apiKey,
368
- );
369
- return readJsonResponse(response, apiKey);
370
- }
371
-
372
- async function deleteDatalabFile(
373
- apiKey: string,
374
- fileId: string,
375
- ): Promise<void> {
376
- try {
377
- await fetchDatalab(
378
- `${getDatalabApiBase()}/files/${encodeURIComponent(fileId)}`,
379
- {
380
- method: "DELETE",
381
- headers: { "x-api-key": apiKey },
382
- signal: AbortSignal.timeout(CLEANUP_TIMEOUT_MS),
383
- },
384
- apiKey,
385
- );
386
- } catch {
387
- // Best-effort cleanup; a leftover file is not worth failing the conversion.
388
- }
389
- }
390
-
391
- function toResult(state: DatalabConversionState): DatalabPDFExtractResult {
392
- const markdown = normalizeString(state.markdown);
393
- if (!markdown) {
394
- throw new Error("Datalab PDF conversion returned empty markdown");
395
- }
396
- const quality = state.parse_quality_score;
397
- return {
398
- markdown,
399
- pages: numericField(state.page_count) ?? countPageMarkers(markdown),
400
- ...(typeof quality === "number" && Number.isFinite(quality)
401
- ? { parseQualityScore: quality }
402
- : {}),
403
- };
404
- }
405
-
406
- function numericField(value: unknown): number | null {
407
- return typeof value === "number" && Number.isFinite(value) && value > 0
408
- ? Math.floor(value)
409
- : null;
410
- }
411
-
412
- function countPageMarkers(markdown: string): number {
413
- return [...markdown.matchAll(/^<!-- Page (\d+) -->$/gm)].length;
414
- }
415
-
416
- function normalizeCheckUrl(value: unknown): string {
417
- if (typeof value !== "string" || !value.trim()) {
418
- throw new Error("Datalab PDF conversion failed: missing request_check_url");
419
- }
420
- const apiBase = getDatalabApiUrl();
421
- let checkUrl: URL;
422
- try {
423
- checkUrl = new URL(value.trim(), apiBase);
424
- } catch {
425
- throw new Error("Datalab PDF conversion failed: invalid request_check_url");
426
- }
427
- if (checkUrl.origin !== apiBase.origin) {
428
- throw new Error(
429
- "Datalab PDF conversion failed: request_check_url has an unexpected origin",
430
- );
431
- }
432
- return checkUrl.toString();
433
- }
434
-
435
- function getDatalabApiUrl(): URL {
436
- try {
437
- return new URL(getDatalabApiBase());
438
- } catch {
439
- throw new Error(
440
- "Failed to parse DATALAB_API_BASE: expected an absolute URL",
441
- );
442
- }
443
- }
444
-
445
- function remaining(deadline: number): number {
446
- return Math.max(1, deadline - Date.now());
447
- }
448
-
449
- function withTimeout(
450
- signal: AbortSignal | undefined,
451
- timeoutMs: number,
452
- ): AbortSignal {
453
- const timeout = AbortSignal.timeout(timeoutMs);
454
- return signal ? AbortSignal.any([signal, timeout]) : timeout;
455
- }
456
-
457
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
458
- return new Promise((resolve, reject) => {
459
- let timer: ReturnType<typeof setTimeout>;
460
- const cleanup = () => signal?.removeEventListener("abort", onAbort);
461
- const onTimeout = () => {
462
- cleanup();
463
- resolve();
464
- };
465
- const onAbort = () => {
466
- clearTimeout(timer);
467
- cleanup();
468
- reject(signal?.reason);
469
- };
470
-
471
- if (signal?.aborted) {
472
- onAbort();
473
- return;
474
- }
475
- timer = setTimeout(onTimeout, ms);
476
- signal?.addEventListener("abort", onAbort, { once: true });
477
- });
478
- }
479
-
480
- async function fetchDatalab(
481
- url: string,
482
- init: RequestInit,
483
- apiKey: string,
484
- ): Promise<Response> {
485
- try {
486
- return await fetch(url, { ...init, redirect: init.redirect ?? "error" });
487
- } catch (error) {
488
- const message = error instanceof Error ? error.message : String(error);
489
- const redacted = redactCredential(message, apiKey);
490
- if (redacted === message) throw error;
491
- const redactedError = new Error(redacted);
492
- if (error instanceof Error) redactedError.name = error.name;
493
- throw redactedError;
494
- }
495
- }
496
-
497
- async function readJsonResponse(
498
- response: Response,
499
- apiKey: string,
500
- ): Promise<Record<string, unknown>> {
501
- const text = await readResponseText(response);
502
- if (!response.ok) {
503
- const detail = text.trim().slice(0, MAX_ERROR_BODY_BYTES);
504
- const message = detail
505
- ? `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}: ${detail}`
506
- : `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}`;
507
- throw new Error(redactCredential(message, apiKey));
508
- }
509
- return parseJsonRecord(text);
510
- }
511
-
512
- function parseJsonRecord(text: string): Record<string, unknown> {
513
- let parsed: unknown;
514
- try {
515
- parsed = JSON.parse(text);
516
- } catch (error) {
517
- throw new Error("Datalab PDF conversion returned invalid JSON", { cause: error });
518
- }
519
- if (Object.prototype.toString.call(parsed) !== "[object Object]") {
520
- throw new Error("Datalab PDF conversion returned invalid JSON object");
521
- }
522
- return parsed as Record<string, unknown>;
523
- }
524
-
525
- async function readResponseText(response: Response): Promise<string> {
526
- const contentLength = Number(response.headers.get("content-length"));
527
- if (Number.isFinite(contentLength) && contentLength > MAX_RESPONSE_BYTES) {
528
- throw new Error("Datalab PDF conversion response too large");
529
- }
530
- if (!response.body) return "";
531
-
532
- const reader = response.body.getReader();
533
- const decoder = new TextDecoder();
534
- const chunks: string[] = [];
535
- let bytesRead = 0;
536
- try {
537
- while (true) {
538
- const { done, value } = await reader.read();
539
- if (done) break;
540
- bytesRead += value.byteLength;
541
- if (bytesRead > MAX_RESPONSE_BYTES) {
542
- try {
543
- await reader.cancel();
544
- } catch {
545
- // The response is already too large; cancellation is best-effort.
546
- }
547
- throw new Error("Datalab PDF conversion response too large");
548
- }
549
- chunks.push(decoder.decode(value, { stream: true }));
550
- }
551
- chunks.push(decoder.decode());
552
- return chunks.join("");
553
- } finally {
554
- reader.releaseLock();
555
- }
556
- }
557
-
558
- function datalabFilename(title: string): string {
559
- return (
560
- title
561
- .toLowerCase()
562
- .replace(/[^a-z0-9\s-]/g, "")
563
- .replace(/\s+/g, "-")
564
- .replace(/-+/g, "-")
565
- .replace(/^-|-$/g, "")
566
- .slice(0, 60) || "document"
567
- );
568
- }
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import {
3
+ hasCredentialSource,
4
+ resolveCredential,
5
+ redactCredential,
6
+ } from "./credential-source.ts";
7
+ import { getWebSearchConfigPath } from "./utils.ts";
8
+
9
+ const DEFAULT_API_HOST = "https://www.datalab.to";
10
+ const API_PREFIX = "/api/v1";
11
+ const DEFAULT_TIMEOUT_MS = 120_000;
12
+ const DEFAULT_POLL_INTERVAL_MS = 1_500;
13
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
14
+ const MAX_ERROR_BODY_BYTES = 300;
15
+ const CLEANUP_TIMEOUT_MS = 5_000;
16
+ const CONFIG_PATH = getWebSearchConfigPath();
17
+
18
+ export type DatalabMode = "fast" | "balanced" | "accurate";
19
+ export type DatalabProcessingLocation = "eu" | "us";
20
+
21
+ export const DATALAB_MODE_VALUES = new Set<DatalabMode>([
22
+ "fast",
23
+ "balanced",
24
+ "accurate",
25
+ ]);
26
+ export const DATALAB_LOCATION_VALUES = new Set<DatalabProcessingLocation>([
27
+ "eu",
28
+ "us",
29
+ ]);
30
+ export const DEFAULT_DATALAB_MODE: DatalabMode = "balanced";
31
+ export const DEFAULT_PROCESSING_LOCATION: DatalabProcessingLocation = "us";
32
+ export const DEFAULT_DATALAB_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
33
+
34
+ interface DatalabConfig {
35
+ datalabApiKey?: unknown;
36
+ }
37
+
38
+ let cachedConfig: DatalabConfig | null = null;
39
+
40
+ function loadConfig(): DatalabConfig {
41
+ if (cachedConfig) return cachedConfig;
42
+ if (!existsSync(CONFIG_PATH)) {
43
+ cachedConfig = {};
44
+ return cachedConfig;
45
+ }
46
+
47
+ const rawText = readFileSync(CONFIG_PATH, "utf-8");
48
+ try {
49
+ cachedConfig = JSON.parse(rawText) as DatalabConfig;
50
+ return cachedConfig;
51
+ } catch (err) {
52
+ const message = err instanceof Error ? err.message : String(err);
53
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
54
+ }
55
+ }
56
+
57
+ function normalizeString(value: unknown): string | null {
58
+ if (typeof value !== "string") return null;
59
+ const normalized = value.trim();
60
+ return normalized.length > 0 ? normalized : null;
61
+ }
62
+
63
+ function normalizeFileId(value: unknown): string | null {
64
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
65
+ return normalizeString(value);
66
+ }
67
+
68
+ export function isDatalabApiAvailable(): boolean {
69
+ return hasCredentialSource({
70
+ provider: "Datalab",
71
+ configuredValue: loadConfig().datalabApiKey,
72
+ environmentValue: process.env.DATALAB_API_KEY,
73
+ });
74
+ }
75
+
76
+ export async function getDatalabApiKey(
77
+ signal?: AbortSignal,
78
+ ): Promise<string | null> {
79
+ return resolveCredential({
80
+ provider: "Datalab",
81
+ configuredValue: loadConfig().datalabApiKey,
82
+ environmentValue: process.env.DATALAB_API_KEY,
83
+ signal,
84
+ });
85
+ }
86
+
87
+ export function getDatalabApiBase(): string {
88
+ const normalized = normalizeString(process.env.DATALAB_API_BASE)?.replace(
89
+ /\/+$/,
90
+ "",
91
+ );
92
+ return normalized || `${DEFAULT_API_HOST}${API_PREFIX}`;
93
+ }
94
+
95
+ /**
96
+ * Resolve the processing region. US storage and processing is the default;
97
+ * set `DATALAB_PROCESSING_LOCATION=eu` to use EU data residency at Datalab's
98
+ * documented 1.25× usage rate. Only `eu` and `us` are supported by the API.
99
+ * Config errors are thrown with a `Failed to parse` prefix so the
100
+ * extraction fallback chain treats them as fatal, mirroring how malformed
101
+ * web-search config is handled elsewhere.
102
+ */
103
+ export function getDatalabProcessingLocation(): DatalabProcessingLocation {
104
+ const value =
105
+ normalizeString(process.env.DATALAB_PROCESSING_LOCATION) ??
106
+ DEFAULT_PROCESSING_LOCATION;
107
+ const normalized = value.toLowerCase() as DatalabProcessingLocation;
108
+ if (!DATALAB_LOCATION_VALUES.has(normalized)) {
109
+ throw new Error(
110
+ `Failed to parse DATALAB_PROCESSING_LOCATION: expected "eu" or "us", got "${value}"`,
111
+ );
112
+ }
113
+ return normalized;
114
+ }
115
+
116
+ export function normalizeDatalabMode(value: unknown): DatalabMode {
117
+ const raw = normalizeString(value);
118
+ if (!raw) return DEFAULT_DATALAB_MODE;
119
+ const normalized = raw.toLowerCase() as DatalabMode;
120
+ if (DATALAB_MODE_VALUES.has(normalized)) return normalized;
121
+ throw new Error(
122
+ `Failed to parse datalab mode: expected "fast", "balanced", or "accurate", got "${value}"`,
123
+ );
124
+ }
125
+
126
+ export interface DatalabPDFExtractOptions {
127
+ maxPages: number;
128
+ title: string;
129
+ signal?: AbortSignal;
130
+ timeoutMs?: number;
131
+ mode?: DatalabMode;
132
+ processingLocation?: DatalabProcessingLocation;
133
+ }
134
+
135
+ export interface DatalabPDFExtractResult {
136
+ markdown: string;
137
+ pages: number;
138
+ parseQualityScore?: number;
139
+ }
140
+
141
+ interface DatalabUploadRequest {
142
+ file_id?: unknown;
143
+ upload_url?: unknown;
144
+ reference?: unknown;
145
+ }
146
+
147
+ interface DatalabConfirmResponse {
148
+ file_id?: unknown;
149
+ reference?: unknown;
150
+ }
151
+
152
+ interface DatalabConversionState {
153
+ status?: unknown;
154
+ success?: unknown;
155
+ request_check_url?: unknown;
156
+ markdown?: unknown;
157
+ page_count?: unknown;
158
+ parse_quality_score?: unknown;
159
+ error?: unknown;
160
+ }
161
+
162
+ /**
163
+ * Convert a PDF buffer to Markdown through the Datalab hosted API.
164
+ *
165
+ * Datalab converts documents with a dedicated extraction engine (Marker),
166
+ * which preserves tables, multi-column reading order, headings, and math
167
+ * where the local `unpdf` fallback only produces flattened text. Conversion
168
+ * is deterministic (no LLM transcription drift), and `accurate` mode handles
169
+ * scanned pages. Completed responses may include a `parse_quality_score` (0–5)
170
+ * for quality gating. Billing is per processed page; the free tier includes a
171
+ * monthly credit (see README) so light use costs nothing.
172
+ *
173
+ * The flow is:
174
+ * 1. request a presigned upload URL for the selected processing region,
175
+ * 2. PUT the PDF bytes directly to storage,
176
+ * 3. confirm the upload to obtain a `datalab://` reference,
177
+ * 4. submit the conversion with that reference, then
178
+ * 5. poll the returned `request_check_url` until `complete` or `failed`.
179
+ *
180
+ * The processing region is fixed at the upload step (US by default; set
181
+ * `DATALAB_PROCESSING_LOCATION=eu` for EU data residency). The convert step
182
+ * deliberately omits `processing_location` because the API rejects multipart form data that
183
+ * carries it; the server processes the file from the storage region it was
184
+ * uploaded to. The uploaded file is deleted best-effort after conversion.
185
+ * The caller's signal and a shared deadline bound the whole exchange.
186
+ */
187
+ export async function extractPDFViaDatalab(
188
+ buffer: ArrayBuffer,
189
+ options: DatalabPDFExtractOptions,
190
+ ): Promise<DatalabPDFExtractResult> {
191
+ options.signal?.throwIfAborted();
192
+ const apiKey = await getDatalabApiKey(options.signal);
193
+ options.signal?.throwIfAborted();
194
+ if (!apiKey) {
195
+ throw new Error(
196
+ "Datalab PDF conversion requires a configured Datalab API key",
197
+ );
198
+ }
199
+
200
+ const mode = options.mode ?? normalizeDatalabMode(process.env.DATALAB_MODE);
201
+ const processingLocation =
202
+ options.processingLocation ?? getDatalabProcessingLocation();
203
+ const timeoutMs =
204
+ typeof options.timeoutMs === "number" &&
205
+ Number.isFinite(options.timeoutMs) &&
206
+ options.timeoutMs > 0
207
+ ? Math.floor(options.timeoutMs)
208
+ : DEFAULT_TIMEOUT_MS;
209
+ const deadline = Date.now() + timeoutMs;
210
+
211
+ const upload = await requestUploadUrl({
212
+ apiKey,
213
+ title: options.title,
214
+ processingLocation,
215
+ signal: options.signal,
216
+ deadline,
217
+ });
218
+ if (typeof upload.upload_url !== "string" || !upload.upload_url) {
219
+ throw new Error("Datalab PDF conversion failed: missing upload_url");
220
+ }
221
+ const uploadFileId = normalizeFileId(upload.file_id);
222
+ if (!uploadFileId) {
223
+ throw new Error("Datalab PDF conversion failed: missing file_id");
224
+ }
225
+
226
+ let fileId = uploadFileId;
227
+ let reference = normalizeString(upload.reference);
228
+
229
+ try {
230
+ const put = await fetchDatalab(
231
+ upload.upload_url,
232
+ {
233
+ method: "PUT",
234
+ headers: { "content-type": "application/pdf" },
235
+ body: new Blob([buffer], { type: "application/pdf" }),
236
+ signal: withTimeout(options.signal, remaining(deadline)),
237
+ },
238
+ apiKey,
239
+ );
240
+ if (!put.ok) {
241
+ throw new Error(
242
+ `Datalab PDF upload failed: HTTP ${put.status} ${put.statusText}`,
243
+ );
244
+ }
245
+
246
+ const confirmed = await confirmUpload(
247
+ apiKey,
248
+ String(fileId),
249
+ options.signal,
250
+ deadline,
251
+ );
252
+ fileId = normalizeFileId(confirmed.file_id) ?? fileId;
253
+ reference = normalizeString(confirmed.reference) ?? reference;
254
+ if (!reference) {
255
+ throw new Error("Datalab PDF conversion failed: missing file reference");
256
+ }
257
+
258
+ const form = new FormData();
259
+ form.append("file_url", reference);
260
+ form.append("output_format", "markdown");
261
+ form.append("mode", mode);
262
+ form.append("max_pages", String(options.maxPages));
263
+ form.append("paginate", "true");
264
+
265
+ // The conversion itself must NOT repeat processing_location: the API
266
+ // rejects multipart form data carrying processing_location (HTTP 403).
267
+ // The region was already fixed when the presigned upload was issued for
268
+ // storage in the selected region, so the server processes the file
269
+ // wherever it was stored (US by default; use the env override for EU).
270
+
271
+ const submit = await fetchDatalab(
272
+ `${getDatalabApiBase()}/convert`,
273
+ {
274
+ method: "POST",
275
+ headers: { "x-api-key": apiKey },
276
+ body: form,
277
+ signal: withTimeout(options.signal, remaining(deadline)),
278
+ },
279
+ apiKey,
280
+ );
281
+ const state = await readJsonResponse(submit, apiKey);
282
+
283
+ // The submit response is an acceptance ack ({ success: true,
284
+ // request_check_url }) with no status field and no markdown; only the
285
+ // polled result carries a status. Key on status, never on success.
286
+ if (state.status === "complete") return toResult(state);
287
+ if (state.status === "failed") {
288
+ throw new Error(
289
+ `Datalab PDF conversion failed: ${state.error ?? "unknown error"}`,
290
+ );
291
+ }
292
+
293
+ const checkUrl = normalizeCheckUrl(state.request_check_url);
294
+ while (Date.now() < deadline) {
295
+ await sleep(
296
+ Math.min(DEFAULT_POLL_INTERVAL_MS, remaining(deadline)),
297
+ options.signal,
298
+ );
299
+ if (Date.now() >= deadline) break;
300
+ const poll = await fetchDatalab(
301
+ checkUrl,
302
+ {
303
+ method: "GET",
304
+ headers: { "x-api-key": apiKey },
305
+ signal: withTimeout(options.signal, remaining(deadline)),
306
+ },
307
+ apiKey,
308
+ );
309
+ const next = await readJsonResponse(poll, apiKey);
310
+ if (next.status === "complete") return toResult(next);
311
+ if (next.status === "failed") {
312
+ throw new Error(
313
+ `Datalab PDF conversion failed: ${next.error ?? "unknown error"}`,
314
+ );
315
+ }
316
+ }
317
+
318
+ throw new Error("Datalab PDF conversion timed out");
319
+ } finally {
320
+ // File deletion is best-effort. Do not extend a caller's timeout or
321
+ // cancellation while waiting for a remote cleanup request.
322
+ void deleteDatalabFile(apiKey, fileId);
323
+ }
324
+ }
325
+
326
+ async function requestUploadUrl(options: {
327
+ apiKey: string;
328
+ title: string;
329
+ processingLocation: DatalabProcessingLocation;
330
+ signal: AbortSignal | undefined;
331
+ deadline: number;
332
+ }): Promise<DatalabUploadRequest> {
333
+ const { apiKey, title, processingLocation, signal, deadline } = options;
334
+ const response = await fetchDatalab(
335
+ `${getDatalabApiBase()}/files/upload`,
336
+ {
337
+ method: "POST",
338
+ headers: {
339
+ "x-api-key": apiKey,
340
+ "content-type": "application/json",
341
+ },
342
+ body: JSON.stringify({
343
+ filename: `${datalabFilename(title)}.pdf`,
344
+ content_type: "application/pdf",
345
+ processing_location: processingLocation,
346
+ }),
347
+ signal: withTimeout(signal, remaining(deadline)),
348
+ },
349
+ apiKey,
350
+ );
351
+ return readJsonResponse(response, apiKey);
352
+ }
353
+
354
+ async function confirmUpload(
355
+ apiKey: string,
356
+ fileId: string,
357
+ signal: AbortSignal | undefined,
358
+ deadline: number,
359
+ ): Promise<DatalabConfirmResponse> {
360
+ const response = await fetchDatalab(
361
+ `${getDatalabApiBase()}/files/${encodeURIComponent(fileId)}/confirm`,
362
+ {
363
+ method: "GET",
364
+ headers: { "x-api-key": apiKey },
365
+ signal: withTimeout(signal, remaining(deadline)),
366
+ },
367
+ apiKey,
368
+ );
369
+ return readJsonResponse(response, apiKey);
370
+ }
371
+
372
+ async function deleteDatalabFile(
373
+ apiKey: string,
374
+ fileId: string,
375
+ ): Promise<void> {
376
+ try {
377
+ await fetchDatalab(
378
+ `${getDatalabApiBase()}/files/${encodeURIComponent(fileId)}`,
379
+ {
380
+ method: "DELETE",
381
+ headers: { "x-api-key": apiKey },
382
+ signal: AbortSignal.timeout(CLEANUP_TIMEOUT_MS),
383
+ },
384
+ apiKey,
385
+ );
386
+ } catch {
387
+ // Best-effort cleanup; a leftover file is not worth failing the conversion.
388
+ }
389
+ }
390
+
391
+ function toResult(state: DatalabConversionState): DatalabPDFExtractResult {
392
+ const markdown = normalizeString(state.markdown);
393
+ if (!markdown) {
394
+ throw new Error("Datalab PDF conversion returned empty markdown");
395
+ }
396
+ const quality = state.parse_quality_score;
397
+ return {
398
+ markdown,
399
+ pages: numericField(state.page_count) ?? countPageMarkers(markdown),
400
+ ...(typeof quality === "number" && Number.isFinite(quality)
401
+ ? { parseQualityScore: quality }
402
+ : {}),
403
+ };
404
+ }
405
+
406
+ function numericField(value: unknown): number | null {
407
+ return typeof value === "number" && Number.isFinite(value) && value > 0
408
+ ? Math.floor(value)
409
+ : null;
410
+ }
411
+
412
+ function countPageMarkers(markdown: string): number {
413
+ return [...markdown.matchAll(/^<!-- Page (\d+) -->$/gm)].length;
414
+ }
415
+
416
+ function normalizeCheckUrl(value: unknown): string {
417
+ if (typeof value !== "string" || !value.trim()) {
418
+ throw new Error("Datalab PDF conversion failed: missing request_check_url");
419
+ }
420
+ const apiBase = getDatalabApiUrl();
421
+ let checkUrl: URL;
422
+ try {
423
+ checkUrl = new URL(value.trim(), apiBase);
424
+ } catch {
425
+ throw new Error("Datalab PDF conversion failed: invalid request_check_url");
426
+ }
427
+ if (checkUrl.origin !== apiBase.origin) {
428
+ throw new Error(
429
+ "Datalab PDF conversion failed: request_check_url has an unexpected origin",
430
+ );
431
+ }
432
+ return checkUrl.toString();
433
+ }
434
+
435
+ function getDatalabApiUrl(): URL {
436
+ try {
437
+ return new URL(getDatalabApiBase());
438
+ } catch {
439
+ throw new Error(
440
+ "Failed to parse DATALAB_API_BASE: expected an absolute URL",
441
+ );
442
+ }
443
+ }
444
+
445
+ function remaining(deadline: number): number {
446
+ return Math.max(1, deadline - Date.now());
447
+ }
448
+
449
+ function withTimeout(
450
+ signal: AbortSignal | undefined,
451
+ timeoutMs: number,
452
+ ): AbortSignal {
453
+ const timeout = AbortSignal.timeout(timeoutMs);
454
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
455
+ }
456
+
457
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
458
+ return new Promise((resolve, reject) => {
459
+ let timer: ReturnType<typeof setTimeout>;
460
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
461
+ const onTimeout = () => {
462
+ cleanup();
463
+ resolve();
464
+ };
465
+ const onAbort = () => {
466
+ clearTimeout(timer);
467
+ cleanup();
468
+ reject(signal?.reason);
469
+ };
470
+
471
+ if (signal?.aborted) {
472
+ onAbort();
473
+ return;
474
+ }
475
+ timer = setTimeout(onTimeout, ms);
476
+ signal?.addEventListener("abort", onAbort, { once: true });
477
+ });
478
+ }
479
+
480
+ async function fetchDatalab(
481
+ url: string,
482
+ init: RequestInit,
483
+ apiKey: string,
484
+ ): Promise<Response> {
485
+ try {
486
+ return await fetch(url, { ...init, redirect: init.redirect ?? "error" });
487
+ } catch (error) {
488
+ const message = error instanceof Error ? error.message : String(error);
489
+ const redacted = redactCredential(message, apiKey);
490
+ if (redacted === message) throw error;
491
+ const redactedError = new Error(redacted);
492
+ if (error instanceof Error) redactedError.name = error.name;
493
+ throw redactedError;
494
+ }
495
+ }
496
+
497
+ async function readJsonResponse(
498
+ response: Response,
499
+ apiKey: string,
500
+ ): Promise<Record<string, unknown>> {
501
+ const text = await readResponseText(response);
502
+ if (!response.ok) {
503
+ const detail = text.trim().slice(0, MAX_ERROR_BODY_BYTES);
504
+ const message = detail
505
+ ? `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}: ${detail}`
506
+ : `Datalab PDF conversion failed: HTTP ${response.status} ${response.statusText}`;
507
+ throw new Error(redactCredential(message, apiKey));
508
+ }
509
+ return parseJsonRecord(text);
510
+ }
511
+
512
+ function parseJsonRecord(text: string): Record<string, unknown> {
513
+ let parsed: unknown;
514
+ try {
515
+ parsed = JSON.parse(text);
516
+ } catch (error) {
517
+ throw new Error("Datalab PDF conversion returned invalid JSON", { cause: error });
518
+ }
519
+ if (Object.prototype.toString.call(parsed) !== "[object Object]") {
520
+ throw new Error("Datalab PDF conversion returned invalid JSON object");
521
+ }
522
+ return parsed as Record<string, unknown>;
523
+ }
524
+
525
+ async function readResponseText(response: Response): Promise<string> {
526
+ const contentLength = Number(response.headers.get("content-length"));
527
+ if (Number.isFinite(contentLength) && contentLength > MAX_RESPONSE_BYTES) {
528
+ throw new Error("Datalab PDF conversion response too large");
529
+ }
530
+ if (!response.body) return "";
531
+
532
+ const reader = response.body.getReader();
533
+ const decoder = new TextDecoder();
534
+ const chunks: string[] = [];
535
+ let bytesRead = 0;
536
+ try {
537
+ while (true) {
538
+ const { done, value } = await reader.read();
539
+ if (done) break;
540
+ bytesRead += value.byteLength;
541
+ if (bytesRead > MAX_RESPONSE_BYTES) {
542
+ try {
543
+ await reader.cancel();
544
+ } catch {
545
+ // The response is already too large; cancellation is best-effort.
546
+ }
547
+ throw new Error("Datalab PDF conversion response too large");
548
+ }
549
+ chunks.push(decoder.decode(value, { stream: true }));
550
+ }
551
+ chunks.push(decoder.decode());
552
+ return chunks.join("");
553
+ } finally {
554
+ reader.releaseLock();
555
+ }
556
+ }
557
+
558
+ function datalabFilename(title: string): string {
559
+ return (
560
+ title
561
+ .toLowerCase()
562
+ .replace(/[^a-z0-9\s-]/g, "")
563
+ .replace(/\s+/g, "-")
564
+ .replace(/-+/g, "-")
565
+ .replace(/^-|-$/g, "")
566
+ .slice(0, 60) || "document"
567
+ );
568
+ }