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
@@ -0,0 +1,2814 @@
1
+ import { fileURLToPath as __WIKIGRAPH_FILE_URL_TO_PATH__ } from "url";
2
+ import { resolve as __WIKIGRAPH_RESOLVE__ } from "path";
3
+ globalThis.__WIKIGRAPH_DATA_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL("./data", import.meta.url)));
4
+
5
+ // src/archive/archive.ts
6
+ import { randomUUID as randomUUID2 } from "crypto";
7
+ import { link, mkdtemp, rename as rename2, rm as rm3, stat as stat2 } from "fs/promises";
8
+ import { tmpdir } from "os";
9
+ import { basename as basename2, dirname as dirname2, join as join3 } from "path";
10
+ import { Readable as Readable2 } from "stream";
11
+ import {
12
+ addChapter,
13
+ applyChapterTree,
14
+ assertNoActiveBuildJobConflicts,
15
+ assertNoActiveBuildJobs,
16
+ deleteArchiveSearchSessions,
17
+ DirectoryDocument,
18
+ finalizeWikiGraphLibraryArchiveWrite,
19
+ findArchiveObjects,
20
+ formatLocatedWikiGraphUri,
21
+ isArchiveSearchIndexCurrent as isArchiveSearchIndexCurrent2,
22
+ isSourceLocatorScopeUri,
23
+ listArchiveCollection,
24
+ listArchiveEvidence,
25
+ listArchiveQueryableChapterIds,
26
+ listArchiveSourceLocators,
27
+ listChapters as listChapters2,
28
+ listRelatedArchiveObjects,
29
+ moveChapter,
30
+ packArchiveContext,
31
+ parseLocatedWikiGraphUri,
32
+ parseWikiGraphLibraryUri,
33
+ readArchivePage,
34
+ readSearchIndexCapabilityStatus,
35
+ readWikiGraphLibraryIndexState,
36
+ rebuildArchiveSearchIndex,
37
+ rebuildWikiGraphLibraryIndex,
38
+ removeChapter,
39
+ resetChapter,
40
+ resolveChapterPathReadonly,
41
+ resolveWikiGraphLibraryArchiveFile,
42
+ setChapterSource,
43
+ setChapterSummary,
44
+ setChapterTitle,
45
+ getChapterTree,
46
+ WikiGraph as WikiGraph2,
47
+ WikiGraphArchiveFile,
48
+ TOC_FILE_VERSION,
49
+ writeWikgArchive,
50
+ ObjectMetadataKind
51
+ } from "wiki-graph-core";
52
+
53
+ // src/conversions.ts
54
+ import { rm as rm2 } from "fs/promises";
55
+ import {
56
+ WikiGraph
57
+ } from "wiki-graph-core";
58
+
59
+ // src/llm.ts
60
+ import { createAnthropic } from "@ai-sdk/anthropic";
61
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
62
+ import { createOpenAI } from "@ai-sdk/openai";
63
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
64
+ function buildWikiGraphLLMOptions(config) {
65
+ const llm = config.llm;
66
+ if (llm?.provider === void 0 || llm.model === void 0) {
67
+ throw new Error(
68
+ "Missing LLM configuration. Set --llm for one run, or configure `wikg://local/config/llm` with provider and model."
69
+ );
70
+ }
71
+ return {
72
+ model: createLanguageModel(llm.provider, llm.model, {
73
+ apiKey: llm.apiKey,
74
+ baseURL: llm.baseURL,
75
+ name: llm.name
76
+ }),
77
+ ...config.concurrent?.request === void 0 ? {} : { concurrent: config.concurrent.request }
78
+ };
79
+ }
80
+ function createLanguageModel(provider, model, options) {
81
+ switch (provider) {
82
+ case "anthropic": {
83
+ const anthropic = createAnthropic({
84
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
85
+ ...options.name === void 0 ? {} : { name: options.name }
86
+ });
87
+ return anthropic(model);
88
+ }
89
+ case "google": {
90
+ const google = createGoogleGenerativeAI({
91
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
92
+ ...options.name === void 0 ? {} : { name: options.name }
93
+ });
94
+ return google(model);
95
+ }
96
+ case "openai": {
97
+ if (options.baseURL !== void 0) {
98
+ throw new Error(
99
+ "openai does not accept llm.baseURL or baseURL in --llm JSON. Use openai-compatible for third-party OpenAI-style APIs."
100
+ );
101
+ }
102
+ const openai = createOpenAI({
103
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
104
+ ...options.name === void 0 ? {} : { name: options.name }
105
+ });
106
+ return openai(model);
107
+ }
108
+ case "openai-compatible": {
109
+ if (options.baseURL === void 0) {
110
+ throw new Error(
111
+ "openai-compatible requires llm.baseURL or baseURL in --llm JSON."
112
+ );
113
+ }
114
+ const openaiCompatible = createOpenAICompatible({
115
+ baseURL: options.baseURL,
116
+ name: options.name ?? createOpenAICompatibleName(options.baseURL),
117
+ ...options.apiKey === void 0 ? {} : { apiKey: options.apiKey }
118
+ });
119
+ return openaiCompatible(model);
120
+ }
121
+ }
122
+ }
123
+ function createOpenAICompatibleName(baseURL) {
124
+ try {
125
+ return new URL(baseURL).hostname;
126
+ } catch {
127
+ return "openai-compatible";
128
+ }
129
+ }
130
+
131
+ // src/node-platform.ts
132
+ import * as asyncHooks from "async_hooks";
133
+ import * as crypto from "crypto";
134
+ import * as fs from "fs";
135
+ import * as fsPromises from "fs/promises";
136
+ import * as os from "os";
137
+ import * as pathModule from "path";
138
+ import * as process2 from "process";
139
+ import { Readable, Writable } from "stream";
140
+ import { pipeline } from "stream/promises";
141
+ import * as sqlite3 from "sqlite3";
142
+ import * as yauzl from "yauzl";
143
+ import * as yazl from "yazl";
144
+ import { Environment, Loader } from "nunjucks";
145
+ import {
146
+ getWikiGraphStorage,
147
+ installWikiGraphPlatform,
148
+ installWikiGraphStorage,
149
+ withWikiGraphStorage,
150
+ normalizeTemplateName
151
+ } from "wiki-graph-core/platform";
152
+ var nodeProcess = process2.default ?? process2;
153
+ var nodeSqlite3 = sqlite3.default ?? sqlite3;
154
+ var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
155
+ var NodeFile = class {
156
+ constructor(path, name = pathModule.basename(path)) {
157
+ this.path = path;
158
+ this.identity = encodeNodeResourceIdentity("file", path);
159
+ this.name = name;
160
+ }
161
+ path;
162
+ kind = "file";
163
+ [NODE_RESOURCE_KIND] = "file";
164
+ identity;
165
+ name;
166
+ async openReader() {
167
+ const handle = await fsPromises.open(this.path, "r");
168
+ let closed = false;
169
+ try {
170
+ const stats = await handle.stat();
171
+ if (!stats.isFile())
172
+ throw new Error("File reader requires a regular file");
173
+ const { size } = stats;
174
+ return {
175
+ size,
176
+ close: async () => {
177
+ if (!closed) await handle.close();
178
+ closed = true;
179
+ },
180
+ read: async (offset, length) => {
181
+ if (closed) throw new Error("Cannot read from a closed FileReader");
182
+ assertFileRange(offset, length, size);
183
+ const buffer = Buffer.allocUnsafe(length);
184
+ let bytesRead = 0;
185
+ while (bytesRead < length) {
186
+ const result = await handle.read(
187
+ buffer,
188
+ bytesRead,
189
+ length - bytesRead,
190
+ offset + bytesRead
191
+ );
192
+ if (result.bytesRead === 0) {
193
+ throw new Error("File changed while reading its byte range");
194
+ }
195
+ bytesRead += result.bytesRead;
196
+ }
197
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, bytesRead);
198
+ }
199
+ };
200
+ } catch (error) {
201
+ await handle.close();
202
+ throw error;
203
+ }
204
+ }
205
+ async getLastModified() {
206
+ try {
207
+ return (await fsPromises.stat(this.path)).mtimeMs;
208
+ } catch (error) {
209
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
210
+ return void 0;
211
+ }
212
+ throw error;
213
+ }
214
+ }
215
+ async openWriter() {
216
+ await fsPromises.mkdir(pathModule.dirname(this.path), { recursive: true });
217
+ const temporary = `${this.path}.tmp-${crypto.randomUUID()}`;
218
+ const handle = await fsPromises.open(temporary, "wx");
219
+ let closed = false;
220
+ return {
221
+ write: async (data) => {
222
+ if (closed) throw new Error("Cannot write to a closed FileWriter");
223
+ await writeNodeFileHandle(handle, data);
224
+ },
225
+ writeAt: async (offset, data) => {
226
+ if (closed) throw new Error("Cannot write to a closed FileWriter");
227
+ assertFileOffset(offset);
228
+ await writeNodeFileHandle(handle, data, offset);
229
+ },
230
+ commit: async () => {
231
+ if (!closed) {
232
+ await handle.close();
233
+ await fsPromises.rename(temporary, this.path);
234
+ }
235
+ closed = true;
236
+ },
237
+ abort: async () => {
238
+ if (!closed) {
239
+ await handle.close();
240
+ await fsPromises.rm(temporary, { force: true });
241
+ }
242
+ closed = true;
243
+ }
244
+ };
245
+ }
246
+ };
247
+ async function writeNodeFileHandle(handle, data, position) {
248
+ const buffer = Buffer.from(data);
249
+ let written = 0;
250
+ while (written < buffer.byteLength) {
251
+ const result = await handle.write(
252
+ buffer,
253
+ written,
254
+ buffer.byteLength - written,
255
+ position === void 0 ? null : position + written
256
+ );
257
+ if (result.bytesWritten === 0) {
258
+ throw new Error("File writer made no progress");
259
+ }
260
+ written += result.bytesWritten;
261
+ }
262
+ }
263
+ function assertFileRange(offset, length, size) {
264
+ assertFileOffset(offset);
265
+ if (!Number.isSafeInteger(length) || length < 0) {
266
+ throw new RangeError(
267
+ "File read length must be a non-negative safe integer"
268
+ );
269
+ }
270
+ if (offset > size || length > size - offset) {
271
+ throw new RangeError("File read range exceeds the file size");
272
+ }
273
+ }
274
+ function assertFileOffset(offset) {
275
+ if (!Number.isSafeInteger(offset) || offset < 0) {
276
+ throw new RangeError("File offset must be a non-negative safe integer");
277
+ }
278
+ }
279
+ var NodeDirectory = class _NodeDirectory {
280
+ constructor(path) {
281
+ this.path = path;
282
+ this.identity = encodeNodeResourceIdentity("directory", path);
283
+ this.name = pathModule.basename(path);
284
+ }
285
+ path;
286
+ kind = "directory";
287
+ [NODE_RESOURCE_KIND] = "directory";
288
+ identity;
289
+ name;
290
+ async getFile(name) {
291
+ assertChildName(name);
292
+ const file = new NodeFile(pathModule.join(this.path, name));
293
+ try {
294
+ return (await fsPromises.stat(file.path)).isFile() ? file : void 0;
295
+ } catch {
296
+ return void 0;
297
+ }
298
+ }
299
+ async getLastModified() {
300
+ try {
301
+ return (await fsPromises.stat(this.path)).mtimeMs;
302
+ } catch (error) {
303
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
304
+ return void 0;
305
+ }
306
+ throw error;
307
+ }
308
+ }
309
+ async getDirectory(name) {
310
+ assertChildName(name);
311
+ const directory = new _NodeDirectory(pathModule.join(this.path, name));
312
+ try {
313
+ return (await fsPromises.stat(directory.path)).isDirectory() ? directory : void 0;
314
+ } catch {
315
+ return void 0;
316
+ }
317
+ }
318
+ async list() {
319
+ const entries = await fsPromises.readdir(this.path, {
320
+ withFileTypes: true
321
+ });
322
+ return entries.map(
323
+ (entry) => entry.isDirectory() ? new _NodeDirectory(pathModule.join(this.path, entry.name)) : new NodeFile(pathModule.join(this.path, entry.name), entry.name)
324
+ );
325
+ }
326
+ async createFile(name) {
327
+ assertChildName(name);
328
+ await fsPromises.mkdir(this.path, { recursive: true });
329
+ const file = new NodeFile(pathModule.join(this.path, name));
330
+ await fsPromises.writeFile(file.path, "", { flag: "wx" });
331
+ return file;
332
+ }
333
+ async createDirectory(name) {
334
+ assertChildName(name);
335
+ await fsPromises.mkdir(this.path, { recursive: true });
336
+ const directory = new _NodeDirectory(pathModule.join(this.path, name));
337
+ await fsPromises.mkdir(directory.path);
338
+ return directory;
339
+ }
340
+ async remove(name, options) {
341
+ assertChildName(name);
342
+ await fsPromises.rm(pathModule.join(this.path, name), {
343
+ force: true,
344
+ recursive: options?.recursive === true
345
+ });
346
+ }
347
+ };
348
+ function encodeNodeResourceIdentity(kind, path) {
349
+ return `node-${kind}:${Buffer.from(pathModule.resolve(path), "utf8").toString("base64url")}`;
350
+ }
351
+ function decodeNodeResourceIdentity(identity, kind) {
352
+ const prefix = `node-${kind}:`;
353
+ if (!identity.startsWith(prefix)) {
354
+ return pathModule.isAbsolute(identity) ? identity : void 0;
355
+ }
356
+ try {
357
+ return Buffer.from(identity.slice(prefix.length), "base64url").toString(
358
+ "utf8"
359
+ );
360
+ } catch {
361
+ return void 0;
362
+ }
363
+ }
364
+ function getNodeResourcePath(resource) {
365
+ const brandedPath = getBrandedNodeResourcePath(resource, resource.kind);
366
+ if (brandedPath !== void 0) return brandedPath;
367
+ if (typeof resource === "object" && resource !== null && "path" in resource && typeof resource.path === "string") {
368
+ return resource.path;
369
+ }
370
+ throw new TypeError("Expected a Node File or Directory resource");
371
+ }
372
+ function assertChildName(name) {
373
+ if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
374
+ throw new TypeError(`Directory child must be a relative name: ${name}`);
375
+ }
376
+ }
377
+ var NodeDatabaseConnection = class {
378
+ constructor(database) {
379
+ this.database = database;
380
+ }
381
+ database;
382
+ async close() {
383
+ await new Promise((resolve3, reject) => {
384
+ this.database.close((error) => {
385
+ if (error) reject(error);
386
+ else resolve3();
387
+ });
388
+ });
389
+ }
390
+ async execute(sql) {
391
+ await new Promise((resolve3, reject) => {
392
+ this.database.exec(sql, (error) => {
393
+ if (error) reject(error);
394
+ else resolve3();
395
+ });
396
+ });
397
+ }
398
+ async queryAll(sql, params = []) {
399
+ return await new Promise((resolve3, reject) => {
400
+ this.database.all(sql, [...params], (error, rows) => {
401
+ if (error) reject(error);
402
+ else resolve3(rows);
403
+ });
404
+ });
405
+ }
406
+ async queryOne(sql, params = []) {
407
+ return await new Promise((resolve3, reject) => {
408
+ this.database.get(sql, [...params], (error, row) => {
409
+ if (error) reject(error);
410
+ else resolve3(row);
411
+ });
412
+ });
413
+ }
414
+ async run(sql, params = []) {
415
+ await new Promise((resolve3, reject) => {
416
+ this.database.run(sql, [...params], (error) => {
417
+ if (error) reject(error);
418
+ else resolve3();
419
+ });
420
+ });
421
+ }
422
+ };
423
+ async function openNodeDatabase(file, options) {
424
+ const flags = (options.mode === "readonly" ? nodeSqlite3.OPEN_READONLY : nodeSqlite3.OPEN_READWRITE | (options.create ? nodeSqlite3.OPEN_CREATE : 0)) | nodeSqlite3.OPEN_FULLMUTEX;
425
+ return new NodeDatabaseConnection(await openNativeNodeDatabase(file, flags));
426
+ }
427
+ async function openNativeNodeDatabase(file, flags) {
428
+ const path = getBrandedNodeResourcePath(file, "file");
429
+ if (path === void 0) {
430
+ throw new TypeError("The Node database adapter requires a NodeFile");
431
+ }
432
+ return await new Promise((resolve3, reject) => {
433
+ const database = new nodeSqlite3.Database(path, flags, (error) => {
434
+ if (error) reject(error);
435
+ else resolve3(database);
436
+ });
437
+ });
438
+ }
439
+ async function openNodeZip(file) {
440
+ const path = getBrandedNodeResourcePath(file, "file");
441
+ if (path === void 0) {
442
+ throw new TypeError("The Node ZIP adapter requires a NodeFile");
443
+ }
444
+ const zipFile = await new Promise((resolve3, reject) => {
445
+ yauzl.open(
446
+ path,
447
+ { autoClose: false, lazyEntries: true },
448
+ (error, opened) => {
449
+ if (error || opened === void 0)
450
+ reject(error ?? new Error("Cannot open ZIP"));
451
+ else resolve3(opened);
452
+ }
453
+ );
454
+ });
455
+ const entries = await new Promise(
456
+ (resolve3, reject) => {
457
+ const discovered = /* @__PURE__ */ new Map();
458
+ const rejectAndClose = (error) => {
459
+ zipFile.close();
460
+ reject(
461
+ error instanceof Error ? error : new Error("Cannot scan ZIP central directory")
462
+ );
463
+ };
464
+ const resolveEntries = () => {
465
+ zipFile.off("error", rejectAndClose);
466
+ resolve3(discovered);
467
+ };
468
+ zipFile.on("entry", (entry) => {
469
+ if (!entry.fileName.endsWith("/")) {
470
+ discovered.set(entry.fileName, entry);
471
+ }
472
+ zipFile.readEntry();
473
+ });
474
+ zipFile.once("error", rejectAndClose);
475
+ zipFile.once("end", resolveEntries);
476
+ zipFile.readEntry();
477
+ }
478
+ );
479
+ let closed = false;
480
+ return {
481
+ close: () => {
482
+ if (!closed) zipFile.close();
483
+ closed = true;
484
+ return Promise.resolve();
485
+ },
486
+ copyEntry: async (name, target) => {
487
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
488
+ const entry = entries.get(name);
489
+ if (entry === void 0) return false;
490
+ await copyNodeZipEntry(zipFile, entry, target);
491
+ return true;
492
+ },
493
+ getEntrySize: (name) => {
494
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
495
+ return Promise.resolve(entries.get(name)?.uncompressedSize);
496
+ },
497
+ listEntries: () => Promise.resolve([...entries.keys()]),
498
+ readEntryRange: async (name, offset, length) => {
499
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
500
+ const entry = entries.get(name);
501
+ if (entry === void 0) return void 0;
502
+ return await readNodeZipEntryRange(zipFile, entry, offset, length);
503
+ },
504
+ readEntry: async (name) => {
505
+ if (closed) throw new Error("Cannot read a closed ZIP archive");
506
+ const entry = entries.get(name);
507
+ if (entry === void 0) return void 0;
508
+ return await readNodeZipEntry(zipFile, entry);
509
+ }
510
+ };
511
+ }
512
+ async function copyNodeZipEntry(zipFile, entry, target) {
513
+ const writer = await target.openWriter();
514
+ try {
515
+ const stream = await openNodeZipEntryStream(zipFile, entry);
516
+ await writeNodeStream(stream, writer);
517
+ await writer.commit();
518
+ } catch (error) {
519
+ await writer.abort().catch(() => void 0);
520
+ throw error;
521
+ }
522
+ }
523
+ async function readNodeZipEntry(zipFile, entry) {
524
+ return await collectNodeStream(await openNodeZipEntryStream(zipFile, entry));
525
+ }
526
+ async function readNodeZipEntryRange(zipFile, entry, offset, length) {
527
+ assertFileRange(offset, length, entry.uncompressedSize);
528
+ if (length === 0) return new Uint8Array();
529
+ if (entry.compressionMethod !== 0) {
530
+ const content2 = await collectDecodedNodeStreamRange(
531
+ await openNodeZipEntryStream(zipFile, entry),
532
+ offset,
533
+ length
534
+ );
535
+ return new Uint8Array(
536
+ content2.buffer,
537
+ content2.byteOffset,
538
+ content2.byteLength
539
+ );
540
+ }
541
+ const content = await collectNodeStream(
542
+ await openNodeZipEntryStream(zipFile, entry, {
543
+ decompress: null,
544
+ decrypt: null,
545
+ end: offset + length,
546
+ start: offset
547
+ })
548
+ );
549
+ return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
550
+ }
551
+ async function collectDecodedNodeStreamRange(input, offset, length) {
552
+ const chunks = [];
553
+ const end = offset + length;
554
+ let position = 0;
555
+ let collected = 0;
556
+ for await (const value of input) {
557
+ const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
558
+ const chunkEnd = position + chunk.byteLength;
559
+ if (chunkEnd > offset && position < end) {
560
+ const selected = chunk.subarray(
561
+ Math.max(0, offset - position),
562
+ Math.min(chunk.byteLength, end - position)
563
+ );
564
+ chunks.push(selected);
565
+ collected += selected.byteLength;
566
+ }
567
+ position = chunkEnd;
568
+ if (position >= end) break;
569
+ }
570
+ if (collected !== length) {
571
+ throw new Error("ZIP entry changed while reading its byte range");
572
+ }
573
+ return Buffer.concat(chunks, collected);
574
+ }
575
+ async function openNodeZipEntryStream(zipFile, entry, options) {
576
+ return await new Promise((resolve3, reject) => {
577
+ const callback = (error, opened) => {
578
+ if (error || opened === void 0) {
579
+ reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
580
+ } else {
581
+ resolve3(opened);
582
+ }
583
+ };
584
+ if (options === void 0) zipFile.openReadStream(entry, callback);
585
+ else zipFile.openReadStream(entry, options, callback);
586
+ });
587
+ }
588
+ async function writeNodeZip(file, entries) {
589
+ const zipFile = new yazl.ZipFile();
590
+ const writer = await file.openWriter();
591
+ const outputStream = zipFile.outputStream;
592
+ const outputDone = writeNodeStream(outputStream, writer);
593
+ const entryState = { cancelled: false, complete: false };
594
+ let iterator;
595
+ try {
596
+ iterator = getNodeZipEntryIterator(entries);
597
+ const entriesDone = addNodeZipEntries(zipFile, iterator, entryState);
598
+ await Promise.race([entriesDone, outputDone]);
599
+ if (!entryState.complete) {
600
+ throw new Error("ZIP output ended before entry production completed");
601
+ }
602
+ zipFile.end();
603
+ await outputDone;
604
+ await writer.commit();
605
+ } catch (error) {
606
+ entryState.cancelled = true;
607
+ if (!entryState.complete && iterator !== void 0) {
608
+ closeNodeZipEntryIterator(iterator);
609
+ }
610
+ if (!outputStream.destroyed) {
611
+ outputStream.destroy(
612
+ error instanceof Error ? error : new Error("Cannot write ZIP archive")
613
+ );
614
+ }
615
+ await outputDone.catch(() => void 0);
616
+ await writer.abort().catch(() => void 0);
617
+ throw error;
618
+ }
619
+ }
620
+ async function addNodeZipEntries(zipFile, iterator, state) {
621
+ while (!state.cancelled) {
622
+ const result = await iterator.next();
623
+ if (state.cancelled) return;
624
+ if (result.done) {
625
+ state.complete = true;
626
+ return;
627
+ }
628
+ if ("file" in result.value) {
629
+ zipFile.addReadStream(
630
+ createNodeFileReadStream(result.value.file),
631
+ result.value.name,
632
+ { compress: false }
633
+ );
634
+ } else if ("data" in result.value) {
635
+ zipFile.addBuffer(Buffer.from(result.value.data), result.value.name, {
636
+ compress: false
637
+ });
638
+ } else {
639
+ zipFile.addReadStream(
640
+ createNodeRangeReadStream(result.value),
641
+ result.value.name,
642
+ { compress: false, size: result.value.size }
643
+ );
644
+ }
645
+ }
646
+ }
647
+ function createNodeFileReadStream(file) {
648
+ return Readable.from(
649
+ (async function* () {
650
+ const reader = await file.openReader();
651
+ try {
652
+ for (let offset = 0; offset < reader.size; ) {
653
+ const chunk = await reader.read(
654
+ offset,
655
+ Math.min(64 * 1024, reader.size - offset)
656
+ );
657
+ offset += chunk.byteLength;
658
+ yield chunk;
659
+ }
660
+ } finally {
661
+ await reader.close();
662
+ }
663
+ })()
664
+ );
665
+ }
666
+ function getBrandedNodeResourcePath(resource, kind) {
667
+ if (typeof resource !== "object" || resource === null) return void 0;
668
+ const candidate = resource;
669
+ return candidate[NODE_RESOURCE_KIND] === kind && typeof candidate.path === "string" ? candidate.path : void 0;
670
+ }
671
+ function createNodeRangeReadStream(entry) {
672
+ return Readable.from(
673
+ (async function* () {
674
+ for (let offset = 0; offset < entry.size; ) {
675
+ const chunk = await entry.read(
676
+ offset,
677
+ Math.min(64 * 1024, entry.size - offset)
678
+ );
679
+ offset += chunk.byteLength;
680
+ yield chunk;
681
+ }
682
+ })()
683
+ );
684
+ }
685
+ function getNodeZipEntryIterator(entries) {
686
+ const asyncIterator = entries[Symbol.asyncIterator];
687
+ return asyncIterator === void 0 ? entries[Symbol.iterator]() : asyncIterator.call(entries);
688
+ }
689
+ function closeNodeZipEntryIterator(iterator) {
690
+ if (iterator.return === void 0) return;
691
+ try {
692
+ void Promise.resolve(iterator.return()).catch(() => void 0);
693
+ } catch {
694
+ }
695
+ }
696
+ async function writeNodeStream(input, writer) {
697
+ await pipeline(
698
+ input,
699
+ new Writable({
700
+ write: (chunk, _encoding, callback) => {
701
+ void writer.write(chunk).then(
702
+ () => callback(),
703
+ (error) => callback(
704
+ error instanceof Error ? error : new Error("Cannot stream ZIP archive")
705
+ )
706
+ );
707
+ }
708
+ })
709
+ );
710
+ }
711
+ async function collectNodeStream(input) {
712
+ return await new Promise((resolve3, reject) => {
713
+ const chunks = [];
714
+ input.on("data", (chunk) => chunks.push(chunk));
715
+ input.once("error", reject);
716
+ input.once("end", () => resolve3(Buffer.concat(chunks)));
717
+ });
718
+ }
719
+ var nodeWikiGraphPlatform = {
720
+ asyncContext: {
721
+ create: () => new asyncHooks.AsyncLocalStorage()
722
+ },
723
+ database: { open: openNodeDatabase },
724
+ lifecycle: {
725
+ instanceId: `node-process:${nodeProcess.pid}`,
726
+ isInstanceAlive: (instanceId) => {
727
+ const match = /^node-process:(\d+)$/u.exec(instanceId);
728
+ if (match === null) return Promise.resolve(void 0);
729
+ try {
730
+ nodeProcess.kill(Number(match[1]), 0);
731
+ return Promise.resolve(true);
732
+ } catch (error) {
733
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH") {
734
+ return Promise.resolve(false);
735
+ }
736
+ return Promise.resolve(true);
737
+ }
738
+ }
739
+ },
740
+ resources: {
741
+ getDirectory: (identity) => {
742
+ const path = decodeNodeResourceIdentity(identity, "directory");
743
+ return Promise.resolve(
744
+ path === void 0 ? void 0 : new NodeDirectory(path)
745
+ );
746
+ },
747
+ getFile: (identity) => {
748
+ const path = decodeNodeResourceIdentity(identity, "file");
749
+ return Promise.resolve(
750
+ path === void 0 ? void 0 : new NodeFile(path)
751
+ );
752
+ },
753
+ resolveLegacyDirectory: (reference) => {
754
+ const path = decodeNodeResourceIdentity(reference, "directory");
755
+ return Promise.resolve(
756
+ path === void 0 ? void 0 : new NodeDirectory(path)
757
+ );
758
+ }
759
+ },
760
+ templates: {
761
+ createEnvironment: (options) => new Environment(new NodeTemplateLoader(), options)
762
+ },
763
+ zip: {
764
+ open: openNodeZip,
765
+ write: writeNodeZip
766
+ }
767
+ };
768
+ var NodeTemplateLoader = class extends Loader {
769
+ #dataDirectory;
770
+ constructor(dataDirectory) {
771
+ super();
772
+ this.#dataDirectory = dataDirectory;
773
+ }
774
+ getSource(templateName) {
775
+ const name = normalizeTemplateName(templateName);
776
+ const filePath = pathModule.join(
777
+ this.#dataDirectory ?? resolveNodeDataDirectory(),
778
+ name
779
+ );
780
+ return {
781
+ noCache: false,
782
+ path: name,
783
+ src: fs.readFileSync(filePath, "utf8")
784
+ };
785
+ }
786
+ };
787
+ function resolveNodeDataDirectory() {
788
+ const injected = globalThis.__WIKIGRAPH_DATA_DIR__;
789
+ if (typeof injected === "string" && injected !== "") return injected;
790
+ let directory = nodeProcess.cwd();
791
+ while (true) {
792
+ for (const candidate of [
793
+ pathModule.join(directory, "data"),
794
+ pathModule.join(directory, "packages", "core", "data")
795
+ ]) {
796
+ try {
797
+ if (fs.statSync(candidate).isDirectory()) return candidate;
798
+ } catch {
799
+ }
800
+ }
801
+ const parent = pathModule.dirname(directory);
802
+ if (parent === directory)
803
+ throw new Error("Could not locate data directory");
804
+ directory = parent;
805
+ }
806
+ }
807
+
808
+ // src/runtime-config.ts
809
+ import { z } from "zod";
810
+
811
+ // src/local-config.ts
812
+ import { openSharedStateDatabase } from "wiki-graph-core";
813
+
814
+ // src/runtime-context.ts
815
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
816
+ var RUNTIME_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.runtime-context.v1");
817
+ var runtimeContext = getRuntimeContextStorage();
818
+ function getRuntimeContextStorage() {
819
+ const runtimeGlobal = globalThis;
820
+ const existing = runtimeGlobal[RUNTIME_CONTEXT_KEY];
821
+ if (existing !== void 0) {
822
+ return existing;
823
+ }
824
+ const storage = new AsyncLocalStorage2();
825
+ Object.defineProperty(runtimeGlobal, RUNTIME_CONTEXT_KEY, {
826
+ configurable: false,
827
+ enumerable: false,
828
+ value: storage,
829
+ writable: false
830
+ });
831
+ return storage;
832
+ }
833
+ function getWikiGraphSDKRuntimeContext() {
834
+ return runtimeContext.getStore() ?? {
835
+ cwd: process.cwd(),
836
+ env: process.env,
837
+ envPolicy: "production"
838
+ };
839
+ }
840
+ function getWikiGraphSDKStateDir() {
841
+ return getWikiGraphSDKRuntimeContext().stateDir;
842
+ }
843
+
844
+ // src/local-config.ts
845
+ import { join as join2 } from "path";
846
+ import { homedir as homedir2 } from "os";
847
+ var LOCAL_CONFIG_SCHEMA_SQL = `
848
+ CREATE TABLE IF NOT EXISTS config_sections (
849
+ section TEXT PRIMARY KEY,
850
+ value_json TEXT NOT NULL,
851
+ updated_at INTEGER NOT NULL
852
+ );
853
+ `;
854
+ async function readLocalConfigSection(section) {
855
+ return await withLocalConfigDatabase(async (database) => {
856
+ return await readLocalConfigSectionInDatabase(database, section);
857
+ });
858
+ }
859
+ function validateLocalConfigSection(section, value) {
860
+ switch (section) {
861
+ case "embeddings":
862
+ return validateEmbeddingsConfig(value);
863
+ case "llm":
864
+ return validateLLMConfig(value);
865
+ case "concurrent":
866
+ return validateConcurrentConfig(value);
867
+ case "wikimedia":
868
+ return validateWikimediaConfig(value);
869
+ case "wikispine":
870
+ return validateWikispineConfig(value);
871
+ }
872
+ }
873
+ async function withLocalConfigDatabase(operation) {
874
+ const database = await openSharedStateDatabase(
875
+ new NodeFile(
876
+ join2(
877
+ getWikiGraphSDKStateDir() ?? join2(homedir2(), ".wikigraph"),
878
+ "core.sqlite"
879
+ )
880
+ ),
881
+ LOCAL_CONFIG_SCHEMA_SQL
882
+ );
883
+ try {
884
+ return await operation(database);
885
+ } finally {
886
+ await database.close();
887
+ }
888
+ }
889
+ async function readLocalConfigSectionInDatabase(database, section) {
890
+ const value = await database.queryOne(
891
+ "SELECT value_json FROM config_sections WHERE section = ?",
892
+ [section],
893
+ (row) => String(row.value_json)
894
+ );
895
+ return value === void 0 ? {} : parseSectionJSON(section, value);
896
+ }
897
+ function parseSectionJSON(section, value) {
898
+ let parsed;
899
+ try {
900
+ parsed = JSON.parse(value);
901
+ } catch (error) {
902
+ throw new Error(
903
+ `Invalid local config JSON for ${section}: ${formatError(error)}`
904
+ );
905
+ }
906
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
907
+ throw new Error(
908
+ `Invalid local config section ${section}: expected object.`
909
+ );
910
+ }
911
+ return validateLocalConfigSection(section, parsed);
912
+ }
913
+ function validateEmbeddingsConfig(value) {
914
+ const allowedKeys = /* @__PURE__ */ new Set([
915
+ "apiKey",
916
+ "baseURL",
917
+ "dimensions",
918
+ "model",
919
+ "name",
920
+ "provider"
921
+ ]);
922
+ const allowedProviders = /* @__PURE__ */ new Set(["openai", "openai-compatible"]);
923
+ const next = {};
924
+ for (const [key, entry] of Object.entries(value)) {
925
+ if (!allowedKeys.has(key)) {
926
+ throw new Error(`Unknown embeddings config key: ${key}`);
927
+ }
928
+ if (key === "dimensions") {
929
+ const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
930
+ if (!Number.isInteger(parsed) || parsed <= 0) {
931
+ throw new Error("embeddings.dimensions must be a positive integer.");
932
+ }
933
+ next[key] = parsed;
934
+ continue;
935
+ }
936
+ if (typeof entry !== "string" || entry.trim() === "") {
937
+ throw new Error(`embeddings.${key} must be a non-empty string.`);
938
+ }
939
+ const normalized = entry.trim();
940
+ if (key === "provider" && !allowedProviders.has(normalized)) {
941
+ throw new Error(`Unknown embeddings.provider: ${normalized}`);
942
+ }
943
+ next[key] = normalized;
944
+ }
945
+ return next;
946
+ }
947
+ function validateLLMConfig(value) {
948
+ const allowedKeys = /* @__PURE__ */ new Set([
949
+ "apiKey",
950
+ "baseURL",
951
+ "model",
952
+ "name",
953
+ "provider"
954
+ ]);
955
+ const allowedProviders = /* @__PURE__ */ new Set([
956
+ "anthropic",
957
+ "google",
958
+ "openai",
959
+ "openai-compatible"
960
+ ]);
961
+ const next = {};
962
+ for (const [key, entry] of Object.entries(value)) {
963
+ if (!allowedKeys.has(key)) {
964
+ throw new Error(`Unknown llm config key: ${key}`);
965
+ }
966
+ if (typeof entry !== "string" || entry.trim() === "") {
967
+ throw new Error(`llm.${key} must be a non-empty string.`);
968
+ }
969
+ const normalized = entry.trim();
970
+ if (key === "provider" && !allowedProviders.has(normalized)) {
971
+ throw new Error(`Unknown llm.provider: ${normalized}`);
972
+ }
973
+ next[key] = normalized;
974
+ }
975
+ return next;
976
+ }
977
+ function validateConcurrentConfig(value) {
978
+ const allowedKeys = /* @__PURE__ */ new Set(["job", "request"]);
979
+ const next = {};
980
+ for (const [key, entry] of Object.entries(value)) {
981
+ if (!allowedKeys.has(key)) {
982
+ throw new Error(`Unknown concurrent config key: ${key}`);
983
+ }
984
+ const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
985
+ if (!Number.isInteger(parsed) || parsed <= 0) {
986
+ throw new Error(`concurrent.${key} must be a positive integer.`);
987
+ }
988
+ next[key] = parsed;
989
+ }
990
+ return next;
991
+ }
992
+ function validateWikispineConfig(value) {
993
+ const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "provider", "token"]);
994
+ const allowedProviders = /* @__PURE__ */ new Set(["cli", "fetch"]);
995
+ const next = {};
996
+ for (const [key, entry] of Object.entries(value)) {
997
+ if (!allowedKeys.has(key)) {
998
+ throw new Error(`Unknown wikispine config key: ${key}`);
999
+ }
1000
+ if (typeof entry !== "string" || entry.trim() === "") {
1001
+ throw new Error(`wikispine.${key} must be a non-empty string.`);
1002
+ }
1003
+ const normalized = entry.trim();
1004
+ if (key === "provider" && !allowedProviders.has(normalized)) {
1005
+ throw new Error(`Unknown wikispine.provider: ${normalized}`);
1006
+ }
1007
+ next[key] = normalized;
1008
+ }
1009
+ return next;
1010
+ }
1011
+ function validateWikimediaConfig(value) {
1012
+ return validateEndpointConfig("wikimedia", value);
1013
+ }
1014
+ function validateEndpointConfig(section, value) {
1015
+ const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "token"]);
1016
+ const next = {};
1017
+ for (const [key, entry] of Object.entries(value)) {
1018
+ if (!allowedKeys.has(key)) {
1019
+ throw new Error(`Unknown ${section} config key: ${key}`);
1020
+ }
1021
+ if (typeof entry !== "string" || entry.trim() === "") {
1022
+ throw new Error(`${section}.${key} must be a non-empty string.`);
1023
+ }
1024
+ next[key] = entry.trim();
1025
+ }
1026
+ return next;
1027
+ }
1028
+ function formatError(error) {
1029
+ return error instanceof Error ? error.message : String(error);
1030
+ }
1031
+
1032
+ // src/runtime-config.ts
1033
+ var WIKI_GRAPH_PROVIDER_VALUES = [
1034
+ "anthropic",
1035
+ "google",
1036
+ "openai",
1037
+ "openai-compatible"
1038
+ ];
1039
+ var wikiGraphProviderSchema = z.enum(WIKI_GRAPH_PROVIDER_VALUES);
1040
+ var inlineLLMConfigSchema = z.object({
1041
+ apiKey: z.string().min(1).optional(),
1042
+ baseURL: z.string().min(1).optional(),
1043
+ baseUrl: z.string().min(1).optional(),
1044
+ chatCompletionsUrl: z.string().min(1).optional(),
1045
+ llm: z.object({
1046
+ apiKey: z.string().min(1).optional(),
1047
+ baseURL: z.string().min(1).optional(),
1048
+ baseUrl: z.string().min(1).optional(),
1049
+ chatCompletionsUrl: z.string().min(1).optional(),
1050
+ model: z.string().min(1).optional(),
1051
+ name: z.string().min(1).optional(),
1052
+ provider: wikiGraphProviderSchema.optional()
1053
+ }).optional(),
1054
+ model: z.string().min(1).optional(),
1055
+ name: z.string().min(1).optional(),
1056
+ provider: wikiGraphProviderSchema.optional()
1057
+ });
1058
+ async function loadWikiGraphRuntimeConfig(options) {
1059
+ const [embedding, localLLM, concurrent, wikimedia, wikispine] = await Promise.all([
1060
+ readLocalConfigSection("embeddings"),
1061
+ readLocalConfigSection("llm"),
1062
+ readLocalConfigSection("concurrent"),
1063
+ readLocalConfigSection("wikimedia"),
1064
+ readLocalConfigSection("wikispine")
1065
+ ]);
1066
+ const inlineLLMConfig = options?.llmJSON === void 0 ? void 0 : parseInlineLLMConfig(options.llmJSON);
1067
+ const llm = createLLMConfig({
1068
+ apiKey: firstDefined(inlineLLMConfig?.apiKey, readString(localLLM.apiKey)),
1069
+ baseURL: firstDefined(
1070
+ inlineLLMConfig?.baseURL,
1071
+ readString(localLLM.baseURL)
1072
+ ),
1073
+ model: firstDefined(inlineLLMConfig?.model, readString(localLLM.model)),
1074
+ name: firstDefined(inlineLLMConfig?.name, readString(localLLM.name)),
1075
+ provider: firstDefined(
1076
+ inlineLLMConfig?.provider,
1077
+ readProvider(localLLM.provider)
1078
+ )
1079
+ });
1080
+ const requestConcurrent = readPositiveInteger(concurrent.request);
1081
+ const jobConcurrent = readPositiveInteger(concurrent.job);
1082
+ const envPolicy = getWikiGraphSDKRuntimeContext().envPolicy;
1083
+ const wikispineConfig = resolveWikispineConfig(wikispine, envPolicy);
1084
+ const wikimediaConfig = createWikimediaConfig(wikimedia, envPolicy);
1085
+ const embeddingConfig = createEmbeddingConfig(embedding);
1086
+ return {
1087
+ ...jobConcurrent === void 0 && requestConcurrent === void 0 ? {} : {
1088
+ concurrent: {
1089
+ ...jobConcurrent === void 0 ? {} : { job: jobConcurrent },
1090
+ ...requestConcurrent === void 0 ? {} : { request: requestConcurrent }
1091
+ }
1092
+ },
1093
+ ...embeddingConfig === void 0 ? {} : { embedding: embeddingConfig },
1094
+ ...llm === void 0 ? {} : { llm },
1095
+ ...wikimediaConfig === void 0 ? {} : { wikimedia: wikimediaConfig },
1096
+ ...wikispineConfig === void 0 ? {} : { wikispine: wikispineConfig }
1097
+ };
1098
+ }
1099
+ function createWikimediaConfig(input, envPolicy) {
1100
+ const endpoint = readString(input?.endpoint);
1101
+ const token = readString(input?.token);
1102
+ if (endpoint === void 0 && token === void 0) return void 0;
1103
+ if (token === void 0) {
1104
+ throw new Error(
1105
+ "Remote Wikimedia access requires an API key. Configure `wikg://local/config/wikimedia` token with `put token --secret`."
1106
+ );
1107
+ }
1108
+ return {
1109
+ endpoint: endpoint ?? resolveHostedProviderEndpoint("wg-wikimedia", envPolicy),
1110
+ token
1111
+ };
1112
+ }
1113
+ function createEmbeddingConfig(input) {
1114
+ const value = input ?? {};
1115
+ const provider = readEmbeddingProvider(value.provider);
1116
+ const apiKey = readString(value.apiKey);
1117
+ const baseURL = readString(value.baseURL);
1118
+ const dimensions = typeof value.dimensions === "number" && Number.isInteger(value.dimensions) && value.dimensions > 0 ? value.dimensions : void 0;
1119
+ const model = readString(value.model);
1120
+ const name = readString(value.name);
1121
+ if (provider === void 0 || model === void 0 || provider === "openai-compatible" && baseURL === void 0 || provider === "openai" && baseURL !== void 0) {
1122
+ return void 0;
1123
+ }
1124
+ return {
1125
+ ...apiKey === void 0 ? {} : { apiKey },
1126
+ ...baseURL === void 0 ? {} : { baseURL },
1127
+ ...dimensions === void 0 ? {} : { dimensions },
1128
+ ...model === void 0 ? {} : { model },
1129
+ ...name === void 0 ? {} : { name },
1130
+ ...provider === void 0 ? {} : { provider }
1131
+ };
1132
+ }
1133
+ function parseInlineLLMConfig(value) {
1134
+ const normalized = normalizeString(value);
1135
+ if (normalized === void 0) {
1136
+ throw new Error("--llm must be a non-empty JSON object.");
1137
+ }
1138
+ let parsedJson;
1139
+ try {
1140
+ parsedJson = JSON.parse(normalized);
1141
+ } catch (error) {
1142
+ throw new Error(`Invalid --llm JSON: ${formatError2(error)}`);
1143
+ }
1144
+ const parsed = inlineLLMConfigSchema.safeParse(parsedJson);
1145
+ if (!parsed.success) {
1146
+ throw new Error(
1147
+ `Invalid --llm config: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ")}`
1148
+ );
1149
+ }
1150
+ const input = parsed.data.llm ?? parsed.data;
1151
+ const provider = input.provider ?? inferInlineProvider(input);
1152
+ const baseURL = resolveInlineBaseURL(input);
1153
+ const config = createLLMConfig({
1154
+ apiKey: input.apiKey,
1155
+ baseURL,
1156
+ model: input.model,
1157
+ name: input.name,
1158
+ provider
1159
+ });
1160
+ if (config === void 0) {
1161
+ throw new Error("--llm must contain at least one supported LLM field.");
1162
+ }
1163
+ return config;
1164
+ }
1165
+ function inferInlineProvider(input) {
1166
+ if (input.provider === void 0 && (input.baseURL !== void 0 || input.baseUrl !== void 0 || input.chatCompletionsUrl !== void 0)) {
1167
+ return "openai-compatible";
1168
+ }
1169
+ return input.provider;
1170
+ }
1171
+ function inferBaseURLFromChatCompletionsURL(input) {
1172
+ if (input.chatCompletionsUrl === void 0) {
1173
+ return void 0;
1174
+ }
1175
+ const suffix = "/chat/completions";
1176
+ if (!input.chatCompletionsUrl.endsWith(suffix)) {
1177
+ throw new Error(
1178
+ "--llm chatCompletionsUrl must end with /chat/completions when baseURL is not provided."
1179
+ );
1180
+ }
1181
+ return input.chatCompletionsUrl.slice(0, -suffix.length);
1182
+ }
1183
+ function resolveInlineBaseURL(input) {
1184
+ if (input.baseURL !== void 0) {
1185
+ return input.baseURL;
1186
+ }
1187
+ if (input.baseUrl !== void 0) {
1188
+ return input.baseUrl;
1189
+ }
1190
+ return inferBaseURLFromChatCompletionsURL(input);
1191
+ }
1192
+ function createLLMConfig(input) {
1193
+ if (input.apiKey === void 0 && input.baseURL === void 0 && input.model === void 0 && input.name === void 0 && input.provider === void 0) {
1194
+ return void 0;
1195
+ }
1196
+ return {
1197
+ ...input.apiKey === void 0 ? {} : { apiKey: input.apiKey },
1198
+ ...input.baseURL === void 0 ? {} : { baseURL: input.baseURL },
1199
+ ...input.model === void 0 ? {} : { model: input.model },
1200
+ ...input.name === void 0 ? {} : { name: input.name },
1201
+ ...input.provider === void 0 ? {} : { provider: input.provider }
1202
+ };
1203
+ }
1204
+ function readProvider(value) {
1205
+ if (typeof value !== "string") {
1206
+ return void 0;
1207
+ }
1208
+ const parsed = wikiGraphProviderSchema.safeParse(value);
1209
+ return parsed.success ? parsed.data : void 0;
1210
+ }
1211
+ function resolveWikispineConfig(value, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
1212
+ const provider = readWikispineProvider(value.provider);
1213
+ const endpoint = readString(value.endpoint);
1214
+ const token = readString(value.token);
1215
+ if (provider === void 0) {
1216
+ return void 0;
1217
+ }
1218
+ if (provider === "cli") return { provider };
1219
+ if (token === void 0) {
1220
+ throw new Error(
1221
+ "Remote WikiSpine access requires an API key. Configure `wikg://local/config/wikispine` token with `put token --secret`."
1222
+ );
1223
+ }
1224
+ return {
1225
+ endpoint: endpoint ?? resolveHostedProviderEndpoint("wikispine", envPolicy),
1226
+ provider,
1227
+ token
1228
+ };
1229
+ }
1230
+ function resolveHostedProviderEndpoint(scope, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
1231
+ const origin = envPolicy === "development" ? "https://pdf-craft-api.oomol.dev" : "https://api.pdfcraft.ai";
1232
+ return `${origin}/v1/${scope}`;
1233
+ }
1234
+ function readWikispineProvider(value) {
1235
+ return value === "cli" || value === "fetch" ? value : void 0;
1236
+ }
1237
+ function readEmbeddingProvider(value) {
1238
+ return value === "openai" || value === "openai-compatible" ? value : void 0;
1239
+ }
1240
+ function readString(value) {
1241
+ return typeof value === "string" ? value : void 0;
1242
+ }
1243
+ function readPositiveInteger(value) {
1244
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
1245
+ }
1246
+ function firstDefined(first, second) {
1247
+ return first ?? second;
1248
+ }
1249
+ function normalizeString(value) {
1250
+ const normalized = value?.trim();
1251
+ return normalized === void 0 || normalized === "" ? void 0 : normalized;
1252
+ }
1253
+ function formatError2(error) {
1254
+ return error instanceof Error ? error.message : String(error);
1255
+ }
1256
+
1257
+ // src/runtime-path.ts
1258
+ import { homedir as homedir3 } from "os";
1259
+ import { isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
1260
+ function resolveWikiGraphRuntimePath(path) {
1261
+ const context = getWikiGraphSDKRuntimeContext();
1262
+ const environmentHome = context.env.HOME?.trim();
1263
+ const home = environmentHome === void 0 || environmentHome === "" ? homedir3() : environmentHome;
1264
+ if (path === "~") return home;
1265
+ if (path.startsWith("~/")) return resolve2(home, path.slice(2));
1266
+ return isAbsolute2(path) ? path : resolve2(context.cwd, path);
1267
+ }
1268
+
1269
+ // src/conversions.ts
1270
+ var WikiGraphConversionManager = class {
1271
+ #runtime;
1272
+ constructor(runtime) {
1273
+ this.#runtime = runtime;
1274
+ }
1275
+ async convert(options) {
1276
+ return await this.#runtime.run(async () => await this.#convert(options));
1277
+ }
1278
+ async #convert(options) {
1279
+ const targetStage = options.targetStage ?? "summarized";
1280
+ if (options.targetStage !== void 0 && options.output.format !== "wikg") {
1281
+ throw new Error("targetStage is only supported for wikg output.");
1282
+ }
1283
+ if (options.targetStage !== void 0 && options.input.format === "wikg") {
1284
+ throw new Error(
1285
+ "targetStage is only supported when creating a wikg archive."
1286
+ );
1287
+ }
1288
+ const requiresDigest = options.input.format !== "wikg";
1289
+ const requiresLLM = requiresDigest && targetStage !== "planned" && targetStage !== "sourced";
1290
+ const config = await loadWikiGraphRuntimeConfig({
1291
+ ...options.llmJSON === void 0 ? {} : { llmJSON: options.llmJSON }
1292
+ });
1293
+ const app = new WikiGraph({
1294
+ ...options.verbose === true ? { verbose: true } : {},
1295
+ ...requiresLLM ? { llm: buildWikiGraphLLMOptions(config) } : {}
1296
+ });
1297
+ const documentDirectory = await prepareDigestDirectory(
1298
+ options.digestDirectory,
1299
+ requiresDigest
1300
+ );
1301
+ const write = async (archive) => {
1302
+ await writeArchive(archive, options.output.path, options.output.format);
1303
+ };
1304
+ if (options.input.format === "wikg") {
1305
+ if (!("path" in options.input)) {
1306
+ throw new Error("wikg input requires a file path.");
1307
+ }
1308
+ await app.openSession(
1309
+ new NodeFile(resolveWikiGraphRuntimePath(options.input.path)),
1310
+ write
1311
+ );
1312
+ } else if ("stream" in options.input) {
1313
+ await app.digestTextStreamSession(
1314
+ {
1315
+ ...documentDirectory === void 0 ? {} : { documentDirectory },
1316
+ ...options.onProgress === void 0 ? {} : { onProgress: options.onProgress },
1317
+ sourceFormat: options.input.format,
1318
+ stream: options.input.stream,
1319
+ ...(options.prompt ?? config.prompt) === void 0 ? {} : { extractionPrompt: options.prompt ?? config.prompt },
1320
+ targetStage
1321
+ },
1322
+ write
1323
+ );
1324
+ } else {
1325
+ const digestOptions = {
1326
+ ...documentDirectory === void 0 ? {} : { documentDirectory },
1327
+ file: new NodeFile(resolveWikiGraphRuntimePath(options.input.path)),
1328
+ ...options.onProgress === void 0 ? {} : { onProgress: options.onProgress },
1329
+ ...(options.prompt ?? config.prompt) === void 0 ? {} : { extractionPrompt: options.prompt ?? config.prompt },
1330
+ targetStage
1331
+ };
1332
+ if (options.input.format === "epub") {
1333
+ await app.digestEpubSession(digestOptions, write);
1334
+ } else if (options.input.format === "markdown") {
1335
+ await app.digestMarkdownSession(digestOptions, write);
1336
+ } else {
1337
+ await app.digestTxtSession(digestOptions, write);
1338
+ }
1339
+ }
1340
+ return {
1341
+ inputFormat: options.input.format,
1342
+ outputFormat: options.output.format,
1343
+ outputPath: options.output.path
1344
+ };
1345
+ }
1346
+ };
1347
+ async function prepareDigestDirectory(path, required) {
1348
+ const normalized = path?.trim();
1349
+ if (!required || normalized === void 0 || normalized === "")
1350
+ return void 0;
1351
+ const resolved = resolveWikiGraphRuntimePath(normalized);
1352
+ await rm2(resolved, { force: true, recursive: true });
1353
+ return new NodeDirectory(resolved);
1354
+ }
1355
+ async function writeArchive(archive, path, format) {
1356
+ const file = new NodeFile(resolveWikiGraphRuntimePath(path));
1357
+ if (format === "epub") await archive.exportEpub(file);
1358
+ else if (format === "wikg") await archive.saveAs(file);
1359
+ else await archive.exportText(file);
1360
+ }
1361
+
1362
+ // src/query-runtime.ts
1363
+ import {
1364
+ openWikimediaResolver
1365
+ } from "wiki-graph-core";
1366
+
1367
+ // src/embedding.ts
1368
+ import { embed, embedMany } from "ai";
1369
+ import { createOpenAI as createOpenAI2 } from "@ai-sdk/openai";
1370
+ import { createOpenAICompatible as createOpenAICompatible2 } from "@ai-sdk/openai-compatible";
1371
+ var EMBEDDING_BATCH_SIZE = 10;
1372
+ async function readWikiGraphEmbeddingConfig() {
1373
+ const config = await readLocalConfigSection("embeddings");
1374
+ return {
1375
+ ...typeof config.apiKey === "string" ? { apiKey: config.apiKey } : {},
1376
+ ...typeof config.baseURL === "string" ? { baseURL: config.baseURL } : {},
1377
+ ...typeof config.dimensions === "number" ? { dimensions: config.dimensions } : {},
1378
+ ...typeof config.model === "string" ? { model: config.model } : {},
1379
+ ...typeof config.name === "string" ? { name: config.name } : {},
1380
+ ...typeof config.provider === "string" ? { provider: parseEmbeddingProvider(config.provider) } : {}
1381
+ };
1382
+ }
1383
+ function buildSearchIndexEmbeddingProvider(config) {
1384
+ const provider = requireEmbeddingProvider(config.provider);
1385
+ const model = requireEmbeddingModel(config.model);
1386
+ const embeddingModel = createEmbeddingModel(provider, model, config);
1387
+ const providerOptions = createEmbeddingProviderOptions(provider, config);
1388
+ return {
1389
+ ...config.dimensions === void 0 ? {} : { dimensions: config.dimensions },
1390
+ identity: createEmbeddingIdentity(provider, model, config),
1391
+ model,
1392
+ embedTexts: async (texts, options) => {
1393
+ const embeddings = [];
1394
+ let tokens = 0;
1395
+ for (const batch of chunkTexts(texts, EMBEDDING_BATCH_SIZE)) {
1396
+ options?.signal?.throwIfAborted();
1397
+ const result = await embedMany({
1398
+ ...options?.signal === void 0 ? {} : { abortSignal: options.signal },
1399
+ model: embeddingModel,
1400
+ ...providerOptions === void 0 ? {} : { providerOptions },
1401
+ values: [...batch]
1402
+ });
1403
+ embeddings.push(...result.embeddings);
1404
+ tokens += result.usage.tokens ?? 0;
1405
+ }
1406
+ return {
1407
+ embeddings,
1408
+ ...tokens === 0 ? {} : { tokens }
1409
+ };
1410
+ }
1411
+ };
1412
+ }
1413
+ function createEmbeddingIdentity(provider, model, config) {
1414
+ return JSON.stringify({
1415
+ ...config.baseURL === void 0 ? {} : { baseURL: config.baseURL },
1416
+ ...config.dimensions === void 0 ? {} : { dimensions: config.dimensions },
1417
+ model,
1418
+ provider
1419
+ });
1420
+ }
1421
+ function* chunkTexts(texts, size) {
1422
+ for (let index = 0; index < texts.length; index += size) {
1423
+ yield texts.slice(index, index + size);
1424
+ }
1425
+ }
1426
+ function createEmbeddingModel(provider, model, config) {
1427
+ switch (provider) {
1428
+ case "openai": {
1429
+ if (config.baseURL !== void 0) {
1430
+ throw new Error(
1431
+ "openai does not accept embeddings.baseURL. Use openai-compatible for third-party OpenAI-style embeddings APIs."
1432
+ );
1433
+ }
1434
+ return createOpenAI2({
1435
+ ...config.apiKey === void 0 ? {} : { apiKey: config.apiKey },
1436
+ ...config.name === void 0 ? {} : { name: config.name }
1437
+ }).embeddingModel(model);
1438
+ }
1439
+ case "openai-compatible": {
1440
+ if (config.baseURL === void 0) {
1441
+ throw new Error("openai-compatible requires embeddings.baseURL.");
1442
+ }
1443
+ return createOpenAICompatible2({
1444
+ baseURL: config.baseURL,
1445
+ name: config.name ?? createOpenAICompatibleName2(config.baseURL),
1446
+ ...config.apiKey === void 0 ? {} : { apiKey: config.apiKey }
1447
+ }).embeddingModel(model);
1448
+ }
1449
+ }
1450
+ }
1451
+ function createEmbeddingProviderOptions(provider, config) {
1452
+ if (config.dimensions === void 0) {
1453
+ return void 0;
1454
+ }
1455
+ return {
1456
+ [getEmbeddingProviderOptionsName(provider, config)]: {
1457
+ dimensions: config.dimensions
1458
+ }
1459
+ };
1460
+ }
1461
+ function getEmbeddingProviderOptionsName(provider, _config) {
1462
+ if (provider === "openai") {
1463
+ return "openai";
1464
+ }
1465
+ return "openaiCompatible";
1466
+ }
1467
+ function requireEmbeddingProvider(provider) {
1468
+ if (provider !== void 0) {
1469
+ return provider;
1470
+ }
1471
+ throw new Error(
1472
+ "Missing embeddings configuration. Configure `wikg://local/config/embeddings` with provider and model."
1473
+ );
1474
+ }
1475
+ function requireEmbeddingModel(model) {
1476
+ if (model !== void 0) {
1477
+ return model;
1478
+ }
1479
+ throw new Error(
1480
+ "Missing embeddings.model. Configure `wikg://local/config/embeddings` before using Dense search."
1481
+ );
1482
+ }
1483
+ function parseEmbeddingProvider(value) {
1484
+ switch (value) {
1485
+ case "openai":
1486
+ case "openai-compatible":
1487
+ return value;
1488
+ default:
1489
+ throw new Error(
1490
+ `Invalid embeddings.provider: ${value}. Expected openai or openai-compatible.`
1491
+ );
1492
+ }
1493
+ }
1494
+ function createOpenAICompatibleName2(baseURL) {
1495
+ try {
1496
+ return new URL(baseURL).hostname;
1497
+ } catch {
1498
+ return "openai-compatible";
1499
+ }
1500
+ }
1501
+
1502
+ // src/query-runtime.ts
1503
+ async function createConfiguredEmbeddingProvider() {
1504
+ const config = await readWikiGraphEmbeddingConfig();
1505
+ if (config.provider === void 0 || config.model === void 0 || config.provider === "openai-compatible" && config.baseURL === void 0 || config.provider === "openai" && config.baseURL !== void 0) {
1506
+ return void 0;
1507
+ }
1508
+ return buildSearchIndexEmbeddingProvider(config);
1509
+ }
1510
+ async function withConfiguredWikimediaResolver(objectUri, operation) {
1511
+ if (!objectUri.endsWith("/wikipage")) return await operation({});
1512
+ const config = await loadWikiGraphRuntimeConfig();
1513
+ const resolver = await openWikimediaResolver(
1514
+ config.wikimedia === void 0 ? { kind: "local" } : {
1515
+ endpoint: config.wikimedia.endpoint,
1516
+ kind: "remote",
1517
+ token: config.wikimedia.token
1518
+ }
1519
+ );
1520
+ try {
1521
+ return await operation({ wikimediaResolver: resolver });
1522
+ } finally {
1523
+ await resolver.close();
1524
+ }
1525
+ }
1526
+
1527
+ // src/archive/inspect.ts
1528
+ import {
1529
+ isArchiveSearchIndexCurrent,
1530
+ listChapters
1531
+ } from "wiki-graph-core";
1532
+
1533
+ // src/planning.ts
1534
+ var DEFAULT_GENERATION_JOB_CONCURRENCY = 3;
1535
+ var DEFAULT_GENERATION_REQUEST_CONCURRENCY = 6;
1536
+ function planGenerationTask(task, words, chapters, concurrent, model) {
1537
+ const profile = getGenerationPlanningProfile(task);
1538
+ const calls = Math.max(chapters, Math.ceil(words / profile.wordsPerCall));
1539
+ const effectiveConcurrency = Math.max(
1540
+ 1,
1541
+ task === "reading-graph" ? 1 : concurrent.request
1542
+ );
1543
+ const callBatches = Math.ceil(calls / effectiveConcurrency);
1544
+ const wordSeconds = words * profile.secondsPerWord;
1545
+ return {
1546
+ model,
1547
+ timeSeconds: {
1548
+ max: Math.ceil(callBatches * profile.maxSecondsPerCall + wordSeconds),
1549
+ min: Math.ceil(callBatches * profile.minSecondsPerCall + wordSeconds)
1550
+ },
1551
+ tokens: {
1552
+ cacheableInput: Math.ceil(words * profile.cacheableInputTokenPerWord),
1553
+ input: Math.ceil(words * profile.inputTokenPerWord),
1554
+ output: Math.ceil(words * profile.outputTokenPerWord)
1555
+ }
1556
+ };
1557
+ }
1558
+ function createGenerationPerformanceHints(input) {
1559
+ if (!input.hasJobWork) {
1560
+ return [];
1561
+ }
1562
+ const hints = [];
1563
+ const recommendedRequest = input.concurrent.request < 4 ? DEFAULT_GENERATION_REQUEST_CONCURRENCY : input.concurrent.request < 8 ? 8 : void 0;
1564
+ if (input.hasRequestWork && recommendedRequest !== void 0) {
1565
+ hints.push({
1566
+ configKey: "request",
1567
+ configValue: recommendedRequest,
1568
+ current: input.concurrent.request,
1569
+ kind: "request",
1570
+ message: "LLM request concurrency can often be higher. Use at least 4; 6-8 is usually faster when the provider allows it.",
1571
+ recommended: recommendedRequest
1572
+ });
1573
+ }
1574
+ if (input.concurrent.job < 4 && input.chapters > 1) {
1575
+ hints.push({
1576
+ configKey: "job",
1577
+ configValue: 4,
1578
+ current: input.concurrent.job,
1579
+ kind: "job",
1580
+ message: "Multiple chapters need work and job concurrency is below 4. Raising it lets chapter jobs run in parallel.",
1581
+ recommended: 4
1582
+ });
1583
+ }
1584
+ return hints;
1585
+ }
1586
+ function formatGenerationPlanningModel(llm) {
1587
+ if (llm?.model === void 0) {
1588
+ return "not configured";
1589
+ }
1590
+ return llm.provider === void 0 ? llm.model : `${llm.provider}/${llm.model}`;
1591
+ }
1592
+ function getGenerationPlanningProfile(task) {
1593
+ switch (task) {
1594
+ case "index-fts":
1595
+ return {
1596
+ cacheableInputTokenPerWord: 0,
1597
+ inputTokenPerWord: 0,
1598
+ maxSecondsPerCall: 1,
1599
+ minSecondsPerCall: 0,
1600
+ outputTokenPerWord: 0,
1601
+ secondsPerWord: 5e-4,
1602
+ wordsPerCall: 1e5
1603
+ };
1604
+ case "index-embedding-source":
1605
+ case "index-embedding-summary":
1606
+ return {
1607
+ cacheableInputTokenPerWord: 0,
1608
+ inputTokenPerWord: 0,
1609
+ maxSecondsPerCall: 10,
1610
+ minSecondsPerCall: 1,
1611
+ outputTokenPerWord: 0,
1612
+ secondsPerWord: 2e-3,
1613
+ wordsPerCall: 1e4
1614
+ };
1615
+ case "knowledge-graph":
1616
+ return {
1617
+ cacheableInputTokenPerWord: 60,
1618
+ inputTokenPerWord: 80,
1619
+ maxSecondsPerCall: 35,
1620
+ minSecondsPerCall: 15,
1621
+ outputTokenPerWord: 25,
1622
+ secondsPerWord: 0.02,
1623
+ wordsPerCall: 35
1624
+ };
1625
+ case "reading-graph":
1626
+ return {
1627
+ cacheableInputTokenPerWord: 20,
1628
+ inputTokenPerWord: 25,
1629
+ maxSecondsPerCall: 45,
1630
+ minSecondsPerCall: 15,
1631
+ outputTokenPerWord: 4,
1632
+ secondsPerWord: 0.01,
1633
+ wordsPerCall: 160
1634
+ };
1635
+ case "reading-summary":
1636
+ return {
1637
+ cacheableInputTokenPerWord: 45,
1638
+ inputTokenPerWord: 55,
1639
+ maxSecondsPerCall: 25,
1640
+ minSecondsPerCall: 10,
1641
+ outputTokenPerWord: 4,
1642
+ secondsPerWord: 0.01,
1643
+ wordsPerCall: 110
1644
+ };
1645
+ }
1646
+ }
1647
+
1648
+ // src/archive/inspect.ts
1649
+ async function createWikiGraphArchiveInspectReport(document, options) {
1650
+ const { archiveUri } = options;
1651
+ const [
1652
+ chapters,
1653
+ summaryWords,
1654
+ indexCacheCurrent,
1655
+ config,
1656
+ ftsArtifactCoverage,
1657
+ sourceEmbeddingArtifactCoverage,
1658
+ summaryEmbeddingArtifactCoverage
1659
+ ] = await Promise.all([
1660
+ readInspectChapters(document, options.chapterId),
1661
+ readSummaryWords(document, options.chapterId),
1662
+ isArchiveSearchIndexCurrent(document),
1663
+ loadWikiGraphRuntimeConfig(),
1664
+ readIndexArtifactCoverage(document, "fts", options.chapterId),
1665
+ readIndexArtifactCoverage(document, "embedding-source", options.chapterId),
1666
+ readIndexArtifactCoverage(document, "embedding-summary", options.chapterId)
1667
+ ]);
1668
+ const selectedChapter = options.chapterId === void 0 ? void 0 : chapters[0];
1669
+ const scopeUri = selectedChapter === void 0 ? archiveUri : formatInspectLocatedChapterUri(archiveUri, selectedChapter);
1670
+ const concurrent = {
1671
+ job: config.concurrent?.job ?? DEFAULT_GENERATION_JOB_CONCURRENCY,
1672
+ request: config.concurrent?.request ?? DEFAULT_GENERATION_REQUEST_CONCURRENCY
1673
+ };
1674
+ const planningModel = formatGenerationPlanningModel(config.llm);
1675
+ const contentChapters = chapters.filter(
1676
+ (chapter) => chapter.stage !== "planned"
1677
+ );
1678
+ const sourceWords = sumWords(contentChapters);
1679
+ const readingGraphCovered = contentChapters.filter(
1680
+ (chapter) => chapter.readingGraphReady
1681
+ );
1682
+ const knowledgeGraphCovered = contentChapters.filter(
1683
+ (chapter) => chapter.knowledgeGraphReady
1684
+ );
1685
+ const summaryCovered = contentChapters.filter(
1686
+ (chapter) => chapter.summaryReady
1687
+ );
1688
+ const ftsArtifactCovered = filterChaptersByCurrentIndexArtifact(
1689
+ contentChapters,
1690
+ ftsArtifactCoverage
1691
+ );
1692
+ const sourceEmbeddingArtifactCovered = filterChaptersByCurrentIndexArtifact(
1693
+ contentChapters,
1694
+ sourceEmbeddingArtifactCoverage
1695
+ );
1696
+ const summaryEmbeddingArtifactCovered = filterChaptersByCurrentIndexArtifact(
1697
+ contentChapters,
1698
+ summaryEmbeddingArtifactCoverage
1699
+ );
1700
+ const queryBlockedContentChapters = contentChapters.filter(
1701
+ (chapter) => !ftsArtifactCovered.includes(chapter) && !sourceEmbeddingArtifactCovered.includes(chapter)
1702
+ );
1703
+ const queryBlockedChapters = queryBlockedContentChapters.map(
1704
+ (chapter) => createInspectChapterReference(archiveUri, chapter)
1705
+ );
1706
+ const queryReady = queryBlockedChapters.length === 0;
1707
+ const improvements = createInspectImprovements({
1708
+ concurrent,
1709
+ contentChapters,
1710
+ indexCacheCurrent,
1711
+ planningModel,
1712
+ queryBlockedChapters: queryBlockedContentChapters,
1713
+ summaryCovered,
1714
+ knowledgeGraphCovered,
1715
+ readingGraphCovered
1716
+ });
1717
+ const performanceHints = createGenerationPerformanceHints({
1718
+ chapters: Math.max(
1719
+ 0,
1720
+ ...improvements.map((improvement) => improvement.missingChapters ?? 0)
1721
+ ),
1722
+ concurrent,
1723
+ hasJobWork: improvements.some(
1724
+ (improvement) => improvement.planning !== void 0
1725
+ ),
1726
+ hasRequestWork: improvements.some(
1727
+ (improvement) => improvement.planning !== void 0
1728
+ )
1729
+ });
1730
+ return {
1731
+ archiveUri,
1732
+ uri: scopeUri,
1733
+ scope: options.chapterId === void 0 ? { type: "archive" } : { chapterId: options.chapterId, type: "chapter" },
1734
+ content: {
1735
+ chapters: {
1736
+ content: contentChapters.length,
1737
+ planned: chapters.length - contentChapters.length,
1738
+ total: chapters.length
1739
+ },
1740
+ sourceWords,
1741
+ summaryWords
1742
+ },
1743
+ localIndexCache: {
1744
+ current: indexCacheCurrent,
1745
+ ...!queryReady ? {
1746
+ blockedBy: "missing-search-artifacts",
1747
+ impact: "The cache cannot be built until every content chapter has a current FTS or source embedding artifact."
1748
+ } : indexCacheCurrent ? {} : {
1749
+ impact: "The next archive query may need to sync index cache first.",
1750
+ resource: "local CPU/disk time only; no provider calls."
1751
+ },
1752
+ status: !queryReady ? "blocked" : indexCacheCurrent ? "current" : "missing-or-outdated",
1753
+ syncAvailable: queryReady && !indexCacheCurrent
1754
+ },
1755
+ coverage: {
1756
+ ftsIndexArtifact: createInspectCoverage(
1757
+ ftsArtifactCovered,
1758
+ contentChapters
1759
+ ),
1760
+ knowledgeGraph: createInspectCoverage(
1761
+ knowledgeGraphCovered,
1762
+ contentChapters
1763
+ ),
1764
+ readingGraph: createInspectCoverage(readingGraphCovered, contentChapters),
1765
+ summary: createInspectCoverage(summaryCovered, contentChapters),
1766
+ sourceEmbeddingIndexArtifact: createInspectCoverage(
1767
+ sourceEmbeddingArtifactCovered,
1768
+ contentChapters
1769
+ ),
1770
+ summaryEmbeddingIndexArtifact: createInspectCoverage(
1771
+ summaryEmbeddingArtifactCovered,
1772
+ contentChapters
1773
+ )
1774
+ },
1775
+ query: {
1776
+ ready: queryReady
1777
+ },
1778
+ searchArtifacts: {
1779
+ blockedChapters: queryBlockedChapters,
1780
+ ...!queryReady ? {
1781
+ resource: "local CPU/disk time only; no provider calls."
1782
+ } : {},
1783
+ ready: queryReady,
1784
+ status: queryReady ? "ready" : "incomplete"
1785
+ },
1786
+ retrievalGuidance: formatRetrievalGuidance({
1787
+ indexCacheCurrent,
1788
+ knowledgeGraphCovered,
1789
+ readingGraphCovered,
1790
+ contentChapters,
1791
+ queryReady,
1792
+ sourceWords
1793
+ }),
1794
+ improvements,
1795
+ performanceHints,
1796
+ summaryCoverageNote: "Summary coverage means a current summary artifact exists for the chapter; it does not guarantee that every source topic is represented in the summary text."
1797
+ };
1798
+ }
1799
+ function createInspectChapterReference(archiveUri, chapter) {
1800
+ return {
1801
+ chapterId: chapter.chapterId,
1802
+ locatedUri: formatInspectLocatedChapterUri(archiveUri, chapter),
1803
+ title: chapter.title,
1804
+ uri: chapter.uri
1805
+ };
1806
+ }
1807
+ function formatInspectLocatedChapterUri(archiveUri, chapter) {
1808
+ return `${archiveUri.replace(/\/+$/u, "")}/${chapter.uri.replace(/^wikg:\/\//u, "")}`;
1809
+ }
1810
+ async function readInspectChapters(document, chapterId) {
1811
+ const chapters = chapterId === void 0 ? await listChapters(document) : (await listChapters(document)).filter(
1812
+ (chapter) => chapter.chapterId === chapterId
1813
+ );
1814
+ if (chapterId !== void 0 && chapters.length === 0) {
1815
+ throw new Error(`Chapter ${chapterId} does not exist.`);
1816
+ }
1817
+ return await Promise.all(
1818
+ chapters.map(async (chapter) => {
1819
+ const serial = await document.serials.getById(chapter.chapterId);
1820
+ return {
1821
+ ...chapter,
1822
+ knowledgeGraphReady: serial?.knowledgeGraphReady === true,
1823
+ readingGraphReady: serial?.topologyReady === true,
1824
+ summaryReady: chapter.stage === "summarized"
1825
+ };
1826
+ })
1827
+ );
1828
+ }
1829
+ async function readSummaryWords(document, chapterId) {
1830
+ return await document.readDatabase(
1831
+ async (database) => await database.queryOne(
1832
+ `
1833
+ SELECT COALESCE(SUM(words_count), 0) AS words
1834
+ FROM text_sentence_records
1835
+ WHERE kind = 2
1836
+ ${chapterId === void 0 ? "" : "AND chapter_id = ?"}
1837
+ `,
1838
+ chapterId === void 0 ? void 0 : [chapterId],
1839
+ (row) => Number(row.words)
1840
+ ) ?? 0
1841
+ );
1842
+ }
1843
+ async function readIndexArtifactCoverage(document, kind, chapterId) {
1844
+ const coverage = await document.indexArtifacts.listCoverage(kind);
1845
+ return chapterId === void 0 ? coverage : coverage.filter((item) => item.serialId === chapterId);
1846
+ }
1847
+ function filterChaptersByCurrentIndexArtifact(chapters, coverage) {
1848
+ const currentChapterIds = new Set(
1849
+ coverage.filter((item) => item.current).map((item) => item.serialId)
1850
+ );
1851
+ return chapters.filter((chapter) => currentChapterIds.has(chapter.chapterId));
1852
+ }
1853
+ function createInspectCoverage(covered, total) {
1854
+ const coveredWords = sumWords(covered);
1855
+ const totalWords = sumWords(total);
1856
+ return {
1857
+ coveredChapters: covered.length,
1858
+ coveredWords,
1859
+ percent: formatPercent(coveredWords, totalWords),
1860
+ totalChapters: total.length,
1861
+ totalWords
1862
+ };
1863
+ }
1864
+ function formatRetrievalGuidance(input) {
1865
+ if (input.sourceWords === 0 || input.contentChapters.length === 0) {
1866
+ return [
1867
+ "Source content: empty.",
1868
+ "Add source text before using query coverage or graph-based retrieval."
1869
+ ];
1870
+ }
1871
+ const lines = [
1872
+ input.queryReady ? `Query: available; local index cache is ${input.indexCacheCurrent ? "current" : "missing or outdated and can be synced from artifacts"}.` : "Query: unavailable until every content chapter has a current FTS or source embedding artifact."
1873
+ ];
1874
+ lines.push(
1875
+ formatObjectSearchGuidance(
1876
+ "Reading Graph object retrieval",
1877
+ input.readingGraphCovered,
1878
+ input.contentChapters
1879
+ )
1880
+ );
1881
+ lines.push(
1882
+ formatObjectSearchGuidance(
1883
+ "Entity/triple retrieval",
1884
+ input.knowledgeGraphCovered,
1885
+ input.contentChapters
1886
+ )
1887
+ );
1888
+ return lines;
1889
+ }
1890
+ function formatObjectSearchGuidance(label, covered, total) {
1891
+ const coveredWords = sumWords(covered);
1892
+ const totalWords = sumWords(total);
1893
+ const ratio = totalWords === 0 ? 0 : coveredWords / totalWords;
1894
+ const coverage = formatPercent(coveredWords, totalWords);
1895
+ if (ratio >= 1) {
1896
+ return `${label}: covers all source content; it can represent the full scope for object retrieval.`;
1897
+ }
1898
+ if (ratio >= 0.9) {
1899
+ return `${label}: covers ${coverage}; use it as the main path, but source --query is needed for uncovered content.`;
1900
+ }
1901
+ if (ratio >= 0.5) {
1902
+ return `${label}: covers ${coverage}; use it as leads, not as a full-scope substitute for source --query.`;
1903
+ }
1904
+ return `${label}: covers ${coverage}; build missing graph coverage before relying on object retrieval.`;
1905
+ }
1906
+ function createInspectImprovements(input) {
1907
+ const improvements = [];
1908
+ if (input.contentChapters.length === 0) {
1909
+ improvements.push({
1910
+ kind: "add-source",
1911
+ recommendation: "No source content is available yet; add or import source text before graph or summary generation.",
1912
+ title: "Add source content"
1913
+ });
1914
+ return improvements;
1915
+ }
1916
+ if (input.queryBlockedChapters.length > 0) {
1917
+ improvements.push({
1918
+ kind: "build",
1919
+ missingChapters: input.queryBlockedChapters.length,
1920
+ missingWords: sumWords(input.queryBlockedChapters),
1921
+ recommendation: "Build local FTS artifacts to make this scope queryable. This does not call a provider.",
1922
+ task: "index-fts",
1923
+ title: "Enable query with local FTS"
1924
+ });
1925
+ } else if (!input.indexCacheCurrent) {
1926
+ improvements.push({
1927
+ kind: "sync-index",
1928
+ recommendation: "Sync the index cache from chapter index artifacts so query starts without a lazy cache rebuild.",
1929
+ title: "Sync index cache"
1930
+ });
1931
+ }
1932
+ improvements.push(
1933
+ ...createGraphImprovement({
1934
+ concurrent: input.concurrent,
1935
+ covered: input.readingGraphCovered,
1936
+ planningModel: input.planningModel,
1937
+ task: "reading-graph",
1938
+ title: "Complete Reading Graph coverage",
1939
+ total: input.contentChapters
1940
+ })
1941
+ );
1942
+ improvements.push(
1943
+ ...createGraphImprovement({
1944
+ concurrent: input.concurrent,
1945
+ covered: input.knowledgeGraphCovered,
1946
+ planningModel: input.planningModel,
1947
+ task: "knowledge-graph",
1948
+ title: "Complete Knowledge Graph coverage",
1949
+ total: input.contentChapters
1950
+ })
1951
+ );
1952
+ improvements.push(
1953
+ ...createGraphImprovement({
1954
+ concurrent: input.concurrent,
1955
+ covered: input.summaryCovered,
1956
+ planningModel: input.planningModel,
1957
+ task: "reading-summary",
1958
+ title: "Complete Summary coverage",
1959
+ total: input.contentChapters
1960
+ })
1961
+ );
1962
+ return improvements;
1963
+ }
1964
+ function createGraphImprovement(input) {
1965
+ const coveredIds = new Set(input.covered.map((chapter) => chapter.chapterId));
1966
+ const missing = input.total.filter(
1967
+ (chapter) => !coveredIds.has(chapter.chapterId)
1968
+ );
1969
+ if (missing.length === 0) {
1970
+ return [];
1971
+ }
1972
+ const missingWords = sumWords(missing);
1973
+ return [
1974
+ {
1975
+ kind: "build",
1976
+ missingChapters: missing.length,
1977
+ missingWords,
1978
+ planning: planGenerationTask(
1979
+ input.task,
1980
+ missingWords,
1981
+ missing.length,
1982
+ input.concurrent,
1983
+ input.planningModel
1984
+ ),
1985
+ recommendation: formatImprovementRecommendation(
1986
+ input.covered,
1987
+ input.total,
1988
+ missingWords
1989
+ ),
1990
+ task: input.task,
1991
+ title: input.title
1992
+ }
1993
+ ];
1994
+ }
1995
+ function formatImprovementRecommendation(covered, total, missingWords) {
1996
+ const totalWords = sumWords(total);
1997
+ const coveredWords = sumWords(covered);
1998
+ if (totalWords === 0) {
1999
+ return "No source content is available.";
2000
+ }
2001
+ if (total.length === 1 || coveredWords / totalWords >= 0.9 || missingWords <= 1e3) {
2002
+ return "Queue the full scope to finish the remaining gap.";
2003
+ }
2004
+ return "Queue selected chapters first if only part of the scope matters.";
2005
+ }
2006
+ function sumWords(chapters) {
2007
+ return chapters.reduce((total, chapter) => total + chapter.words, 0);
2008
+ }
2009
+ function formatPercent(numerator, denominator) {
2010
+ if (denominator === 0) {
2011
+ return "n/a";
2012
+ }
2013
+ const percent = numerator / denominator * 100;
2014
+ return `${Number.isInteger(percent) ? percent.toFixed(0) : percent.toFixed(1)}%`;
2015
+ }
2016
+
2017
+ // src/archive/archive.ts
2018
+ var WikiGraphArchiveExistsError = class extends Error {
2019
+ code = "WIKI_GRAPH_ARCHIVE_EXISTS";
2020
+ path;
2021
+ constructor(path) {
2022
+ super(`Archive already exists: ${path}`);
2023
+ this.name = "WikiGraphArchiveExistsError";
2024
+ this.path = path;
2025
+ }
2026
+ };
2027
+ var WikiGraphArchiveManager = class {
2028
+ #runtime;
2029
+ constructor(runtime) {
2030
+ this.#runtime = runtime;
2031
+ }
2032
+ async create(options) {
2033
+ return await this.#runtime.run(async () => {
2034
+ const path = resolveWikiGraphRuntimePath(options.path);
2035
+ if (options.replace !== true && await nodePathExists(path)) {
2036
+ throw new WikiGraphArchiveExistsError(path);
2037
+ }
2038
+ const outputPath = join3(
2039
+ dirname2(path),
2040
+ `.${basename2(path)}.${randomUUID2()}.tmp.wikg`
2041
+ );
2042
+ try {
2043
+ if (options.importPath === void 0) {
2044
+ await createEmptyArchiveFile(outputPath);
2045
+ } else {
2046
+ await new WikiGraphConversionManager(this.#runtime).convert({
2047
+ input: { format: "epub", path: options.importPath },
2048
+ ...options.onProgress === void 0 ? {} : { onProgress: options.onProgress },
2049
+ output: { format: "wikg", path: outputPath },
2050
+ targetStage: "sourced"
2051
+ });
2052
+ }
2053
+ if (options.replace === true) {
2054
+ await rename2(outputPath, path);
2055
+ } else {
2056
+ try {
2057
+ await link(outputPath, path);
2058
+ } catch (error) {
2059
+ if (isNodeEEXISTError(error)) {
2060
+ throw new WikiGraphArchiveExistsError(path);
2061
+ }
2062
+ throw error;
2063
+ }
2064
+ }
2065
+ return { locatedUri: formatLocatedWikiGraphUri(path), path };
2066
+ } finally {
2067
+ await rm3(outputPath, { force: true, recursive: true });
2068
+ }
2069
+ }, options.signal);
2070
+ }
2071
+ async open(uriOrPath, options = {}) {
2072
+ const location = await this.#runtime.run(
2073
+ async () => await resolveWikiGraphArchiveLocation(uriOrPath),
2074
+ options.signal
2075
+ );
2076
+ return new WikiGraphArchiveHandle(this.#runtime, location);
2077
+ }
2078
+ };
2079
+ var WikiGraphArchiveHandle = class {
2080
+ #runtime;
2081
+ #location;
2082
+ constructor(runtime, location) {
2083
+ this.#runtime = runtime;
2084
+ this.#location = location;
2085
+ }
2086
+ get archiveKey() {
2087
+ return this.#location.archiveKey;
2088
+ }
2089
+ get indexScope() {
2090
+ return this.#location.indexScope;
2091
+ }
2092
+ get locatedUri() {
2093
+ return this.#location.locatedUri;
2094
+ }
2095
+ get objectUri() {
2096
+ return parseLocatedWikiGraphUri(this.#location.locatedUri).objectUri ?? "wikg://";
2097
+ }
2098
+ get path() {
2099
+ return this.#location.archivePath;
2100
+ }
2101
+ async inspect(options = {}) {
2102
+ return await this.#readDocument(
2103
+ async (document) => await createWikiGraphArchiveInspectReport(document, {
2104
+ archiveUri: this.#location.publicArchiveUri ?? this.locatedUri,
2105
+ ...options.chapterId === void 0 ? {} : { chapterId: options.chapterId }
2106
+ }),
2107
+ options
2108
+ );
2109
+ }
2110
+ async search(query, options = {}) {
2111
+ const embeddingProvider = await this.#runtime.run(
2112
+ createConfiguredEmbeddingProvider,
2113
+ options.signal
2114
+ );
2115
+ return await this.#writeDocument(
2116
+ async (document) => {
2117
+ const chapters = await this.#resolveQueryChapters(document, options);
2118
+ await ensureArchiveSearchIndex(document, {
2119
+ ...chapters === void 0 ? {} : { chapters },
2120
+ ...embeddingProvider === void 0 ? {} : { embeddingProvider }
2121
+ });
2122
+ return await findArchiveObjects(document, query, {
2123
+ ...withoutOperationAndScope(options),
2124
+ archiveKey: this.archiveKey,
2125
+ ...chapters === void 0 ? {} : { chapters },
2126
+ ...embeddingProvider === void 0 ? {} : { embeddingProvider }
2127
+ });
2128
+ },
2129
+ {
2130
+ searchIndexWritebackPolicy: "cache",
2131
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2132
+ }
2133
+ );
2134
+ }
2135
+ async list(options = {}) {
2136
+ return await this.#readDocument(async (document) => {
2137
+ if (isSourceLocatorScopeUri(this.objectUri)) {
2138
+ return await listArchiveSourceLocators(document, this.objectUri, {
2139
+ ...options.cursor === void 0 ? {} : { cursor: options.cursor },
2140
+ ...options.limit === void 0 ? {} : { limit: options.limit }
2141
+ });
2142
+ }
2143
+ const chapters = await this.#resolveScope(document, options);
2144
+ return await listArchiveCollection(document, {
2145
+ ...withoutOperationAndScope(options),
2146
+ ...chapters === void 0 ? {} : { chapters }
2147
+ });
2148
+ }, options);
2149
+ }
2150
+ async ensureSearchIndex(options = {}) {
2151
+ const embeddingProvider = await this.#runtime.run(
2152
+ createConfiguredEmbeddingProvider,
2153
+ options.signal
2154
+ );
2155
+ await this.#writeDocument(
2156
+ async (document) => {
2157
+ const chapters = await this.#resolveScope(document, options);
2158
+ await ensureArchiveSearchIndex(document, {
2159
+ ...chapters === void 0 ? {} : { chapters },
2160
+ ...embeddingProvider === void 0 ? {} : { embeddingProvider }
2161
+ });
2162
+ },
2163
+ {
2164
+ searchIndexWritebackPolicy: "cache",
2165
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2166
+ }
2167
+ );
2168
+ }
2169
+ async getSearchIndexStatus(options = {}) {
2170
+ return await this.#readDocument(
2171
+ async (document) => ({
2172
+ capabilities: await readSearchIndexCapabilityStatus(document),
2173
+ current: await isArchiveSearchIndexCurrent2(document)
2174
+ }),
2175
+ options
2176
+ );
2177
+ }
2178
+ async syncSearchIndex(options = {}) {
2179
+ const rebuilt = await this.#writeDocument(
2180
+ async (document) => {
2181
+ const scope = options.skipUnindexed === true ? { chapters: await listArchiveQueryableChapterIds(document) } : {};
2182
+ if (scope.chapters?.length === 0) {
2183
+ throw new Error(
2184
+ "Wiki Graph index cache is not ready. No chapters have a current FTS artifact or source embedding artifact."
2185
+ );
2186
+ }
2187
+ if (await isArchiveSearchIndexCurrent2(document, scope)) return false;
2188
+ await rebuildArchiveSearchIndex(document, options.onProgress, scope);
2189
+ return true;
2190
+ },
2191
+ {
2192
+ searchIndexWritebackPolicy: "cache",
2193
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2194
+ }
2195
+ );
2196
+ await this.#runtime.run(
2197
+ async () => await deleteArchiveSearchSessions(this.path),
2198
+ options.signal
2199
+ );
2200
+ return { rebuilt };
2201
+ }
2202
+ async cleanSearchIndex(options = {}) {
2203
+ const status = await this.#writeDocument(
2204
+ async (document) => {
2205
+ await document.deleteSearchIndexDatabase();
2206
+ return {
2207
+ capabilities: {
2208
+ dense: { current: false },
2209
+ indexes: "missing"
2210
+ },
2211
+ current: false
2212
+ };
2213
+ },
2214
+ {
2215
+ searchIndexWritebackPolicy: "cache",
2216
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2217
+ }
2218
+ );
2219
+ await this.#runtime.run(
2220
+ async () => await deleteArchiveSearchSessions(this.path),
2221
+ options.signal
2222
+ );
2223
+ return status;
2224
+ }
2225
+ async listChapters(options = {}) {
2226
+ return await this.#readDocument(
2227
+ async (document) => await listChapters2(document),
2228
+ options
2229
+ );
2230
+ }
2231
+ async getChapter(path, options = {}) {
2232
+ return await this.#readDocument(async (document) => {
2233
+ const chapterId = await resolveChapterPathReadonly(document, path);
2234
+ return requireChapter(await listChapters2(document), chapterId);
2235
+ }, options);
2236
+ }
2237
+ async addChapter(options) {
2238
+ return await this.#writeDocument(async (document) => {
2239
+ const parentChapterId = await resolveOptionalChapterPath(
2240
+ document,
2241
+ options.parentPath
2242
+ );
2243
+ await assertNoActiveBuildJobConflicts({
2244
+ archive: this.#location.archiveFile,
2245
+ operation: "Adding chapter",
2246
+ scope: { kind: "archive" }
2247
+ });
2248
+ let details = await addChapter(document, {
2249
+ ...parentChapterId === void 0 ? {} : { parentChapterId },
2250
+ ...options.title === void 0 ? {} : { title: options.title }
2251
+ });
2252
+ if (options.source !== void 0) {
2253
+ details = await setChapterSource(
2254
+ document,
2255
+ details.chapterId,
2256
+ asTextStream(options.source)
2257
+ );
2258
+ }
2259
+ return details;
2260
+ });
2261
+ }
2262
+ async getChapterArtifact(path, kind) {
2263
+ return await this.#readDocument(async (document) => {
2264
+ const chapterId = await resolveChapterPathReadonly(document, path);
2265
+ const [artifact, revision] = await Promise.all([
2266
+ document.indexArtifacts.get(chapterId, kind),
2267
+ document.serials.getRevision(chapterId)
2268
+ ]);
2269
+ return {
2270
+ ...artifact === void 0 ? {} : {
2271
+ artifact: {
2272
+ createdAt: artifact.createdAt,
2273
+ metadata: artifact.metadata,
2274
+ sourceRevision: artifact.sourceRevision
2275
+ }
2276
+ },
2277
+ chapterId,
2278
+ current: artifact?.sourceRevision === revision,
2279
+ kind,
2280
+ missing: artifact === void 0,
2281
+ revision
2282
+ };
2283
+ });
2284
+ }
2285
+ async deleteChapterArtifact(path, kind) {
2286
+ return await this.#writeDocument(async (document) => {
2287
+ const chapterId = await resolveChapterPathReadonly(document, path);
2288
+ await document.indexArtifacts.delete(chapterId, kind);
2289
+ return { chapterId, deleted: true, kind };
2290
+ });
2291
+ }
2292
+ async moveChapter(path, options) {
2293
+ return await this.#writeDocument(async (document) => {
2294
+ const chapterId = await resolveChapterPathReadonly(document, path);
2295
+ const [afterChapterId, beforeChapterId, parentChapterId] = await Promise.all([
2296
+ resolveOptionalChapterPath(document, options.afterPath),
2297
+ resolveOptionalChapterPath(document, options.beforePath),
2298
+ resolveOptionalChapterPath(document, options.parentPath)
2299
+ ]);
2300
+ await assertNoActiveBuildJobConflicts({
2301
+ archive: this.#location.archiveFile,
2302
+ operation: "Moving chapter",
2303
+ scope: { kind: "archive" }
2304
+ });
2305
+ return await moveChapter(document, chapterId, {
2306
+ ...afterChapterId === void 0 ? {} : { afterChapterId },
2307
+ ...beforeChapterId === void 0 ? {} : { beforeChapterId },
2308
+ ...parentChapterId === void 0 ? {} : { parentChapterId },
2309
+ ...options.first === void 0 ? {} : { first: options.first },
2310
+ ...options.last === void 0 ? {} : { last: options.last },
2311
+ ...options.root === void 0 ? {} : { root: options.root }
2312
+ });
2313
+ });
2314
+ }
2315
+ async removeChapter(path, recursive = false) {
2316
+ await this.#writeDocument(async (document) => {
2317
+ const chapterId = await resolveChapterPathReadonly(document, path);
2318
+ await assertNoActiveBuildJobConflicts({
2319
+ archive: this.#location.archiveFile,
2320
+ operation: "Removing chapter",
2321
+ scope: { kind: "archive" }
2322
+ });
2323
+ await removeChapter(document, chapterId, { recursive });
2324
+ });
2325
+ }
2326
+ async resetChapter(path, stage) {
2327
+ return await this.#writeDocument(async (document) => {
2328
+ const chapterId = await resolveChapterPathReadonly(document, path);
2329
+ await assertChapterResetAllowed(
2330
+ this.#location.archiveFile,
2331
+ chapterId,
2332
+ stage
2333
+ );
2334
+ return await resetChapter(document, chapterId, stage);
2335
+ });
2336
+ }
2337
+ async setChapterSource(path, source, options = {}) {
2338
+ return await this.#writeDocument(async (document) => {
2339
+ const chapterId = await resolveChapterPathReadonly(document, path);
2340
+ await assertNoActiveBuildJobs({
2341
+ archive: this.#location.archiveFile,
2342
+ chapterIds: [chapterId],
2343
+ operation: "Setting chapter source"
2344
+ });
2345
+ return await setChapterSource(
2346
+ document,
2347
+ chapterId,
2348
+ asTextStream(source),
2349
+ options
2350
+ );
2351
+ });
2352
+ }
2353
+ async setChapterSummary(path, summary) {
2354
+ return await this.#writeDocument(async (document) => {
2355
+ const chapterId = await resolveChapterPathReadonly(document, path);
2356
+ await assertNoActiveBuildJobs({
2357
+ archive: this.#location.archiveFile,
2358
+ chapterIds: [chapterId],
2359
+ operation: "Setting chapter summary",
2360
+ requiresTarget: "reading-summary"
2361
+ });
2362
+ return await setChapterSummary(document, chapterId, summary);
2363
+ });
2364
+ }
2365
+ async setChapterTitle(path, title) {
2366
+ return await this.#writeDocument(async (document) => {
2367
+ const chapterId = await resolveChapterPathReadonly(document, path);
2368
+ await assertNoActiveBuildJobs({
2369
+ archive: this.#location.archiveFile,
2370
+ chapterIds: [chapterId],
2371
+ operation: "Setting chapter title"
2372
+ });
2373
+ return await setChapterTitle(document, chapterId, title);
2374
+ });
2375
+ }
2376
+ async getChapterTree() {
2377
+ return await this.#readDocument(
2378
+ async (document) => await getChapterTree(document)
2379
+ );
2380
+ }
2381
+ async applyChapterTree(tree, options = {}) {
2382
+ return await this.#writeDocument(
2383
+ async (document) => {
2384
+ if (options.dryRun !== true) {
2385
+ await assertNoActiveBuildJobConflicts({
2386
+ archive: this.#location.archiveFile,
2387
+ operation: "Changing chapter tree",
2388
+ scope: { kind: "archive" }
2389
+ });
2390
+ }
2391
+ return await applyChapterTree(document, tree, {
2392
+ dryRun: options.dryRun ?? false
2393
+ });
2394
+ },
2395
+ { refreshLibraryIndex: options.dryRun !== true }
2396
+ );
2397
+ }
2398
+ async page(objectUri = this.objectUri, options = {}) {
2399
+ return await this.#runtime.run(
2400
+ async () => await withConfiguredWikimediaResolver(
2401
+ objectUri,
2402
+ async (wikimediaOptions) => await this.#readDocument(
2403
+ async (document) => await readArchivePage(document, objectUri, {
2404
+ ...withoutOperation(options),
2405
+ ...wikimediaOptions
2406
+ }),
2407
+ options
2408
+ )
2409
+ ),
2410
+ options.signal
2411
+ );
2412
+ }
2413
+ async related(objectUri = this.objectUri, options = {}) {
2414
+ if (options.query === void 0) {
2415
+ return await this.#readDocument(async (document) => {
2416
+ const chapters = await this.#resolveScope(document, {});
2417
+ return await listRelatedArchiveObjects(document, objectUri, {
2418
+ ...withoutOperation(options),
2419
+ ...chapters === void 0 ? {} : { chapters }
2420
+ });
2421
+ }, options);
2422
+ }
2423
+ const embeddingProvider = await this.#runtime.run(
2424
+ createConfiguredEmbeddingProvider,
2425
+ options.signal
2426
+ );
2427
+ return await this.#writeDocument(
2428
+ async (document) => {
2429
+ const chapters = await this.#resolveQueryChapters(document, options);
2430
+ await ensureArchiveSearchIndex(document, {
2431
+ ...chapters === void 0 ? {} : { chapters },
2432
+ ...embeddingProvider === void 0 ? {} : { embeddingProvider }
2433
+ });
2434
+ return await listRelatedArchiveObjects(document, objectUri, {
2435
+ ...withoutOperation(options),
2436
+ ...chapters === void 0 ? {} : { chapters }
2437
+ });
2438
+ },
2439
+ {
2440
+ searchIndexWritebackPolicy: "cache",
2441
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2442
+ }
2443
+ );
2444
+ }
2445
+ async evidence(objectUri = this.objectUri, options = {}) {
2446
+ if (options.query === void 0) {
2447
+ return await this.#readDocument(async (document) => {
2448
+ const chapters = await this.#resolveScope(document, {});
2449
+ return await listArchiveEvidence(document, objectUri, {
2450
+ ...withoutOperation(options),
2451
+ ...chapters === void 0 ? {} : { chapters }
2452
+ });
2453
+ }, options);
2454
+ }
2455
+ const embeddingProvider = await this.#runtime.run(
2456
+ createConfiguredEmbeddingProvider,
2457
+ options.signal
2458
+ );
2459
+ return await this.#writeDocument(
2460
+ async (document) => {
2461
+ const chapters = await this.#resolveQueryChapters(document, options);
2462
+ await ensureArchiveSearchIndex(document, {
2463
+ ...chapters === void 0 ? {} : { chapters },
2464
+ ...embeddingProvider === void 0 ? {} : { embeddingProvider }
2465
+ });
2466
+ return await listArchiveEvidence(document, objectUri, {
2467
+ ...withoutOperation(options),
2468
+ ...chapters === void 0 ? {} : { chapters }
2469
+ });
2470
+ },
2471
+ {
2472
+ searchIndexWritebackPolicy: "cache",
2473
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2474
+ }
2475
+ );
2476
+ }
2477
+ async pack(objectUri = this.objectUri, budget = 5e3, options = {}) {
2478
+ return await this.#readDocument(
2479
+ async (document) => await packArchiveContext(document, objectUri, budget),
2480
+ options
2481
+ );
2482
+ }
2483
+ async getMetadata(objectPath, options = {}) {
2484
+ return await this.#readDocument(
2485
+ async (document) => await document.metadata.getMap(objectPath),
2486
+ options
2487
+ );
2488
+ }
2489
+ async readBookMeta(options = {}) {
2490
+ return await this.#readDocument(
2491
+ async (document) => await document.readBookMeta(),
2492
+ options
2493
+ );
2494
+ }
2495
+ async replaceBookMeta(meta, options = {}) {
2496
+ return await this.#writeDocument(async (document) => {
2497
+ await document.replaceBookMeta(meta);
2498
+ return meta;
2499
+ }, options);
2500
+ }
2501
+ async readCover(options = {}) {
2502
+ const app = new WikiGraph2({});
2503
+ return await this.#runtime.run(
2504
+ async () => await app.openSession(
2505
+ this.#location.archiveFile,
2506
+ async (archive) => await archive.readCover()
2507
+ ),
2508
+ options.signal
2509
+ );
2510
+ }
2511
+ async replaceMetadata(objectPath, value, options = {}) {
2512
+ return await this.#writeDocument(async (document) => {
2513
+ await document.metadata.replaceMap(
2514
+ parseObjectMetadataTarget(objectPath),
2515
+ value
2516
+ );
2517
+ return await document.metadata.getMap(objectPath);
2518
+ }, options);
2519
+ }
2520
+ async putMetadata(objectPath, key, value, options = {}) {
2521
+ return await this.#writeDocument(async (document) => {
2522
+ await document.metadata.put(
2523
+ parseObjectMetadataTarget(objectPath),
2524
+ key,
2525
+ value
2526
+ );
2527
+ return await document.metadata.getMap(objectPath);
2528
+ }, options);
2529
+ }
2530
+ async deleteMetadata(objectPath, key, options = {}) {
2531
+ return await this.#writeDocument(async (document) => {
2532
+ await document.metadata.deleteKey(objectPath, key);
2533
+ return await document.metadata.getMap(objectPath);
2534
+ }, options);
2535
+ }
2536
+ async clearMetadata(objectPath, options = {}) {
2537
+ return await this.#writeDocument(async (document) => {
2538
+ await document.metadata.clear(objectPath);
2539
+ return await document.metadata.getMap(objectPath);
2540
+ }, options);
2541
+ }
2542
+ async resolveScope(options = {}) {
2543
+ return await this.#readDocument(
2544
+ async (document) => await resolveArchiveScope(document, this.objectUri, options.depth),
2545
+ options
2546
+ );
2547
+ }
2548
+ async #readDocument(operation, options = {}) {
2549
+ return await this.#runtime.run(
2550
+ async () => await new WikiGraphArchiveFile(this.#location.archiveFile).readDocument(
2551
+ operation
2552
+ ),
2553
+ options.signal
2554
+ );
2555
+ }
2556
+ async #writeDocument(operation, options = {}) {
2557
+ return await this.#runtime.run(async () => {
2558
+ const result = await new WikiGraphArchiveFile(
2559
+ this.#location.archiveFile
2560
+ ).write(operation, {
2561
+ ...options.searchIndexWritebackPolicy === void 0 ? {} : {
2562
+ searchIndexWritebackPolicy: options.searchIndexWritebackPolicy
2563
+ }
2564
+ });
2565
+ if (options.refreshLibraryIndex !== false) {
2566
+ await this.#refreshLibraryIndex(options.onIndexSyncError);
2567
+ }
2568
+ return result;
2569
+ }, options.signal);
2570
+ }
2571
+ async #resolveScope(document, options) {
2572
+ if (options.chapters !== void 0) return options.chapters;
2573
+ return (await resolveArchiveScope(document, this.objectUri, options.depth))?.chapterIds;
2574
+ }
2575
+ async #resolveQueryChapters(document, options) {
2576
+ const chapters = await this.#resolveScope(document, options);
2577
+ if (options.skipUnindexed !== true) return chapters;
2578
+ const queryable = await listArchiveQueryableChapterIds(document, {
2579
+ ...chapters === void 0 ? {} : { chapters }
2580
+ });
2581
+ if (queryable.length === 0) {
2582
+ throw new Error(
2583
+ "Wiki Graph query is not ready. No chapters in this scope have a current FTS artifact or source embedding artifact."
2584
+ );
2585
+ }
2586
+ return queryable;
2587
+ }
2588
+ async #refreshLibraryIndex(onError) {
2589
+ if (this.#location.libraryDirtyTarget === void 0) return;
2590
+ if (this.#location.libraryArchiveTarget !== void 0) {
2591
+ await finalizeWikiGraphLibraryArchiveWrite({
2592
+ target: this.#location.libraryArchiveTarget
2593
+ });
2594
+ }
2595
+ try {
2596
+ const state = await readWikiGraphLibraryIndexState(
2597
+ this.#location.libraryDirtyTarget
2598
+ );
2599
+ if (state.status !== "missing") {
2600
+ await rebuildWikiGraphLibraryIndex(this.#location.libraryDirtyTarget);
2601
+ }
2602
+ } catch (error) {
2603
+ onError?.(error);
2604
+ }
2605
+ }
2606
+ };
2607
+ async function resolveWikiGraphArchiveLocation(uriOrPath) {
2608
+ if (!uriOrPath.startsWith("wikg://")) {
2609
+ return createPathLocation(resolveWikiGraphRuntimePath(uriOrPath));
2610
+ }
2611
+ const parsed = parseLocatedWikiGraphUri(uriOrPath);
2612
+ const portableArchiveLocator = parsed.archivePath ?? uriOrPath;
2613
+ const archiveLocator = portableArchiveLocator.startsWith("wikg://lib/") ? portableArchiveLocator : resolveWikiGraphRuntimePath(portableArchiveLocator);
2614
+ const libraryArchiveTarget = archiveLocator.startsWith("wikg://lib/") ? parseWikiGraphLibraryUri(archiveLocator) : void 0;
2615
+ const archiveFile = libraryArchiveTarget?.kind === "archive" ? await resolveWikiGraphLibraryArchiveFile(archiveLocator) : new NodeFile(archiveLocator);
2616
+ const archivePath = getNodeResourcePath(archiveFile);
2617
+ return {
2618
+ archiveFile,
2619
+ archiveKey: archivePath,
2620
+ archivePath,
2621
+ indexScope: { archiveKey: archivePath, archivePath, kind: "archive-index" },
2622
+ ...libraryArchiveTarget?.kind === "archive" ? {
2623
+ libraryArchiveTarget,
2624
+ libraryDirtyTarget: {
2625
+ isDefault: libraryArchiveTarget.isDefault,
2626
+ kind: "scope",
2627
+ ...libraryArchiveTarget.publicId === void 0 ? {} : { publicId: libraryArchiveTarget.publicId }
2628
+ },
2629
+ publicArchiveUri: portableArchiveLocator
2630
+ } : {},
2631
+ locatedUri: formatLocatedWikiGraphUri(archivePath, parsed.objectUri)
2632
+ };
2633
+ }
2634
+ async function ensureArchiveSearchIndex(document, options = {}) {
2635
+ const scope = options.chapters === void 0 ? {} : { chapters: options.chapters };
2636
+ if (await isArchiveSearchIndexCurrent2(document, scope)) return;
2637
+ await rebuildArchiveSearchIndex(document, void 0, {
2638
+ ...scope,
2639
+ ...options.embeddingProvider === void 0 ? {} : { embeddingProvider: options.embeddingProvider }
2640
+ });
2641
+ }
2642
+ async function resolveArchiveScope(document, objectUri, depth) {
2643
+ const parsed = parseChapterScopePath(objectUri);
2644
+ if (parsed === void 0 || parsed.kind === "collection" && depth === void 0) {
2645
+ return void 0;
2646
+ }
2647
+ const chapters = await listChapters2(document);
2648
+ const entries = parsed.kind === "collection" ? chapters.filter((chapter) => chapter.depth <= depth) : selectChapterSubtree(
2649
+ chapters,
2650
+ await resolveChapterPathReadonly(document, parsed.chapterPath),
2651
+ depth
2652
+ );
2653
+ return { chapterIds: entries.map((entry) => entry.chapterId), entries };
2654
+ }
2655
+ function parseChapterScopePath(objectUri) {
2656
+ if (objectUri === "wikg://chapter" || objectUri === "wikg://chapter/") {
2657
+ return { kind: "collection" };
2658
+ }
2659
+ const match = /^wikg:\/\/chapter\/([^/].*?)(?:\/)?$/u.exec(objectUri);
2660
+ return match?.[1] === void 0 ? void 0 : { chapterPath: decodeURIComponent(match[1]), kind: "chapter" };
2661
+ }
2662
+ function selectChapterSubtree(chapters, rootChapterId, depth) {
2663
+ const root = chapters.find((chapter) => chapter.chapterId === rootChapterId);
2664
+ if (root === void 0) {
2665
+ throw new Error(`Chapter ${rootChapterId} does not exist.`);
2666
+ }
2667
+ const prefix = `${root.path}/`;
2668
+ return chapters.filter(
2669
+ (chapter) => chapter.chapterId === root.chapterId || chapter.path.startsWith(prefix) && (depth === void 0 || chapter.depth - root.depth <= depth)
2670
+ );
2671
+ }
2672
+ function createPathLocation(path) {
2673
+ return {
2674
+ archiveFile: new NodeFile(path),
2675
+ archiveKey: path,
2676
+ archivePath: path,
2677
+ indexScope: { archiveKey: path, archivePath: path, kind: "archive-index" },
2678
+ locatedUri: formatLocatedWikiGraphUri(path)
2679
+ };
2680
+ }
2681
+ async function createEmptyArchiveFile(path) {
2682
+ const directoryPath = await mkdtemp(
2683
+ join3(tmpdir(), "wikigraph-archive-write-")
2684
+ );
2685
+ try {
2686
+ const directory = new NodeDirectory(directoryPath);
2687
+ const document = await DirectoryDocument.open(directory);
2688
+ try {
2689
+ await document.openSession(async (openedDocument) => {
2690
+ await openedDocument.writeToc({ items: [], version: TOC_FILE_VERSION });
2691
+ });
2692
+ } finally {
2693
+ await document.release();
2694
+ }
2695
+ await writeWikgArchive(directory, new NodeFile(path));
2696
+ } finally {
2697
+ await rm3(directoryPath, { force: true, recursive: true });
2698
+ }
2699
+ }
2700
+ function isNodeEEXISTError(error) {
2701
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
2702
+ }
2703
+ async function nodePathExists(path) {
2704
+ try {
2705
+ await stat2(path);
2706
+ return true;
2707
+ } catch (error) {
2708
+ if (isNodeENOENTError(error)) return false;
2709
+ throw error;
2710
+ }
2711
+ }
2712
+ function isNodeENOENTError(error) {
2713
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
2714
+ }
2715
+ function parseObjectMetadataTarget(objectPath) {
2716
+ if (objectPath === "") {
2717
+ return { kind: ObjectMetadataKind.Archive, objectPath };
2718
+ }
2719
+ const chapter = /^chapter\/([1-9][0-9]*)(?:\/.*)?$/u.exec(objectPath);
2720
+ if (chapter?.[1] !== void 0) {
2721
+ return {
2722
+ chapterId: Number(chapter[1]),
2723
+ kind: ObjectMetadataKind.Chapter,
2724
+ objectPath
2725
+ };
2726
+ }
2727
+ const chunk = /^chunk\/([1-9][0-9]*)$/u.exec(objectPath);
2728
+ if (chunk?.[1] !== void 0) {
2729
+ return {
2730
+ chunkId: Number(chunk[1]),
2731
+ kind: ObjectMetadataKind.Chunk,
2732
+ objectPath
2733
+ };
2734
+ }
2735
+ const entity = /^entity\/(Q[1-9][0-9]*)$/u.exec(objectPath);
2736
+ if (entity?.[1] !== void 0) {
2737
+ return {
2738
+ entityQid: entity[1],
2739
+ kind: ObjectMetadataKind.Entity,
2740
+ objectPath
2741
+ };
2742
+ }
2743
+ const triple = /^triple\/(Q[1-9][0-9]*)\/([^/]+)\/(Q[1-9][0-9]*)$/u.exec(
2744
+ objectPath
2745
+ );
2746
+ if (triple?.[1] !== void 0) {
2747
+ return {
2748
+ kind: ObjectMetadataKind.Triple,
2749
+ objectPath,
2750
+ tripleObjectQid: triple[3],
2751
+ triplePredicate: decodeURIComponent(triple[2]),
2752
+ tripleSubjectQid: triple[1]
2753
+ };
2754
+ }
2755
+ return { kind: ObjectMetadataKind.Object, objectPath };
2756
+ }
2757
+ function withoutOperation(options) {
2758
+ const { signal: _signal, ...rest } = options;
2759
+ return rest;
2760
+ }
2761
+ function withoutOperationAndScope(options) {
2762
+ const {
2763
+ chapters: _chapters,
2764
+ depth: _depth,
2765
+ signal: _signal,
2766
+ ...rest
2767
+ } = options;
2768
+ return rest;
2769
+ }
2770
+ async function resolveOptionalChapterPath(document, path) {
2771
+ return path === void 0 ? void 0 : await resolveChapterPathReadonly(document, path);
2772
+ }
2773
+ function requireChapter(chapters, chapterId) {
2774
+ const chapter = chapters.find((entry) => entry.chapterId === chapterId);
2775
+ if (chapter === void 0) {
2776
+ throw new Error(`Chapter internal id ${chapterId} does not exist.`);
2777
+ }
2778
+ return chapter;
2779
+ }
2780
+ function asTextStream(text) {
2781
+ return Readable2.from([text]);
2782
+ }
2783
+ async function assertChapterResetAllowed(archive, chapterId, stage) {
2784
+ if (stage === "planned") {
2785
+ await assertNoActiveBuildJobs({
2786
+ archive,
2787
+ chapterIds: [chapterId],
2788
+ operation: "Resetting chapter to planned"
2789
+ });
2790
+ return;
2791
+ }
2792
+ if (stage === "sourced") {
2793
+ await assertNoActiveBuildJobs({
2794
+ archive,
2795
+ chapterIds: [chapterId],
2796
+ operation: "Resetting chapter graph",
2797
+ requiresTarget: "reading-graph"
2798
+ });
2799
+ }
2800
+ await assertNoActiveBuildJobs({
2801
+ archive,
2802
+ chapterIds: [chapterId],
2803
+ operation: "Resetting chapter summary",
2804
+ requiresTarget: "reading-summary"
2805
+ });
2806
+ }
2807
+ export {
2808
+ WikiGraphArchiveExistsError,
2809
+ WikiGraphArchiveHandle,
2810
+ WikiGraphArchiveManager,
2811
+ createWikiGraphArchiveInspectReport,
2812
+ resolveWikiGraphArchiveLocation
2813
+ };
2814
+ //# sourceMappingURL=archives.js.map