wiki-graph-sdk 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +32 -0
  3. package/dist/archives.cjs +2799 -0
  4. package/dist/archives.cjs.map +1 -0
  5. package/dist/archives.d.ts +249 -0
  6. package/dist/archives.js +2814 -0
  7. package/dist/archives.js.map +1 -0
  8. package/dist/conversions.cjs +1332 -0
  9. package/dist/conversions.cjs.map +1 -0
  10. package/dist/conversions.d.ts +37 -0
  11. package/dist/conversions.js +1308 -0
  12. package/dist/conversions.js.map +1 -0
  13. package/dist/data/editor/clue_reviewer.jinja +410 -0
  14. package/dist/data/editor/clue_reviewer_generator.jinja +428 -0
  15. package/dist/data/editor/revision_feedback.jinja +5 -0
  16. package/dist/data/editor/text_compressor.jinja +131 -0
  17. package/dist/data/guaranteed/response_intent_classifier.jinja +8 -0
  18. package/dist/data/output/epub/cover.xhtml.jinja +13 -0
  19. package/dist/data/output/epub/nav.xhtml.jinja +12 -0
  20. package/dist/data/output/epub/package.opf.xml.jinja +39 -0
  21. package/dist/data/output/epub/section.xhtml.jinja +12 -0
  22. package/dist/data/topologization/book_coherence_extraction.jinja +223 -0
  23. package/dist/data/topologization/chunk_extraction.jinja +233 -0
  24. package/dist/data/topologization/evidence_choice.jinja +38 -0
  25. package/dist/data/topologization/translate_chunks.jinja +138 -0
  26. package/dist/data/topologization/user_focused_extraction.jinja +378 -0
  27. package/dist/default-worker.cjs +1709 -0
  28. package/dist/default-worker.cjs.map +1 -0
  29. package/dist/default-worker.d.ts +10 -0
  30. package/dist/default-worker.js +1705 -0
  31. package/dist/default-worker.js.map +1 -0
  32. package/dist/embedding.cjs +1091 -0
  33. package/dist/embedding.cjs.map +1 -0
  34. package/dist/embedding.d.ts +26 -0
  35. package/dist/embedding.js +1062 -0
  36. package/dist/embedding.js.map +1 -0
  37. package/dist/entry-context.cjs +91 -0
  38. package/dist/entry-context.cjs.map +1 -0
  39. package/dist/entry-context.d.ts +20 -0
  40. package/dist/entry-context.js +68 -0
  41. package/dist/entry-context.js.map +1 -0
  42. package/dist/gc.cjs +731 -0
  43. package/dist/gc.cjs.map +1 -0
  44. package/dist/gc.d.ts +14 -0
  45. package/dist/gc.js +707 -0
  46. package/dist/gc.js.map +1 -0
  47. package/dist/index.cjs +4760 -0
  48. package/dist/index.cjs.map +1 -0
  49. package/dist/index.d.ts +213 -0
  50. package/dist/index.js +4808 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/jobs-Dd5PMSId.d.ts +98 -0
  53. package/dist/llm.cjs +101 -0
  54. package/dist/llm.cjs.map +1 -0
  55. package/dist/llm.d.ts +7 -0
  56. package/dist/llm.js +79 -0
  57. package/dist/llm.js.map +1 -0
  58. package/dist/local-config.cjs +1024 -0
  59. package/dist/local-config.cjs.map +1 -0
  60. package/dist/local-config.d.ts +14 -0
  61. package/dist/local-config.js +989 -0
  62. package/dist/local-config.js.map +1 -0
  63. package/dist/maintenance.cjs +800 -0
  64. package/dist/maintenance.cjs.map +1 -0
  65. package/dist/maintenance.d.ts +24 -0
  66. package/dist/maintenance.js +778 -0
  67. package/dist/maintenance.js.map +1 -0
  68. package/dist/node-platform.cjs +758 -0
  69. package/dist/node-platform.cjs.map +1 -0
  70. package/dist/node-platform.d.ts +49 -0
  71. package/dist/node-platform.js +723 -0
  72. package/dist/node-platform.js.map +1 -0
  73. package/dist/planning.cjs +164 -0
  74. package/dist/planning.cjs.map +1 -0
  75. package/dist/planning.d.ts +43 -0
  76. package/dist/planning.js +137 -0
  77. package/dist/planning.js.map +1 -0
  78. package/dist/runtime-config.cjs +1155 -0
  79. package/dist/runtime-config.cjs.map +1 -0
  80. package/dist/runtime-config.d.ts +50 -0
  81. package/dist/runtime-config.js +1127 -0
  82. package/dist/runtime-config.js.map +1 -0
  83. package/dist/stage.cjs +1265 -0
  84. package/dist/stage.cjs.map +1 -0
  85. package/dist/stage.d.ts +16 -0
  86. package/dist/stage.js +1239 -0
  87. package/dist/stage.js.map +1 -0
  88. package/dist/wikispine.cjs +85 -0
  89. package/dist/wikispine.cjs.map +1 -0
  90. package/dist/wikispine.d.ts +6 -0
  91. package/dist/wikispine.js +63 -0
  92. package/dist/wikispine.js.map +1 -0
  93. package/dist/worker.cjs +738 -0
  94. package/dist/worker.cjs.map +1 -0
  95. package/dist/worker.d.ts +157 -0
  96. package/dist/worker.js +715 -0
  97. package/dist/worker.js.map +1 -0
  98. package/package.json +151 -0
package/dist/stage.cjs ADDED
@@ -0,0 +1,1265 @@
1
+ globalThis.__WIKIGRAPH_DATA_DIR__ ??= require("path").resolve(__dirname, "data");
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/stage.ts
32
+ var stage_exports = {};
33
+ __export(stage_exports, {
34
+ DEFAULT_EXTRACTION_PROMPT: () => import_wiki_graph_core2.DEFAULT_EXTRACTION_PROMPT,
35
+ DEFAULT_KNOWLEDGE_GRAPH_RECALL_PROMPT: () => import_wiki_graph_core2.DEFAULT_KNOWLEDGE_GRAPH_RECALL_PROMPT,
36
+ createStageLLM: () => createStageLLM,
37
+ loadRequiredStageConfig: () => loadRequiredStageConfig,
38
+ resolveExtractionPrompt: () => import_wiki_graph_core2.resolveExtractionPrompt,
39
+ resolveKnowledgeGraphRecallPrompt: () => import_wiki_graph_core2.resolveKnowledgeGraphRecallPrompt
40
+ });
41
+ module.exports = __toCommonJS(stage_exports);
42
+ var import_wiki_graph_core2 = require("wiki-graph-core");
43
+ var import_wiki_graph_core3 = require("wiki-graph-core");
44
+ var import_wiki_graph_core4 = require("wiki-graph-core");
45
+
46
+ // src/runtime-config.ts
47
+ var import_zod = require("zod");
48
+
49
+ // src/local-config.ts
50
+ var import_wiki_graph_core = require("wiki-graph-core");
51
+
52
+ // src/runtime-context.ts
53
+ var import_async_hooks = require("async_hooks");
54
+ var RUNTIME_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.runtime-context.v1");
55
+ var runtimeContext = getRuntimeContextStorage();
56
+ function getRuntimeContextStorage() {
57
+ const runtimeGlobal = globalThis;
58
+ const existing = runtimeGlobal[RUNTIME_CONTEXT_KEY];
59
+ if (existing !== void 0) {
60
+ return existing;
61
+ }
62
+ const storage = new import_async_hooks.AsyncLocalStorage();
63
+ Object.defineProperty(runtimeGlobal, RUNTIME_CONTEXT_KEY, {
64
+ configurable: false,
65
+ enumerable: false,
66
+ value: storage,
67
+ writable: false
68
+ });
69
+ return storage;
70
+ }
71
+ function getWikiGraphSDKRuntimeContext() {
72
+ return runtimeContext.getStore() ?? {
73
+ cwd: process.cwd(),
74
+ env: process.env,
75
+ envPolicy: "production"
76
+ };
77
+ }
78
+ function getWikiGraphSDKStateDir() {
79
+ return getWikiGraphSDKRuntimeContext().stateDir;
80
+ }
81
+
82
+ // src/node-platform.ts
83
+ var asyncHooks = __toESM(require("async_hooks"), 1);
84
+ var crypto = __toESM(require("crypto"), 1);
85
+ var fs = __toESM(require("fs"), 1);
86
+ var fsPromises = __toESM(require("fs/promises"), 1);
87
+ var os = __toESM(require("os"), 1);
88
+ var pathModule = __toESM(require("path"), 1);
89
+ var process2 = __toESM(require("process"), 1);
90
+ var import_node_stream = require("stream");
91
+ var import_promises = require("stream/promises");
92
+ var sqlite3 = __toESM(require("sqlite3"), 1);
93
+ var yauzl = __toESM(require("yauzl"), 1);
94
+ var yazl = __toESM(require("yazl"), 1);
95
+ var import_nunjucks = require("nunjucks");
96
+ var import_platform = require("wiki-graph-core/platform");
97
+ var nodeProcess = process2.default ?? process2;
98
+ var nodeSqlite3 = sqlite3.default ?? sqlite3;
99
+ var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
100
+ var NodeFile = class {
101
+ constructor(path, name = pathModule.basename(path)) {
102
+ this.path = path;
103
+ this.identity = encodeNodeResourceIdentity("file", path);
104
+ this.name = name;
105
+ }
106
+ path;
107
+ kind = "file";
108
+ [NODE_RESOURCE_KIND] = "file";
109
+ identity;
110
+ name;
111
+ async openReader() {
112
+ const handle = await fsPromises.open(this.path, "r");
113
+ let closed = false;
114
+ try {
115
+ const stats = await handle.stat();
116
+ if (!stats.isFile())
117
+ throw new Error("File reader requires a regular file");
118
+ const { size } = stats;
119
+ return {
120
+ size,
121
+ close: async () => {
122
+ if (!closed) await handle.close();
123
+ closed = true;
124
+ },
125
+ read: async (offset, length) => {
126
+ if (closed) throw new Error("Cannot read from a closed FileReader");
127
+ assertFileRange(offset, length, size);
128
+ const buffer = Buffer.allocUnsafe(length);
129
+ let bytesRead = 0;
130
+ while (bytesRead < length) {
131
+ const result = await handle.read(
132
+ buffer,
133
+ bytesRead,
134
+ length - bytesRead,
135
+ offset + bytesRead
136
+ );
137
+ if (result.bytesRead === 0) {
138
+ throw new Error("File changed while reading its byte range");
139
+ }
140
+ bytesRead += result.bytesRead;
141
+ }
142
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, bytesRead);
143
+ }
144
+ };
145
+ } catch (error) {
146
+ await handle.close();
147
+ throw error;
148
+ }
149
+ }
150
+ async getLastModified() {
151
+ try {
152
+ return (await fsPromises.stat(this.path)).mtimeMs;
153
+ } catch (error) {
154
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
155
+ return void 0;
156
+ }
157
+ throw error;
158
+ }
159
+ }
160
+ async openWriter() {
161
+ await fsPromises.mkdir(pathModule.dirname(this.path), { recursive: true });
162
+ const temporary = `${this.path}.tmp-${crypto.randomUUID()}`;
163
+ const handle = await fsPromises.open(temporary, "wx");
164
+ let closed = false;
165
+ return {
166
+ write: async (data) => {
167
+ if (closed) throw new Error("Cannot write to a closed FileWriter");
168
+ await writeNodeFileHandle(handle, data);
169
+ },
170
+ writeAt: async (offset, data) => {
171
+ if (closed) throw new Error("Cannot write to a closed FileWriter");
172
+ assertFileOffset(offset);
173
+ await writeNodeFileHandle(handle, data, offset);
174
+ },
175
+ commit: async () => {
176
+ if (!closed) {
177
+ await handle.close();
178
+ await fsPromises.rename(temporary, this.path);
179
+ }
180
+ closed = true;
181
+ },
182
+ abort: async () => {
183
+ if (!closed) {
184
+ await handle.close();
185
+ await fsPromises.rm(temporary, { force: true });
186
+ }
187
+ closed = true;
188
+ }
189
+ };
190
+ }
191
+ };
192
+ async function writeNodeFileHandle(handle, data, position) {
193
+ const buffer = Buffer.from(data);
194
+ let written = 0;
195
+ while (written < buffer.byteLength) {
196
+ const result = await handle.write(
197
+ buffer,
198
+ written,
199
+ buffer.byteLength - written,
200
+ position === void 0 ? null : position + written
201
+ );
202
+ if (result.bytesWritten === 0) {
203
+ throw new Error("File writer made no progress");
204
+ }
205
+ written += result.bytesWritten;
206
+ }
207
+ }
208
+ function assertFileRange(offset, length, size) {
209
+ assertFileOffset(offset);
210
+ if (!Number.isSafeInteger(length) || length < 0) {
211
+ throw new RangeError(
212
+ "File read length must be a non-negative safe integer"
213
+ );
214
+ }
215
+ if (offset > size || length > size - offset) {
216
+ throw new RangeError("File read range exceeds the file size");
217
+ }
218
+ }
219
+ function assertFileOffset(offset) {
220
+ if (!Number.isSafeInteger(offset) || offset < 0) {
221
+ throw new RangeError("File offset must be a non-negative safe integer");
222
+ }
223
+ }
224
+ var NodeDirectory = class _NodeDirectory {
225
+ constructor(path) {
226
+ this.path = path;
227
+ this.identity = encodeNodeResourceIdentity("directory", path);
228
+ this.name = pathModule.basename(path);
229
+ }
230
+ path;
231
+ kind = "directory";
232
+ [NODE_RESOURCE_KIND] = "directory";
233
+ identity;
234
+ name;
235
+ async getFile(name) {
236
+ assertChildName(name);
237
+ const file = new NodeFile(pathModule.join(this.path, name));
238
+ try {
239
+ return (await fsPromises.stat(file.path)).isFile() ? file : void 0;
240
+ } catch {
241
+ return void 0;
242
+ }
243
+ }
244
+ async getLastModified() {
245
+ try {
246
+ return (await fsPromises.stat(this.path)).mtimeMs;
247
+ } catch (error) {
248
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
249
+ return void 0;
250
+ }
251
+ throw error;
252
+ }
253
+ }
254
+ async getDirectory(name) {
255
+ assertChildName(name);
256
+ const directory = new _NodeDirectory(pathModule.join(this.path, name));
257
+ try {
258
+ return (await fsPromises.stat(directory.path)).isDirectory() ? directory : void 0;
259
+ } catch {
260
+ return void 0;
261
+ }
262
+ }
263
+ async list() {
264
+ const entries = await fsPromises.readdir(this.path, {
265
+ withFileTypes: true
266
+ });
267
+ return entries.map(
268
+ (entry) => entry.isDirectory() ? new _NodeDirectory(pathModule.join(this.path, entry.name)) : new NodeFile(pathModule.join(this.path, entry.name), entry.name)
269
+ );
270
+ }
271
+ async createFile(name) {
272
+ assertChildName(name);
273
+ await fsPromises.mkdir(this.path, { recursive: true });
274
+ const file = new NodeFile(pathModule.join(this.path, name));
275
+ await fsPromises.writeFile(file.path, "", { flag: "wx" });
276
+ return file;
277
+ }
278
+ async createDirectory(name) {
279
+ assertChildName(name);
280
+ await fsPromises.mkdir(this.path, { recursive: true });
281
+ const directory = new _NodeDirectory(pathModule.join(this.path, name));
282
+ await fsPromises.mkdir(directory.path);
283
+ return directory;
284
+ }
285
+ async remove(name, options) {
286
+ assertChildName(name);
287
+ await fsPromises.rm(pathModule.join(this.path, name), {
288
+ force: true,
289
+ recursive: options?.recursive === true
290
+ });
291
+ }
292
+ };
293
+ function encodeNodeResourceIdentity(kind, path) {
294
+ return `node-${kind}:${Buffer.from(pathModule.resolve(path), "utf8").toString("base64url")}`;
295
+ }
296
+ function decodeNodeResourceIdentity(identity, kind) {
297
+ const prefix = `node-${kind}:`;
298
+ if (!identity.startsWith(prefix)) {
299
+ return pathModule.isAbsolute(identity) ? identity : void 0;
300
+ }
301
+ try {
302
+ return Buffer.from(identity.slice(prefix.length), "base64url").toString(
303
+ "utf8"
304
+ );
305
+ } catch {
306
+ return void 0;
307
+ }
308
+ }
309
+ function assertChildName(name) {
310
+ if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
311
+ throw new TypeError(`Directory child must be a relative name: ${name}`);
312
+ }
313
+ }
314
+ var NodeDatabaseConnection = class {
315
+ constructor(database) {
316
+ this.database = database;
317
+ }
318
+ database;
319
+ async close() {
320
+ await new Promise((resolve2, reject) => {
321
+ this.database.close((error) => {
322
+ if (error) reject(error);
323
+ else resolve2();
324
+ });
325
+ });
326
+ }
327
+ async execute(sql) {
328
+ await new Promise((resolve2, reject) => {
329
+ this.database.exec(sql, (error) => {
330
+ if (error) reject(error);
331
+ else resolve2();
332
+ });
333
+ });
334
+ }
335
+ async queryAll(sql, params = []) {
336
+ return await new Promise((resolve2, reject) => {
337
+ this.database.all(sql, [...params], (error, rows) => {
338
+ if (error) reject(error);
339
+ else resolve2(rows);
340
+ });
341
+ });
342
+ }
343
+ async queryOne(sql, params = []) {
344
+ return await new Promise((resolve2, reject) => {
345
+ this.database.get(sql, [...params], (error, row) => {
346
+ if (error) reject(error);
347
+ else resolve2(row);
348
+ });
349
+ });
350
+ }
351
+ async run(sql, params = []) {
352
+ await new Promise((resolve2, reject) => {
353
+ this.database.run(sql, [...params], (error) => {
354
+ if (error) reject(error);
355
+ else resolve2();
356
+ });
357
+ });
358
+ }
359
+ };
360
+ async function openNodeDatabase(file, options) {
361
+ const flags = (options.mode === "readonly" ? nodeSqlite3.OPEN_READONLY : nodeSqlite3.OPEN_READWRITE | (options.create ? nodeSqlite3.OPEN_CREATE : 0)) | nodeSqlite3.OPEN_FULLMUTEX;
362
+ return new NodeDatabaseConnection(await openNativeNodeDatabase(file, flags));
363
+ }
364
+ async function openNativeNodeDatabase(file, flags) {
365
+ const path = getBrandedNodeResourcePath(file, "file");
366
+ if (path === void 0) {
367
+ throw new TypeError("The Node database adapter requires a NodeFile");
368
+ }
369
+ return await new Promise((resolve2, reject) => {
370
+ const database = new nodeSqlite3.Database(path, flags, (error) => {
371
+ if (error) reject(error);
372
+ else resolve2(database);
373
+ });
374
+ });
375
+ }
376
+ async function openNodeZip(file) {
377
+ const path = getBrandedNodeResourcePath(file, "file");
378
+ if (path === void 0) {
379
+ throw new TypeError("The Node ZIP adapter requires a NodeFile");
380
+ }
381
+ const zipFile = await new Promise((resolve2, reject) => {
382
+ yauzl.open(
383
+ path,
384
+ { autoClose: false, lazyEntries: true },
385
+ (error, opened) => {
386
+ if (error || opened === void 0)
387
+ reject(error ?? new Error("Cannot open ZIP"));
388
+ else resolve2(opened);
389
+ }
390
+ );
391
+ });
392
+ const entries = await new Promise(
393
+ (resolve2, reject) => {
394
+ const discovered = /* @__PURE__ */ new Map();
395
+ const rejectAndClose = (error) => {
396
+ zipFile.close();
397
+ reject(
398
+ error instanceof Error ? error : new Error("Cannot scan ZIP central directory")
399
+ );
400
+ };
401
+ const resolveEntries = () => {
402
+ zipFile.off("error", rejectAndClose);
403
+ resolve2(discovered);
404
+ };
405
+ zipFile.on("entry", (entry) => {
406
+ if (!entry.fileName.endsWith("/")) {
407
+ discovered.set(entry.fileName, entry);
408
+ }
409
+ zipFile.readEntry();
410
+ });
411
+ zipFile.once("error", rejectAndClose);
412
+ zipFile.once("end", resolveEntries);
413
+ zipFile.readEntry();
414
+ }
415
+ );
416
+ let closed = false;
417
+ return {
418
+ close: () => {
419
+ if (!closed) zipFile.close();
420
+ closed = true;
421
+ return Promise.resolve();
422
+ },
423
+ copyEntry: async (name, target) => {
424
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
425
+ const entry = entries.get(name);
426
+ if (entry === void 0) return false;
427
+ await copyNodeZipEntry(zipFile, entry, target);
428
+ return true;
429
+ },
430
+ getEntrySize: (name) => {
431
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
432
+ return Promise.resolve(entries.get(name)?.uncompressedSize);
433
+ },
434
+ listEntries: () => Promise.resolve([...entries.keys()]),
435
+ readEntryRange: async (name, offset, length) => {
436
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
437
+ const entry = entries.get(name);
438
+ if (entry === void 0) return void 0;
439
+ return await readNodeZipEntryRange(zipFile, entry, offset, length);
440
+ },
441
+ readEntry: async (name) => {
442
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
443
+ const entry = entries.get(name);
444
+ if (entry === void 0) return void 0;
445
+ return await readNodeZipEntry(zipFile, entry);
446
+ }
447
+ };
448
+ }
449
+ async function copyNodeZipEntry(zipFile, entry, target) {
450
+ const writer = await target.openWriter();
451
+ try {
452
+ const stream = await openNodeZipEntryStream(zipFile, entry);
453
+ await writeNodeStream(stream, writer);
454
+ await writer.commit();
455
+ } catch (error) {
456
+ await writer.abort().catch(() => void 0);
457
+ throw error;
458
+ }
459
+ }
460
+ async function readNodeZipEntry(zipFile, entry) {
461
+ return await collectNodeStream(await openNodeZipEntryStream(zipFile, entry));
462
+ }
463
+ async function readNodeZipEntryRange(zipFile, entry, offset, length) {
464
+ assertFileRange(offset, length, entry.uncompressedSize);
465
+ if (length === 0) return new Uint8Array();
466
+ if (entry.compressionMethod !== 0) {
467
+ const content2 = await collectDecodedNodeStreamRange(
468
+ await openNodeZipEntryStream(zipFile, entry),
469
+ offset,
470
+ length
471
+ );
472
+ return new Uint8Array(
473
+ content2.buffer,
474
+ content2.byteOffset,
475
+ content2.byteLength
476
+ );
477
+ }
478
+ const content = await collectNodeStream(
479
+ await openNodeZipEntryStream(zipFile, entry, {
480
+ decompress: null,
481
+ decrypt: null,
482
+ end: offset + length,
483
+ start: offset
484
+ })
485
+ );
486
+ return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
487
+ }
488
+ async function collectDecodedNodeStreamRange(input, offset, length) {
489
+ const chunks = [];
490
+ const end = offset + length;
491
+ let position = 0;
492
+ let collected = 0;
493
+ for await (const value of input) {
494
+ const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
495
+ const chunkEnd = position + chunk.byteLength;
496
+ if (chunkEnd > offset && position < end) {
497
+ const selected = chunk.subarray(
498
+ Math.max(0, offset - position),
499
+ Math.min(chunk.byteLength, end - position)
500
+ );
501
+ chunks.push(selected);
502
+ collected += selected.byteLength;
503
+ }
504
+ position = chunkEnd;
505
+ if (position >= end) break;
506
+ }
507
+ if (collected !== length) {
508
+ throw new Error("ZIP entry changed while reading its byte range");
509
+ }
510
+ return Buffer.concat(chunks, collected);
511
+ }
512
+ async function openNodeZipEntryStream(zipFile, entry, options) {
513
+ return await new Promise((resolve2, reject) => {
514
+ const callback = (error, opened) => {
515
+ if (error || opened === void 0) {
516
+ reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
517
+ } else {
518
+ resolve2(opened);
519
+ }
520
+ };
521
+ if (options === void 0) zipFile.openReadStream(entry, callback);
522
+ else zipFile.openReadStream(entry, options, callback);
523
+ });
524
+ }
525
+ async function writeNodeZip(file, entries) {
526
+ const zipFile = new yazl.ZipFile();
527
+ const writer = await file.openWriter();
528
+ const outputStream = zipFile.outputStream;
529
+ const outputDone = writeNodeStream(outputStream, writer);
530
+ const entryState = { cancelled: false, complete: false };
531
+ let iterator;
532
+ try {
533
+ iterator = getNodeZipEntryIterator(entries);
534
+ const entriesDone = addNodeZipEntries(zipFile, iterator, entryState);
535
+ await Promise.race([entriesDone, outputDone]);
536
+ if (!entryState.complete) {
537
+ throw new Error("ZIP output ended before entry production completed");
538
+ }
539
+ zipFile.end();
540
+ await outputDone;
541
+ await writer.commit();
542
+ } catch (error) {
543
+ entryState.cancelled = true;
544
+ if (!entryState.complete && iterator !== void 0) {
545
+ closeNodeZipEntryIterator(iterator);
546
+ }
547
+ if (!outputStream.destroyed) {
548
+ outputStream.destroy(
549
+ error instanceof Error ? error : new Error("Cannot write ZIP archive")
550
+ );
551
+ }
552
+ await outputDone.catch(() => void 0);
553
+ await writer.abort().catch(() => void 0);
554
+ throw error;
555
+ }
556
+ }
557
+ async function addNodeZipEntries(zipFile, iterator, state) {
558
+ while (!state.cancelled) {
559
+ const result = await iterator.next();
560
+ if (state.cancelled) return;
561
+ if (result.done) {
562
+ state.complete = true;
563
+ return;
564
+ }
565
+ if ("file" in result.value) {
566
+ zipFile.addReadStream(
567
+ createNodeFileReadStream(result.value.file),
568
+ result.value.name,
569
+ { compress: false }
570
+ );
571
+ } else if ("data" in result.value) {
572
+ zipFile.addBuffer(Buffer.from(result.value.data), result.value.name, {
573
+ compress: false
574
+ });
575
+ } else {
576
+ zipFile.addReadStream(
577
+ createNodeRangeReadStream(result.value),
578
+ result.value.name,
579
+ { compress: false, size: result.value.size }
580
+ );
581
+ }
582
+ }
583
+ }
584
+ function createNodeFileReadStream(file) {
585
+ return import_node_stream.Readable.from(
586
+ (async function* () {
587
+ const reader = await file.openReader();
588
+ try {
589
+ for (let offset = 0; offset < reader.size; ) {
590
+ const chunk = await reader.read(
591
+ offset,
592
+ Math.min(64 * 1024, reader.size - offset)
593
+ );
594
+ offset += chunk.byteLength;
595
+ yield chunk;
596
+ }
597
+ } finally {
598
+ await reader.close();
599
+ }
600
+ })()
601
+ );
602
+ }
603
+ function getBrandedNodeResourcePath(resource, kind) {
604
+ if (typeof resource !== "object" || resource === null) return void 0;
605
+ const candidate = resource;
606
+ return candidate[NODE_RESOURCE_KIND] === kind && typeof candidate.path === "string" ? candidate.path : void 0;
607
+ }
608
+ function createNodeRangeReadStream(entry) {
609
+ return import_node_stream.Readable.from(
610
+ (async function* () {
611
+ for (let offset = 0; offset < entry.size; ) {
612
+ const chunk = await entry.read(
613
+ offset,
614
+ Math.min(64 * 1024, entry.size - offset)
615
+ );
616
+ offset += chunk.byteLength;
617
+ yield chunk;
618
+ }
619
+ })()
620
+ );
621
+ }
622
+ function getNodeZipEntryIterator(entries) {
623
+ const asyncIterator = entries[Symbol.asyncIterator];
624
+ return asyncIterator === void 0 ? entries[Symbol.iterator]() : asyncIterator.call(entries);
625
+ }
626
+ function closeNodeZipEntryIterator(iterator) {
627
+ if (iterator.return === void 0) return;
628
+ try {
629
+ void Promise.resolve(iterator.return()).catch(() => void 0);
630
+ } catch {
631
+ }
632
+ }
633
+ async function writeNodeStream(input, writer) {
634
+ await (0, import_promises.pipeline)(
635
+ input,
636
+ new import_node_stream.Writable({
637
+ write: (chunk, _encoding, callback) => {
638
+ void writer.write(chunk).then(
639
+ () => callback(),
640
+ (error) => callback(
641
+ error instanceof Error ? error : new Error("Cannot stream ZIP archive")
642
+ )
643
+ );
644
+ }
645
+ })
646
+ );
647
+ }
648
+ async function collectNodeStream(input) {
649
+ return await new Promise((resolve2, reject) => {
650
+ const chunks = [];
651
+ input.on("data", (chunk) => chunks.push(chunk));
652
+ input.once("error", reject);
653
+ input.once("end", () => resolve2(Buffer.concat(chunks)));
654
+ });
655
+ }
656
+ var nodeWikiGraphPlatform = {
657
+ asyncContext: {
658
+ create: () => new asyncHooks.AsyncLocalStorage()
659
+ },
660
+ database: { open: openNodeDatabase },
661
+ lifecycle: {
662
+ instanceId: `node-process:${nodeProcess.pid}`,
663
+ isInstanceAlive: (instanceId) => {
664
+ const match = /^node-process:(\d+)$/u.exec(instanceId);
665
+ if (match === null) return Promise.resolve(void 0);
666
+ try {
667
+ nodeProcess.kill(Number(match[1]), 0);
668
+ return Promise.resolve(true);
669
+ } catch (error) {
670
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH") {
671
+ return Promise.resolve(false);
672
+ }
673
+ return Promise.resolve(true);
674
+ }
675
+ }
676
+ },
677
+ resources: {
678
+ getDirectory: (identity) => {
679
+ const path = decodeNodeResourceIdentity(identity, "directory");
680
+ return Promise.resolve(
681
+ path === void 0 ? void 0 : new NodeDirectory(path)
682
+ );
683
+ },
684
+ getFile: (identity) => {
685
+ const path = decodeNodeResourceIdentity(identity, "file");
686
+ return Promise.resolve(
687
+ path === void 0 ? void 0 : new NodeFile(path)
688
+ );
689
+ },
690
+ resolveLegacyDirectory: (reference) => {
691
+ const path = decodeNodeResourceIdentity(reference, "directory");
692
+ return Promise.resolve(
693
+ path === void 0 ? void 0 : new NodeDirectory(path)
694
+ );
695
+ }
696
+ },
697
+ templates: {
698
+ createEnvironment: (options) => new import_nunjucks.Environment(new NodeTemplateLoader(), options)
699
+ },
700
+ zip: {
701
+ open: openNodeZip,
702
+ write: writeNodeZip
703
+ }
704
+ };
705
+ var NodeTemplateLoader = class extends import_nunjucks.Loader {
706
+ #dataDirectory;
707
+ constructor(dataDirectory) {
708
+ super();
709
+ this.#dataDirectory = dataDirectory;
710
+ }
711
+ getSource(templateName) {
712
+ const name = (0, import_platform.normalizeTemplateName)(templateName);
713
+ const filePath = pathModule.join(
714
+ this.#dataDirectory ?? resolveNodeDataDirectory(),
715
+ name
716
+ );
717
+ return {
718
+ noCache: false,
719
+ path: name,
720
+ src: fs.readFileSync(filePath, "utf8")
721
+ };
722
+ }
723
+ };
724
+ function resolveNodeDataDirectory() {
725
+ const injected = globalThis.__WIKIGRAPH_DATA_DIR__;
726
+ if (typeof injected === "string" && injected !== "") return injected;
727
+ let directory = nodeProcess.cwd();
728
+ while (true) {
729
+ for (const candidate of [
730
+ pathModule.join(directory, "data"),
731
+ pathModule.join(directory, "packages", "core", "data")
732
+ ]) {
733
+ try {
734
+ if (fs.statSync(candidate).isDirectory()) return candidate;
735
+ } catch {
736
+ }
737
+ }
738
+ const parent = pathModule.dirname(directory);
739
+ if (parent === directory)
740
+ throw new Error("Could not locate data directory");
741
+ directory = parent;
742
+ }
743
+ }
744
+
745
+ // src/local-config.ts
746
+ var import_path = require("path");
747
+ var import_os = require("os");
748
+ var LOCAL_CONFIG_SCHEMA_SQL = `
749
+ CREATE TABLE IF NOT EXISTS config_sections (
750
+ section TEXT PRIMARY KEY,
751
+ value_json TEXT NOT NULL,
752
+ updated_at INTEGER NOT NULL
753
+ );
754
+ `;
755
+ async function readLocalConfigSection(section) {
756
+ return await withLocalConfigDatabase(async (database) => {
757
+ return await readLocalConfigSectionInDatabase(database, section);
758
+ });
759
+ }
760
+ function validateLocalConfigSection(section, value) {
761
+ switch (section) {
762
+ case "embeddings":
763
+ return validateEmbeddingsConfig(value);
764
+ case "llm":
765
+ return validateLLMConfig(value);
766
+ case "concurrent":
767
+ return validateConcurrentConfig(value);
768
+ case "wikimedia":
769
+ return validateWikimediaConfig(value);
770
+ case "wikispine":
771
+ return validateWikispineConfig(value);
772
+ }
773
+ }
774
+ async function withLocalConfigDatabase(operation) {
775
+ const database = await (0, import_wiki_graph_core.openSharedStateDatabase)(
776
+ new NodeFile(
777
+ (0, import_path.join)(
778
+ getWikiGraphSDKStateDir() ?? (0, import_path.join)((0, import_os.homedir)(), ".wikigraph"),
779
+ "core.sqlite"
780
+ )
781
+ ),
782
+ LOCAL_CONFIG_SCHEMA_SQL
783
+ );
784
+ try {
785
+ return await operation(database);
786
+ } finally {
787
+ await database.close();
788
+ }
789
+ }
790
+ async function readLocalConfigSectionInDatabase(database, section) {
791
+ const value = await database.queryOne(
792
+ "SELECT value_json FROM config_sections WHERE section = ?",
793
+ [section],
794
+ (row) => String(row.value_json)
795
+ );
796
+ return value === void 0 ? {} : parseSectionJSON(section, value);
797
+ }
798
+ function parseSectionJSON(section, value) {
799
+ let parsed;
800
+ try {
801
+ parsed = JSON.parse(value);
802
+ } catch (error) {
803
+ throw new Error(
804
+ `Invalid local config JSON for ${section}: ${formatError(error)}`
805
+ );
806
+ }
807
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
808
+ throw new Error(
809
+ `Invalid local config section ${section}: expected object.`
810
+ );
811
+ }
812
+ return validateLocalConfigSection(section, parsed);
813
+ }
814
+ function validateEmbeddingsConfig(value) {
815
+ const allowedKeys = /* @__PURE__ */ new Set([
816
+ "apiKey",
817
+ "baseURL",
818
+ "dimensions",
819
+ "model",
820
+ "name",
821
+ "provider"
822
+ ]);
823
+ const allowedProviders = /* @__PURE__ */ new Set(["openai", "openai-compatible"]);
824
+ const next = {};
825
+ for (const [key, entry] of Object.entries(value)) {
826
+ if (!allowedKeys.has(key)) {
827
+ throw new Error(`Unknown embeddings config key: ${key}`);
828
+ }
829
+ if (key === "dimensions") {
830
+ const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
831
+ if (!Number.isInteger(parsed) || parsed <= 0) {
832
+ throw new Error("embeddings.dimensions must be a positive integer.");
833
+ }
834
+ next[key] = parsed;
835
+ continue;
836
+ }
837
+ if (typeof entry !== "string" || entry.trim() === "") {
838
+ throw new Error(`embeddings.${key} must be a non-empty string.`);
839
+ }
840
+ const normalized = entry.trim();
841
+ if (key === "provider" && !allowedProviders.has(normalized)) {
842
+ throw new Error(`Unknown embeddings.provider: ${normalized}`);
843
+ }
844
+ next[key] = normalized;
845
+ }
846
+ return next;
847
+ }
848
+ function validateLLMConfig(value) {
849
+ const allowedKeys = /* @__PURE__ */ new Set([
850
+ "apiKey",
851
+ "baseURL",
852
+ "model",
853
+ "name",
854
+ "provider"
855
+ ]);
856
+ const allowedProviders = /* @__PURE__ */ new Set([
857
+ "anthropic",
858
+ "google",
859
+ "openai",
860
+ "openai-compatible"
861
+ ]);
862
+ const next = {};
863
+ for (const [key, entry] of Object.entries(value)) {
864
+ if (!allowedKeys.has(key)) {
865
+ throw new Error(`Unknown llm config key: ${key}`);
866
+ }
867
+ if (typeof entry !== "string" || entry.trim() === "") {
868
+ throw new Error(`llm.${key} must be a non-empty string.`);
869
+ }
870
+ const normalized = entry.trim();
871
+ if (key === "provider" && !allowedProviders.has(normalized)) {
872
+ throw new Error(`Unknown llm.provider: ${normalized}`);
873
+ }
874
+ next[key] = normalized;
875
+ }
876
+ return next;
877
+ }
878
+ function validateConcurrentConfig(value) {
879
+ const allowedKeys = /* @__PURE__ */ new Set(["job", "request"]);
880
+ const next = {};
881
+ for (const [key, entry] of Object.entries(value)) {
882
+ if (!allowedKeys.has(key)) {
883
+ throw new Error(`Unknown concurrent config key: ${key}`);
884
+ }
885
+ const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
886
+ if (!Number.isInteger(parsed) || parsed <= 0) {
887
+ throw new Error(`concurrent.${key} must be a positive integer.`);
888
+ }
889
+ next[key] = parsed;
890
+ }
891
+ return next;
892
+ }
893
+ function validateWikispineConfig(value) {
894
+ const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "provider", "token"]);
895
+ const allowedProviders = /* @__PURE__ */ new Set(["cli", "fetch"]);
896
+ const next = {};
897
+ for (const [key, entry] of Object.entries(value)) {
898
+ if (!allowedKeys.has(key)) {
899
+ throw new Error(`Unknown wikispine config key: ${key}`);
900
+ }
901
+ if (typeof entry !== "string" || entry.trim() === "") {
902
+ throw new Error(`wikispine.${key} must be a non-empty string.`);
903
+ }
904
+ const normalized = entry.trim();
905
+ if (key === "provider" && !allowedProviders.has(normalized)) {
906
+ throw new Error(`Unknown wikispine.provider: ${normalized}`);
907
+ }
908
+ next[key] = normalized;
909
+ }
910
+ return next;
911
+ }
912
+ function validateWikimediaConfig(value) {
913
+ return validateEndpointConfig("wikimedia", value);
914
+ }
915
+ function validateEndpointConfig(section, value) {
916
+ const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "token"]);
917
+ const next = {};
918
+ for (const [key, entry] of Object.entries(value)) {
919
+ if (!allowedKeys.has(key)) {
920
+ throw new Error(`Unknown ${section} config key: ${key}`);
921
+ }
922
+ if (typeof entry !== "string" || entry.trim() === "") {
923
+ throw new Error(`${section}.${key} must be a non-empty string.`);
924
+ }
925
+ next[key] = entry.trim();
926
+ }
927
+ return next;
928
+ }
929
+ function formatError(error) {
930
+ return error instanceof Error ? error.message : String(error);
931
+ }
932
+
933
+ // src/runtime-config.ts
934
+ var WIKI_GRAPH_PROVIDER_VALUES = [
935
+ "anthropic",
936
+ "google",
937
+ "openai",
938
+ "openai-compatible"
939
+ ];
940
+ var wikiGraphProviderSchema = import_zod.z.enum(WIKI_GRAPH_PROVIDER_VALUES);
941
+ var inlineLLMConfigSchema = import_zod.z.object({
942
+ apiKey: import_zod.z.string().min(1).optional(),
943
+ baseURL: import_zod.z.string().min(1).optional(),
944
+ baseUrl: import_zod.z.string().min(1).optional(),
945
+ chatCompletionsUrl: import_zod.z.string().min(1).optional(),
946
+ llm: import_zod.z.object({
947
+ apiKey: import_zod.z.string().min(1).optional(),
948
+ baseURL: import_zod.z.string().min(1).optional(),
949
+ baseUrl: import_zod.z.string().min(1).optional(),
950
+ chatCompletionsUrl: import_zod.z.string().min(1).optional(),
951
+ model: import_zod.z.string().min(1).optional(),
952
+ name: import_zod.z.string().min(1).optional(),
953
+ provider: wikiGraphProviderSchema.optional()
954
+ }).optional(),
955
+ model: import_zod.z.string().min(1).optional(),
956
+ name: import_zod.z.string().min(1).optional(),
957
+ provider: wikiGraphProviderSchema.optional()
958
+ });
959
+ async function loadWikiGraphRuntimeConfig(options) {
960
+ const [embedding, localLLM, concurrent, wikimedia, wikispine] = await Promise.all([
961
+ readLocalConfigSection("embeddings"),
962
+ readLocalConfigSection("llm"),
963
+ readLocalConfigSection("concurrent"),
964
+ readLocalConfigSection("wikimedia"),
965
+ readLocalConfigSection("wikispine")
966
+ ]);
967
+ const inlineLLMConfig = options?.llmJSON === void 0 ? void 0 : parseInlineLLMConfig(options.llmJSON);
968
+ const llm = createLLMConfig({
969
+ apiKey: firstDefined(inlineLLMConfig?.apiKey, readString(localLLM.apiKey)),
970
+ baseURL: firstDefined(
971
+ inlineLLMConfig?.baseURL,
972
+ readString(localLLM.baseURL)
973
+ ),
974
+ model: firstDefined(inlineLLMConfig?.model, readString(localLLM.model)),
975
+ name: firstDefined(inlineLLMConfig?.name, readString(localLLM.name)),
976
+ provider: firstDefined(
977
+ inlineLLMConfig?.provider,
978
+ readProvider(localLLM.provider)
979
+ )
980
+ });
981
+ const requestConcurrent = readPositiveInteger(concurrent.request);
982
+ const jobConcurrent = readPositiveInteger(concurrent.job);
983
+ const envPolicy = getWikiGraphSDKRuntimeContext().envPolicy;
984
+ const wikispineConfig = resolveWikispineConfig(wikispine, envPolicy);
985
+ const wikimediaConfig = createWikimediaConfig(wikimedia, envPolicy);
986
+ const embeddingConfig = createEmbeddingConfig(embedding);
987
+ return {
988
+ ...jobConcurrent === void 0 && requestConcurrent === void 0 ? {} : {
989
+ concurrent: {
990
+ ...jobConcurrent === void 0 ? {} : { job: jobConcurrent },
991
+ ...requestConcurrent === void 0 ? {} : { request: requestConcurrent }
992
+ }
993
+ },
994
+ ...embeddingConfig === void 0 ? {} : { embedding: embeddingConfig },
995
+ ...llm === void 0 ? {} : { llm },
996
+ ...wikimediaConfig === void 0 ? {} : { wikimedia: wikimediaConfig },
997
+ ...wikispineConfig === void 0 ? {} : { wikispine: wikispineConfig }
998
+ };
999
+ }
1000
+ function createWikimediaConfig(input, envPolicy) {
1001
+ const endpoint = readString(input?.endpoint);
1002
+ const token = readString(input?.token);
1003
+ if (endpoint === void 0 && token === void 0) return void 0;
1004
+ if (token === void 0) {
1005
+ throw new Error(
1006
+ "Remote Wikimedia access requires an API key. Configure `wikg://local/config/wikimedia` token with `put token --secret`."
1007
+ );
1008
+ }
1009
+ return {
1010
+ endpoint: endpoint ?? resolveHostedProviderEndpoint("wg-wikimedia", envPolicy),
1011
+ token
1012
+ };
1013
+ }
1014
+ function createEmbeddingConfig(input) {
1015
+ const value = input ?? {};
1016
+ const provider = readEmbeddingProvider(value.provider);
1017
+ const apiKey = readString(value.apiKey);
1018
+ const baseURL = readString(value.baseURL);
1019
+ const dimensions = typeof value.dimensions === "number" && Number.isInteger(value.dimensions) && value.dimensions > 0 ? value.dimensions : void 0;
1020
+ const model = readString(value.model);
1021
+ const name = readString(value.name);
1022
+ if (provider === void 0 || model === void 0 || provider === "openai-compatible" && baseURL === void 0 || provider === "openai" && baseURL !== void 0) {
1023
+ return void 0;
1024
+ }
1025
+ return {
1026
+ ...apiKey === void 0 ? {} : { apiKey },
1027
+ ...baseURL === void 0 ? {} : { baseURL },
1028
+ ...dimensions === void 0 ? {} : { dimensions },
1029
+ ...model === void 0 ? {} : { model },
1030
+ ...name === void 0 ? {} : { name },
1031
+ ...provider === void 0 ? {} : { provider }
1032
+ };
1033
+ }
1034
+ function parseInlineLLMConfig(value) {
1035
+ const normalized = normalizeString(value);
1036
+ if (normalized === void 0) {
1037
+ throw new Error("--llm must be a non-empty JSON object.");
1038
+ }
1039
+ let parsedJson;
1040
+ try {
1041
+ parsedJson = JSON.parse(normalized);
1042
+ } catch (error) {
1043
+ throw new Error(`Invalid --llm JSON: ${formatError2(error)}`);
1044
+ }
1045
+ const parsed = inlineLLMConfigSchema.safeParse(parsedJson);
1046
+ if (!parsed.success) {
1047
+ throw new Error(
1048
+ `Invalid --llm config: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ")}`
1049
+ );
1050
+ }
1051
+ const input = parsed.data.llm ?? parsed.data;
1052
+ const provider = input.provider ?? inferInlineProvider(input);
1053
+ const baseURL = resolveInlineBaseURL(input);
1054
+ const config = createLLMConfig({
1055
+ apiKey: input.apiKey,
1056
+ baseURL,
1057
+ model: input.model,
1058
+ name: input.name,
1059
+ provider
1060
+ });
1061
+ if (config === void 0) {
1062
+ throw new Error("--llm must contain at least one supported LLM field.");
1063
+ }
1064
+ return config;
1065
+ }
1066
+ function inferInlineProvider(input) {
1067
+ if (input.provider === void 0 && (input.baseURL !== void 0 || input.baseUrl !== void 0 || input.chatCompletionsUrl !== void 0)) {
1068
+ return "openai-compatible";
1069
+ }
1070
+ return input.provider;
1071
+ }
1072
+ function inferBaseURLFromChatCompletionsURL(input) {
1073
+ if (input.chatCompletionsUrl === void 0) {
1074
+ return void 0;
1075
+ }
1076
+ const suffix = "/chat/completions";
1077
+ if (!input.chatCompletionsUrl.endsWith(suffix)) {
1078
+ throw new Error(
1079
+ "--llm chatCompletionsUrl must end with /chat/completions when baseURL is not provided."
1080
+ );
1081
+ }
1082
+ return input.chatCompletionsUrl.slice(0, -suffix.length);
1083
+ }
1084
+ function resolveInlineBaseURL(input) {
1085
+ if (input.baseURL !== void 0) {
1086
+ return input.baseURL;
1087
+ }
1088
+ if (input.baseUrl !== void 0) {
1089
+ return input.baseUrl;
1090
+ }
1091
+ return inferBaseURLFromChatCompletionsURL(input);
1092
+ }
1093
+ function createLLMConfig(input) {
1094
+ if (input.apiKey === void 0 && input.baseURL === void 0 && input.model === void 0 && input.name === void 0 && input.provider === void 0) {
1095
+ return void 0;
1096
+ }
1097
+ return {
1098
+ ...input.apiKey === void 0 ? {} : { apiKey: input.apiKey },
1099
+ ...input.baseURL === void 0 ? {} : { baseURL: input.baseURL },
1100
+ ...input.model === void 0 ? {} : { model: input.model },
1101
+ ...input.name === void 0 ? {} : { name: input.name },
1102
+ ...input.provider === void 0 ? {} : { provider: input.provider }
1103
+ };
1104
+ }
1105
+ function readProvider(value) {
1106
+ if (typeof value !== "string") {
1107
+ return void 0;
1108
+ }
1109
+ const parsed = wikiGraphProviderSchema.safeParse(value);
1110
+ return parsed.success ? parsed.data : void 0;
1111
+ }
1112
+ function resolveWikispineConfig(value, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
1113
+ const provider = readWikispineProvider(value.provider);
1114
+ const endpoint = readString(value.endpoint);
1115
+ const token = readString(value.token);
1116
+ if (provider === void 0) {
1117
+ return void 0;
1118
+ }
1119
+ if (provider === "cli") return { provider };
1120
+ if (token === void 0) {
1121
+ throw new Error(
1122
+ "Remote WikiSpine access requires an API key. Configure `wikg://local/config/wikispine` token with `put token --secret`."
1123
+ );
1124
+ }
1125
+ return {
1126
+ endpoint: endpoint ?? resolveHostedProviderEndpoint("wikispine", envPolicy),
1127
+ provider,
1128
+ token
1129
+ };
1130
+ }
1131
+ function resolveHostedProviderEndpoint(scope, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
1132
+ const origin = envPolicy === "development" ? "https://pdf-craft-api.oomol.dev" : "https://api.pdfcraft.ai";
1133
+ return `${origin}/v1/${scope}`;
1134
+ }
1135
+ function readWikispineProvider(value) {
1136
+ return value === "cli" || value === "fetch" ? value : void 0;
1137
+ }
1138
+ function readEmbeddingProvider(value) {
1139
+ return value === "openai" || value === "openai-compatible" ? value : void 0;
1140
+ }
1141
+ function readString(value) {
1142
+ return typeof value === "string" ? value : void 0;
1143
+ }
1144
+ function readPositiveInteger(value) {
1145
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
1146
+ }
1147
+ function firstDefined(first, second) {
1148
+ return first ?? second;
1149
+ }
1150
+ function normalizeString(value) {
1151
+ const normalized = value?.trim();
1152
+ return normalized === void 0 || normalized === "" ? void 0 : normalized;
1153
+ }
1154
+ function formatError2(error) {
1155
+ return error instanceof Error ? error.message : String(error);
1156
+ }
1157
+
1158
+ // src/llm.ts
1159
+ var import_anthropic = require("@ai-sdk/anthropic");
1160
+ var import_google = require("@ai-sdk/google");
1161
+ var import_openai = require("@ai-sdk/openai");
1162
+ var import_openai_compatible = require("@ai-sdk/openai-compatible");
1163
+ function buildWikiGraphLLMOptions(config) {
1164
+ const llm = config.llm;
1165
+ if (llm?.provider === void 0 || llm.model === void 0) {
1166
+ throw new Error(
1167
+ "Missing LLM configuration. Set --llm for one run, or configure `wikg://local/config/llm` with provider and model."
1168
+ );
1169
+ }
1170
+ return {
1171
+ model: createLanguageModel(llm.provider, llm.model, {
1172
+ apiKey: llm.apiKey,
1173
+ baseURL: llm.baseURL,
1174
+ name: llm.name
1175
+ }),
1176
+ ...config.concurrent?.request === void 0 ? {} : { concurrent: config.concurrent.request }
1177
+ };
1178
+ }
1179
+ function createLanguageModel(provider, model, options) {
1180
+ switch (provider) {
1181
+ case "anthropic": {
1182
+ const anthropic = (0, import_anthropic.createAnthropic)({
1183
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
1184
+ ...options.name === void 0 ? {} : { name: options.name }
1185
+ });
1186
+ return anthropic(model);
1187
+ }
1188
+ case "google": {
1189
+ const google = (0, import_google.createGoogleGenerativeAI)({
1190
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
1191
+ ...options.name === void 0 ? {} : { name: options.name }
1192
+ });
1193
+ return google(model);
1194
+ }
1195
+ case "openai": {
1196
+ if (options.baseURL !== void 0) {
1197
+ throw new Error(
1198
+ "openai does not accept llm.baseURL or baseURL in --llm JSON. Use openai-compatible for third-party OpenAI-style APIs."
1199
+ );
1200
+ }
1201
+ const openai = (0, import_openai.createOpenAI)({
1202
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
1203
+ ...options.name === void 0 ? {} : { name: options.name }
1204
+ });
1205
+ return openai(model);
1206
+ }
1207
+ case "openai-compatible": {
1208
+ if (options.baseURL === void 0) {
1209
+ throw new Error(
1210
+ "openai-compatible requires llm.baseURL or baseURL in --llm JSON."
1211
+ );
1212
+ }
1213
+ const openaiCompatible = (0, import_openai_compatible.createOpenAICompatible)({
1214
+ baseURL: options.baseURL,
1215
+ name: options.name ?? createOpenAICompatibleName(options.baseURL),
1216
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey }
1217
+ });
1218
+ return openaiCompatible(model);
1219
+ }
1220
+ }
1221
+ }
1222
+ function createOpenAICompatibleName(baseURL) {
1223
+ try {
1224
+ return new URL(baseURL).hostname;
1225
+ } catch {
1226
+ return "openai-compatible";
1227
+ }
1228
+ }
1229
+
1230
+ // src/stage.ts
1231
+ function createStageLLM(config, options) {
1232
+ const llmOptions = buildWikiGraphLLMOptions(config);
1233
+ return new import_wiki_graph_core4.LLM({
1234
+ sampling: (0, import_wiki_graph_core3.createDefaultWikiGraphSampling)({
1235
+ ...llmOptions.temperature === void 0 ? {} : { temperature: llmOptions.temperature },
1236
+ ...llmOptions.topP === void 0 ? {} : { topP: llmOptions.topP }
1237
+ }),
1238
+ ...llmOptions,
1239
+ ...options?.cacheDirectory === void 0 ? {} : { cacheDirectory: options.cacheDirectory },
1240
+ ...options?.logDirectory === void 0 ? {} : { logDirectory: options.logDirectory },
1241
+ ...options?.onStreamProgress === void 0 ? {} : { onStreamProgress: options.onStreamProgress },
1242
+ ...options?.onTokenUsage === void 0 ? {} : { onTokenUsage: options.onTokenUsage }
1243
+ });
1244
+ }
1245
+ async function loadRequiredStageConfig(options) {
1246
+ const config = await loadWikiGraphRuntimeConfig({
1247
+ ...options.llmJSON === void 0 ? {} : { llmJSON: options.llmJSON }
1248
+ });
1249
+ if (config.llm?.provider === void 0 || config.llm.model === void 0) {
1250
+ throw new Error(
1251
+ "Missing LLM configuration. Set --llm for one run, or configure `wikg://local/config/llm` with provider and model."
1252
+ );
1253
+ }
1254
+ return config;
1255
+ }
1256
+ // Annotate the CommonJS export names for ESM import in node:
1257
+ 0 && (module.exports = {
1258
+ DEFAULT_EXTRACTION_PROMPT,
1259
+ DEFAULT_KNOWLEDGE_GRAPH_RECALL_PROMPT,
1260
+ createStageLLM,
1261
+ loadRequiredStageConfig,
1262
+ resolveExtractionPrompt,
1263
+ resolveKnowledgeGraphRecallPrompt
1264
+ });
1265
+ //# sourceMappingURL=stage.cjs.map