wiki-graph 0.7.0 → 0.8.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.
package/dist/gc-worker.js CHANGED
@@ -3,28 +3,28 @@ import { fileURLToPath as __WIKIGRAPH_FILE_URL_TO_PATH__ } from "url";
3
3
  import { resolve as __WIKIGRAPH_RESOLVE__ } from "path";
4
4
  globalThis.__WIKIGRAPH_CLI_DIST_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL(".", import.meta.url)));
5
5
  globalThis.__WIKIGRAPH_DATA_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL("./data", import.meta.url)));
6
- var Cw=Object.defineProperty;var i=(n,e)=>()=>(n&&(e=n(n=0)),e);var Tw=(n,e)=>{for(var t in e)Cw(n,t,{get:e[t],enumerable:!0})};async function oi(n){let e=await n.openReader();try{return e.size}finally{await e.close()}}async function pn(n){return await oi(n)===0}async function ae(n){return new TextDecoder().decode(await $n(n))}async function $n(n){let e=await n.openReader();try{let t=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));t.set(a,r),r+=a.byteLength}return t}finally{await e.close()}}async function me(n,e){let t=await n.openWriter();try{await t.write(e),await t.commit()}catch(r){throw await t.abort().catch(()=>{}),r}}async function Ie(n){if(j(n)){let e=0;for(let t of await n.list())e+=await Ie(t);return e}return await oi(n)}async function ze(n){return await n.getLastModified?.()}function j(n){return n.kind==="directory"}var pu=i(()=>{"use strict"});function Ja(n){Jn().installedPlatform=n}function L(){let{installedPlatform:n}=Jn();if(n===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return n}async function hn(n){if(typeof n!="string")return n;let e=await L().resources.getFile(n);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(n,e){let t=e.replaceAll("\\","/").split("/").filter(Boolean);if(t.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=t.pop();if(!r)return;let a=n;for(let o of t){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function Oe(n,e){let t=Ka(e),r=n;for(let a of t){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function z(n,e){let t=Ka(e),r=n;for(let a of t){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(n,e){let t=Ka(e),r=t.pop();if(!r)throw new TypeError("File name must remain relative");let a=await z(n,t.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let d=await a.getFile(r);if(d!==void 0)return d;throw s}}function Ka(n){let e=n.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${n}`);let t=e.split("/").filter(Boolean);if(t.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${n}`);return t}function Jn(){let n=globalThis,e=n[hu];if(e!==void 0)return e;let t={storageContext:new $a};return Object.defineProperty(n,hu,{configurable:!1,enumerable:!1,value:t,writable:!1}),t}function za(n){Jn().installedStorage=n}async function di(n,e){return n===void 0?await e():await Jn().storageContext.run(n,e)}function v(){let{installedStorage:n,storageContext:e}=Jn(),t=e.getStore()??n;if(t===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return t}var hu,$a,y=i(()=>{"use strict";pu();hu=Symbol.for("wiki-graph-core.runtime.v1");$a=class{#e;#n;run(e,t){let r=this.#t();if(r!==void 0)return r.run(e,t);let a=this.#n;this.#n=e;try{return t()}finally{this.#n=a}}enterWith(e){let t=this.#t();t!==void 0?t.enterWith(e):this.#n=e}getStore(){return this.#t()?.getStore()??this.#n}#t(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=Jn();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#n!==void 0&&(this.#e.enterWith(this.#n),this.#n=void 0),this.#e}}});function ci(n){if(Pw.test(n))throw new Error(`invalid template name ${n}`);let t=n.replace(Aw,"").replace(_w,"");if(t.split("/").includes(".."))throw new Error(`invalid template name ${n}`);return`${t}.jinja`}var _w,Pw,Aw,Tt=i(()=>{"use strict";y();_w=/\.jinja$/iu,Pw=/^\.+\//u,Aw=/^\/+/u});var yu=i(()=>{"use strict";y();Tt()});import*as bu from"async_hooks";import*as Su from"crypto";import*as li from"fs";import*as B from"fs/promises";import*as wu from"os";import*as O from"path";import*as Za from"process";import{Readable as ku,Writable as Lw}from"stream";import{pipeline as Ow}from"stream/promises";import*as eo from"sqlite3";import*as xu from"yauzl";import*as Iu from"yazl";import{Environment as Nw,Loader as Dw}from"nunjucks";async function gu(n,e,t){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await n.write(r,a,r.byteLength-a,t===void 0?null:t+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function Eu(n,e,t){if(Ru(n),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(n>t||e>t-n)throw new RangeError("File read range exceeds the file size")}function Ru(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("File offset must be a non-negative safe integer")}function vu(n,e){return`node-${n}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function Qa(n,e){let t=`node-${e}:`;if(!n.startsWith(t))return O.isAbsolute(n)?n:void 0;try{return Buffer.from(n.slice(t.length),"base64url").toString("utf8")}catch{return}}function _t(n){if(n.length===0||n==="."||n===".."||O.isAbsolute(n)||n.includes("/")||n.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${n}`)}async function Ww(n,e){let t=(e.mode==="readonly"?Pt.OPEN_READONLY:Pt.OPEN_READWRITE|(e.create?Pt.OPEN_CREATE:0))|Pt.OPEN_FULLMUTEX;return new Va(await Fw(n,t))}async function Fw(n,e){let t=Cu(n,"file");if(t===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new Pt.Database(t,e,s=>{s?a(s):r(o)})})}async function Mw(n){let e=Cu(n,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let t=await new Promise((o,s)=>{xu.open(e,{autoClose:!1,lazyEntries:!0},(d,c)=>{d||c===void 0?s(d??new Error("Cannot open ZIP")):o(c)})}),r=await new Promise((o,s)=>{let d=new Map,c=m=>{t.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{t.off("error",c),o(d)};t.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),t.readEntry()}),t.once("error",c),t.once("end",u),t.readEntry()}),a=!1;return{close:()=>(a||t.close(),a=!0,Promise.resolve()),copyEntry:async(o,s)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let d=r.get(o);return d===void 0?!1:(await Gw(t,d,s),!0)},getEntrySize:o=>{if(a)throw new Error("Cannot read a closed ZIP archive");return Promise.resolve(r.get(o)?.uncompressedSize)},listEntries:()=>Promise.resolve([...r.keys()]),readEntryRange:async(o,s,d)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let c=r.get(o);if(c!==void 0)return await Bw(t,c,s,d)},readEntry:async o=>{if(a)throw new Error("Cannot read a closed ZIP archive");let s=r.get(o);if(s!==void 0)return await jw(t,s)}}}async function Gw(n,e,t){let r=await t.openWriter();try{let a=await ui(n,e);await Tu(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function jw(n,e){return await _u(await ui(n,e))}async function Bw(n,e,t,r){if(Eu(t,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Uw(await ui(n,e),t,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await _u(await ui(n,e,{decompress:null,decrypt:null,end:t+r,start:t}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Uw(n,e,t){let r=[],a=e+t,o=0,s=0;for await(let d of n){let c=Buffer.isBuffer(d)?d:Buffer.from(d),u=o+c.byteLength;if(u>e&&o<a){let m=c.subarray(Math.max(0,e-o),Math.min(c.byteLength,a-o));r.push(m),s+=m.byteLength}if(o=u,o>=a)break}if(s!==t)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function ui(n,e,t){return await new Promise((r,a)=>{let o=(s,d)=>{s||d===void 0?a(s??new Error(`Cannot read ZIP entry: ${e.fileName}`)):r(d)};t===void 0?n.openReadStream(e,o):n.openReadStream(e,t,o)})}async function qw(n,e){let t=new Iu.ZipFile,r=await n.openWriter(),a=t.outputStream,o=Tu(a,r),s={cancelled:!1,complete:!1},d;try{d=Kw(e);let c=Hw(t,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");t.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&zw(d),a.destroyed||a.destroy(c instanceof Error?c:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),c}}async function Hw(n,e,t){for(;!t.cancelled;){let r=await e.next();if(t.cancelled)return;if(r.done){t.complete=!0;return}"file"in r.value?n.addReadStream($w(r.value.file),r.value.name,{compress:!1}):"data"in r.value?n.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):n.addReadStream(Jw(r.value),r.value.name,{compress:!1,size:r.value.size})}}function $w(n){return ku.from((async function*(){let e=await n.openReader();try{for(let t=0;t<e.size;){let r=await e.read(t,Math.min(65536,e.size-t));t+=r.byteLength,yield r}}finally{await e.close()}})())}function Cu(n,e){if(typeof n!="object"||n===null)return;let t=n;return t[no]===e&&typeof t.path=="string"?t.path:void 0}function Jw(n){return ku.from((async function*(){for(let e=0;e<n.size;){let t=await n.read(e,Math.min(65536,n.size-e));e+=t.byteLength,yield t}})())}function Kw(n){let e=n[Symbol.asyncIterator];return e===void 0?n[Symbol.iterator]():e.call(n)}function zw(n){if(n.return!==void 0)try{Promise.resolve(n.return()).catch(()=>{})}catch{}}async function Tu(n,e){await Ow(n,new Lw({write:(t,r,a)=>{e.write(t).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function _u(n){return await new Promise((e,t)=>{let r=[];n.on("data",a=>r.push(a)),n.once("error",t),n.once("end",()=>e(Buffer.concat(r)))})}function Xw(){let n=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof n=="string"&&n!=="")return n;let e=Xa.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(li.statSync(r).isDirectory())return r}catch{}let t=O.dirname(e);if(t===e)throw new Error("Could not locate data directory");e=t}}function Pu(n=O.join(wu.homedir(),".wikigraph")){return{library:new Ne(n),documentStore:new Ne(O.join(n,"documents"))}}function At(n){Ja(Qw),za(Pu(n))}async function Kn(n,e){return await di(n===void 0?void 0:Pu(n),e)}var Xa,Pt,no,de,Ne,Va,Qw,Ya,ce=i(()=>{"use strict";yu();Xa=Za.default??Za,Pt=eo.default??eo,no=Symbol.for("wiki-graph-sdk.node-resource.v1"),de=class{constructor(e,t=O.basename(e)){this.path=e;this.identity=vu("file",e),this.name=t}path;kind="file";[no]="file";identity;name;async openReader(){let e=await B.open(this.path,"r"),t=!1;try{let r=await e.stat();if(!r.isFile())throw new Error("File reader requires a regular file");let{size:a}=r;return{size:a,close:async()=>{t||await e.close(),t=!0},read:async(o,s)=>{if(t)throw new Error("Cannot read from a closed FileReader");Eu(o,s,a);let d=Buffer.allocUnsafe(s),c=0;for(;c<s;){let u=await e.read(d,c,s-c,o+c);if(u.bytesRead===0)throw new Error("File changed while reading its byte range");c+=u.bytesRead}return new Uint8Array(d.buffer,d.byteOffset,c)}}}catch(r){throw await e.close(),r}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await B.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Su.randomUUID()}`,t=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await gu(t,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Ru(a),await gu(t,o,a)},commit:async()=>{r||(await t.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await t.close(),await B.rm(e,{force:!0})),r=!0}}}};Ne=class n{constructor(e){this.path=e;this.identity=vu("directory",e),this.name=O.basename(e)}path;kind="directory";[no]="directory";identity;name;async getFile(e){_t(e);let t=new de(O.join(this.path,e));try{return(await B.stat(t.path)).isFile()?t:void 0}catch{return}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){_t(e);let t=new n(O.join(this.path,e));try{return(await B.stat(t.path)).isDirectory()?t:void 0}catch{return}}async list(){return(await B.readdir(this.path,{withFileTypes:!0})).map(t=>t.isDirectory()?new n(O.join(this.path,t.name)):new de(O.join(this.path,t.name),t.name))}async createFile(e){_t(e),await B.mkdir(this.path,{recursive:!0});let t=new de(O.join(this.path,e));return await B.writeFile(t.path,"",{flag:"wx"}),t}async createDirectory(e){_t(e),await B.mkdir(this.path,{recursive:!0});let t=new n(O.join(this.path,e));return await B.mkdir(t.path),t}async remove(e,t){_t(e),await B.rm(O.join(this.path,e),{force:!0,recursive:t?.recursive===!0})}};Va=class{constructor(e){this.database=e}database;async close(){await new Promise((e,t)=>{this.database.close(r=>{r?t(r):e()})})}async execute(e){await new Promise((t,r)=>{this.database.exec(e,a=>{a?r(a):t()})})}async queryAll(e,t=[]){return await new Promise((r,a)=>{this.database.all(e,[...t],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,t=[]){return await new Promise((r,a)=>{this.database.get(e,[...t],(o,s)=>{o?a(o):r(s)})})}async run(e,t=[]){await new Promise((r,a)=>{this.database.run(e,[...t],o=>{o?a(o):r()})})}};Qw={asyncContext:{create:()=>new bu.AsyncLocalStorage},database:{open:Ww},lifecycle:{instanceId:`node-process:${Xa.pid}`,isInstanceAlive:n=>{let e=/^node-process:(\d+)$/u.exec(n);if(e===null)return Promise.resolve(void 0);try{return Xa.kill(Number(e[1]),0),Promise.resolve(!0)}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:n=>{let e=Qa(n,"directory");return Promise.resolve(e===void 0?void 0:new Ne(e))},getFile:n=>{let e=Qa(n,"file");return Promise.resolve(e===void 0?void 0:new de(e))},resolveLegacyDirectory:n=>{let e=Qa(n,"directory");return Promise.resolve(e===void 0?void 0:new Ne(e))}},templates:{createEnvironment:n=>new Nw(new Ya,n)},zip:{open:Mw,write:qw}},Ya=class extends Dw{#e;constructor(e){super(),this.#e=e}getSource(e){let t=ci(e),r=O.join(this.#e??Xw(),t);return{noCache:!1,path:t,src:li.readFileSync(r,"utf8")}}}});var De=i(()=>{"use strict"});function Au(n){return new TextEncoder().encode(n)}function fn(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}var Ee=i(()=>{"use strict"});import{sha1 as Vw}from"@noble/hashes/legacy.js";import{sha256 as Yw,sha512 as Zw}from"@noble/hashes/sha2.js";function oe(n){let e=ek(n);return{update(t){return e.update(typeof t=="string"?Au(t):t),this},digest(t){let r=e.digest();return t==="hex"?fn(r):r}}}function Lt(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function Qe(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let n=Lt(16);n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=fn(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function ek(n){switch(n){case"sha1":return Vw.create();case"sha256":return Yw.create();case"sha512":return Zw.create()}}var U=i(()=>{"use strict";Ee()});var mi=i(()=>{"use strict";U()});var Ou=i(()=>{"use strict";y()});var Nu=i(()=>{"use strict";Ou()});var Du=i(()=>{"use strict"});function We(n){return n instanceof Error}function zn(n){let e=[],t=new Set,r=n;for(;r!==void 0&&!t.has(r);){if(t.add(r),r instanceof Error){Wu(e,ok(r)),r=r.cause;continue}Wu(e,String(r));break}return e.join(": ")}function ok(n){let e=n,t=n.message.trim(),r=typeof e.code=="string"&&e.code!==""?e.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&sk(t)?`${n.name} (${r})`:t===""?n.name:r===void 0?t:`${t} (${r})`}function sk(n){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(n)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(n)||/\bfile:\/\//iu.test(n)}function Wu(n,e){let t=e.trim();if(t==="")return;let r=n.at(-1);if(r===void 0){n.push(t);return}if(!(r===t||r.includes(t))){if(t.includes(r)){n[n.length-1]=t;return}n.push(t)}}var pe=i(()=>{"use strict";y()});var Fu=i(()=>{"use strict";pe()});var Mu=i(()=>{"use strict"});import{APICallError as IP}from"ai";var Gu=i(()=>{"use strict";y()});var Xe=i(()=>{"use strict";y()});var yn,Nt=i(()=>{"use strict";yn=class{#e=0;#n;#t=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#n=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#n){this.#e+=1;return}await new Promise(e=>{this.#t.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#t.shift()?.()}}});var ro=i(()=>{"use strict";Xe()});var io=i(()=>{"use strict"});var ju=i(()=>{"use strict";y()});var ao=i(()=>{"use strict"});import{generateText as XP,streamText as VP}from"ai";var Uu=i(()=>{"use strict";Nu();Du();Fu();Mu();Gu();Xe();Tt();Nt();mi();pe();ro();io();ju();ao()});var qu=i(()=>{"use strict";Uu()});var so=i(()=>{"use strict";qu();ro();io();ao()});var lk,co,Hu,Qn=i(()=>{"use strict";lk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),co=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Hu=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Q,Z=i(()=>{"use strict";Q=class extends Error{code;details;constructor(e,t,r={},a={}){super(t,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var uo=i(()=>{"use strict"});async function pk(n){try{return await pn(n)}catch(e){if(We(e)&&e.code==="ENOENT")return!0;throw e}}function S(n,e){let t=n[e];if(typeof t!="number")throw new TypeError(`Expected ${e} to be a number`);return t}function E(n,e){let t=n[e];if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}var mk,N,lo,w=i(()=>{"use strict";y();pe();mk=900*1e3;N=class n{#e;#n;#t;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,t={}){this.#e=e,this.#n=t.onWrite,this.#t=L().asyncContext.create()}static async open(e,t,r){let a=await hn(e),o=r.mode==="readwrite"&&r.create&&t.trim()!==""&&await pk(a),s=r.mode==="readonly"?await L().database.open(a,{mode:"readonly"}):await L().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new n(new lo(s),r),await d.#o(`PRAGMA busy_timeout = ${mk}`),r.mode==="readwrite"&&t.trim()!==""&&(await d.#o(t),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,t){let r=await n.open(e,"",{create:!0,mode:"readwrite"});try{t.trim()!==""&&await r.#o(t)}finally{await r.close()}}async queryAll(e,t,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,t)).map(r)))}async queryOne(e,t,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,t);return a===void 0?void 0:r(a)})}async run(e,t){await this.#a(async()=>{this.#s(),await this.#h(e,t),this.#c()})}async execute(e){await this.#a(async()=>{this.#s(),await this.#o(e),this.#c()})}async transaction(e){return await this.#a(async()=>{this.#s();let t=this.#d===0,r=this.#r??Symbol("database transaction scope");t&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#t.run(r,e);return t&&await this.#o("COMMIT"),a}catch(a){throw t&&await this.#o("ROLLBACK"),a}finally{this.#d-=1,t&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,t=>S(t,"row_id"));if(e===void 0)throw new Error("Could not read last_insert_rowid()");return e}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(e){let t=this.#t.getStore();if(t!==void 0&&t===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#n?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,t){return await this.#e.queryAll(e,t)}async#p(e,t){return await this.#e.queryOne(e,t)}async#h(e,t){await this.#e.run(e,t)}};lo=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,t){return[...await this.#e.queryAll(e,t)]}async queryOne(e,t){return await this.#e.queryOne(e,t)}async run(e,t){await this.#e.run(e,t)}}});async function gn(){let n=v().library,e=hi.get(n.identity);if(e!==void 0){await e;return}let t=fk(n);hi.set(n.identity,t);try{await t}finally{hi.get(n.identity)===t&&hi.delete(n.identity)}}async function Si(){let n=await J(v().library,"core.sqlite");if(n===void 0||await wi(n))return 0;let e=await N.open(n,"",{mode:"readonly"});try{return await Xn(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],t=>S(t,"version"))??1:1}finally{await e.close()}}async function fk(n){let e=await Si();if(e>mo)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let t=await H(n,"core.sqlite");if(e===0){await fi(t,mo);return}for(;e<mo;)switch(e){case 1:await $u(n),await fi(t,2),e=2;break;case 2:await $u(n),await fi(t,3),e=3;break;case 3:await yk(t),await fi(t,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function $u(n){await Xu(n),await Qu(n)}async function yk(n){let e=v().library;await Xu(e),await gk(n),await Qu(e)}async function gk(n){let e=await N.open(n,"",{create:!1,mode:"readwrite"});try{if(!await Xn(e,"libraries"))return;let t=await gi(e,"libraries"),r=t.has("folder_identity")?"folder_identity":t.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await e.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:S(s,"id"),reference:E(s,"folder_reference")})),o=[];for(let s of a){let d=L().resources,c=r==="folder_identity"||d.resolveLegacyDirectory===void 0?await d.getDirectory(s.reference):await d.resolveLegacyDirectory(s.reference);if(c===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:c.identity})}await e.transaction(async()=>{t.has("folder_identity")||await e.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await e.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await e.close()}}async function fi(n,e){let t=await N.open(n,"",{create:!0,mode:"readwrite"});try{await t.execute(hk),await t.run(`INSERT INTO schema_versions (scope, version, updated_at)
6
+ var Jw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Kw=(t,e)=>{for(var n in e)Jw(t,n,{get:e[n],enumerable:!0})};async function di(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function gt(t){return await di(t)===0}async function ae(t){return new TextDecoder().decode(await Xt(t))}async function Xt(t){let e=await t.openReader();try{let n=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));n.set(a,r),r+=a.byteLength}return n}finally{await e.close()}}async function me(t,e){let n=await t.openWriter();try{await n.write(e),await n.commit()}catch(r){throw await n.abort().catch(()=>{}),r}}async function Ee(t){if(U(t)){let e=0;for(let n of await t.list())e+=await Ee(n);return e}return await di(t)}async function Qe(t){return await t.getLastModified?.()}function U(t){return t.kind==="directory"}var Eu=i(()=>{"use strict"});function no(t){Vt().installedPlatform=t}function A(){let{installedPlatform:t}=Vt();if(t===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return t}async function bt(t){if(typeof t!="string")return t;let e=await A().resources.getFile(t);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(t,e){let n=e.replaceAll("\\","/").split("/").filter(Boolean);if(n.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=n.pop();if(!r)return;let a=t;for(let o of n){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function We(t,e){let n=ro(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function z(t,e){let n=ro(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(t,e){let n=ro(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await z(t,n.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let d=await a.getFile(r);if(d!==void 0)return d;throw s}}function ro(t){let e=t.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${t}`);return n}function Vt(){let t=globalThis,e=t[Ru];if(e!==void 0)return e;let n={storageContext:new to};return Object.defineProperty(t,Ru,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function io(t){Vt().installedStorage=t}async function ui(t,e){return t===void 0?await e():await Vt().storageContext.run(t,e)}function v(){let{installedStorage:t,storageContext:e}=Vt(),n=e.getStore()??t;if(n===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return n}var Ru,to,y=i(()=>{"use strict";Eu();Ru=Symbol.for("wiki-graph-core.runtime.v1");to=class{#e;#t;run(e,n){let r=this.#n();if(r!==void 0)return r.run(e,n);let a=this.#t;this.#t=e;try{return n()}finally{this.#t=a}}enterWith(e){let n=this.#n();n!==void 0?n.enterWith(e):this.#t=e}getStore(){return this.#n()?.getStore()??this.#t}#n(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=Vt();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#t!==void 0&&(this.#e.enterWith(this.#t),this.#t=void 0),this.#e}}});function li(t){if(Qw.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(Xw,"").replace(zw,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var zw,Qw,Xw,Nn=i(()=>{"use strict";y();zw=/\.jinja$/iu,Qw=/^\.+\//u,Xw=/^\/+/u});var Cu=i(()=>{"use strict";y();Nn()});import*as _u from"async_hooks";import*as Pu from"crypto";import*as pi from"fs";import*as B from"fs/promises";import*as Au from"os";import*as O from"path";import*as uo from"process";import{Readable as Lu,Writable as Vw}from"stream";import{pipeline as Yw}from"stream/promises";import*as lo from"sqlite3";import*as Ou from"yauzl";import*as Nu from"yazl";import{Environment as Zw,Loader as ek}from"nunjucks";async function Tu(t,e,n){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await t.write(r,a,r.byteLength-a,n===void 0?null:n+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function Wu(t,e,n){if(Du(t),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(t>n||e>n-t)throw new RangeError("File read range exceeds the file size")}function Du(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function Mu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function ao(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return O.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function Wn(t){if(t.length===0||t==="."||t===".."||O.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function tk(t,e){let n=(e.mode==="readonly"?Dn.OPEN_READONLY:Dn.OPEN_READWRITE|(e.create?Dn.OPEN_CREATE:0))|Dn.OPEN_FULLMUTEX;return new so(await nk(t,n))}async function nk(t,e){let n=Fu(t,"file");if(n===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new Dn.Database(n,e,s=>{s?a(s):r(o)})})}async function rk(t){let e=Fu(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{Ou.open(e,{autoClose:!1,lazyEntries:!0},(d,c)=>{d||c===void 0?s(d??new Error("Cannot open ZIP")):o(c)})}),r=await new Promise((o,s)=>{let d=new Map,c=m=>{n.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{n.off("error",c),o(d)};n.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),n.readEntry()}),n.once("error",c),n.once("end",u),n.readEntry()}),a=!1;return{close:()=>(a||n.close(),a=!0,Promise.resolve()),copyEntry:async(o,s)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let d=r.get(o);return d===void 0?!1:(await ik(n,d,s),!0)},getEntrySize:o=>{if(a)throw new Error("Cannot read a closed ZIP archive");return Promise.resolve(r.get(o)?.uncompressedSize)},listEntries:()=>Promise.resolve([...r.keys()]),readEntryRange:async(o,s,d)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let c=r.get(o);if(c!==void 0)return await ok(n,c,s,d)},readEntry:async o=>{if(a)throw new Error("Cannot read a closed ZIP archive");let s=r.get(o);if(s!==void 0)return await ak(n,s)}}}async function ik(t,e,n){let r=await n.openWriter();try{let a=await mi(t,e);await Gu(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function ak(t,e){return await ju(await mi(t,e))}async function ok(t,e,n,r){if(Wu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await sk(await mi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await ju(await mi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function sk(t,e,n){let r=[],a=e+n,o=0,s=0;for await(let d of t){let c=Buffer.isBuffer(d)?d:Buffer.from(d),u=o+c.byteLength;if(u>e&&o<a){let m=c.subarray(Math.max(0,e-o),Math.min(c.byteLength,a-o));r.push(m),s+=m.byteLength}if(o=u,o>=a)break}if(s!==n)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function mi(t,e,n){return await new Promise((r,a)=>{let o=(s,d)=>{s||d===void 0?a(s??new Error(`Cannot read ZIP entry: ${e.fileName}`)):r(d)};n===void 0?t.openReadStream(e,o):t.openReadStream(e,n,o)})}async function dk(t,e){let n=new Nu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=Gu(a,r),s={cancelled:!1,complete:!1},d;try{d=mk(e);let c=ck(n,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");n.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&pk(d),a.destroyed||a.destroy(c instanceof Error?c:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),c}}async function ck(t,e,n){for(;!n.cancelled;){let r=await e.next();if(n.cancelled)return;if(r.done){n.complete=!0;return}"file"in r.value?t.addReadStream(uk(r.value.file),r.value.name,{compress:!1}):"data"in r.value?t.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):t.addReadStream(lk(r.value),r.value.name,{compress:!1,size:r.value.size})}}function uk(t){return Lu.from((async function*(){let e=await t.openReader();try{for(let n=0;n<e.size;){let r=await e.read(n,Math.min(65536,e.size-n));n+=r.byteLength,yield r}}finally{await e.close()}})())}function Fu(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[mo]===e&&typeof n.path=="string"?n.path:void 0}function lk(t){return Lu.from((async function*(){for(let e=0;e<t.size;){let n=await t.read(e,Math.min(65536,t.size-e));e+=n.byteLength,yield n}})())}function mk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function pk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function Gu(t,e){await Yw(t,new Vw({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function ju(t){return await new Promise((e,n)=>{let r=[];t.on("data",a=>r.push(a)),t.once("error",n),t.once("end",()=>e(Buffer.concat(r)))})}function fk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=oo.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(pi.statSync(r).isDirectory())return r}catch{}let n=O.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function Uu(t=O.join(Au.homedir(),".wikigraph")){return{library:new De(t),documentStore:new De(O.join(t,"documents"))}}function Mn(t){no(hk),io(Uu(t))}async function Yt(t,e){return await ui(t===void 0?void 0:Uu(t),e)}var oo,Dn,mo,se,De,so,hk,co,de=i(()=>{"use strict";Cu();oo=uo.default??uo,Dn=lo.default??lo,mo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=Mu("file",e),this.name=n}path;kind="file";[mo]="file";identity;name;async openReader(){let e=await B.open(this.path,"r"),n=!1;try{let r=await e.stat();if(!r.isFile())throw new Error("File reader requires a regular file");let{size:a}=r;return{size:a,close:async()=>{n||await e.close(),n=!0},read:async(o,s)=>{if(n)throw new Error("Cannot read from a closed FileReader");Wu(o,s,a);let d=Buffer.allocUnsafe(s),c=0;for(;c<s;){let u=await e.read(d,c,s-c,o+c);if(u.bytesRead===0)throw new Error("File changed while reading its byte range");c+=u.bytesRead}return new Uint8Array(d.buffer,d.byteOffset,c)}}}catch(r){throw await e.close(),r}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await B.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Pu.randomUUID()}`,n=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await Tu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Du(a),await Tu(n,o,a)},commit:async()=>{r||(await n.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await B.rm(e,{force:!0})),r=!0}}}};De=class t{constructor(e){this.path=e;this.identity=Mu("directory",e),this.name=O.basename(e)}path;kind="directory";[mo]="directory";identity;name;async getFile(e){Wn(e);let n=new se(O.join(this.path,e));try{return(await B.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){Wn(e);let n=new t(O.join(this.path,e));try{return(await B.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await B.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(O.join(this.path,n.name)):new se(O.join(this.path,n.name),n.name))}async createFile(e){Wn(e),await B.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await B.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Wn(e),await B.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await B.mkdir(n.path),n}async remove(e,n){Wn(e),await B.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};so=class{constructor(e){this.database=e}database;async close(){await new Promise((e,n)=>{this.database.close(r=>{r?n(r):e()})})}async execute(e){await new Promise((n,r)=>{this.database.exec(e,a=>{a?r(a):n()})})}async queryAll(e,n=[]){return await new Promise((r,a)=>{this.database.all(e,[...n],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,n=[]){return await new Promise((r,a)=>{this.database.get(e,[...n],(o,s)=>{o?a(o):r(s)})})}async run(e,n=[]){await new Promise((r,a)=>{this.database.run(e,[...n],o=>{o?a(o):r()})})}};hk={asyncContext:{create:()=>new _u.AsyncLocalStorage},database:{open:tk},lifecycle:{instanceId:`node-process:${oo.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return oo.kill(Number(e[1]),0),Promise.resolve(!0)}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:t=>{let e=ao(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=ao(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=ao(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new Zw(new co,t)},zip:{open:rk,write:dk}},co=class extends ek{#e;constructor(e){super(),this.#e=e}getSource(e){let n=li(e),r=O.join(this.#e??fk(),n);return{noCache:!1,path:n,src:pi.readFileSync(r,"utf8")}}}});var Me=i(()=>{"use strict"});function Bu(t){return new TextEncoder().encode(t)}function St(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var Re=i(()=>{"use strict"});import{sha1 as yk}from"@noble/hashes/legacy.js";import{sha256 as gk,sha512 as bk}from"@noble/hashes/sha2.js";function oe(t){let e=Sk(t);return{update(n){return e.update(typeof n=="string"?Bu(n):n),this},digest(n){let r=e.digest();return n==="hex"?St(r):r}}}function Fn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function Xe(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=Fn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=St(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Sk(t){switch(t){case"sha1":return yk.create();case"sha256":return gk.create();case"sha512":return bk.create()}}var F=i(()=>{"use strict";Re()});var hi=i(()=>{"use strict";F()});var Hu=i(()=>{"use strict";y()});var $u=i(()=>{"use strict";Hu()});var Ju=i(()=>{"use strict"});function Fe(t){return t instanceof Error}function Zt(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Ku(e,Rk(r)),r=r.cause;continue}Ku(e,String(r));break}return e.join(": ")}function Rk(t){let e=t,n=t.message.trim(),r=typeof e.code=="string"&&e.code!==""?e.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&vk(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function vk(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function Ku(t,e){let n=e.trim();if(n==="")return;let r=t.at(-1);if(r===void 0){t.push(n);return}if(!(r===n||r.includes(n))){if(n.includes(r)){t[t.length-1]=n;return}t.push(n)}}var pe=i(()=>{"use strict";y()});var zu=i(()=>{"use strict";pe()});var Qu=i(()=>{"use strict"});import{APICallError as KP}from"ai";var Xu=i(()=>{"use strict";y()});var Ve=i(()=>{"use strict";y()});var wt,jn=i(()=>{"use strict";wt=class{#e=0;#t;#n=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#t=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(e=>{this.#n.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#n.shift()?.()}}});var ho=i(()=>{"use strict";Ve()});var fo=i(()=>{"use strict"});var Vu=i(()=>{"use strict";y()});var yo=i(()=>{"use strict"});import{generateText as wA,streamText as kA}from"ai";var Zu=i(()=>{"use strict";$u();Ju();zu();Qu();Xu();Ve();Nn();jn();hi();pe();ho();fo();Vu();yo()});var el=i(()=>{"use strict";Zu()});var bo=i(()=>{"use strict";el();ho();fo();yo()});var Pk,So,tl,en=i(()=>{"use strict";Pk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),So=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),tl=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Q,Z=i(()=>{"use strict";Q=class extends Error{code;details;constructor(e,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var wo=i(()=>{"use strict"});async function Lk(t){try{return await gt(t)}catch(e){if(Fe(e)&&e.code==="ENOENT")return!0;throw e}}function S(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function E(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var Ak,N,ko,w=i(()=>{"use strict";y();pe();Ak=900*1e3;N=class t{#e;#t;#n;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,n={}){this.#e=e,this.#t=n.onWrite,this.#n=A().asyncContext.create()}static async open(e,n,r){let a=await bt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await Lk(a),s=r.mode==="readonly"?await A().database.open(a,{mode:"readonly"}):await A().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new ko(s),r),await d.#o(`PRAGMA busy_timeout = ${Ak}`),r.mode==="readwrite"&&n.trim()!==""&&(await d.#o(n),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,n){let r=await t.open(e,"",{create:!0,mode:"readwrite"});try{n.trim()!==""&&await r.#o(n)}finally{await r.close()}}async queryAll(e,n,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,n)).map(r)))}async queryOne(e,n,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,n);return a===void 0?void 0:r(a)})}async run(e,n){await this.#a(async()=>{this.#s(),await this.#h(e,n),this.#c()})}async execute(e){await this.#a(async()=>{this.#s(),await this.#o(e),this.#c()})}async transaction(e){return await this.#a(async()=>{this.#s();let n=this.#d===0,r=this.#r??Symbol("database transaction scope");n&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#n.run(r,e);return n&&await this.#o("COMMIT"),a}catch(a){throw n&&await this.#o("ROLLBACK"),a}finally{this.#d-=1,n&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,n=>S(n,"row_id"));if(e===void 0)throw new Error("Could not read last_insert_rowid()");return e}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(e){let n=this.#n.getStore();if(n!==void 0&&n===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#t?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,n){return await this.#e.queryAll(e,n)}async#p(e,n){return await this.#e.queryOne(e,n)}async#h(e,n){await this.#e.run(e,n)}};ko=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,n){return[...await this.#e.queryAll(e,n)]}async queryOne(e,n){return await this.#e.queryOne(e,n)}async run(e,n){await this.#e.run(e,n)}}});async function kt(){let t=v().library,e=yi.get(t.identity);if(e!==void 0){await e;return}let n=Nk(t);yi.set(t.identity,n);try{await n}finally{yi.get(t.identity)===n&&yi.delete(t.identity)}}async function ki(){let t=await J(v().library,"core.sqlite");if(t===void 0||await xi(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await tn(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>S(n,"version"))??1:1}finally{await e.close()}}async function Nk(t){let e=await ki();if(e>xo)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await gi(n,xo);return}for(;e<xo;)switch(e){case 1:await nl(t),await gi(n,2),e=2;break;case 2:await nl(t),await gi(n,3),e=3;break;case 3:await Wk(n),await gi(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function nl(t){await sl(t),await ol(t)}async function Wk(t){let e=v().library;await sl(e),await Dk(t),await ol(e)}async function Dk(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await tn(e,"libraries"))return;let n=await Si(e,"libraries"),r=n.has("folder_identity")?"folder_identity":n.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await e.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:S(s,"id"),reference:E(s,"folder_reference")})),o=[];for(let s of a){let d=A().resources,c=r==="folder_identity"||d.resolveLegacyDirectory===void 0?await d.getDirectory(s.reference):await d.resolveLegacyDirectory(s.reference);if(c===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:c.identity})}await e.transaction(async()=>{n.has("folder_identity")||await e.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await e.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await e.close()}}async function gi(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(Ok),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
7
7
  VALUES (?, ?, ?)
8
8
  ON CONFLICT(scope) DO UPDATE SET
9
9
  version = excluded.version,
10
- updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await t.close()}}async function Qu(n){await Dt(await n.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await n.getDirectory("staging");await Dt(e,["library","work"]),await yi(e,"staging.sqlite");let t=await n.getDirectory("tmp");await yi(t,"gc.sqlite"),await yi(t,"wikg-coordinator.sqlite"),await Dt(t,["gc.last-run"]);let r=await n.getDirectory("jobs");await Dt(r,["cache","work"]),await yi(r,"job.sqlite");let a=v().documentStore,o;try{o=await a.list()}catch(s){if(We(s)&&s.code==="ENOENT")return;throw s}for(let s of o)(s.name===".wikg-work"||s.name===".wikg-cache"||s.name.startsWith(".wikg-session-")||s.name.startsWith(".wikg-upgrade-"))&&await a.remove(s.name,{recursive:j(s)})}async function yi(n,e){await Dt(n,[e,`${e}-wal`,`${e}-shm`])}async function Dt(n,e){if(n===void 0)return;let t=new Map((await n.list()).map(r=>[r.name,r]));for(let r of e){let a=t.get(r);a!==void 0&&await n.remove(r,{recursive:j(a)})}}async function Xu(n){await Ku(await J(n,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await Ku(await J(n,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await bk(await J(n,"jobs/job.sqlite")),await Ju(await J(n,"staging/staging.sqlite"),"legacy coordinator"),await Ju(await J(n,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function bk(n){if(n===void 0||await wi(n))return;let e=await N.open(n,"",{mode:"readonly"});try{if(await Xn(e,"build_worker_lease")){let t=await gi(e,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>t.has(s)).map(s=>`${s} IS NOT NULL`).join(" OR ");if(await e.queryOne(`SELECT 1 AS active FROM build_worker_lease
10
+ updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function ol(t){await Un(await t.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await t.getDirectory("staging");await Un(e,["library","work"]),await bi(e,"staging.sqlite");let n=await t.getDirectory("tmp");await bi(n,"gc.sqlite"),await bi(n,"wikg-coordinator.sqlite"),await Un(n,["gc.last-run"]);let r=await t.getDirectory("jobs");await Un(r,["cache","work"]),await bi(r,"job.sqlite");let a=v().documentStore,o;try{o=await a.list()}catch(s){if(Fe(s)&&s.code==="ENOENT")return;throw s}for(let s of o)(s.name===".wikg-work"||s.name===".wikg-cache"||s.name.startsWith(".wikg-session-")||s.name.startsWith(".wikg-upgrade-"))&&await a.remove(s.name,{recursive:U(s)})}async function bi(t,e){await Un(t,[e,`${e}-wal`,`${e}-shm`])}async function Un(t,e){if(t===void 0)return;let n=new Map((await t.list()).map(r=>[r.name,r]));for(let r of e){let a=n.get(r);a!==void 0&&await t.remove(r,{recursive:U(a)})}}async function sl(t){await il(await J(t,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await il(await J(t,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await Mk(await J(t,"jobs/job.sqlite")),await rl(await J(t,"staging/staging.sqlite"),"legacy coordinator"),await rl(await J(t,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function Mk(t){if(t===void 0||await xi(t))return;let e=await N.open(t,"",{mode:"readonly"});try{if(await tn(e,"build_worker_lease")){let n=await Si(e,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>n.has(s)).map(s=>`${s} IS NOT NULL`).join(" OR ");if(await e.queryOne(`SELECT 1 AS active FROM build_worker_lease
11
11
  WHERE heartbeat_at IS NOT NULL
12
12
  AND heartbeat_at >= ?
13
13
  ${a===""?"":`AND (${a})`}
14
- LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function Ju(n,e){if(n===void 0||await wi(n))return;let t=await N.open(n,"",{mode:"readonly"});try{if(await Xn(t,"archive_owners")){let r=await gi(t,"archive_owners"),a=await t.queryAll(`SELECT heartbeat_at${r.has("host_instance_id")?", host_instance_id":""}
15
- FROM archive_owners`,void 0,o=>({heartbeatAt:S(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(zu(o.heartbeatAt))throw Wt(`Cannot upgrade home with active ${e} state.`);continue}let s=await L().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&zu(o.heartbeatAt))throw Wt(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await Xn(t,r)||!(await gi(t,r)).has("heartbeat_at"))continue;if(await t.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt(`Cannot upgrade home with active ${e} state.`)}}finally{await t.close()}}async function Ku(n,e){if(n===void 0||await wi(n))return;let t=await N.open(n,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await Xn(t,r))continue;if(await t.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt(a)}}finally{await t.close()}}function Wt(n){return new Q("home_upgrade_blocked",n)}function zu(n){return n!==void 0&&Date.now()-n<=bi}async function wi(n){return await pn(n)}async function gi(n,e){return new Set(await n.queryAll(`PRAGMA table_info(${e})`,void 0,t=>E(t,"name")))}async function Xn(n,e){return await n.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var mo,bi,hk,hi,ki=i(()=>{"use strict";y();pe();Z();w();mo=4,bi=300*1e3,hk=`
14
+ LIMIT 1`,[Date.now()-wi],()=>!0)===!0)throw Bn("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function rl(t,e){if(t===void 0||await xi(t))return;let n=await N.open(t,"",{mode:"readonly"});try{if(await tn(n,"archive_owners")){let r=await Si(n,"archive_owners"),a=await n.queryAll(`SELECT heartbeat_at${r.has("host_instance_id")?", host_instance_id":""}
15
+ FROM archive_owners`,void 0,o=>({heartbeatAt:S(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(al(o.heartbeatAt))throw Bn(`Cannot upgrade home with active ${e} state.`);continue}let s=await A().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&al(o.heartbeatAt))throw Bn(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await tn(n,r)||!(await Si(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-wi],()=>!0)===!0)throw Bn(`Cannot upgrade home with active ${e} state.`)}}finally{await n.close()}}async function il(t,e){if(t===void 0||await xi(t))return;let n=await N.open(t,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await tn(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-wi],()=>!0)===!0)throw Bn(a)}}finally{await n.close()}}function Bn(t){return new Q("home_upgrade_blocked",t)}function al(t){return t!==void 0&&Date.now()-t<=wi}async function xi(t){return await gt(t)}async function Si(t,e){return new Set(await t.queryAll(`PRAGMA table_info(${e})`,void 0,n=>E(n,"name")))}async function tn(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var xo,wi,Ok,yi,Ii=i(()=>{"use strict";y();pe();Z();w();xo=4,wi=300*1e3,Ok=`
16
16
  CREATE TABLE IF NOT EXISTS schema_versions (
17
17
  scope TEXT PRIMARY KEY,
18
18
  version INTEGER NOT NULL,
19
19
  updated_at TEXT NOT NULL
20
20
  );
21
- `,hi=new Map});async function X(n,e,t={create:!0,mode:"readwrite"}){await gn();let r=await H(v().library,n);return t.mode==="readonly"?await Ft(r,e,t):await Ft(r,e,t)}async function Ft(n,e,t={create:!0,mode:"readwrite"}){let r=await hn(n);return t.mode==="readonly"?await N.open(r,e,t):await N.open(r,e,t)}var Vu=i(()=>{"use strict";y();ki();w()});function Ii(...n){let e=[];for(let t of n)for(let r of t.replaceAll("\\","/").split("/"))if(!(r===""||r==="."))if(r===".."){if(e.length===0)throw new TypeError("Relative path escapes its root");e.pop()}else e.push(r);return e.join("/")}function po(n){return Ii(n).split("/").at(-1)??""}var bn=i(()=>{"use strict"});var Mt=i(()=>{"use strict";bn()});var Yu=i(()=>{"use strict"});function Vn(n){let e=new Set(Object.values(n));return t=>e.has(t)}function Gt(n,e){let t=Vn(n);return r=>{if(t(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var ho=i(()=>{"use strict"});var he,Zu,fo,Re,el,Ei,ve=i(()=>{"use strict";ho();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),Zu=Vn(he),fo=Gt(he,"chunk retention"),Re=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(Re||{}),el=Vn(Re),Ei=Gt(Re,"chunk importance")});var yo=i(()=>{"use strict";ve()});function Sn(n){let e=0,t=!1;for(let r of n.trim()){if(Sk.test(r)){e+=1,t=!1;continue}if(wk.test(r)){t||(e+=1),t=!0;continue}t&&kk.test(r)||(t=!1)}return e}var Sk,wk,kk,wn=i(()=>{"use strict";Sk=new RegExp("\\p{Script=Han}","u"),wk=/[\p{Letter}\p{Number}]/u,kk=new RegExp("\\p{Mark}","u")});var tl=i(()=>{"use strict";wn();ve()});var Ri=i(()=>{"use strict"});var bo=i(()=>{"use strict";Mt();ve();yo();tl();Ri()});var rl=i(()=>{"use strict";Mt();Yu();bo()});var So=i(()=>{"use strict";rl();yo();bo();Ri()});var vi=i(()=>{"use strict";y();bn()});var wo=i(()=>{"use strict"});var al=i(()=>{"use strict";bn();vi()});var ol=i(()=>{"use strict";wn()});var ko=i(()=>{"use strict"});var xo=i(()=>{"use strict";bn();pe();wo();vi();al();ol();ko()});var sl=i(()=>{"use strict";bn();vi();xo()});var Io=i(()=>{"use strict";sl();wo();xo();ko()});import{z as fe}from"zod";var dl,Ve,cl,ul,jt=i(()=>{"use strict";dl=["epub","pdf","txt","markdown"],Ve=1,cl=fe.enum(dl),ul=fe.object({version:fe.literal(Ve),sourceFormat:cl,title:fe.string().min(1).nullable(),authors:fe.array(fe.string().min(1)),language:fe.string().min(1).nullable(),identifier:fe.string().min(1).nullable(),publisher:fe.string().min(1).nullable(),publishedAt:fe.string().min(1).nullable(),description:fe.string().min(1).nullable()})});function ll(n,e="chapter key"){if(n===""||n==="."||n===".."||n.includes("/"))throw new Error(`Invalid ${e}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new Error(`Invalid ${e}: ${n}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(n))throw new Error(`Invalid ${e}: numeric chapter keys are not accepted.`);if(_k.has(n))throw new Error(`Invalid ${e}: ${n} is reserved.`);return n}var _k,ye=i(()=>{"use strict";Ee();U();_k=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as Fe}from"zod";var Ye,Eo,ml,Ro=i(()=>{"use strict";ye();Ye=1,Eo=Fe.object({key:Fe.string().min(1).transform(n=>ll(n)).optional(),title:Fe.string().min(1).nullable().optional(),serialId:Fe.number().int().nonnegative().optional(),children:Fe.lazy(()=>Fe.array(Eo))}),ml=Fe.object({version:Fe.literal(Ye),items:Fe.array(Eo)})});function Ce(n){let e=[];for(let t of n.replaceAll("\\","/").trim().split("/"))t===""||t==="."||(t===".."?e.pop():e.push(t));return e.join("/")}function Pk(n){let[e]=n.split("#",1);return Ce(e??"")}function vo(n){if(n===void 0)return;let e=n.startsWith("#")?n.slice(1):n;return e===""?void 0:e}function Bt(n){let[e,t]=n.split("#",2);return{path:Ce(e??""),fragment:vo(t)}}function Ak(n){return n.split("/").slice(0,-1).join("/")}function Lk(...n){return n.filter(Boolean).join("/")}var Ci,Ut=i(()=>{"use strict";y();U();Ci=class n{#e;#n;#t;#r;constructor(e,t,r,a){this.#e=e,this.#t=t,this.#n=r,this.#r=a}static async open(e){let t=await e.openReader(),r=oe("sha256");try{for(let s=0;s<t.size;){let d=await t.read(s,Math.min(65536,t.size-s));r.update(d),s+=d.byteLength}}finally{await t.close()}let a=r.digest("hex"),o=await L().zip.open(e);try{let s=new Map;for(let d of await o.listEntries()){let c=Ce(d);c!==""&&s.set(c,d)}return new n(e,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#t.close()}hasEntry(e){return this.#n.has(Ce(e))}listEntries(){return[...this.#n.keys()]}async readText(e){return new TextDecoder().decode(await this.readBuffer(e))}async readBuffer(e){let t=this.#i(e),r=await this.#t.readEntry(t);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Ce(e)}`);return r}resolveRelativePath(e,t){let r=Pk(t);if(r==="")throw new Error(`Invalid EPUB href: ${t}`);return Ce(Lk(Ak(Ce(e)),r))}createSectionId(e,t){let r=Ce(e);return t===void 0||t===""?r:`${r}#${t}`}createSyntheticSectionId(e,t){let r=Ce(e);return`toc:${oe("sha1").update(`${r}:${t??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(e){let t=Ce(e),r=this.#n.get(t);if(r===void 0)throw new Error(`EPUB entry does not exist: ${t}`);return r}}});import{parseDocument as Ok}from"htmlparser2";async function bl(n,e){let t=new Map;for(let[r,a]of e.entries()){let o=await Sl(n,r),s=wl(o,a);for(let d of a){let c=s.get(d.id)??"";t.set(d.id,{hasContent:c.trim()!=="",wordsCount:Sn(c)})}}return t}function Wk(n){let e=new Map;for(let[t,r]of n.entries())for(let a of r)e.set(a.id,{path:t,targets:r});return e}async function Sl(n,e){return await n.readText(e)}function wl(n,e){let t=kl(n,e,!1);return new Map([...t.entries()].map(([r,a])=>[e[r].id,a.text]))}function Fk(n,e,t){let r=kl(n,e,!0),a=e.findIndex(s=>s.id===t),o=r.get(a);if(o===void 0)throw new Error("EPUB section content could not be parsed.");return o}function kl(n,e,t){let r=new Map,a=new Map,o=[...e],d=o[0]?.fragment===void 0&&o[0]!==void 0?0:-1;o.forEach((g,C)=>{a.set(C,[]),g.fragment!==void 0&&!r.has(g.fragment)&&r.set(g.fragment,C)});let c=Ok(n,{decodeEntities:!0}),u=(c.children??[]).find(fl);if(u===void 0){if(t)throw new Error("EPUB XHTML document has no root element for CFI.");m(c,"")}else m(u,"");return new Map([...a.entries()].map(([g,C])=>{let A=Gk(C);return[g,{segments:A.segments,text:A.text}]}));function m(g,C){if(hl(g)){if(d<0||d>=o.length)return;let G=g.data??"";if(G==="")return;let ie=o[d],mn=ie?.spineIndex;if(t&&mn===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let ai=t&&mn!==void 0?gl(mn,C,0,G.length):Co;f(d,G,ai,t?0:void 0,t?G.length:void 0);return}let A=Uk(g);if(A===void 0){b(g,C);return}if(Dk.has(A))return;let K=C,q=g.attribs?.id??g.attribs?.["xml:id"];if(q!==void 0){let G=r.get(q);G!==void 0&&G>d&&(d=G)}A==="br"&&k(d,`
22
- `,K),b(g,K),Nk.has(A)&&k(d,`
21
+ `,yi=new Map});async function X(t,e,n={create:!0,mode:"readwrite"}){await kt();let r=await H(v().library,t);return n.mode==="readonly"?await qn(r,e,n):await qn(r,e,n)}async function qn(t,e,n={create:!0,mode:"readwrite"}){let r=await bt(t);return n.mode==="readonly"?await N.open(r,e,n):await N.open(r,e,n)}var dl=i(()=>{"use strict";y();Ii();w()});function Ri(...t){let e=[];for(let n of t)for(let r of n.replaceAll("\\","/").split("/"))if(!(r===""||r==="."))if(r===".."){if(e.length===0)throw new TypeError("Relative path escapes its root");e.pop()}else e.push(r);return e.join("/")}function Io(t){return Ri(t).split("/").at(-1)??""}var xt=i(()=>{"use strict"});var Hn=i(()=>{"use strict";xt()});var cl=i(()=>{"use strict"});function nn(t){let e=new Set(Object.values(t));return n=>e.has(n)}function $n(t,e){let n=nn(t);return r=>{if(n(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var Eo=i(()=>{"use strict"});var he,ul,Ro,ve,ll,vi,Ce=i(()=>{"use strict";Eo();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),ul=nn(he),Ro=$n(he,"chunk retention"),ve=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(ve||{}),ll=nn(ve),vi=$n(ve,"chunk importance")});var vo=i(()=>{"use strict";Ce()});function Ye(t){let e=0,n=!1;for(let r of t.trim()){if(Fk.test(r)){e+=1,n=!1;continue}if(Gk.test(r)){n||(e+=1),n=!0;continue}n&&jk.test(r)||(n=!1)}return e}var Fk,Gk,jk,Ze=i(()=>{"use strict";Fk=new RegExp("\\p{Script=Han}","u"),Gk=/[\p{Letter}\p{Number}]/u,jk=new RegExp("\\p{Mark}","u")});var pl=i(()=>{"use strict";Ze();Ce()});var Ci=i(()=>{"use strict"});var To=i(()=>{"use strict";Hn();Ce();vo();pl();Ci()});var hl=i(()=>{"use strict";Hn();cl();To()});var _o=i(()=>{"use strict";hl();vo();To();Ci()});var Ti=i(()=>{"use strict";y();xt()});var Po=i(()=>{"use strict"});var yl=i(()=>{"use strict";xt();Ti()});var gl=i(()=>{"use strict";Ze()});var Ao=i(()=>{"use strict"});var Lo=i(()=>{"use strict";xt();pe();Po();Ti();yl();gl();Ao()});var bl=i(()=>{"use strict";xt();Ti();Lo()});var Oo=i(()=>{"use strict";bl();Po();Lo();Ao()});import{z as fe}from"zod";var Sl,et,wl,kl,Jn=i(()=>{"use strict";Sl=["epub","pdf","txt","markdown"],et=1,wl=fe.enum(Sl),kl=fe.object({version:fe.literal(et),sourceFormat:wl,title:fe.string().min(1).nullable(),authors:fe.array(fe.string().min(1)),language:fe.string().min(1).nullable(),identifier:fe.string().min(1).nullable(),publisher:fe.string().min(1).nullable(),publishedAt:fe.string().min(1).nullable(),description:fe.string().min(1).nullable()})});function xl(t,e="chapter key"){if(t===""||t==="."||t===".."||t.includes("/"))throw new Error(`Invalid ${e}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(t))throw new Error(`Invalid ${e}: ${t}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(t))throw new Error(`Invalid ${e}: numeric chapter keys are not accepted.`);if(zk.has(t))throw new Error(`Invalid ${e}: ${t} is reserved.`);return t}var zk,ye=i(()=>{"use strict";Re();F();zk=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as Ge}from"zod";var tt,No,Il,Wo=i(()=>{"use strict";ye();tt=1,No=Ge.object({key:Ge.string().min(1).transform(t=>xl(t)).optional(),title:Ge.string().min(1).nullable().optional(),serialId:Ge.number().int().nonnegative().optional(),children:Ge.lazy(()=>Ge.array(No))}),Il=Ge.object({version:Ge.literal(tt),items:Ge.array(No)})});function Te(t){let e=[];for(let n of t.replaceAll("\\","/").trim().split("/"))n===""||n==="."||(n===".."?e.pop():e.push(n));return e.join("/")}function Qk(t){let[e]=t.split("#",1);return Te(e??"")}function Do(t){if(t===void 0)return;let e=t.startsWith("#")?t.slice(1):t;return e===""?void 0:e}function Kn(t){let[e,n]=t.split("#",2);return{path:Te(e??""),fragment:Do(n)}}function Xk(t){return t.split("/").slice(0,-1).join("/")}function Vk(...t){return t.filter(Boolean).join("/")}var _i,zn=i(()=>{"use strict";y();F();_i=class t{#e;#t;#n;#r;constructor(e,n,r,a){this.#e=e,this.#n=n,this.#t=r,this.#r=a}static async open(e){let n=await e.openReader(),r=oe("sha256");try{for(let s=0;s<n.size;){let d=await n.read(s,Math.min(65536,n.size-s));r.update(d),s+=d.byteLength}}finally{await n.close()}let a=r.digest("hex"),o=await A().zip.open(e);try{let s=new Map;for(let d of await o.listEntries()){let c=Te(d);c!==""&&s.set(c,d)}return new t(e,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#n.close()}hasEntry(e){return this.#t.has(Te(e))}listEntries(){return[...this.#t.keys()]}async readText(e){return new TextDecoder().decode(await this.readBuffer(e))}async readBuffer(e){let n=this.#i(e),r=await this.#n.readEntry(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Te(e)}`);return r}resolveRelativePath(e,n){let r=Qk(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Te(Vk(Xk(Te(e)),r))}createSectionId(e,n){let r=Te(e);return n===void 0||n===""?r:`${r}#${n}`}createSyntheticSectionId(e,n){let r=Te(e);return`toc:${oe("sha1").update(`${r}:${n??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(e){let n=Te(e),r=this.#t.get(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${n}`);return r}}});import{parseDocument as Yk}from"htmlparser2";async function _l(t,e){let n=new Map;for(let[r,a]of e.entries()){let o=await Pl(t,r),s=Al(o,a);for(let d of a){let c=s.get(d.id)??"";n.set(d.id,{hasContent:c.trim()!=="",wordsCount:Ye(c)})}}return n}function tx(t){let e=new Map;for(let[n,r]of t.entries())for(let a of r)e.set(a.id,{path:n,targets:r});return e}async function Pl(t,e){return await t.readText(e)}function Al(t,e){let n=Ll(t,e,!1);return new Map([...n.entries()].map(([r,a])=>[e[r].id,a.text]))}function nx(t,e,n){let r=Ll(t,e,!0),a=e.findIndex(s=>s.id===n),o=r.get(a);if(o===void 0)throw new Error("EPUB section content could not be parsed.");return o}function Ll(t,e,n){let r=new Map,a=new Map,o=[...e],d=o[0]?.fragment===void 0&&o[0]!==void 0?0:-1;o.forEach((g,C)=>{a.set(C,[]),g.fragment!==void 0&&!r.has(g.fragment)&&r.set(g.fragment,C)});let c=Yk(t,{decodeEntities:!0}),u=(c.children??[]).find(vl);if(u===void 0){if(n)throw new Error("EPUB XHTML document has no root element for CFI.");m(c,"")}else m(u,"");return new Map([...a.entries()].map(([g,C])=>{let L=ix(C);return[g,{segments:L.segments,text:L.text}]}));function m(g,C){if(Rl(g)){if(d<0||d>=o.length)return;let j=g.data??"";if(j==="")return;let ie=o[d],yt=ie?.spineIndex;if(n&&yt===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let si=n&&yt!==void 0?Tl(yt,C,0,j.length):Mo;f(d,j,si,n?0:void 0,n?j.length:void 0);return}let L=sx(g);if(L===void 0){b(g,C);return}if(ex.has(L))return;let K=C,q=g.attribs?.id??g.attribs?.["xml:id"];if(q!==void 0){let j=r.get(q);j!==void 0&&j>d&&(d=j)}L==="br"&&k(d,`
22
+ `,K),b(g,K),Zk.has(L)&&k(d,`
23
23
 
24
- `,K)}function b(g,C){let A=0,K=new Map;for(let q of g.children??[]){if(hl(q)){if(d<0||d>=o.length)continue;let ie=q.data??"";if(ie==="")continue;let mn=A*2+1,ai=K.get(mn)??0;K.set(mn,ai+ie.length);let vw=yl(C,mn,!0);R(q,vw,ai,ie.length);continue}if(!fl(q))continue;let G=yl(C,A,!1,q.attribs?.id??q.attribs?.["xml:id"]);A+=1,m(q,G)}}function R(g,C,A,K){if(d<0||d>=o.length)return;let q=g.data??"",G=o[d],ie=G?.spineIndex;if(t&&ie===void 0)throw new Error(`EPUB section ${G?.id??"unknown"} cannot produce a CFI locator.`);f(d,q,t&&ie!==void 0?gl(ie,C,A,A+K):Co,t?A:void 0,t?A+K:void 0)}function f(g,C,A,K,q){let G=a.get(g);G!==void 0&&G.push({locator:A,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function k(g,C,A){if(g<0||g>=o.length)return;let K=o[g],q=K?.spineIndex;if(t&&q===void 0)throw new Error(`EPUB section ${K?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,t&&q!==void 0?Hk(q,A):Co)}}function Mk(n,e){let t=[],r=0;for(let a of n){let o=r;r+=Array.from(a.text).length,o!==r&&t.push({artifactDigest:e,locator:a.locator,sourceEnd:r,sourceStart:o})}return t}function Gk(n){let e=[];for(let c of n){let u=Array.from(c.text),m=0;for(let b=0;b<u.length;b+=1){let R=u[b],f=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=R.length;let k=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;R==="\r"&&u[b+1]===`
24
+ `,K)}function b(g,C){let L=0,K=new Map;for(let q of g.children??[]){if(Rl(q)){if(d<0||d>=o.length)continue;let ie=q.data??"";if(ie==="")continue;let yt=L*2+1,si=K.get(yt)??0;K.set(yt,si+ie.length);let $w=Cl(C,yt,!0);R(q,$w,si,ie.length);continue}if(!vl(q))continue;let j=Cl(C,L,!1,q.attribs?.id??q.attribs?.["xml:id"]);L+=1,m(q,j)}}function R(g,C,L,K){if(d<0||d>=o.length)return;let q=g.data??"",j=o[d],ie=j?.spineIndex;if(n&&ie===void 0)throw new Error(`EPUB section ${j?.id??"unknown"} cannot produce a CFI locator.`);f(d,q,n&&ie!==void 0?Tl(ie,C,L,L+K):Mo,n?L:void 0,n?L+K:void 0)}function f(g,C,L,K,q){let j=a.get(g);j!==void 0&&j.push({locator:L,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function k(g,C,L){if(g<0||g>=o.length)return;let K=o[g],q=K?.spineIndex;if(n&&q===void 0)throw new Error(`EPUB section ${K?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,n&&q!==void 0?cx(q,L):Mo)}}function rx(t,e){let n=[],r=0;for(let a of t){let o=r;r+=Array.from(a.text).length,o!==r&&n.push({artifactDigest:e,locator:a.locator,sourceEnd:r,sourceStart:o})}return n}function ix(t){let e=[];for(let c of t){let u=Array.from(c.text),m=0;for(let b=0;b<u.length;b+=1){let R=u[b],f=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=R.length;let k=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;R==="\r"&&u[b+1]===`
25
25
  `?(m+=1,k=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
26
- `,locator:To(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:R,locator:To(c.locator,f,k),locatorEnd:k,locatorStart:f})}}let t=[],r=0;for(let c of e){if(c.char===`
27
- `){if(r+=1,r>2)continue}else r=0;t.push(c)}let a=0;for(;a<t.length&&t[a].char.trim()==="";)a+=1;let o=t.length;for(;o>a&&t[o-1].char.trim()==="";)o-=1;let s=t.slice(a,o),d=[];for(let c of s){let u=d.at(-1);u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorEnd===c.locatorStart&&u.locatorStart!==void 0&&c.locatorEnd!==void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:To(u.locatorBase??u.locator,u.locatorStart,c.locatorEnd),locatorEnd:c.locatorEnd,locatorStart:u.locatorStart,text:u.text+c.char}:u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorStart===void 0&&c.locatorStart===void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+c.char}:d.push({locatorBase:c.baseLocator,locator:c.locator,...c.locatorEnd===void 0?{}:{locatorEnd:c.locatorEnd},...c.locatorStart===void 0?{}:{locatorStart:c.locatorStart},text:c.char})}return{segments:d,text:s.map(c=>c.char).join("")}}function To(n,e,t){if(e===void 0||t===void 0)return n;let r=n.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=jk(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...n,cfi:`epubcfi(${a.parentPath},${pl(a.startPath,e)},${pl(a.endPath,t)})`}}function jk(n){if(!n.startsWith("epubcfi(")||!n.endsWith(")"))return;let e=Bk(n.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[t,r,a]=e;if(!(t===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:t,startPath:r}}function Bk(n){let e=[],t=0,r=0,a=!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(e.push(n.slice(t,o)),t=o+1)}return e.push(n.slice(t)),e}function pl(n,e){if(!/:\d+$/u.test(n))throw new Error("EPUB text mapping has an invalid CFI offset.");return n.replace(/:\d+$/u,`:${e}`)}function Uk(n){return n.name?.toLowerCase()}function hl(n){return n.type==="text"}function fl(n){return n.name!==void 0&&n.type!=="directive"}function yl(n,e,t,r){let a=t?e:(e+1)*2,o=t||r===void 0?"":`[${Jk(r)}]`;return`${n}/${a}${o}`}function gl(n,e,t,r){let a=xl(n),{parentPath:o,textPath:s}=qk(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${t}`:`${s}:${t}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function qk(n){let e=n.lastIndexOf("/");if(e<0||e===n.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${n}`);return{parentPath:n.slice(0,e),textPath:n.slice(e)}}function Hk(n,e){return{cfi:`epubcfi(${$k(n)}${e})`}}function $k(n){return`${xl(n)}!`}function xl(n){return`/6/${(n+1)*2}`}function Jk(n){return[...n].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Nk,Dk,Co,Ti,Il=i(()=>{"use strict";wn();Nk=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),Dk=new Set(["script","style"]),Co={},Ti=class{#e;#n;constructor(e,t){this.#e=e,this.#n=Wk(t)}async openSection(e){let t=this.#n.get(e);return t===void 0?[]:[(await this.#t(t.path,t.targets)).get(e)??""]}async openSectionWithProvenance(e,t){let r=this.#n.get(e);if(r===void 0)return{stream:[]};if(r.targets.find(c=>c.id===e)?.spineIndex===void 0)throw new Error(`EPUB section ${e} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=Fk(o,r.targets,e),d=Mk(s.segments,t.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[t],mappings:d},stream:[s.text]}}async#t(e,t){let r=await Sl(this.#e,e);return wl(r,t)}}});import{SaxesParser as Kk}from"saxes";function qt(n){let e=new Kk({xmlns:!1}),t=[],r;if(e.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([d,c])=>[d,String(c)])),children:[],text:""},s=t[t.length-1];s===void 0?r=o:s.children.push(o),t.push(o)}),e.on("text",a=>{let o=t[t.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=t[t.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{t.pop()}),e.write(n).close(),r===void 0)throw new Error("XML document is empty");return El(r)}function ge(n,e){return n.children.find(t=>$t(t.name)===e)}function Ze(n,e){return n.children.filter(t=>$t(t.name)===e)}function ee(n,e){return n.attributes[e]}function Ht(n){let e=n.text;for(let t of n.children)e+=Ht(t);return e}function $t(n){let e=n.indexOf(":");return e===-1?n:n.slice(e+1)}function El(n){return{name:n.name,attributes:Object.freeze({...n.attributes}),children:Object.freeze(n.children.map(El)),text:n.text}}var _o=i(()=>{"use strict"});async function vl(n){let e=await Xk(n),t=qt(await n.readText(e)),r=Vk(ee(t,"version")),a=ge(t,"metadata"),o=ge(t,"manifest"),s=ge(t,"spine"),d=ge(t,"guide"),c=Zk(n,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=ex(s,c),b=nx(n,e,d),R=Yk(a),f=tx(c),k=rx(c,s),g=ix(c,a);return{version:r,opfPath:e,metadata:{...R,version:Ve,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function Xk(n){let e=qt(await n.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>$t(o.name)==="rootfile"),a=r===void 0?void 0:ee(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function Vk(n){return n?.trim().startsWith("3")===!0?3:2}function Yk(n){if(n===void 0)return Rl();let e=kn(n,"title"),t=kn(n,"creator"),r=kn(n,"language"),a=kn(n,"identifier"),o=kn(n,"publisher"),s=kn(n,"date"),d=kn(n,"description");return{...Rl(),title:e[0]??null,authors:[...t],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function Rl(){return{version:Ve,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function kn(n,e){return n.children.filter(t=>$t(t.name)===e).map(t=>ox(Ht(t))).filter(t=>t!==void 0)}function Zk(n,e,t){let r=new Map;if(t===void 0)return r;for(let a of Ze(t,"item")){let o=ee(a,"id"),s=ee(a,"href"),d=ee(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:n.resolveRelativePath(e,s),mediaType:d,properties:new Set((ee(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function ex(n,e){return n===void 0?[]:Ze(n,"itemref").map((t,r)=>{let a=ee(t,"idref");if(a===void 0)return;let o=e.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(t=>t!==void 0)}function nx(n,e,t){let r=new Set;if(t===void 0)return r;for(let a of Ze(t,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!Qk.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(n.resolveRelativePath(e,Bt(s).path))}return r}function tx(n){for(let e of n.values())if(e.properties.has("nav"))return e.path}function rx(n,e){let t=e===void 0?void 0:ee(e,"toc");if(t!==void 0)return n.get(t)?.path;for(let r of n.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function ix(n,e){for(let r of n.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let t=ax(e);if(t!==void 0){let r=n.get(t);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of zk){let a=n.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of n.values())if(r.mediaType.startsWith("image/")&&po(r.path).toLowerCase().includes("cover"))return r}function ax(n){if(n!==void 0)for(let e of Ze(n,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function ox(n){let e=n.replace(/\s+/gu," ").trim();return e===""?void 0:e}var zk,Qk,Po=i(()=>{"use strict";bn();jt();Ut();_o();zk=["cover-image","coverimg","cover-img","cover"],Qk=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as sx}from"htmlparser2";async function Tl(n,e){let t=await cx(n,e)??await ux(n,e)??[];if(t.length===0)return Cl(e,new Set);let r=Al(t),a=Cl(e,r);return a.length===0?t:[...t,...a]}async function cx(n,e){if(e.navPath===void 0)return;let t=sx(await n.readText(e.navPath),{decodeEntities:!0}),r=Ao(t,s=>en(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=Ao(r,s=>en(s)==="ol");if(a===void 0)return;let o=Jt(a).filter(s=>en(s)==="li").map(s=>_l(n,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function ux(n,e){if(e.ncxPath===void 0)return;let t=qt(await n.readText(e.ncxPath)),r=ge(t,"navMap");if(r===void 0)return;let a=Ze(r,"navPoint").map(o=>Pl(n,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function _l(n,e,t){let r=Ll(t),a=r===void 0?void 0:Dl(Ol(r)),o=r!==void 0&&en(r)==="a"?r.attribs?.href:void 0,s=mx(n,e,o),d=Jt(t).filter(c=>en(c)==="ol").flatMap(c=>Jt(c)).filter(c=>en(c)==="li").map(c=>_l(n,e,c)).filter(c=>c!==void 0);if(!(a===void 0&&s.path===void 0&&d.length===0))return{title:a,path:s.path,fragment:s.fragment,children:d}}function Pl(n,e,t){let r=ge(t,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Dl(Ht(a)),s=ge(t,"content"),d=px(n,e,ee(s??t,"src")),c=Ze(t,"navPoint").map(u=>Pl(n,e,u)).filter(u=>u!==void 0);if(!(o===void 0&&d.path===void 0&&c.length===0))return{title:o,path:d.path,fragment:d.fragment,children:c}}function Cl(n,e){return n.spine.filter(t=>!lx(n,t.path,e)).filter(t=>!e.has(t.path)).map(t=>({title:hx(t.path),path:t.path,fragment:void 0,children:[]}))}function lx(n,e,t){if(n.guideNonContentPaths.has(e))return!0;let r=Lo(e).toLowerCase();return n.navPath===e?!0:dx.has(r)&&!t.has(e)}function Al(n){let e=new Set;for(let t of n){t.path!==void 0&&e.add(t.path);for(let r of Al(t.children))e.add(r)}return e}function mx(n,e,t){if(t===void 0||t.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Bt(t);return{path:r===""?void 0:n.resolveRelativePath(e,r),fragment:a}}function px(n,e,t){if(t===void 0||t.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Bt(t);return{path:r===""?void 0:n.resolveRelativePath(e,r),fragment:a}}function Ao(n,e){if(Nl(n)&&e(n))return n;for(let t of n.children??[]){let r=Ao(t,e);if(r!==void 0)return r}}function Ll(n){for(let e of Jt(n)){let t=en(e);if(t==="a"||t==="span")return e}for(let e of Jt(n)){if(en(e)==="ol")continue;let t=Ll(e);if(t!==void 0)return t}}function Ol(n){return n.type==="text"?n.data??"":(n.children??[]).map(Ol).join("")}function Jt(n){return(n.children??[]).filter(Nl)}function Nl(n){return n.type==="tag"||n.type==="script"||n.type==="style"}function en(n){return n.name?.toLowerCase()}function hx(n){let e=fx(n),t=Lo(n).slice(0,-e.length||void 0).trim();return t===""?void 0:t}function Lo(n){return n.replaceAll("\\","/").split("/").at(-1)??""}function fx(n){let e=Lo(n),t=e.lastIndexOf(".");return t<=0?"":e.slice(t)}function Dl(n){let e=n.replace(/\s+/gu," ").trim();return e===""?void 0:e}var dx,Wl=i(()=>{"use strict";Ut();Po();_o();dx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function yx(n){if(n.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function gx(n,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await n.readBuffer(e.coverPath)}}function bx(n,e){let t=new Map;return e.map((r,a)=>Fl(n,r,[a],t))}function Fl(n,e,t,r){let a=vo(e.fragment),o=e.path===void 0?`toc:${t.join(".")}`:n.createSectionId(e.path,a),s=Sx(o,r);return{hasContent:e.path!==void 0,id:s,title:e.title,path:e.path,fragment:a,wordsCount:0,children:e.children.map((d,c)=>Fl(n,d,[...t,c],r))}}function Ml(n,e){return n.map(t=>{let r=e.get(t.id);return{...t,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Ml(t.children,e)}})}function Sx(n,e){let t=e.get(n)??0;return e.set(n,t+1),t===0?n:`${n}~${t+1}`}function wx(n,e){let t=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of Gl(n)){if(a.path===void 0)continue;let o=t.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),t.set(a.path,o)}return t}function Gl(n){let e=[];for(let t of n)e.push(t),e.push(...Gl(t.children));return e}var Oo,No,Kt,Do,jl=i(()=>{"use strict";Ut();Ut();Il();Wl();Po();Oo=class n{#e;#n;constructor(e,t){this.#e=e,this.#n=t}get id(){return this.#n.id}get hasContent(){return this.#n.hasContent}get title(){return this.#n.title}get wordsCount(){return this.#n.wordsCount}get children(){return this.#n.children.map(e=>new n(this.#e,e))}async open(){return await this.#e.openSection(this.#n.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#n.id)}},No=class n{#e;#n;#t;#r;#i;constructor(e,t,r,a,o){this.#e=e,this.#n=t,this.#t=r,this.#r=a,this.#i=o}static async open(e){yx(e);let t=await vl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...t.metadata.identifier===null?{}:{identifier:t.metadata.identifier}},a=await Tl(e,t),o=bx(e,a),s=wx(o,t),d=await bl(e,s),c=Ml(o,d),u=await gx(e,t);return new n(r,t,u,c,new Ti(e,s))}readMeta(){return Promise.resolve(this.#n.metadata)}readCover(){return Promise.resolve(this.#t)}readSections(){return Promise.resolve(this.#r.map(e=>new Oo(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},Kt=class{get format(){return"epub"}async openSession(e,t){let r=await Ci.open(e);try{let a=await No.open(r);return await t(a)}finally{await r.close()}}},Do=new Kt});var Bl=i(()=>{"use strict";jl()});async function*xx(n){let e=await n.openReader(),t=new TextDecoder,r="";try{for(let a=0;a<e.size;){let o=await e.read(a,Math.min(65536,e.size-a));a+=o.byteLength,r+=t.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=t.decode(),r!==""&&(yield r)}finally{await e.close()}}function Ix(n){let e=n.lastIndexOf("."),t=(e<=0?n:n.slice(0,e)).trim();return t===""?null:t}var kx,Wo,Fo,zt,Ul,ql,Hl=i(()=>{"use strict";jt();kx="root",Wo=class{#e;#n;constructor(e,t=kx){this.#e=e,this.#n=t}get id(){return this.#n}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(xx(this.#e))}},Fo=class{#e;#n;#t;constructor(e,t){this.#n=e,this.#t=t,this.#e=new Wo(e)}readMeta(){return Promise.resolve({version:Ve,sourceFormat:this.#t,title:Ix(this.#n.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},zt=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,t){return await(await e.openReader()).close(),await t(new Fo(e,this.#e))}},Ul=new zt("txt"),ql=new zt("markdown")});var Qt=i(()=>{"use strict"});import{z as ue}from"zod";var WO,FO,$l=i(()=>{"use strict";Qt();WO=ue.object({type:ue.literal("artifact"),digest:ue.string().regex(/^[0-9a-f]{64}$/iu),mediaType:ue.string().min(1),name:ue.string().optional(),identifier:ue.string().max(1024).optional()}),FO=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var xn=i(()=>{"use strict";jt();Bl();Hl();$l();Ro()});var Go=i(()=>{"use strict"});var Xt=i(()=>{"use strict";xn();ye();Go();Z()});var Ex,Kl,zl,Ql,Vt=i(()=>{"use strict";w();Qt();Ex=`
26
+ `,locator:Fo(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:R,locator:Fo(c.locator,f,k),locatorEnd:k,locatorStart:f})}}let n=[],r=0;for(let c of e){if(c.char===`
27
+ `){if(r+=1,r>2)continue}else r=0;n.push(c)}let a=0;for(;a<n.length&&n[a].char.trim()==="";)a+=1;let o=n.length;for(;o>a&&n[o-1].char.trim()==="";)o-=1;let s=n.slice(a,o),d=[];for(let c of s){let u=d.at(-1);u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorEnd===c.locatorStart&&u.locatorStart!==void 0&&c.locatorEnd!==void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:Fo(u.locatorBase??u.locator,u.locatorStart,c.locatorEnd),locatorEnd:c.locatorEnd,locatorStart:u.locatorStart,text:u.text+c.char}:u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorStart===void 0&&c.locatorStart===void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+c.char}:d.push({locatorBase:c.baseLocator,locator:c.locator,...c.locatorEnd===void 0?{}:{locatorEnd:c.locatorEnd},...c.locatorStart===void 0?{}:{locatorStart:c.locatorStart},text:c.char})}return{segments:d,text:s.map(c=>c.char).join("")}}function Fo(t,e,n){if(e===void 0||n===void 0)return t;let r=t.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=ax(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${El(a.startPath,e)},${El(a.endPath,n)})`}}function ax(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=ox(t.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[n,r,a]=e;if(!(n===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:n,startPath:r}}function ox(t){let e=[],n=0,r=0,a=!1;for(let o=0;o<t.length;o+=1){let s=t[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(e.push(t.slice(n,o)),n=o+1)}return e.push(t.slice(n)),e}function El(t,e){if(!/:\d+$/u.test(t))throw new Error("EPUB text mapping has an invalid CFI offset.");return t.replace(/:\d+$/u,`:${e}`)}function sx(t){return t.name?.toLowerCase()}function Rl(t){return t.type==="text"}function vl(t){return t.name!==void 0&&t.type!=="directive"}function Cl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${lx(r)}]`;return`${t}/${a}${o}`}function Tl(t,e,n,r){let a=Ol(t),{parentPath:o,textPath:s}=dx(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${n}`:`${s}:${n}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function dx(t){let e=t.lastIndexOf("/");if(e<0||e===t.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${t}`);return{parentPath:t.slice(0,e),textPath:t.slice(e)}}function cx(t,e){return{cfi:`epubcfi(${ux(t)}${e})`}}function ux(t){return`${Ol(t)}!`}function Ol(t){return`/6/${(t+1)*2}`}function lx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Zk,ex,Mo,Pi,Nl=i(()=>{"use strict";Ze();Zk=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),ex=new Set(["script","style"]),Mo={},Pi=class{#e;#t;constructor(e,n){this.#e=e,this.#t=tx(n)}async openSection(e){let n=this.#t.get(e);return n===void 0?[]:[(await this.#n(n.path,n.targets)).get(e)??""]}async openSectionWithProvenance(e,n){let r=this.#t.get(e);if(r===void 0)return{stream:[]};if(r.targets.find(c=>c.id===e)?.spineIndex===void 0)throw new Error(`EPUB section ${e} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=nx(o,r.targets,e),d=rx(s.segments,n.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[n],mappings:d},stream:[s.text]}}async#n(e,n){let r=await Pl(this.#e,e);return Al(r,n)}}});import{SaxesParser as mx}from"saxes";function rn(t){let e=new mx({xmlns:!1}),n=[],r;if(e.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([d,c])=>[d,String(c)])),children:[],text:""},s=n[n.length-1];s===void 0?r=o:s.children.push(o),n.push(o)}),e.on("text",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{n.pop()}),e.write(t).close(),r===void 0)throw new Error("XML document is empty");return Wl(r)}function ge(t,e){return t.children.find(n=>Xn(n.name)===e)}function je(t,e){return t.children.filter(n=>Xn(n.name)===e)}function ee(t,e){return t.attributes[e]}function Qn(t){let e=t.text;for(let n of t.children)e+=Qn(n);return e}function Xn(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function Wl(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(Wl)),text:t.text}}var Ai=i(()=>{"use strict"});async function Ml(t){let e=await fx(t),n=rn(await t.readText(e)),r=yx(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=bx(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=Sx(s,c),b=wx(t,e,d),R=gx(a),f=kx(c),k=xx(c,s),g=Ix(c,a);return{version:r,opfPath:e,metadata:{...R,version:et,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function fx(t){let e=rn(await t.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>Xn(o.name)==="rootfile"),a=r===void 0?void 0:ee(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function yx(t){return t?.trim().startsWith("3")===!0?3:2}function gx(t){if(t===void 0)return Dl();let e=It(t,"title"),n=It(t,"creator"),r=It(t,"language"),a=It(t,"identifier"),o=It(t,"publisher"),s=It(t,"date"),d=It(t,"description");return{...Dl(),title:e[0]??null,authors:[...n],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function Dl(){return{version:et,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function It(t,e){return t.children.filter(n=>Xn(n.name)===e).map(n=>Rx(Qn(n))).filter(n=>n!==void 0)}function bx(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of je(n,"item")){let o=ee(a,"id"),s=ee(a,"href"),d=ee(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:t.resolveRelativePath(e,s),mediaType:d,properties:new Set((ee(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function Sx(t,e){return t===void 0?[]:je(t,"itemref").map((n,r)=>{let a=ee(n,"idref");if(a===void 0)return;let o=e.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(n=>n!==void 0)}function wx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of je(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!hx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Kn(s).path))}return r}function kx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function xx(t,e){let n=e===void 0?void 0:ee(e,"toc");if(n!==void 0)return t.get(n)?.path;for(let r of t.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function Ix(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Ex(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of px){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Io(r.path).toLowerCase().includes("cover"))return r}function Ex(t){if(t!==void 0)for(let e of je(t,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function Rx(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var px,hx,Go=i(()=>{"use strict";xt();Jn();zn();Ai();px=["cover-image","coverimg","cover-img","cover"],hx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as vx}from"htmlparser2";async function Gl(t,e){let n=await Tx(t,e)??await _x(t,e)??[];if(n.length===0)return Fl(e,new Set);let r=Bl(n),a=Fl(e,r);return a.length===0?n:[...n,...a]}async function Tx(t,e){if(e.navPath===void 0)return;let n=vx(await t.readText(e.navPath),{decodeEntities:!0}),r=jo(n,s=>nt(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=jo(r,s=>nt(s)==="ol");if(a===void 0)return;let o=Vn(a).filter(s=>nt(s)==="li").map(s=>jl(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function _x(t,e){if(e.ncxPath===void 0)return;let n=rn(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=je(r,"navPoint").map(o=>Ul(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function jl(t,e,n){let r=ql(n),a=r===void 0?void 0:Jl(Hl(r)),o=r!==void 0&&nt(r)==="a"?r.attribs?.href:void 0,s=Ax(t,e,o),d=Vn(n).filter(c=>nt(c)==="ol").flatMap(c=>Vn(c)).filter(c=>nt(c)==="li").map(c=>jl(t,e,c)).filter(c=>c!==void 0);if(!(a===void 0&&s.path===void 0&&d.length===0))return{title:a,path:s.path,fragment:s.fragment,children:d}}function Ul(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Jl(Qn(a)),s=ge(n,"content"),d=Lx(t,e,ee(s??n,"src")),c=je(n,"navPoint").map(u=>Ul(t,e,u)).filter(u=>u!==void 0);if(!(o===void 0&&d.path===void 0&&c.length===0))return{title:o,path:d.path,fragment:d.fragment,children:c}}function Fl(t,e){return t.spine.filter(n=>!Px(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:Ox(n.path),path:n.path,fragment:void 0,children:[]}))}function Px(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=Uo(e).toLowerCase();return t.navPath===e?!0:Cx.has(r)&&!n.has(e)}function Bl(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of Bl(n.children))e.add(r)}return e}function Ax(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Kn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Lx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Kn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function jo(t,e){if($l(t)&&e(t))return t;for(let n of t.children??[]){let r=jo(n,e);if(r!==void 0)return r}}function ql(t){for(let e of Vn(t)){let n=nt(e);if(n==="a"||n==="span")return e}for(let e of Vn(t)){if(nt(e)==="ol")continue;let n=ql(e);if(n!==void 0)return n}}function Hl(t){return t.type==="text"?t.data??"":(t.children??[]).map(Hl).join("")}function Vn(t){return(t.children??[]).filter($l)}function $l(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function nt(t){return t.name?.toLowerCase()}function Ox(t){let e=Nx(t),n=Uo(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function Uo(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function Nx(t){let e=Uo(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function Jl(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Cx,Kl=i(()=>{"use strict";zn();Go();Ai();Cx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function Wx(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function Dx(t,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await t.readBuffer(e.coverPath)}}function Mx(t,e){let n=new Map;return e.map((r,a)=>zl(t,r,[a],n))}function zl(t,e,n,r){let a=Do(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Fx(o,r);return{hasContent:e.path!==void 0,id:s,title:e.title,path:e.path,fragment:a,wordsCount:0,children:e.children.map((d,c)=>zl(t,d,[...n,c],r))}}function Ql(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Ql(n.children,e)}})}function Fx(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function Gx(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of Xl(t)){if(a.path===void 0)continue;let o=n.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),n.set(a.path,o)}return n}function Xl(t){let e=[];for(let n of t)e.push(n),e.push(...Xl(n.children));return e}var Bo,qo,Yn,Ho,Vl=i(()=>{"use strict";zn();zn();Nl();Kl();Go();Bo=class t{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get id(){return this.#t.id}get hasContent(){return this.#t.hasContent}get title(){return this.#t.title}get wordsCount(){return this.#t.wordsCount}get children(){return this.#t.children.map(e=>new t(this.#e,e))}async open(){return await this.#e.openSection(this.#t.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#t.id)}},qo=class t{#e;#t;#n;#r;#i;constructor(e,n,r,a,o){this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o}static async open(e){Wx(e);let n=await Ml(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Gl(e,n),o=Mx(e,a),s=Gx(o,n),d=await _l(e,s),c=Ql(o,d),u=await Dx(e,n);return new t(r,n,u,c,new Pi(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new Bo(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},Yn=class{get format(){return"epub"}async openSession(e,n){let r=await _i.open(e);try{let a=await qo.open(r);return await n(a)}finally{await r.close()}}},Ho=new Yn});var Yl=i(()=>{"use strict";Vl()});var Zl=i(()=>{"use strict";y()});import{SaxesParser as aN}from"saxes";var em=i(()=>{"use strict";Ze();Ai();Zl()});var nm=i(()=>{"use strict";em()});async function*Ux(t){let e=await t.openReader(),n=new TextDecoder,r="";try{for(let a=0;a<e.size;){let o=await e.read(a,Math.min(65536,e.size-a));a+=o.byteLength,r+=n.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=n.decode(),r!==""&&(yield r)}finally{await e.close()}}function Bx(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var jx,$o,Jo,Zn,rm,im,am=i(()=>{"use strict";Jn();jx="root",$o=class{#e;#t;constructor(e,n=jx){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Ux(this.#e))}},Jo=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new $o(e)}readMeta(){return Promise.resolve({version:et,sourceFormat:this.#n,title:Bx(this.#t.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},Zn=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new Jo(e,this.#e))}},rm=new Zn("txt"),im=new Zn("markdown")});var er=i(()=>{"use strict"});import{z as ue}from"zod";var gN,bN,om=i(()=>{"use strict";er();gN=ue.object({type:ue.literal("artifact"),digest:ue.string().regex(/^[0-9a-f]{64}$/iu),mediaType:ue.string().min(1),name:ue.string().optional(),identifier:ue.string().max(1024).optional()}),bN=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var Et=i(()=>{"use strict";Jn();Yl();nm();am();om();Wo()});var zo=i(()=>{"use strict"});var tr=i(()=>{"use strict";Et();ye();zo();Z()});var qx,dm,cm,um,nr=i(()=>{"use strict";w();er();qx=`
28
28
  id INTEGER PRIMARY KEY AUTOINCREMENT,
29
29
  digest BLOB NOT NULL UNIQUE,
30
30
  short_uid TEXT NOT NULL UNIQUE
@@ -34,7 +34,7 @@ var Cw=Object.defineProperty;var i=(n,e)=>()=>(n&&(e=n(n=0)),e);var Tw=(n,e)=>{f
34
34
  media_type TEXT NOT NULL,
35
35
  name TEXT,
36
36
  identifier TEXT
37
- `,Kl=`
37
+ `,dm=`
38
38
  CREATE TABLE IF NOT EXISTS serials (
39
39
  id INTEGER PRIMARY KEY,
40
40
  document_order INTEGER NOT NULL DEFAULT 0
@@ -330,7 +330,7 @@ var Cw=Object.defineProperty;var i=(n,e)=>()=>(n&&(e=n(n=0)),e);var Tw=(n,e)=>{f
330
330
  ON text_sentence_records(kind, chapter_id, sentence_index);
331
331
 
332
332
  CREATE TABLE IF NOT EXISTS source_artifacts (
333
- ${Ex}
333
+ ${qx}
334
334
  );
335
335
 
336
336
  CREATE TABLE IF NOT EXISTS source_locators (
@@ -396,7 +396,7 @@ ${Ex}
396
396
  triple_predicate,
397
397
  triple_object_qid
398
398
  );
399
- `,zl=`
399
+ `,cm=`
400
400
  id INTEGER PRIMARY KEY,
401
401
  archive_id INTEGER NOT NULL,
402
402
  kind INTEGER NOT NULL,
@@ -406,14 +406,14 @@ ${Ex}
406
406
  byte_offset INTEGER NOT NULL DEFAULT 0,
407
407
  byte_length INTEGER NOT NULL DEFAULT 0,
408
408
  UNIQUE(archive_id, kind, chapter_id, sentence_index)
409
- `,Ql=`
409
+ `,um=`
410
410
  CREATE TABLE IF NOT EXISTS search_index_state (
411
411
  key TEXT PRIMARY KEY,
412
412
  value TEXT NOT NULL
413
413
  );
414
414
 
415
415
  CREATE TABLE IF NOT EXISTS text_sentence_records (
416
- ${zl}
416
+ ${cm}
417
417
  );
418
418
 
419
419
  CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
@@ -470,22 +470,22 @@ ${zl}
470
470
  updated_at INTEGER NOT NULL,
471
471
  PRIMARY KEY (archive_id, chapter_id)
472
472
  );
473
- `});var In=i(()=>{"use strict";w();ve()});var Xl=i(()=>{"use strict";w();In()});var Vl=i(()=>{"use strict";w()});var Yl=i(()=>{"use strict";w();mi()});var Zl=i(()=>{"use strict";w();ve()});var em=i(()=>{"use strict";w();In()});var nm=i(()=>{"use strict";w();In()});var tm=i(()=>{"use strict";w();In()});var rm=i(()=>{"use strict";w();In()});var im=i(()=>{"use strict";w();In()});var sm=i(()=>{"use strict";Ee();w();Qt()});var dm=i(()=>{"use strict";w()});var cm=i(()=>{"use strict";w()});var um=i(()=>{"use strict";w()});var lm=i(()=>{"use strict";dm();cm();um()});var qo=i(()=>{"use strict";Xl();Vl();Yl();Zl();em();nm();tm();rm();im();sm();lm()});var Ho=i(()=>{"use strict"});var Rm=i(()=>{"use strict";y()});var vm=i(()=>{"use strict";pe();Mt()});var En=i(()=>{"use strict"});var Cm=i(()=>{"use strict";y();w();Vt();En()});var Tm=i(()=>{"use strict";pe();Ho()});var _m=i(()=>{"use strict"});import{z as $o}from"zod";var hW,Am=i(()=>{"use strict";y();jt();Ro();Xt();w();So();Vt();qo();ve();Ho();Rm();vm();Cm();Mt();Tm();_m();hW=$o.object({mediaType:$o.string().min(1),path:$o.string()})});var Lm=i(()=>{"use strict"});var Ko=i(()=>{"use strict";Am();Lm()});var Nm=i(()=>{"use strict";Io()});var _=i(()=>{"use strict";w();Vu();So();Io();Ko();Nm();Vt();Qt();qo();ve()});var Qo=i(()=>{"use strict"});var Ge=i(()=>{"use strict";Qo()});async function Mm(n){let e=await Lx(n);try{return await Ax(e,n),await e.queryOne(`
473
+ `});var Rt=i(()=>{"use strict";w();Ce()});var lm=i(()=>{"use strict";w();Rt()});var mm=i(()=>{"use strict";w()});var pm=i(()=>{"use strict";w();hi()});var hm=i(()=>{"use strict";w();Ce()});var fm=i(()=>{"use strict";w();Rt()});var ym=i(()=>{"use strict";w();Rt()});var gm=i(()=>{"use strict";w();Rt()});var bm=i(()=>{"use strict";w();Rt()});var Sm=i(()=>{"use strict";w();Rt()});var xm=i(()=>{"use strict";Re();w();er()});var Im=i(()=>{"use strict";w()});var Em=i(()=>{"use strict";w()});var Rm=i(()=>{"use strict";w()});var vm=i(()=>{"use strict";Im();Em();Rm()});var Yo=i(()=>{"use strict";lm();mm();pm();hm();fm();ym();gm();bm();Sm();xm();vm()});var Zo=i(()=>{"use strict"});var jm=i(()=>{"use strict";y()});var Um=i(()=>{"use strict";pe();Hn()});var vt=i(()=>{"use strict"});var Bm=i(()=>{"use strict";y();w();nr();vt()});var qm=i(()=>{"use strict";pe();Zo()});var Hm=i(()=>{"use strict"});import{z as es}from"zod";var XD,Jm=i(()=>{"use strict";y();Jn();Wo();tr();w();_o();nr();Yo();Ce();Zo();jm();Um();Bm();Hn();qm();Hm();XD=es.object({mediaType:es.string().min(1),path:es.string()})});var Km=i(()=>{"use strict"});var ns=i(()=>{"use strict";Jm();Km()});var Qm=i(()=>{"use strict";Oo()});var _=i(()=>{"use strict";w();dl();_o();Oo();ns();Qm();nr();er();Yo();Ce()});var is=i(()=>{"use strict"});var Be=i(()=>{"use strict";is()});async function Zm(t){let e=await Vx(t);try{return await Xx(e,t),await e.queryOne(`
474
474
  SELECT 1 AS active
475
475
  FROM state_locks
476
476
  WHERE scope = ? AND resource_key = ?
477
477
  LIMIT 1
478
- `,[n.scope,n.resourceKey],()=>!0)===!0}finally{await e.close()}}async function Ax(n,e){let t=[],r=[];e.scope!==void 0&&(t.push("scope = ?"),r.push(e.scope)),e.resourceKey!==void 0&&(t.push("resource_key = ?"),r.push(e.resourceKey));let a=await n.queryAll(`
478
+ `,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function Xx(t,e){let n=[],r=[];e.scope!==void 0&&(n.push("scope = ?"),r.push(e.scope)),e.resourceKey!==void 0&&(n.push("resource_key = ?"),r.push(e.resourceKey));let a=await t.queryAll(`
479
479
  SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
480
480
  FROM state_locks
481
- ${t.length===0?"":`WHERE ${t.join(" AND ")}`}
482
- `,r,o=>({lock:Ox(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)Dx(o,e.staleMs)&&await n.run(`
481
+ ${n.length===0?"":`WHERE ${n.join(" AND ")}`}
482
+ `,r,o=>({lock:Yx(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)eI(o,e.staleMs)&&await t.run(`
483
483
  DELETE FROM state_locks
484
484
  WHERE scope = ?
485
485
  AND resource_key = ?
486
486
  AND owner_id = ?
487
487
  AND heartbeat_at = ?
488
- `,[d,s,o.ownerId,o.heartbeatAt])}async function Lx(n){if(n.databaseFile!==void 0)return await N.open(n.databaseFile,Fm,{create:!0,mode:"readwrite"});if(n.stateDatabaseName!==void 0)return await X(n.stateDatabaseName,Fm);throw new Error("State lock requires a database File or state database name.")}function Ox(n){return{heartbeatAt:S(n,"heartbeat_at"),mode:Nx(E(n,"mode")),ownerId:E(n,"owner_id")}}function Nx(n){return n==="read"||n==="write"?n:"write"}function Dx(n,e=Px){return Date.now()-n.heartbeatAt>e}var Fm,Px,Gm=i(()=>{"use strict";U();w();_();Fm=`
488
+ `,[d,s,o.ownerId,o.heartbeatAt])}async function Vx(t){if(t.databaseFile!==void 0)return await N.open(t.databaseFile,Ym,{create:!0,mode:"readwrite"});if(t.stateDatabaseName!==void 0)return await X(t.stateDatabaseName,Ym);throw new Error("State lock requires a database File or state database name.")}function Yx(t){return{heartbeatAt:S(t,"heartbeat_at"),mode:Zx(E(t,"mode")),ownerId:E(t,"owner_id")}}function Zx(t){return t==="read"||t==="write"?t:"write"}function eI(t,e=Qx){return Date.now()-t.heartbeatAt>e}var Ym,Qx,Li=i(()=>{"use strict";F();w();_();Ym=`
489
489
  CREATE TABLE IF NOT EXISTS state_locks (
490
490
  scope TEXT NOT NULL,
491
491
  resource_key TEXT NOT NULL,
@@ -499,7 +499,7 @@ ${zl}
499
499
 
500
500
  CREATE INDEX IF NOT EXISTS idx_state_locks_resource
501
501
  ON state_locks(scope, resource_key);
502
- `,Px=300*1e3});async function Bm(n){return await Mm({stateDatabaseName:"core.sqlite",resourceKey:Mx(n),scope:Fx,staleMs:jm})||await Gx(n)}function Mx(n){return String(n)}async function Gx(n){let e=await jx();try{let t=await e.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[n],r=>({heartbeatAt:S(r,"heartbeat_at"),ownerPid:S(r,"owner_pid")}));return t!==void 0&&Ux(t)}finally{await e.close()}}async function jx(){let n=await X("core.sqlite",Wx);return await Bx(n),n}async function Bx(n){new Set(await n.queryAll("PRAGMA table_info(library_locks)",void 0,t=>E(t,"name"))).has("heartbeat_at")||await n.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function Ux(n){return Date.now()-n.heartbeatAt<=jm}var Wx,Fx,jm,Yt=i(()=>{"use strict";w();_();Gm();Wx=`
502
+ `,Qx=300*1e3});async function np(t){return await Zm({stateDatabaseName:"core.sqlite",resourceKey:rI(t),scope:nI,staleMs:tp})||await iI(t)}function rI(t){return String(t)}async function iI(t){let e=await aI();try{let n=await e.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[t],r=>({heartbeatAt:S(r,"heartbeat_at"),ownerPid:S(r,"owner_pid")}));return n!==void 0&&sI(n)}finally{await e.close()}}async function aI(){let t=await X("core.sqlite",tI);return await oI(t),t}async function oI(t){new Set(await t.queryAll("PRAGMA table_info(library_locks)",void 0,n=>E(n,"name"))).has("heartbeat_at")||await t.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function sI(t){return Date.now()-t.heartbeatAt<=tp}var tI,nI,tp,Ct=i(()=>{"use strict";w();_();Li();tI=`
503
503
  CREATE TABLE IF NOT EXISTS library_locks (
504
504
  library_id INTEGER PRIMARY KEY,
505
505
  mode TEXT NOT NULL,
@@ -508,8 +508,7 @@ ${zl}
508
508
  heartbeat_at INTEGER NOT NULL,
509
509
  created_at INTEGER NOT NULL
510
510
  );
511
- `,Fx="library",jm=300*1e3});var eF,Yn=i(()=>{"use strict";y();w();_();Ge();Ee();U();Yt();Qo();eF=Promise.resolve()});var je=i(()=>{"use strict"});var tn=i(()=>{"use strict";je()});import{z as Zo}from"zod";var er,_i,es,dF,rn=i(()=>{"use strict";je();er=1,_i=5,es=`${JSON.stringify({formatVersion:er,schemaVersion:_i})}
512
- `,dF=Zo.object({formatVersion:Zo.literal(er),schemaVersion:Zo.number().int().positive().optional()})});var Km=i(()=>{"use strict";y();tn();je();rn()});var Pi=i(()=>{"use strict";y();je();rn();tn()});var zm=i(()=>{"use strict";je()});var Xm=i(()=>{"use strict";y();je();zm();rn();tn()});var Zm=i(()=>{"use strict";Km();Pi();rn();Xm()});var op=i(()=>{"use strict";Ge()});var sp=i(()=>{"use strict";Z()});var Di=i(()=>{"use strict"});var rr=i(()=>{"use strict";uo();Tt()});var ss=i(()=>{"use strict";y();Di();rr()});var dp=i(()=>{"use strict";rr()});var cp=i(()=>{"use strict";Di();rr()});var ds=i(()=>{"use strict";rr()});var up=i(()=>{"use strict";ss();dp();cp();ds();Di();Z()});var lp=i(()=>{"use strict";ss();up();ds()});var mp=i(()=>{"use strict";sp();lp()});var Wi=i(()=>{"use strict";Z();y();mp();Be()});var OM,ir=i(()=>{"use strict";OM=new RegExp("\\p{Script=Han}","u")});var cs=i(()=>{"use strict";Ee()});var us,vn=i(()=>{"use strict";us=`
511
+ `,nI="library",tp=300*1e3});var WM,_t=i(()=>{"use strict";y();w();_();Be();Re();F();Ct();is();WM=Promise.resolve()});var MM,ir=i(()=>{"use strict";MM=new RegExp("\\p{Script=Han}","u")});var os=i(()=>{"use strict";Re()});var ss,Pt=i(()=>{"use strict";ss=`
513
512
  CREATE TABLE IF NOT EXISTS search_sessions (
514
513
  session_id TEXT PRIMARY KEY,
515
514
  archive_key TEXT NOT NULL,
@@ -613,72 +612,31 @@ ON search_sessions(expires_at);
613
612
 
614
613
  CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
615
614
  ON search_sessions(accessed_at DESC, created_at DESC, session_id);
616
- `});async function nt(){let n=await X("cache/search-sessions.sqlite",us);return ls?n:await nI(n)?(ls=!0,n):(await eI(n),ls=!0,n)}async function eI(n){await n.execute(`
615
+ `});async function an(){let t=await X("cache/search-sessions.sqlite",ss);return ds?t:await cI(t)?(ds=!0,t):(await dI(t),ds=!0,t)}async function dI(t){await t.execute(`
617
616
  DROP TABLE IF EXISTS search_evidence_hit_events;
618
617
  DROP TABLE IF EXISTS search_triple_hits;
619
618
  DROP TABLE IF EXISTS search_entity_hits;
620
619
  DROP TABLE IF EXISTS search_chunk_hits;
621
620
  DROP TABLE IF EXISTS search_sessions;
622
- ${us}
623
- `)}async function nI(n){return await Fi(n,"search_entity_hits","archive_id")&&await Fi(n,"search_chunk_hits","archive_id")&&await Fi(n,"search_triple_hits","archive_id")&&await Fi(n,"search_evidence_hit_events","archive_id")}async function Fi(n,e,t){return(await n.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(t)}var ls,tt=i(()=>{"use strict";_();vn();ls=!1});var Mi=i(()=>{"use strict"});async function fp(n,e){await yp(n,e),await n.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function yp(n,e){await n.run("DELETE FROM search_results WHERE session_id = ?",[e]),await n.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[e]),await n.run("DELETE FROM search_entity_hits WHERE session_id = ?",[e]),await n.run("DELETE FROM search_triple_hits WHERE session_id = ?",[e]),await n.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[e])}async function gp(n){await n.run(`
621
+ ${ss}
622
+ `)}async function cI(t){return await Oi(t,"search_entity_hits","archive_id")&&await Oi(t,"search_chunk_hits","archive_id")&&await Oi(t,"search_triple_hits","archive_id")&&await Oi(t,"search_evidence_hit_events","archive_id")}async function Oi(t,e,n){return(await t.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(n)}var ds,on=i(()=>{"use strict";_();Pt();ds=!1});var Ni=i(()=>{"use strict"});async function ap(t,e){await op(t,e),await t.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function op(t,e){await t.run("DELETE FROM search_results WHERE session_id = ?",[e]),await t.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[e]),await t.run("DELETE FROM search_entity_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_triple_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[e])}async function sp(t){await t.run(`
624
623
  DELETE FROM predicate_dictionary
625
624
  WHERE NOT EXISTS (
626
625
  SELECT 1
627
626
  FROM search_triple_hits
628
627
  WHERE search_triple_hits.predicate_id = predicate_dictionary.id
629
628
  )
630
- `)}var ms=i(()=>{"use strict";w();tt();Mi();vn()});async function Gi(n){let e=await nt();try{let t=await bp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=n.force?await aI(e):await iI(e,n.now),o=n.force?[]:await oI(e),s=[...new Set([...a,...o])].sort();!n.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await fp(e,c);await gp(e)}),await e.run("VACUUM"));let d=await bp(e);return{freedBytes:Math.max(0,t-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function iI(n,e){return await n.queryAll(`
629
+ `)}var cs=i(()=>{"use strict";w();on();Ni();Pt()});async function Wi(t){let e=await an();try{let n=await dp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=t.force?await pI(e):await mI(e,t.now),o=t.force?[]:await hI(e),s=[...new Set([...a,...o])].sort();!t.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await ap(e,c);await sp(e)}),await e.run("VACUUM"));let d=await dp(e);return{freedBytes:Math.max(0,n-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function mI(t,e){return await t.queryAll(`
631
630
  SELECT session_id
632
631
  FROM search_sessions
633
632
  WHERE expires_at < ?
634
- `,[e],t=>E(t,"session_id"))}async function aI(n){return await n.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function oI(n){return await n.queryAll(`
633
+ `,[e],n=>E(n,"session_id"))}async function pI(t){return await t.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function hI(t){return await t.queryAll(`
635
634
  SELECT session_id
636
635
  FROM search_sessions
637
636
  ORDER BY accessed_at DESC, created_at DESC, session_id
638
637
  LIMIT -1 OFFSET ?
639
- `,[500],e=>E(e,"session_id"))}async function bp(n){let e=await n.queryOne("PRAGMA page_count",void 0,r=>S(r,"page_count"))??0,t=await n.queryOne("PRAGMA page_size",void 0,r=>S(r,"page_size"))??0;return e*t}var Sp=i(()=>{"use strict";w();tt();vn();ms()});var wp=i(()=>{"use strict";vn()});var ps=i(()=>{"use strict"});var ji=i(()=>{"use strict";w();tt();Mi();wp();ps()});var xp=i(()=>{"use strict";U();vn()});var Ip=i(()=>{"use strict";w();cs();tt();ji();xp();Mi();vn();ms()});var Ep=i(()=>{"use strict";w();tt();ji()});var Cn=i(()=>{"use strict";cs();Sp();ji();Ip();Ep();ps()});var Bi=i(()=>{"use strict"});var Lp=i(()=>{"use strict"});var fs=i(()=>{"use strict";Ee()});var Ui=i(()=>{"use strict"});var ys=i(()=>{"use strict";Ui()});var gs=i(()=>{"use strict";Ui()});var qi=i(()=>{"use strict";Bi();fs();ys();gs()});var Mp=i(()=>{"use strict";Ge()});var Gp=i(()=>{"use strict";Bi();Lp();fs();Ui();qi();ys();gs();Mp()});var D=i(()=>{"use strict";Gp()});var Ss=i(()=>{"use strict"});var ws=i(()=>{"use strict";Z();Xt();Go();Ss()});var jp=i(()=>{"use strict";ws()});var Y=i(()=>{"use strict";ws();jp();Ss()});var Vj,Yj,Tn=i(()=>{"use strict";U();Vj=new RegExp("\\p{Script=Han}+","gu"),Yj=new RegExp("^\\p{Script=Han}+$","u")});var Hi=i(()=>{"use strict";U()});var Is=i(()=>{"use strict";En()});var Ji=i(()=>{"use strict";w();Is()});var qp=i(()=>{"use strict";Tn();Hi();Ji();En()});var $p=i(()=>{"use strict";En()});var Jp=i(()=>{"use strict";Tn()});var Kp=i(()=>{"use strict"});var Ts=i(()=>{"use strict";w();Kp();Hi()});var Qp=i(()=>{"use strict";w();Tn();Jp();Is();En();Ts();Ji()});var Xp=i(()=>{"use strict";qp();$p();Hi();Qp();Ts();En();Ji()});var on=i(()=>{"use strict";Xp();Tn()});var Pn=i(()=>{"use strict";Y();on();Tn()});var te=i(()=>{"use strict";ye();Ge();D()});var Se=i(()=>{"use strict";Ge();D()});var Te=i(()=>{"use strict";Y();wn();D();te()});var we=i(()=>{"use strict";Y();on();D();te();Se();Te();D();Pn()});var lr=i(()=>{"use strict";Cn();on();we();Se()});var Ds=i(()=>{"use strict";Y();ir();D();te();Te();Se()});var mr=i(()=>{"use strict";Z()});var Pe=i(()=>{"use strict";Y();mr();D();te();Te()});var pr=i(()=>{"use strict"});var hr=i(()=>{"use strict";Te();Pe()});var Ws=i(()=>{"use strict";D();Pe();pr();hr()});var ch=i(()=>{"use strict";on();Pn();D();we();Pe();pr();Ws();hr();hr();pr()});var uh=i(()=>{"use strict";ch();Ws();pr();hr()});var yr=i(()=>{"use strict";uh()});var mh=i(()=>{"use strict";Cn();D();te();Te();Pe();Se();yr()});var gr=i(()=>{"use strict";te();Pe();D();Se();yr();mh()});var Gs=i(()=>{"use strict";Y();D();te();Te();Pe();gr();br();Se()});var br=i(()=>{"use strict";D();te();Te();Se();Gs()});var Zi=i(()=>{"use strict";D();we();Se()});var ea=i(()=>{"use strict";D();we()});var na=i(()=>{"use strict";Y();ir();Cn();on();D();lr();Ds();gr();br();we();Zi();ea()});var bh=i(()=>{"use strict";ir();Cn();D();Pn();lr();Ds();gr();br();na();we()});var Sh=i(()=>{"use strict";bh();Zi();ea();na();lr();we()});var ta=i(()=>{"use strict";Pe();yr();te()});var Sr=i(()=>{"use strict";D()});var ra=i(()=>{"use strict";D();Pn();te();we();lr();on();Sr()});var Bs=i(()=>{"use strict";D();Se();ta();ra();Sr()});var Us=i(()=>{"use strict"});var kh=i(()=>{"use strict";mr();D();Pe();ta();Bs();ra();Sr();Us();te()});var ia=i(()=>{"use strict";kh();Bs();ta();ra();Sr();Us()});var qs=i(()=>{"use strict";_();Ge();Y();mr();D();Pe();yr();br();Se();ia();te();Te()});var xh=i(()=>{"use strict";_();Y();ye();Ge();Ee();D();Te()});var Ih=i(()=>{"use strict";qs();ia();te()});var Ys=i(()=>{"use strict";Sh();qs();ia();Pn();te();Gs();gr();xh();Ih()});var vh=i(()=>{"use strict";Ys()});var dE,Ch=i(()=>{"use strict";Ee();U();w();_();dE=10080*60*1e3});var Th=i(()=>{"use strict"});var _h=i(()=>{"use strict";w();Ch();Th()});var Ph=i(()=>{"use strict"});var Ah=i(()=>{"use strict";_h();Ph()});var dt=i(()=>{"use strict";vh();Ah();Cn()});var On=i(()=>{"use strict"});var B1,Rr=i(()=>{"use strict";y();w();Nt();On();B1=new yn(1)});var td=i(()=>{"use strict";w();U();On();Rr()});var sa=i(()=>{"use strict";y();U()});var rd=i(()=>{"use strict";U();Rr();sa()});var Wh=i(()=>{"use strict";y();rn();je();tn();Pi();On();td();rd();Rr()});var Fh=i(()=>{"use strict";On();tn()});var Mh=i(()=>{"use strict";y();U();Rr()});var od=i(()=>{"use strict";y();U();Pi();rn();tn();On();Wh();Fh();td();Mh();rd();sa()});var Gh=i(()=>{"use strict";od()});async function da(n){let e=v().documentStore,t=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(We(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:t};throw d}for(let d of o){if(!j(d)||!d.name.startsWith(".wikg-session-"))continue;t+=1;let c=await ze(d);!n.force&&(c===void 0||n.now-c<hE)||(a+=await Ie(d),n.dryRun||await e.remove(d.name,{recursive:!0}),r+=1)}let s=await e.getDirectory(".wikg-cache");if(s!==void 0)for(let d of await s.list())j(d)&&(t+=1,n.force&&(a+=await Ie(d),n.dryRun||await s.remove(d.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:t}}var hE,jh=i(()=>{"use strict";y();pe();hE=3600*1e3});var Bh=i(()=>{"use strict";w();y();U();On();sa()});var sd=i(()=>{"use strict";Gh();od();jh();Bh()});var dd=i(()=>{"use strict";sd()});var qh=i(()=>{"use strict";_();Wi();dt();dd()});var Be=i(()=>{"use strict";Zm();op();qh();dd()});var vr=i(()=>{"use strict";on()});async function Hh(n){let t=await(await v().library.getDirectory("staging"))?.getDirectory("library");if(t===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await bE();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let a=new Set(r.map(u=>String(u))),o=await t.list(),s=0,d=0,c=0;for(let u of o){if(!j(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await Bm(m))continue;let b=await Ie(u);n.dryRun||await t.remove(u.name,{recursive:!0}),d+=1,c+=b}return{freedBytes:c,removed:d,scanned:s}}async function bE(){let n=await X("core.sqlite","");try{return await n.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await n.close()}}var Cr=i(()=>{"use strict";U();y();w();Vt();_();Be();Pn();vr();Tn();Tr();Yn();Yt();Z()});var wE,bz,Tr=i(()=>{"use strict";y();w();_();Ge();Be();Ee();U();Yn();Cr();Yt();wE=`
640
- id INTEGER PRIMARY KEY AUTOINCREMENT,
641
- library_id INTEGER NOT NULL,
642
- public_id TEXT NOT NULL,
643
- relative_path TEXT NOT NULL,
644
- status TEXT NOT NULL DEFAULT 'present',
645
- last_seen_mutation_token TEXT,
646
- last_seen_size INTEGER,
647
- last_seen_mtime_ms INTEGER,
648
- last_scanned_at TEXT,
649
- created_at TEXT NOT NULL,
650
- updated_at TEXT NOT NULL,
651
- UNIQUE(library_id, public_id)
652
- `,bz=`
653
- CREATE TABLE IF NOT EXISTS library_archives (
654
- ${wE}
655
- );
656
-
657
- CREATE INDEX IF NOT EXISTS idx_library_archives_library
658
- ON library_archives(library_id);
659
-
660
- CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
661
- ON library_archives(library_id, relative_path);
662
- `});var ld=i(()=>{"use strict";Be();Tr();Yn()});var Kh=i(()=>{"use strict";Bi();qi();ir();ea();Zi();we();na();Cn();vr();Cr();ld()});var zh=i(()=>{"use strict";Ys();qi();Kh();we();Tr();ld();Yn();Cr()});var ua=i(()=>{"use strict";Yn();Tr();zh();Cr();Yt()});function la(n){let e=n.trim();return e===""?[]:Array.from(LE.segment(e)).map(t=>t.segment.trim()).filter(t=>t!=="")}function ke(n){let e=n.replace(/\s+/gu," ").trim(),t=OE(e),r="";for(let a of t)if(!NE(a)){if(!_r(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function OE(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===void 0)break;if(r!==" "){e.push(r),t+=1;continue}if(e.length>=2&&AE.has(e[e.length-1]??"")&&_r(e[e.length-2]??"")&&t<n.length-1&&_r(n[t+1]??"")){e.pop(),t+=1;continue}let a=e[e.length-1]??"",o=n[t+1]??"";a!==""&&o!==""&&_r(a)&&_r(o)&&e.push(r),t+=1}return e}function _r(n){return n!==""&&new RegExp("\\p{Script=Latin}","u").test(n)&&new RegExp("\\p{L}","u").test(n)}function NE(n){return/[\p{P}\p{S}]/u.test(n)}var AE,LE,Pr=i(()=>{"use strict";AE=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),LE=new Intl.Segmenter(void 0,{granularity:"sentence"})});function pd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Xh(n,e){let t=ma(n,2),r=ma(e,2),a=ma(n,3),o=ma(e,3);return(Qh(t,r)+Qh(a,o))/2}function ma(n,e){if(n.length<=e)return n===""?new Set:new Set([n]);let t=new Set;for(let r=0;r<=n.length-e;r+=1)t.add(n.slice(r,r+e));return t}function Qh(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&(t+=1);return 2*t/(n.size+e.size)}function Vh(n,e){if(n===e)return 1;if(n===""||e==="")return 0;let t=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...n].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(t[d+1]??0)+1,b=(t[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[t,r]=[r,t]}return 1-(t[e.length]??Math.max(n.length,e.length))/Math.max(n.length,e.length)}function Yh(n,e){return 1-Math.abs(n.length-e.length)/Math.max(n.length,e.length)}function Zh(n,e){if(n===e)return 1;let t=n.length,r=e.length;if(t===0||r===0)return 0;let a=Array.from({length:t+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=t;s+=1)for(let d=1;d<=r;d+=1){if(n[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(t+r)}function ef(n){return` - ${n.occurrenceId} score=${n.score.toFixed(3)}
663
- prev: ${md(n.prevText)}
664
- text: ${md(n.text,120)}
665
- next: ${md(n.nextText)}`}function md(n,e=80){let t=n.replace(/\s+/gu," ").trim();return t===""?"(none)":t.length<=e?t:`${t.slice(0,e-3)}...`}var hd=i(()=>{"use strict"});var fd=i(()=>{"use strict"});function tf(n,e,t){return n.mode==="head_tail"?FE(n,e):yd(n.text??"",e,t)}function FE(n,e){let t=n.head??"",r=n.tail??"",a=ke(e),o=ke(t),s=ke(r);if(o===""||s==="")return pd();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=yd(t,e,"start_anchor"),m=yd(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function yd(n,e,t){let r=n.trim(),a=e.trim(),o=ke(r),s=ke(a);if(o===""||s==="")return pd();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=nf({candidateNormalized:s,label:t,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),A=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((A===0?0:K/A)<.35)continue;let G=.35*Xh(o,g)+.35*Zh(o,g)+.2*Vh(o,g)+.1*Yh(o,g)+nf({candidateNormalized:s,label:t,matchEnd:k+f,matchStart:k,queryNormalized:o});G>d&&(d=Math.min(1,G),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function nf(n){if(n.matchStart<0||n.matchEnd<0||n.queryNormalized.length<12||n.label==="start_anchor"&&n.matchStart!==0||n.label==="end_anchor"&&n.matchEnd!==n.candidateNormalized.length)return 0;let e=n.queryNormalized.length/Math.max(1,n.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var rf=i(()=>{"use strict";Pr();hd();fd()});function af(n){if(n==null)return[void 0,"anchor is required"];if(typeof n=="string"){let o=n.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof n!="object")return[void 0,`expected string or object, got ${typeof n}`];let e=n;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function of(n,e){if(n===void 0)return;if(n.mode==="head_tail"){let r=e==="end_anchor"?gd(n.tail??"","end_anchor"):gd(n.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:gd(n.text??"",e)}}function bd(n){return n.mode==="head_tail"?ke(n.head??"").length+ke(n.tail??"").length:ke(n.text??"").length}function gd(n,e){let t=la(n);return t.length<=1?n.trim():e==="end_anchor"?t[t.length-1]??n.trim():t[0]??n.trim()}var sf=i(()=>{"use strict";Pr()});var Nn,lf=i(()=>{"use strict";rf();sf();hd();fd();Nn=class{resolve(e,t,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:t,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:t,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:t.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let t=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(t,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,t){let[r,a]=af(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:t,message:`Invalid evidence.${t}: ${a}`}]:[of(r,t),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let t=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(t=t.filter(m=>m.index>=r)),t.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=t.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#n(e.label,"ambiguous_exact_raw",a)];let o=t.filter(m=>m.exactSubstring);if(o.length===1&&bd(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&bd(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#n(e.label,"ambiguous_exact_substring",o)]}let s=t.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#n(e.label,"ambiguous_exact_normalized",s)]}let d=t[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=t[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:t.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:t.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#n(e.label,"ambiguous_ranked",t)]}rankAnchor(e,t,r,a){let o=[];for(let[s,d]of t.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=tf(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let t=e[0];if(t===void 0)return;let r=e[1]?.score??0;if(t.score>=.9&&t.score-r>=.07)return t}#n(e,t,r){let a=r.slice(0,3),o=a.map(s=>ef(s)).join(`
666
- `);return{candidates:a,code:t,fieldName:e,message:`${e} is ambiguous. Top candidates:
667
- ${o}
668
- Please provide a more specific anchor or surrounding context.`}}}});var mf=i(()=>{"use strict"});var pf=i(()=>{"use strict";lf();mf()});var pa,hf=i(()=>{"use strict";pa=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
669
- `)});var Sd=i(()=>{"use strict"});var ff=i(()=>{"use strict";Sd();Pr()});var lt=i(()=>{"use strict";pf();hf();Sd();ff();Pr()});import{z as Ar}from"zod";var LQ,gf=i(()=>{"use strict";LQ=Ar.object({meanings:Ar.array(Ar.object({information:Ar.string(),qid:Ar.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var bf=i(()=>{"use strict"});var Sf=i(()=>{"use strict"});var wf=i(()=>{"use strict"});var kf=i(()=>{"use strict";gf();bf();Sf();wf()});async function kd(n){let e=await Lr.open();try{return await e.gc(n)}finally{await e.close()}}function YE(n){try{let e=JSON.parse(n);if(typeof e!="object"||e===null)return;let t=e;return typeof t.qid!="string"||typeof t.refreshedAt!="string"||typeof t.disambiguation!="boolean"||!Array.isArray(t.sites)?void 0:{disambiguation:t.disambiguation,qid:t.qid,refreshedAt:t.refreshedAt,sites:t.sites}}catch{return}}var XE,VE,Lr,xf=i(()=>{"use strict";kf();_();XE=`
670
- CREATE TABLE IF NOT EXISTS wikimedia_cache_v1 (
671
- qid TEXT PRIMARY KEY,
672
- record_json TEXT NOT NULL,
673
- refreshed_at TEXT NOT NULL
674
- );
675
- CREATE INDEX IF NOT EXISTS idx_wikimedia_cache_v1_refreshed_at
676
- ON wikimedia_cache_v1(refreshed_at);
677
- `,VE=336*60*60*1e3,Lr=class n{#e;constructor(e){this.#e=e}static async open(){return new n(await X("cache/cache.sqlite",XE))}async get(e){let t=new Map;for(let r of e){let a=await this.#e.queryOne("SELECT record_json FROM wikimedia_cache_v1 WHERE qid = ?",[r],s=>String(s.record_json)),o=a===void 0?void 0:YE(a);o!==void 0&&o.qid===r&&t.set(r,o)}return t}async put(e){await this.#e.transaction(async()=>{for(let t of e)await this.#e.run(`INSERT INTO wikimedia_cache_v1(qid,record_json,refreshed_at)
678
- VALUES(?,?,?)
679
- ON CONFLICT(qid) DO UPDATE SET
680
- record_json=excluded.record_json,
681
- refreshed_at=excluded.refreshed_at`,[t.qid,JSON.stringify(t),t.refreshedAt])})}async close(){await this.#e.close()}async gc(e){let t=new Date(e.now-VE).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_cache_v1",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_cache_v1 WHERE refreshed_at < ?",[t],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.run("DELETE FROM wikimedia_cache_v1 WHERE refreshed_at < ?",[t]),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var Id=i(()=>{"use strict";xf()});var Ed=i(()=>{"use strict"});var Rd=i(()=>{"use strict"});import{jsonrepair as YQ}from"jsonrepair";var If=i(()=>{"use strict"});var Ef=i(()=>{"use strict";Rd();Ed();If()});var Ae=i(()=>{"use strict";Ed();Rd();Ef()});var Or=i(()=>{"use strict"});import{z as He}from"zod";var rR,iR,IX,Td=i(()=>{"use strict";Ae();Or();rR=He.object({candidateId:He.string().min(1),decision:He.enum(["continue","recall","skip_this_time","never_recall"]),qid:He.string().nullable().optional()}).strict(),iR=He.object({decisions:He.array(rR),groupId:He.string().min(1)}).strict(),IX=He.object({groups:He.array(iR)}).strict()});import{z as Nr}from"zod";var sR,_X,Cf=i(()=>{"use strict";Ae();Or();Td();sR=Nr.object({decision:Nr.enum(["keep","reject"]),qid:Nr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),_X=Nr.object({qids:Nr.array(sR)}).strict()});var Tf=i(()=>{"use strict"});import{z as Dr}from"zod";var dR,NX,_f=i(()=>{"use strict";Ae();dR=Dr.object({note:Dr.string().max(24).optional(),surfaceId:Dr.string().min(1)}).strict(),NX=Dr.object({protectedSurfaces:Dr.array(dR)}).strict()});var _d=i(()=>{"use strict"});var Pf=i(()=>{"use strict";_d()});var Af=i(()=>{"use strict"});var Pd=i(()=>{"use strict"});var Lf=i(()=>{"use strict";Pd();Or()});var sn=i(()=>{"use strict";Td();Cf();Or();Tf();_f();Pf();_d();Af();Lf();Pd()});var lV,Ld=i(()=>{"use strict";Qn();lV=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Od=i(()=>{"use strict";Xe()});var Ff=i(()=>{"use strict";Od()});var Mf=i(()=>{"use strict";Ff();Od()});var Gf=i(()=>{"use strict"});var jf=i(()=>{"use strict"});var Bf=i(()=>{"use strict";Gf();jf()});var Wr=i(()=>{"use strict";Ae()});var Uf=i(()=>{"use strict";_();Wr()});var qf=i(()=>{"use strict";Wr()});var Hf=i(()=>{"use strict"});import{z as x}from"zod";var $f,xR,Jf,IR,ER,RR,vR,CR,TR,fa=i(()=>{"use strict";_();$f=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),xR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),Jf=x.union([x.record(x.string(),x.unknown()),x.array(xR)]),IR=x.object({content:x.string(),evidence:Jf.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),ER=x.object({chunks:x.array(IR),fragment_summary:x.string(),links:x.array($f)}),RR=x.object({content:x.string(),evidence:Jf.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),vR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),CR=x.object({chunks:x.array(RR),importance_annotations:x.array(vR),links:x.array($f)}),TR=x.object({choice:x.string()})});var Kf=i(()=>{"use strict";Ae();lt();Hf();Wr();fa()});var zf=i(()=>{"use strict";Ae();_();Uf();Wr();qf();Kf();fa()});var Qf=i(()=>{"use strict";zf();fa()});var ya=i(()=>{"use strict"});import{detect as kY,validateISO2 as xY}from"tinyld";var Nd=i(()=>{"use strict";De()});var Xf=i(()=>{"use strict";Nd();De()});var Vf=i(()=>{"use strict"});import{z as Fr}from"zod";var OR,HY,Zf=i(()=>{"use strict";Ae();lt();Qf();ya();ya();Xf();Vf();OR=Fr.object({content:Fr.string(),id:Fr.number(),label:Fr.string()}),HY=Fr.array(OR)});var Dd=i(()=>{"use strict";Zf()});var ey=i(()=>{"use strict";wn()});var Wd=i(()=>{"use strict";ey()});var ny=i(()=>{"use strict";Bf();Dd();Wd()});var ga=i(()=>{"use strict";ny();Wd()});var ba=i(()=>{"use strict"});var Sa=i(()=>{"use strict";ga();ba()});var ty=i(()=>{"use strict";Sa()});var ry=i(()=>{"use strict"});var wa=i(()=>{"use strict"});var iy=i(()=>{"use strict";wa()});var pt,w2,GR,ka=i(()=>{"use strict";ho();pt=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(pt||{}),w2=Vn(pt),GR=Gt(pt,"review severity")});var R2,Md=i(()=>{"use strict";wa();ka();R2=Object.freeze({critical:9,major:3,minor:1})});var ay=i(()=>{"use strict";Nd();De();ka()});var oy=i(()=>{"use strict";y();Xe();Md()});var Gd=i(()=>{"use strict";_()});var sy=i(()=>{"use strict"});import{z as ht}from"zod";var jR,BR,Q2,dy=i(()=>{"use strict";Xe();Ae();wa();Gd();ka();jR=["critical","major","minor"],BR=ht.object({problem:ht.string(),severity:ht.enum(jR),suggestion:ht.string().default("")}),Q2=ht.object({issues:ht.array(BR)})});var cy=i(()=>{"use strict";ry();iy();Md();ay();oy();Gd();sy();dy()});var jd=i(()=>{"use strict";cy()});var ly=i(()=>{"use strict"});var my=i(()=>{"use strict"});var py=i(()=>{"use strict";ly();my()});var Mr=i(()=>{"use strict"});var _3,P3,ft=i(()=>{"use strict";_();_3={critical:9,helpful:1,important:3},P3={detailed:9,focused:3,relevant:1,verbatim:27}});var yt=i(()=>{"use strict"});var Gr=i(()=>{"use strict"});var Bd=i(()=>{"use strict";yt()});var Ud=i(()=>{"use strict";ft();yt();Mr();Gr();Bd()});var qd=i(()=>{"use strict";Mr();Ud();Gr()});var fy=i(()=>{"use strict";ft();yt();Gr()});var yy=i(()=>{"use strict";ft();yt();Mr();Gr();Bd()});var gy=i(()=>{"use strict";qd();yt();Mr();fy();Ud();yy()});var by=i(()=>{"use strict";gy();qd()});var Sy=i(()=>{"use strict";ft()});var wy=i(()=>{"use strict";by();Sy()});var ky=i(()=>{"use strict";py();wy();ft()});var xy=i(()=>{"use strict";ky()});var Hd=i(()=>{"use strict";Z()});var Iy=i(()=>{"use strict"});var $d=i(()=>{"use strict";Sa()});var Ia=i(()=>{"use strict"});var Ey=i(()=>{"use strict";Nt();Qn();jd();ga();xy();Sa();ba();Hd();Iy();$d();Ia()});var Ry=i(()=>{"use strict";Hd();Ia();Z()});var vy=i(()=>{"use strict";ty();Ey();ba();Ry();$d();Ia()});var gt=i(()=>{"use strict";vy()});var Cy=i(()=>{"use strict";ye();Nt();gt();xn()});var Ty=i(()=>{"use strict";xn();xn();_();ye();Mf();gt();Cy();Wi();y()});var zd,dn=i(()=>{"use strict";zd=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Qd=i(()=>{"use strict";dn()});var Ay=i(()=>{"use strict";Xe();so();Ty();Ld();Be();Qd();y()});var Xd,Vd=i(()=>{"use strict";Xd=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function Ly(){return await z(v().library,"jobs/work")}async function Oy(n){let e=await v().library.getDirectory("jobs");if(e!==void 0)for(let[t,r,a]of[["work",n,!0],["cache",n,!0],["logs",n,!0],["events",`${n}.ndjson`,!1]]){let o=await e.getDirectory(t);o!==void 0&&await o.remove(r,{recursive:a})}}var jr=i(()=>{"use strict";y()});var Br=i(()=>{"use strict";U()});var Yd=i(()=>{"use strict"});var Ur=i(()=>{"use strict";y()});var Ny,Dy=i(()=>{"use strict";Ny=`
638
+ `,[500],e=>E(e,"session_id"))}async function dp(t){let e=await t.queryOne("PRAGMA page_count",void 0,r=>S(r,"page_count"))??0,n=await t.queryOne("PRAGMA page_size",void 0,r=>S(r,"page_size"))??0;return e*n}var cp=i(()=>{"use strict";w();on();Pt();cs()});var up=i(()=>{"use strict";Pt()});var us=i(()=>{"use strict"});var Di=i(()=>{"use strict";w();on();Ni();up();us()});var mp=i(()=>{"use strict";F();Pt()});var pp=i(()=>{"use strict";w();os();on();Di();mp();Ni();Pt();cs()});var hp=i(()=>{"use strict";w();on();Di()});var Lt=i(()=>{"use strict";os();cp();Di();pp();hp();us()});var Mi=i(()=>{"use strict"});var xp=i(()=>{"use strict"});var ms=i(()=>{"use strict";Re()});var Fi=i(()=>{"use strict"});var ps=i(()=>{"use strict";Fi()});var hs=i(()=>{"use strict";Fi()});var Gi=i(()=>{"use strict";Mi();ms();ps();hs()});var Tp=i(()=>{"use strict";Be()});var _p=i(()=>{"use strict";Mi();xp();ms();Fi();Gi();ps();hs();Tp()});var W=i(()=>{"use strict";_p()});var ys=i(()=>{"use strict"});var gs=i(()=>{"use strict";Z();tr();zo();ys()});var Pp=i(()=>{"use strict";gs()});var Y=i(()=>{"use strict";gs();Pp();ys()});var tj,nj,Ot=i(()=>{"use strict";F();tj=new RegExp("\\p{Script=Han}+","gu"),nj=new RegExp("^\\p{Script=Han}+$","u")});var ji=i(()=>{"use strict";F()});var ws=i(()=>{"use strict";vt()});var Bi=i(()=>{"use strict";w();ws()});var Op=i(()=>{"use strict";Ot();ji();Bi();vt()});var Wp=i(()=>{"use strict";vt()});var Dp=i(()=>{"use strict";Ot()});var Mp=i(()=>{"use strict"});var Rs=i(()=>{"use strict";w();Mp();ji()});var Gp=i(()=>{"use strict";w();Ot();Dp();ws();vt();Rs();Bi()});var jp=i(()=>{"use strict";Op();Wp();ji();Gp();Rs();vt();Bi()});var at=i(()=>{"use strict";jp();Ot()});var Wt=i(()=>{"use strict";Y();at();Ot()});var ne=i(()=>{"use strict";ye();Be();W()});var Se=i(()=>{"use strict";Be();W()});var _e=i(()=>{"use strict";Y();Ze();W();ne()});var we=i(()=>{"use strict";Y();at();W();ne();Se();_e();W();Wt()});var ur=i(()=>{"use strict";Lt();at();we();Se()});var Ls=i(()=>{"use strict";Y();ir();W();ne();_e();Se()});var lr=i(()=>{"use strict";Z()});var Ae=i(()=>{"use strict";Y();lr();W();ne();_e()});var mr=i(()=>{"use strict"});var pr=i(()=>{"use strict";_e();Ae()});var Os=i(()=>{"use strict";W();Ae();mr();pr()});var Zp=i(()=>{"use strict";at();Wt();W();we();Ae();mr();Os();pr();pr();mr()});var eh=i(()=>{"use strict";Zp();Os();mr();pr()});var fr=i(()=>{"use strict";eh()});var nh=i(()=>{"use strict";Lt();W();ne();_e();Ae();Se();fr()});var yr=i(()=>{"use strict";ne();Ae();W();Se();fr();nh()});var Ds=i(()=>{"use strict";Y();W();ne();_e();Ae();yr();gr();Se()});var gr=i(()=>{"use strict";W();ne();_e();Se();Ds()});var Qi=i(()=>{"use strict";W();we();Se()});var Xi=i(()=>{"use strict";W();we()});var Vi=i(()=>{"use strict";Y();ir();Lt();at();W();ur();Ls();yr();gr();we();Qi();Xi()});var dh=i(()=>{"use strict";ir();Lt();W();Wt();ur();Ls();yr();gr();Vi();we()});var ch=i(()=>{"use strict";dh();Qi();Xi();Vi();ur();we()});var Yi=i(()=>{"use strict";Ae();fr();ne()});var br=i(()=>{"use strict";W()});var Zi=i(()=>{"use strict";W();Wt();ne();we();ur();at();br()});var Fs=i(()=>{"use strict";W();Se();Yi();Zi();br()});var Gs=i(()=>{"use strict"});var lh=i(()=>{"use strict";lr();W();Ae();Yi();Fs();Zi();br();Gs();ne()});var ea=i(()=>{"use strict";lh();Fs();Yi();Zi();br();Gs()});var js=i(()=>{"use strict";_();Be();Y();lr();W();Ae();fr();gr();Se();ea();ne();_e()});var mh=i(()=>{"use strict";_();Y();ye();Be();Re();W();_e()});var ph=i(()=>{"use strict";js();ea();ne()});var Qs=i(()=>{"use strict";ch();js();ea();Wt();ne();Ds();yr();mh();ph()});var yh=i(()=>{"use strict";Qs()});var yE,gh=i(()=>{"use strict";Re();F();w();_();yE=10080*60*1e3});var bh=i(()=>{"use strict"});var Sh=i(()=>{"use strict";w();gh();bh()});var wh=i(()=>{"use strict"});var kh=i(()=>{"use strict";Sh();wh()});var ot=i(()=>{"use strict";yh();kh();Lt()});var qe=i(()=>{"use strict"});var st=i(()=>{"use strict";qe()});import{z as ed}from"zod";var Rr,ra,td,J$,dt=i(()=>{"use strict";qe();Rr=1,ra=5,td=`${JSON.stringify({formatVersion:Rr,schemaVersion:ra})}
639
+ `,J$=ed.object({formatVersion:ed.literal(Rr),schemaVersion:ed.number().int().positive().optional()})});var Ch=i(()=>{"use strict";y();st();qe();dt()});var ia=i(()=>{"use strict";y();qe();dt();st()});var Th=i(()=>{"use strict";qe()});var Ph=i(()=>{"use strict";y();qe();Th();dt();st()});var Nh=i(()=>{"use strict";Ch();ia();dt();Ph()});var Uh=i(()=>{"use strict";Be()});var Bh=i(()=>{"use strict";Z()});var ua=i(()=>{"use strict"});var Tr=i(()=>{"use strict";wo();Nn()});var od=i(()=>{"use strict";y();ua();Tr()});var qh=i(()=>{"use strict";Tr()});var Hh=i(()=>{"use strict";ua();Tr()});var sd=i(()=>{"use strict";Tr()});var $h=i(()=>{"use strict";od();qh();Hh();sd();ua();Z()});var Jh=i(()=>{"use strict";od();$h();sd()});var Kh=i(()=>{"use strict";Bh();Jh()});var la=i(()=>{"use strict";Z();y();Kh();Le()});var ct=i(()=>{"use strict"});var xJ,_r=i(()=>{"use strict";y();w();jn();ct();xJ=new wt(1)});var cd=i(()=>{"use strict";w();F();ct();_r()});var ma=i(()=>{"use strict";y();F()});var ud=i(()=>{"use strict";F();_r();ma()});var pd=i(()=>{"use strict";y();dt();qe();st();ia();ct();cd();ud();_r()});var Yh=i(()=>{"use strict";ct();st()});var hd=i(()=>{"use strict";y();F();_r()});var fd=i(()=>{"use strict";y();F();ia();dt();st();ct();pd();Yh();cd();hd();ud();ma()});var Zh=i(()=>{"use strict";F();fd();pd();hd();ct()});async function pa(t){let e=v().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(Fe(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw d}for(let d of o){if(!U(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await Qe(d);!t.force&&(c===void 0||t.now-c<ME)||(a+=await Ee(d),t.dryRun||await e.remove(d.name,{recursive:!0}),r+=1)}let s=await e.getDirectory(".wikg-cache");if(s!==void 0)for(let d of await s.list())U(d)&&(n+=1,t.force&&(a+=await Ee(d),t.dryRun||await s.remove(d.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:n}}var ME,ef=i(()=>{"use strict";y();pe();ME=3600*1e3});var tf=i(()=>{"use strict";w();y();F();ct();ma()});var gd=i(()=>{"use strict";Zh();fd();ef();tf()});var bd=i(()=>{"use strict";gd()});var nf=i(()=>{"use strict";_();la();ot();bd()});var Le=i(()=>{"use strict";Nh();Uh();nf();bd()});var wd,kd=i(()=>{"use strict";wd=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function rf(){return await z(v().library,"jobs/work")}async function af(t){let e=await v().library.getDirectory("jobs");if(e!==void 0)for(let[n,r,a]of[["work",t,!0],["cache",t,!0],["logs",t,!0],["events",`${t}.ndjson`,!1]]){let o=await e.getDirectory(n);o!==void 0&&await o.remove(r,{recursive:a})}}var Pr=i(()=>{"use strict";y()});var Ar=i(()=>{"use strict";F()});var xd=i(()=>{"use strict"});var Lr=i(()=>{"use strict";y()});var of,sf=i(()=>{"use strict";of=`
682
640
  CREATE TABLE IF NOT EXISTS build_jobs (
683
641
  job_id TEXT PRIMARY KEY,
684
642
  archive_key TEXT NOT NULL,
@@ -737,7 +695,7 @@ CREATE TABLE IF NOT EXISTS build_worker_lease (
737
695
 
738
696
  INSERT OR IGNORE INTO build_worker_lease (id)
739
697
  VALUES (1);
740
- `});function Fn(n){let e=nv(Wn(n,"current_step"),"current_step"),t=Wn(n,"owner_id"),r=n.owner_pid===null?void 0:se(n,"owner_pid"),a=n.reading_summary_started_at===null?void 0:se(n,"reading_summary_started_at"),o=n.finished_at===null?void 0:se(n,"finished_at"),s=Wn(n,"error_json"),d=n.input_revision===null?void 0:se(n,"input_revision"),c=Wn(n,"llm_json"),u=Wn(n,"prompt");return{archiveKey:Le(n,"archive_key"),archiveIdentity:Le(n,"archive_path"),cacheLocator:Le(n,"cache_path"),chapterId:se(n,"chapter_id"),createdAt:se(n,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Le(n,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Le(n,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Le(n,"log_path"),...c===void 0?{}:{llmJSON:c},...t===void 0?{}:{ownerId:t},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:se(n,"queue_rank"),state:ev(Le(n,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:Wy(Le(n,"target"),"target"),updatedAt:se(n,"updated_at"),workspaceLocator:Le(n,"workspace_path")}}async function Hr(n){let e=L().resources,[t,r,a,o,s]=await Promise.all([e.getFile(n.archiveIdentity),Zd(n.cacheLocator),ZR(n.eventsLocator),Zd(n.logLocator),Zd(n.workspaceLocator)]);if(t===void 0)throw qr("archive");if(r===void 0)throw qr("cache");if(a===void 0)throw qr("events");if(o===void 0)throw qr("log");if(s===void 0)throw qr("workspace");let{archiveIdentity:d,cacheLocator:c,eventsLocator:u,logLocator:m,ownerPid:b,workspaceLocator:R,...f}=n;return{...f,archive:t,cache:r,events:a,log:o,workspace:s}}async function Zd(n){return n.startsWith("jobs/")?await Oe(v().library,n)??YR(n):await L().resources.getDirectory(n)}function YR(n){let e=v().library,t=r=>`${n}/${r}`;return{createDirectory:async r=>await z(e,t(r)),createFile:async r=>await H(e,t(r)),getDirectory:async r=>await Oe(e,t(r)),getFile:async r=>await J(e,t(r)),getLastModified:async()=>await(await Oe(e,n))?.getLastModified?.(),identity:`managed:library:${n}`,kind:"directory",list:async()=>(await Oe(e,n))?.list()??[],name:n.split("/").at(-1)??n,remove:async(r,a)=>{await(await Oe(e,n))?.remove(r,a)}}}async function ZR(n){return n.startsWith("jobs/")?await J(v().library,n):await L().resources.getFile(n)}function qr(n){return new Error(`Build job ${n} resource is unavailable`)}function ev(n){if(Xd.includes(n))return n;throw new Error(`Invalid build job state: ${n}`)}function Wy(n,e){if(n==="index-embedding-source"||n==="index-embedding-summary"||n==="index-fts"||n==="reading-graph"||n==="knowledge-graph"||n==="reading-summary")return n;throw new Error(`Invalid ${e}: ${n}`)}function nv(n,e){return n===void 0?void 0:Wy(n,e)}function Le(n,e){let t=n[e];if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}function se(n,e){let t=n[e];if(typeof t!="number")throw new TypeError(`Expected ${e} to be a number`);return t}function Wn(n,e){let t=n[e];if(t!=null){if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}}var Mn=i(()=>{"use strict";Vd();y()});async function bt(){let n=await X("jobs/job.sqlite",Ny);try{return await n.run(`
698
+ `});function jt(t){let e=qE(Gt(t,"current_step"),"current_step"),n=Gt(t,"owner_id"),r=t.owner_pid===null?void 0:ce(t,"owner_pid"),a=t.reading_summary_started_at===null?void 0:ce(t,"reading_summary_started_at"),o=t.finished_at===null?void 0:ce(t,"finished_at"),s=Gt(t,"error_json"),d=t.input_revision===null?void 0:ce(t,"input_revision"),c=Gt(t,"llm_json"),u=Gt(t,"prompt");return{archiveKey:Oe(t,"archive_key"),archiveIdentity:Oe(t,"archive_path"),cacheLocator:Oe(t,"cache_path"),chapterId:ce(t,"chapter_id"),createdAt:ce(t,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Oe(t,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Oe(t,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Oe(t,"log_path"),...c===void 0?{}:{llmJSON:c},...n===void 0?{}:{ownerId:n},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:ce(t,"queue_rank"),state:BE(Oe(t,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:df(Oe(t,"target"),"target"),updatedAt:ce(t,"updated_at"),workspaceLocator:Oe(t,"workspace_path")}}async function Nr(t){let e=A().resources,[n,r,a,o,s]=await Promise.all([e.getFile(t.archiveIdentity),Id(t.cacheLocator),UE(t.eventsLocator),Id(t.logLocator),Id(t.workspaceLocator)]);if(n===void 0)throw Or("archive");if(r===void 0)throw Or("cache");if(a===void 0)throw Or("events");if(o===void 0)throw Or("log");if(s===void 0)throw Or("workspace");let{archiveIdentity:d,cacheLocator:c,eventsLocator:u,logLocator:m,ownerPid:b,workspaceLocator:R,...f}=t;return{...f,archive:n,cache:r,events:a,log:o,workspace:s}}async function Id(t){return t.startsWith("jobs/")?await We(v().library,t)??jE(t):await A().resources.getDirectory(t)}function jE(t){let e=v().library,n=r=>`${t}/${r}`;return{createDirectory:async r=>await z(e,n(r)),createFile:async r=>await H(e,n(r)),getDirectory:async r=>await We(e,n(r)),getFile:async r=>await J(e,n(r)),getLastModified:async()=>await(await We(e,t))?.getLastModified?.(),identity:`managed:library:${t}`,kind:"directory",list:async()=>(await We(e,t))?.list()??[],name:t.split("/").at(-1)??t,remove:async(r,a)=>{await(await We(e,t))?.remove(r,a)}}}async function UE(t){return t.startsWith("jobs/")?await J(v().library,t):await A().resources.getFile(t)}function Or(t){return new Error(`Build job ${t} resource is unavailable`)}function BE(t){if(wd.includes(t))return t;throw new Error(`Invalid build job state: ${t}`)}function df(t,e){if(t==="index-embedding-source"||t==="index-embedding-summary"||t==="index-fts"||t==="reading-graph"||t==="knowledge-graph"||t==="reading-summary")return t;throw new Error(`Invalid ${e}: ${t}`)}function qE(t,e){return t===void 0?void 0:df(t,e)}function Oe(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}function ce(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function Gt(t,e){let n=t[e];if(n!=null){if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}}var Ut=i(()=>{"use strict";kd();y()});async function hn(){let t=await X("jobs/job.sqlite",of);try{return await t.run(`
741
699
  UPDATE build_jobs
742
700
  SET workspace_path = 'jobs/work/' || job_id,
743
701
  cache_path = 'jobs/cache/' || job_id,
@@ -747,33 +705,92 @@ VALUES (1);
747
705
  OR cache_path NOT LIKE 'jobs/cache/%'
748
706
  OR log_path NOT LIKE 'jobs/logs/%'
749
707
  OR events_path NOT LIKE 'jobs/events/%'
750
- `),n}catch(e){throw await n.close().catch(()=>{}),e}}var St=i(()=>{"use strict";_();y();Dy();Mn()});var Ea=i(()=>{"use strict";Br();Ur();St();jr()});var Ra=i(()=>{"use strict";Mn();Ea();jr()});var ec=i(()=>{"use strict";U();jr();Br();Yd();Ur();St();Ra();Ea();Mn()});var jy=i(()=>{"use strict";Br();St();Ra();Mn()});var By=i(()=>{"use strict";U();Br();Yd();Ur();St();Ra();Ea();ec();Mn()});function dv(n){return ov.has(n)}async function cv(n,e){if((await e.list()).some(a=>!dv(a.name)))return 0;let r=await un(e);return await n.remove(e.name,{recursive:!0}),r}async function Uy(n){let e=0,t=0,r=0;for(let a of await n.list()){if(!j(a))continue;r+=1;let o=await ze(a);if(o===void 0||Date.now()-o<sv)continue;let s=await cv(n,a);(s>0||await n.getDirectory(a.name)===void 0)&&(e+=s,t+=1)}return{freedBytes:e,removed:t,scanned:r}}async function un(n){return await Ie(n)}var ov,sv,nc=i(()=>{"use strict";y();ov=new Set([".DS_Store"]),sv=6e4});async function va(n){let e=await bt(),t=n.force?n.now:n.now-10080*60*1e3;try{let r=await e.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>se(c,"count")),a=await e.queryAll(`
708
+ `),t}catch(e){throw await t.close().catch(()=>{}),e}}var fn=i(()=>{"use strict";_();y();sf();Ut()});var ha=i(()=>{"use strict";Ar();Lr();fn();Pr()});var fa=i(()=>{"use strict";Ut();ha();Pr()});var Ed=i(()=>{"use strict";F();Pr();Ar();xd();Lr();fn();fa();ha();Li();Ut()});var mf=i(()=>{"use strict";Ar();fn();fa();Ut();Li()});var pf=i(()=>{"use strict";F();Ar();xd();Lr();fn();fa();ha();Ed();Ut()});function XE(t){return zE.has(t)}async function VE(t,e){if((await e.list()).some(a=>!XE(a.name)))return 0;let r=await ut(e);return await t.remove(e.name,{recursive:!0}),r}async function hf(t){let e=0,n=0,r=0;for(let a of await t.list()){if(!U(a))continue;r+=1;let o=await Qe(a);if(o===void 0||Date.now()-o<QE)continue;let s=await VE(t,a);(s>0||await t.getDirectory(a.name)===void 0)&&(e+=s,n+=1)}return{freedBytes:e,removed:n,scanned:r}}async function ut(t){return await Ee(t)}var zE,QE,Rd=i(()=>{"use strict";y();zE=new Set([".DS_Store"]),QE=6e4});async function ya(t){let e=await hn(),n=t.force?t.now:t.now-10080*60*1e3;try{let r=await e.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>ce(c,"count")),a=await e.queryAll(`
751
709
  SELECT *
752
710
  FROM build_jobs
753
711
  WHERE state IN ('succeeded', 'failed', 'canceled')
754
712
  AND updated_at <= ?
755
- `,[t],Fn),o=await Promise.all(a.map(Hr)),s=n.dryRun?{freedBytes:0,removed:0,scanned:0}:await Uy(await Ly()),d=0;for(let c of o)d+=await un(c.workspace),d+=await un(c.cache),d+=await un(c.log),d+=await un(c.events),n.dryRun||(await Oy(c.jobId),await e.run("DELETE FROM build_jobs WHERE job_id = ?",[c.jobId]));return{freedBytes:d+s.freedBytes,removed:o.length+s.removed,scanned:(r??0)+s.scanned}}finally{await e.close()}}var qy=i(()=>{"use strict";nc();jr();St();Mn()});var Jy=i(()=>{"use strict";Vd();ec();jy();By();Ur();qy()});var _a=i(()=>{"use strict"});import{z as p}from"zod";var Ky,V,lv,mv,zy,pv,hv,fv,yv,gv,bv,Sv,wv,kv,xv,Iv,Ev,Rv,vv,XZ,wt=i(()=>{"use strict";y();ve();_a();Ky=1,V=p.number().int().nonnegative(),lv=p.literal(Ky),mv=p.string().regex(/^Q[1-9][0-9]*$/u),zy=p.number().min(0).max(1).optional(),pv=p.object({text:p.string(),wordsCount:V}).strict(),hv=p.object({type:p.literal("meta"),schemaVersion:lv,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),fv=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),yv=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(pv)}).strict(),gv=p.object({type:p.literal("reading-chunk"),id:p.string().min(1),generation:p.number().int(),sentenceIndex:V,label:p.string(),content:p.string(),sentenceIndexes:p.array(V).min(1),retention:p.enum(he).optional(),importance:p.enum(Re).optional(),wordsCount:V,weight:p.number()}).strict(),bv=p.object({type:p.literal("reading-edge"),fromChunkId:p.string().min(1),toChunkId:p.string().min(1),strength:p.string().optional(),weight:p.number()}).strict(),Sv=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),wv=p.object({type:p.literal("snake"),id:p.string().min(1),groupId:V,localSnakeId:V,size:V,firstLabel:p.string(),lastLabel:p.string(),wordsCount:V,weight:p.number()}).strict(),kv=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),xv=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),Iv=p.object({type:p.literal("summary"),text:p.string()}).strict(),Ev=p.object({type:p.literal("mention"),id:p.string().min(1),fragmentId:V.optional(),sentenceIndex:V.optional(),rangeStart:V,rangeEnd:V,surface:p.string().min(1),qid:mv,confidence:zy,note:p.string().optional()}).strict(),Rv=p.object({type:p.literal("mention-link"),id:p.string().min(1),sourceMentionId:p.string().min(1),targetMentionId:p.string().min(1),predicate:p.string().min(1),evidenceSentenceIndexes:p.array(V).min(1),confidence:zy,note:p.string().optional()}).strict(),vv=p.object({type:p.literal("end")}).strict(),XZ=p.discriminatedUnion("type",[hv,fv,yv,gv,bv,Sv,wv,kv,xv,Iv,Ev,Rv,vv])});var Qy=i(()=>{"use strict"});var Xy=i(()=>{"use strict"});import{sha256 as n6}from"@noble/hashes/sha2.js";var t6,r6,fc=i(()=>{"use strict";t6=new RegExp("\\p{Script=Han}+","gu"),r6=new RegExp("^\\p{Script=Han}+$","u")});var yc=i(()=>{"use strict";fc()});import{z as l}from"zod";function Vy(){return l.object({content:l.string(),generation:l.number().int(),id:l.string(),importance:l.enum(["critical","helpful","important"]).optional(),label:l.string(),retention:l.enum(["detailed","focused","relevant","verbatim"]).optional(),sentenceIndex:P,sentenceIndexes:l.array(P),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:P})}function Yy(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Zy(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function eg(){return l.object({firstLabel:l.string(),groupId:P,id:l.string(),lastLabel:l.string(),localSnakeId:P,size:P,type:l.literal("snake"),weight:l.number(),wordsCount:P})}function ng(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function tg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function rg(){return l.object({confidence:l.number().optional(),fragmentId:P.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:P,rangeStart:P,sentenceIndex:P.optional(),surface:l.string(),type:l.literal("mention")})}function Cv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(P),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var P,gc,c6,u6,Gn=i(()=>{"use strict";P=l.number().int().nonnegative(),gc={sentenceIndex:P,text:l.string(),wordsCount:P},c6=l.discriminatedUnion("type",[l.object({extractionPrompt:l.string().optional(),language:l.string().optional(),policyPrompt:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...gc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...gc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...gc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Vy(),Yy(),Zy(),eg(),ng(),tg(),rg()]),u6=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Vy(),Yy(),Zy(),eg(),ng(),tg(),rg(),Cv(),l.object({position:P,text:l.string(),type:l.literal("summary-part")}),l.object({metadata:l.record(l.string(),l.unknown()),objectId:l.string(),objectKind:l.string(),rowId:l.string(),sentenceIndex:P.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:P,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:P,segmentIndex:P,startSentenceIndex:P,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:P})])});var bc=i(()=>{"use strict";Gn()});var Sc=i(()=>{"use strict"});var jn,wc=i(()=>{"use strict";jn=["Classify the raw assistant reply into exactly one label.","Labels:","- malformed_json: the reply is trying to provide JSON, but it is broken or truncated","- natural_language: the reply is plain conversational language, apology, refusal, or explanation instead of JSON","- ambiguous: unclear or mixed","Reply with the label only."].join(`
756
- `)});import{jsonrepair as g6}from"jsonrepair";var ig=i(()=>{"use strict"});var ag=i(()=>{"use strict";wc();Sc();ig()});var le=i(()=>{"use strict";Sc();wc();ag()});var dg=i(()=>{"use strict"});var $r=i(()=>{"use strict"});import{z as Je}from"zod";var Av,Lv,q6,xc=i(()=>{"use strict";le();$r();Av=Je.object({candidateId:Je.string().min(1),decision:Je.enum(["continue","recall","skip_this_time","never_recall"]),qid:Je.string().nullable().optional()}).strict(),Lv=Je.object({decisions:Je.array(Av),groupId:Je.string().min(1)}).strict(),q6=Je.object({groups:Je.array(Lv)}).strict()});import{z as Jr}from"zod";var Nv,V6,ug=i(()=>{"use strict";le();$r();xc();Nv=Jr.object({decision:Jr.enum(["keep","reject"]),qid:Jr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),V6=Jr.object({qids:Jr.array(Nv)}).strict()});var Ic=i(()=>{"use strict"});import{z as Kr}from"zod";var Dv,t9,lg=i(()=>{"use strict";le();Dv=Kr.object({note:Kr.string().max(24).optional(),surfaceId:Kr.string().min(1)}).strict(),t9=Kr.object({protectedSurfaces:Kr.array(Dv)}).strict()});var mg=i(()=>{"use strict";Ic()});var pg=i(()=>{"use strict"});var Ec=i(()=>{"use strict"});var hg=i(()=>{"use strict";Ec();$r()});var zr=i(()=>{"use strict";dg();ug();$r();xc();Ic();lg();mg();pg();hg();Ec()});var Aa=i(()=>{"use strict"});var fg=i(()=>{"use strict";zr();Aa()});var yg=i(()=>{"use strict";zr()});var Rc=i(()=>{"use strict"});var gg=i(()=>{"use strict";zr();Aa();yg();Rc()});function La(n){let e=n.trim();return e===""?[]:Array.from(Mv.segment(e)).map(t=>t.segment.trim()).filter(t=>t!=="")}function xe(n){let e=n.replace(/\s+/gu," ").trim(),t=Gv(e),r="";for(let a of t)if(!jv(a)){if(!Qr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function Gv(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===void 0)break;if(r!==" "){e.push(r),t+=1;continue}if(e.length>=2&&Fv.has(e[e.length-1]??"")&&Qr(e[e.length-2]??"")&&t<n.length-1&&Qr(n[t+1]??"")){e.pop(),t+=1;continue}let a=e[e.length-1]??"",o=n[t+1]??"";a!==""&&o!==""&&Qr(a)&&Qr(o)&&e.push(r),t+=1}return e}function Qr(n){return n!==""&&new RegExp("\\p{Script=Latin}","u").test(n)&&new RegExp("\\p{L}","u").test(n)}function jv(n){return/[\p{P}\p{S}]/u.test(n)}var Fv,Mv,Xr=i(()=>{"use strict";Fv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Mv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Cc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Sg(n,e){let t=Oa(n,2),r=Oa(e,2),a=Oa(n,3),o=Oa(e,3);return(bg(t,r)+bg(a,o))/2}function Oa(n,e){if(n.length<=e)return n===""?new Set:new Set([n]);let t=new Set;for(let r=0;r<=n.length-e;r+=1)t.add(n.slice(r,r+e));return t}function bg(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&(t+=1);return 2*t/(n.size+e.size)}function wg(n,e){if(n===e)return 1;if(n===""||e==="")return 0;let t=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...n].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(t[d+1]??0)+1,b=(t[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[t,r]=[r,t]}return 1-(t[e.length]??Math.max(n.length,e.length))/Math.max(n.length,e.length)}function kg(n,e){return 1-Math.abs(n.length-e.length)/Math.max(n.length,e.length)}function xg(n,e){if(n===e)return 1;let t=n.length,r=e.length;if(t===0||r===0)return 0;let a=Array.from({length:t+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=t;s+=1)for(let d=1;d<=r;d+=1){if(n[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(t+r)}function Ig(n){return` - ${n.occurrenceId} score=${n.score.toFixed(3)}
757
- prev: ${vc(n.prevText)}
758
- text: ${vc(n.text,120)}
759
- next: ${vc(n.nextText)}`}function vc(n,e=80){let t=n.replace(/\s+/gu," ").trim();return t===""?"(none)":t.length<=e?t:`${t.slice(0,e-3)}...`}var Tc=i(()=>{"use strict"});var _c=i(()=>{"use strict"});function Rg(n,e,t){return n.mode==="head_tail"?qv(n,e):Pc(n.text??"",e,t)}function qv(n,e){let t=n.head??"",r=n.tail??"",a=xe(e),o=xe(t),s=xe(r);if(o===""||s==="")return Cc();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=Pc(t,e,"start_anchor"),m=Pc(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function Pc(n,e,t){let r=n.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return Cc();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=Eg({candidateNormalized:s,label:t,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),A=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((A===0?0:K/A)<.35)continue;let G=.35*Sg(o,g)+.35*xg(o,g)+.2*wg(o,g)+.1*kg(o,g)+Eg({candidateNormalized:s,label:t,matchEnd:k+f,matchStart:k,queryNormalized:o});G>d&&(d=Math.min(1,G),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function Eg(n){if(n.matchStart<0||n.matchEnd<0||n.queryNormalized.length<12||n.label==="start_anchor"&&n.matchStart!==0||n.label==="end_anchor"&&n.matchEnd!==n.candidateNormalized.length)return 0;let e=n.queryNormalized.length/Math.max(1,n.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var vg=i(()=>{"use strict";Xr();Tc();_c()});function Cg(n){if(n==null)return[void 0,"anchor is required"];if(typeof n=="string"){let o=n.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof n!="object")return[void 0,`expected string or object, got ${typeof n}`];let e=n;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function Tg(n,e){if(n===void 0)return;if(n.mode==="head_tail"){let r=e==="end_anchor"?Ac(n.tail??"","end_anchor"):Ac(n.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Ac(n.text??"",e)}}function Lc(n){return n.mode==="head_tail"?xe(n.head??"").length+xe(n.tail??"").length:xe(n.text??"").length}function Ac(n,e){let t=La(n);return t.length<=1?n.trim():e==="end_anchor"?t[t.length-1]??n.trim():t[0]??n.trim()}var _g=i(()=>{"use strict";Xr()});var kt,Og=i(()=>{"use strict";vg();_g();Tc();_c();kt=class{resolve(e,t,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:t,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:t,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:t.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let t=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(t,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,t){let[r,a]=Cg(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:t,message:`Invalid evidence.${t}: ${a}`}]:[Tg(r,t),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let t=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(t=t.filter(m=>m.index>=r)),t.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=t.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#n(e.label,"ambiguous_exact_raw",a)];let o=t.filter(m=>m.exactSubstring);if(o.length===1&&Lc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Lc(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#n(e.label,"ambiguous_exact_substring",o)]}let s=t.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#n(e.label,"ambiguous_exact_normalized",s)]}let d=t[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=t[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:t.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:t.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#n(e.label,"ambiguous_ranked",t)]}rankAnchor(e,t,r,a){let o=[];for(let[s,d]of t.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=Rg(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let t=e[0];if(t===void 0)return;let r=e[1]?.score??0;if(t.score>=.9&&t.score-r>=.07)return t}#n(e,t,r){let a=r.slice(0,3),o=a.map(s=>Ig(s)).join(`
760
- `);return{candidates:a,code:t,fieldName:e,message:`${e} is ambiguous. Top candidates:
713
+ `,[n],jt),o=await Promise.all(a.map(Nr)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await hf(await rf()),d=0;for(let c of o)d+=await ut(c.workspace),d+=await ut(c.cache),d+=await ut(c.log),d+=await ut(c.events),t.dryRun||(await af(c.jobId),await e.run("DELETE FROM build_jobs WHERE job_id = ?",[c.jobId]));return{freedBytes:d+s.freedBytes,removed:o.length+s.removed,scanned:(r??0)+s.scanned}}finally{await e.close()}}var ff=i(()=>{"use strict";Rd();Pr();fn();Ut()});var Gd=i(()=>{"use strict";kd();Ed();mf();pf();Lr();ff()});var Wr=i(()=>{"use strict";at()});async function bf(t){let n=await(await v().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await eR();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let a=new Set(r.map(u=>String(u))),o=await n.list(),s=0,d=0,c=0;for(let u of o){if(!U(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await np(m))continue;let b=await Ee(u);t.dryRun||await n.remove(u.name,{recursive:!0}),d+=1,c+=b}return{freedBytes:c,removed:d,scanned:s}}async function eR(){let t=await X("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await t.close()}}var yn=i(()=>{"use strict";F();y();w();nr();_();Le();Wt();Wr();Ot();gn();_t();Ct();Z()});var Sf=i(()=>{"use strict"});var tR,BX,gn=i(()=>{"use strict";y();w();_();Be();Le();Le();Gd();ot();Re();F();_t();yn();Ct();Sf();tR=`
714
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
715
+ library_id INTEGER NOT NULL,
716
+ public_id TEXT NOT NULL,
717
+ relative_path TEXT NOT NULL,
718
+ status TEXT NOT NULL DEFAULT 'present',
719
+ last_seen_mutation_token TEXT,
720
+ last_seen_size INTEGER,
721
+ last_seen_mtime_ms INTEGER,
722
+ last_scanned_at TEXT,
723
+ created_at TEXT NOT NULL,
724
+ updated_at TEXT NOT NULL,
725
+ UNIQUE(library_id, public_id)
726
+ `,BX=`
727
+ CREATE TABLE IF NOT EXISTS library_archives (
728
+ ${tR}
729
+ );
730
+
731
+ CREATE INDEX IF NOT EXISTS idx_library_archives_library
732
+ ON library_archives(library_id);
733
+
734
+ CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
735
+ ON library_archives(library_id, relative_path);
736
+ `});var If=i(()=>{"use strict";ot();gn();Ct();yn();_t()});var Ud=i(()=>{"use strict";Le();gn();_t()});var vf=i(()=>{"use strict";Mi();Gi();ir();Xi();Qi();we();Vi();Lt();Wr();yn();Ud()});var Cf=i(()=>{"use strict";Qs();Gi();vf();we();gn();Ud();_t();yn();Ct()});var wa=i(()=>{"use strict";_t();If();gn();Cf();yn();Ct()});function ka(t){let e=t.trim();return e===""?[]:Array.from(pR.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=hR(e),r="";for(let a of n)if(!fR(a)){if(!Mr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function hR(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&mR.has(e[e.length-1]??"")&&Mr(e[e.length-2]??"")&&n<t.length-1&&Mr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Mr(a)&&Mr(o)&&e.push(r),n+=1}return e}function Mr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function fR(t){return/[\p{P}\p{S}]/u.test(t)}var mR,pR,Fr=i(()=>{"use strict";mR=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),pR=new Intl.Segmenter(void 0,{granularity:"sentence"})});function qd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function _f(t,e){let n=xa(t,2),r=xa(e,2),a=xa(t,3),o=xa(e,3);return(Tf(n,r)+Tf(a,o))/2}function xa(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function Tf(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function Pf(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function Af(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Lf(t,e){if(t===e)return 1;let n=t.length,r=e.length;if(n===0||r===0)return 0;let a=Array.from({length:n+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=n;s+=1)for(let d=1;d<=r;d+=1){if(t[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(n+r)}function Of(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
737
+ prev: ${Bd(t.prevText)}
738
+ text: ${Bd(t.text,120)}
739
+ next: ${Bd(t.nextText)}`}function Bd(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Hd=i(()=>{"use strict"});var $d=i(()=>{"use strict"});function Wf(t,e,n){return t.mode==="head_tail"?bR(t,e):Jd(t.text??"",e,n)}function bR(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return qd();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=Jd(n,e,"start_anchor"),m=Jd(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function Jd(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return qd();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=Nf({candidateNormalized:s,label:n,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*_f(o,g)+.35*Lf(o,g)+.2*Pf(o,g)+.1*Af(o,g)+Nf({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function Nf(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var Df=i(()=>{"use strict";Fr();Hd();$d()});function Mf(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function Ff(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?Kd(t.tail??"","end_anchor"):Kd(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Kd(t.text??"",e)}}function zd(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function Kd(t,e){let n=ka(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var Gf=i(()=>{"use strict";Fr()});var Bt,qf=i(()=>{"use strict";Df();Gf();Hd();$d();Bt=class{resolve(e,n,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:n.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=Mf(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Ff(r,n),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&zd(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&zd(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=Wf(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>Of(s)).join(`
740
+ `);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
741
+ ${o}
742
+ Please provide a more specific anchor or surrounding context.`}}}});var Hf=i(()=>{"use strict"});var $f=i(()=>{"use strict";qf();Hf()});var Ia,Jf=i(()=>{"use strict";Ia=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
743
+ `)});var Qd=i(()=>{"use strict"});var Kf=i(()=>{"use strict";Qd();Fr()});var Sn=i(()=>{"use strict";$f();Jf();Qd();Kf();Fr()});import{z as Gr}from"zod";var mY,Qf=i(()=>{"use strict";mY=Gr.object({meanings:Gr.array(Gr.object({information:Gr.string(),qid:Gr.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var Xf=i(()=>{"use strict"});var Ra=i(()=>{"use strict"});var gY,Zf=i(()=>{"use strict";Ra();gY=336*60*60*1e3});var ey=i(()=>{"use strict";Ra()});var ty=i(()=>{"use strict";Qf();Xf();Zf();Ra();ey()});async function Vd(t){let e=await jr.open();try{return await e.gc(t)}finally{await e.close()}}function OR(t){try{let e=JSON.parse(t);if(typeof e!="object"||e===null)return;let n=e;return typeof n.qid!="string"||typeof n.refreshedAt!="string"||!Array.isArray(n.sites)?void 0:{qid:n.qid,refreshedAt:n.refreshedAt,sites:n.sites}}catch{return}}function NR(t){try{let e=JSON.parse(t);return typeof e.qid=="string"&&(e.wiki==="zhwiki"||e.wiki==="enwiki")&&typeof e.pageId=="number"&&typeof e.revisionId=="number"&&typeof e.parsedPage=="object"&&e.parsedPage!==null&&typeof e.profile=="object"&&e.profile!==null?e:void 0}catch{return}}var AR,LR,jr,ny=i(()=>{"use strict";ty();_();AR=`
744
+ CREATE TABLE IF NOT EXISTS wikimedia_qid_cache_v2 (
745
+ qid TEXT PRIMARY KEY,
746
+ record_json TEXT NOT NULL,
747
+ refreshed_at TEXT NOT NULL
748
+ );
749
+ CREATE INDEX IF NOT EXISTS idx_wikimedia_qid_cache_v2_refreshed_at
750
+ ON wikimedia_qid_cache_v2(refreshed_at);
751
+ CREATE TABLE IF NOT EXISTS wikimedia_disambiguation_cache_v2 (
752
+ qid TEXT NOT NULL,
753
+ wiki TEXT NOT NULL,
754
+ page_id INTEGER NOT NULL,
755
+ revision_id INTEGER NOT NULL,
756
+ normalizer_version TEXT NOT NULL,
757
+ model_id TEXT NOT NULL,
758
+ record_json TEXT NOT NULL,
759
+ PRIMARY KEY(qid,wiki,page_id,revision_id,normalizer_version,model_id)
760
+ );
761
+ `,LR=336*60*60*1e3,jr=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await X("cache/cache.sqlite",AR))}async getQids(e,n){if(e.length===0)return new Map;n?.signal?.throwIfAborted();let r=await this.#e.queryAll(`SELECT record_json FROM wikimedia_qid_cache_v2
762
+ WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=OR(o);s!==void 0&&a.set(s.qid,s)}return a}async putQids(e,n){n?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let r of e)n?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_qid_cache_v2(qid,record_json,refreshed_at)
763
+ VALUES(?,?,?)
764
+ ON CONFLICT(qid) DO UPDATE SET
765
+ record_json=excluded.record_json,
766
+ refreshed_at=excluded.refreshed_at`,[r.qid,JSON.stringify(r),r.refreshedAt])})}async getDisambiguations(e,n,r){if(e.length===0)return[];r?.signal?.throwIfAborted();let a=e.map(()=>"(qid=? AND wiki=? AND page_id=? AND revision_id=?)"),o=e.flatMap(d=>[d.qid,d.wiki,d.pageId,d.revisionId]);return(await this.#e.queryAll(`SELECT record_json FROM wikimedia_disambiguation_cache_v2
767
+ WHERE normalizer_version=? AND model_id=?
768
+ AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=NR(d);return c===void 0?[]:[c]})}async putDisambiguations(e,n,r){r?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let a of e)r?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_disambiguation_cache_v2(
769
+ qid,wiki,page_id,revision_id,normalizer_version,model_id,record_json
770
+ ) VALUES(?,?,?,?,?,?,?)
771
+ ON CONFLICT(qid,wiki,page_id,revision_id,normalizer_version,model_id)
772
+ DO UPDATE SET record_json=excluded.record_json`,[a.qid,a.wiki,a.pageId,a.revisionId,n.normalizerVersion,n.modelId,JSON.stringify(a)])})}async close(){await this.#e.close()}async gc(e){let n=new Date(e.now-LR).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.transaction(async()=>{let o=await this.#e.queryAll("SELECT qid FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],s=>String(s.qid));for(let s of o)await this.#e.run("DELETE FROM wikimedia_disambiguation_cache_v2 WHERE qid = ?",[s]);await this.#e.run("DELETE FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n])}),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var Zd=i(()=>{"use strict";ny()});var ec=i(()=>{"use strict"});var tc=i(()=>{"use strict"});import{jsonrepair as MY}from"jsonrepair";var ry=i(()=>{"use strict"});var iy=i(()=>{"use strict";tc();ec();ry()});var Ne=i(()=>{"use strict";ec();tc();iy()});var Ur=i(()=>{"use strict"});import{z as $e}from"zod";var GR,jR,d2,ic=i(()=>{"use strict";Ne();Ur();GR=$e.object({candidateId:$e.string().min(1),decision:$e.enum(["continue","recall","skip_this_time","never_recall"]),qid:$e.string().nullable().optional()}).strict(),jR=$e.object({decisions:$e.array(GR),groupId:$e.string().min(1)}).strict(),d2=$e.object({groups:$e.array(jR)}).strict()});import{z as Br}from"zod";var qR,h2,sy=i(()=>{"use strict";Ne();Ur();ic();qR=Br.object({decision:Br.enum(["keep","reject"]),qid:Br.string().regex(/^Q[1-9][0-9]*$/)}).strict(),h2=Br.object({qids:Br.array(qR)}).strict()});var dy=i(()=>{"use strict"});import{z as qr}from"zod";var HR,S2,cy=i(()=>{"use strict";Ne();HR=qr.object({note:qr.string().max(24).optional(),surfaceId:qr.string().min(1)}).strict(),S2=qr.object({protectedSurfaces:qr.array(HR)}).strict()});var ac=i(()=>{"use strict"});var uy=i(()=>{"use strict";ac()});var ly=i(()=>{"use strict"});var oc=i(()=>{"use strict"});var my=i(()=>{"use strict";oc();Ur()});var mt=i(()=>{"use strict";ic();sy();Ur();dy();cy();uy();ac();ly();my();oc()});var X2,dc=i(()=>{"use strict";en();X2=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var cc=i(()=>{"use strict";Ve()});var gy=i(()=>{"use strict";cc()});var by=i(()=>{"use strict";gy();cc()});var Sy=i(()=>{"use strict"});var wy=i(()=>{"use strict"});var ky=i(()=>{"use strict";Sy();wy()});var Hr=i(()=>{"use strict";Ne()});var xy=i(()=>{"use strict";_();Hr()});var Iy=i(()=>{"use strict";Hr()});var Ey=i(()=>{"use strict"});import{z as x}from"zod";var Ry,iv,vy,av,ov,sv,dv,cv,uv,va=i(()=>{"use strict";_();Ry=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),iv=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),vy=x.union([x.record(x.string(),x.unknown()),x.array(iv)]),av=x.object({content:x.string(),evidence:vy.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),ov=x.object({chunks:x.array(av),fragment_summary:x.string(),links:x.array(Ry)}),sv=x.object({content:x.string(),evidence:vy.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),dv=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),cv=x.object({chunks:x.array(sv),importance_annotations:x.array(dv),links:x.array(Ry)}),uv=x.object({choice:x.string()})});var Cy=i(()=>{"use strict";Ne();Sn();Ey();Hr();va()});var Ty=i(()=>{"use strict";Ne();_();xy();Hr();Iy();Cy();va()});var _y=i(()=>{"use strict";Ty();va()});var Ca=i(()=>{"use strict"});import{detect as o8,validateISO2 as s8}from"tinyld";var uc=i(()=>{"use strict";Me()});var Py=i(()=>{"use strict";uc();Me()});var Ay=i(()=>{"use strict"});import{z as $r}from"zod";var fv,_8,Oy=i(()=>{"use strict";Ne();Sn();_y();Ca();Ca();Py();Ay();fv=$r.object({content:$r.string(),id:$r.number(),label:$r.string()}),_8=$r.array(fv)});var lc=i(()=>{"use strict";Oy()});var Ny=i(()=>{"use strict";Ze()});var mc=i(()=>{"use strict";Ny()});var Wy=i(()=>{"use strict";ky();lc();mc()});var Ta=i(()=>{"use strict";Wy();mc()});var _a=i(()=>{"use strict"});var Pa=i(()=>{"use strict";Ta();_a()});var Dy=i(()=>{"use strict";Pa()});var My=i(()=>{"use strict"});var Aa=i(()=>{"use strict"});var Fy=i(()=>{"use strict";Aa()});var kn,a5,kv,La=i(()=>{"use strict";Eo();kn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(kn||{}),a5=nn(kn),kv=$n(kn,"review severity")});var u5,hc=i(()=>{"use strict";Aa();La();u5=Object.freeze({critical:9,major:3,minor:1})});var Gy=i(()=>{"use strict";uc();Me();La()});var jy=i(()=>{"use strict";y();Ve();hc()});var fc=i(()=>{"use strict";_()});var Uy=i(()=>{"use strict"});import{z as xn}from"zod";var xv,Iv,N5,By=i(()=>{"use strict";Ve();Ne();Aa();fc();La();xv=["critical","major","minor"],Iv=xn.object({problem:xn.string(),severity:xn.enum(xv),suggestion:xn.string().default("")}),N5=xn.object({issues:xn.array(Iv)})});var qy=i(()=>{"use strict";My();Fy();hc();Gy();jy();fc();Uy();By()});var yc=i(()=>{"use strict";qy()});var $y=i(()=>{"use strict"});var Jy=i(()=>{"use strict"});var Ky=i(()=>{"use strict";$y();Jy()});var Jr=i(()=>{"use strict"});var h4,f4,In=i(()=>{"use strict";_();h4={critical:9,helpful:1,important:3},f4={detailed:9,focused:3,relevant:1,verbatim:27}});var En=i(()=>{"use strict"});var Kr=i(()=>{"use strict"});var gc=i(()=>{"use strict";En()});var bc=i(()=>{"use strict";In();En();Jr();Kr();gc()});var Sc=i(()=>{"use strict";Jr();bc();Kr()});var Qy=i(()=>{"use strict";In();En();Kr()});var Xy=i(()=>{"use strict";In();En();Jr();Kr();gc()});var Vy=i(()=>{"use strict";Sc();En();Jr();Qy();bc();Xy()});var Yy=i(()=>{"use strict";Vy();Sc()});var Zy=i(()=>{"use strict";In()});var eg=i(()=>{"use strict";Yy();Zy()});var tg=i(()=>{"use strict";Ky();eg();In()});var ng=i(()=>{"use strict";tg()});var wc=i(()=>{"use strict";Z()});var rg=i(()=>{"use strict"});var kc=i(()=>{"use strict";Pa()});var Na=i(()=>{"use strict"});var ig=i(()=>{"use strict";jn();en();yc();Ta();ng();Pa();_a();wc();rg();kc();Na()});var ag=i(()=>{"use strict";wc();Na();Z()});var og=i(()=>{"use strict";Dy();ig();_a();ag();kc();Na()});var Rn=i(()=>{"use strict";og()});var sg=i(()=>{"use strict";ye();jn();Rn();Et()});var dg=i(()=>{"use strict";Et();Et();_();ye();by();Rn();sg();la();y()});var Ec,pt=i(()=>{"use strict";Ec=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Rc=i(()=>{"use strict";pt()});var lg=i(()=>{"use strict";Ve();bo();dg();dc();Le();Rc();y()});var Wa=i(()=>{"use strict"});import{z as p}from"zod";var mg,V,Wv,Dv,pg,Mv,Fv,Gv,jv,Uv,Bv,qv,Hv,$v,Jv,Kv,zv,Qv,Xv,n9,vn=i(()=>{"use strict";y();Ce();Wa();mg=1,V=p.number().int().nonnegative(),Wv=p.literal(mg),Dv=p.string().regex(/^Q[1-9][0-9]*$/u),pg=p.number().min(0).max(1).optional(),Mv=p.object({text:p.string(),wordsCount:V}).strict(),Fv=p.object({type:p.literal("meta"),schemaVersion:Wv,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),Gv=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),jv=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(Mv)}).strict(),Uv=p.object({type:p.literal("reading-chunk"),id:p.string().min(1),generation:p.number().int(),sentenceIndex:V,label:p.string(),content:p.string(),sentenceIndexes:p.array(V).min(1),retention:p.enum(he).optional(),importance:p.enum(ve).optional(),wordsCount:V,weight:p.number()}).strict(),Bv=p.object({type:p.literal("reading-edge"),fromChunkId:p.string().min(1),toChunkId:p.string().min(1),strength:p.string().optional(),weight:p.number()}).strict(),qv=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),Hv=p.object({type:p.literal("snake"),id:p.string().min(1),groupId:V,localSnakeId:V,size:V,firstLabel:p.string(),lastLabel:p.string(),wordsCount:V,weight:p.number()}).strict(),$v=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),Jv=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),Kv=p.object({type:p.literal("summary"),text:p.string()}).strict(),zv=p.object({type:p.literal("mention"),id:p.string().min(1),fragmentId:V.optional(),sentenceIndex:V.optional(),rangeStart:V,rangeEnd:V,surface:p.string().min(1),qid:Dv,confidence:pg,note:p.string().optional()}).strict(),Qv=p.object({type:p.literal("mention-link"),id:p.string().min(1),sourceMentionId:p.string().min(1),targetMentionId:p.string().min(1),predicate:p.string().min(1),evidenceSentenceIndexes:p.array(V).min(1),confidence:pg,note:p.string().optional()}).strict(),Xv=p.object({type:p.literal("end")}).strict(),n9=p.discriminatedUnion("type",[Fv,Gv,jv,Uv,Bv,qv,Hv,$v,Jv,Kv,zv,Qv,Xv])});var hg=i(()=>{"use strict"});var fg=i(()=>{"use strict"});import{sha256 as s9}from"@noble/hashes/sha2.js";var d9,c9,vc=i(()=>{"use strict";d9=new RegExp("\\p{Script=Han}+","gu"),c9=new RegExp("^\\p{Script=Han}+$","u")});var Cc=i(()=>{"use strict";vc()});import{z as l}from"zod";function yg(){return l.object({content:l.string(),generation:l.number().int(),id:l.string(),importance:l.enum(["critical","helpful","important"]).optional(),label:l.string(),retention:l.enum(["detailed","focused","relevant","verbatim"]).optional(),sentenceIndex:P,sentenceIndexes:l.array(P),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:P})}function gg(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function bg(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function Sg(){return l.object({firstLabel:l.string(),groupId:P,id:l.string(),lastLabel:l.string(),localSnakeId:P,size:P,type:l.literal("snake"),weight:l.number(),wordsCount:P})}function wg(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function kg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function xg(){return l.object({confidence:l.number().optional(),fragmentId:P.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:P,rangeStart:P,sentenceIndex:P.optional(),surface:l.string(),type:l.literal("mention")})}function Vv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(P),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var P,Tc,f9,y9,Ht=i(()=>{"use strict";P=l.number().int().nonnegative(),Tc={sentenceIndex:P,text:l.string(),wordsCount:P},f9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...Tc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...Tc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...Tc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),yg(),gg(),bg(),Sg(),wg(),kg(),xg()]),y9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),yg(),gg(),bg(),Sg(),wg(),kg(),xg(),Vv(),l.object({position:P,text:l.string(),type:l.literal("summary-part")}),l.object({metadata:l.record(l.string(),l.unknown()),objectId:l.string(),objectKind:l.string(),rowId:l.string(),sentenceIndex:P.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:P,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:P,segmentIndex:P,startSentenceIndex:P,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:P})])});var _c=i(()=>{"use strict";Ht()});var Pc=i(()=>{"use strict"});var $t,Ac=i(()=>{"use strict";$t=["Classify the raw assistant reply into exactly one label.","Labels:","- malformed_json: the reply is trying to provide JSON, but it is broken or truncated","- natural_language: the reply is plain conversational language, apology, refusal, or explanation instead of JSON","- ambiguous: unclear or mixed","Reply with the label only."].join(`
773
+ `)});import{jsonrepair as I9}from"jsonrepair";var Ig=i(()=>{"use strict"});var Eg=i(()=>{"use strict";Ac();Pc();Ig()});var le=i(()=>{"use strict";Pc();Ac();Eg()});var Cg=i(()=>{"use strict"});var zr=i(()=>{"use strict"});import{z as Ke}from"zod";var tC,nC,Q9,Oc=i(()=>{"use strict";le();zr();tC=Ke.object({candidateId:Ke.string().min(1),decision:Ke.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ke.string().nullable().optional()}).strict(),nC=Ke.object({decisions:Ke.array(tC),groupId:Ke.string().min(1)}).strict(),Q9=Ke.object({groups:Ke.array(nC)}).strict()});import{z as Qr}from"zod";var iC,r7,_g=i(()=>{"use strict";le();zr();Oc();iC=Qr.object({decision:Qr.enum(["keep","reject"]),qid:Qr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),r7=Qr.object({qids:Qr.array(iC)}).strict()});var Nc=i(()=>{"use strict"});import{z as Xr}from"zod";var aC,d7,Pg=i(()=>{"use strict";le();aC=Xr.object({note:Xr.string().max(24).optional(),surfaceId:Xr.string().min(1)}).strict(),d7=Xr.object({protectedSurfaces:Xr.array(aC)}).strict()});var Ag=i(()=>{"use strict";Nc()});var Lg=i(()=>{"use strict"});var Wc=i(()=>{"use strict"});var Og=i(()=>{"use strict";Wc();zr()});var Vr=i(()=>{"use strict";Cg();_g();zr();Oc();Nc();Pg();Ag();Lg();Og();Wc()});var Ma=i(()=>{"use strict"});var Ng=i(()=>{"use strict";Vr();Ma()});var Wg=i(()=>{"use strict";Vr()});var Dc=i(()=>{"use strict"});var Dg=i(()=>{"use strict";Vr();Ma();Wg();Dc()});function Fa(t){let e=t.trim();return e===""?[]:Array.from(dC.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function Ie(t){let e=t.replace(/\s+/gu," ").trim(),n=cC(e),r="";for(let a of n)if(!uC(a)){if(!Yr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function cC(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&sC.has(e[e.length-1]??"")&&Yr(e[e.length-2]??"")&&n<t.length-1&&Yr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Yr(a)&&Yr(o)&&e.push(r),n+=1}return e}function Yr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function uC(t){return/[\p{P}\p{S}]/u.test(t)}var sC,dC,Zr=i(()=>{"use strict";sC=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),dC=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Fc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Fg(t,e){let n=Ga(t,2),r=Ga(e,2),a=Ga(t,3),o=Ga(e,3);return(Mg(n,r)+Mg(a,o))/2}function Ga(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function Mg(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function Gg(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function jg(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Ug(t,e){if(t===e)return 1;let n=t.length,r=e.length;if(n===0||r===0)return 0;let a=Array.from({length:n+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=n;s+=1)for(let d=1;d<=r;d+=1){if(t[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(n+r)}function Bg(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
774
+ prev: ${Mc(t.prevText)}
775
+ text: ${Mc(t.text,120)}
776
+ next: ${Mc(t.nextText)}`}function Mc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Gc=i(()=>{"use strict"});var jc=i(()=>{"use strict"});function Hg(t,e,n){return t.mode==="head_tail"?pC(t,e):Uc(t.text??"",e,n)}function pC(t,e){let n=t.head??"",r=t.tail??"",a=Ie(e),o=Ie(n),s=Ie(r);if(o===""||s==="")return Fc();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=Uc(n,e,"start_anchor"),m=Uc(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function Uc(t,e,n){let r=t.trim(),a=e.trim(),o=Ie(r),s=Ie(a);if(o===""||s==="")return Fc();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=qg({candidateNormalized:s,label:n,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*Fg(o,g)+.35*Ug(o,g)+.2*Gg(o,g)+.1*jg(o,g)+qg({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function qg(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var $g=i(()=>{"use strict";Zr();Gc();jc()});function Jg(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function Kg(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?Bc(t.tail??"","end_anchor"):Bc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Bc(t.text??"",e)}}function qc(t){return t.mode==="head_tail"?Ie(t.head??"").length+Ie(t.tail??"").length:Ie(t.text??"").length}function Bc(t,e){let n=Fa(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var zg=i(()=>{"use strict";Zr()});var Cn,Yg=i(()=>{"use strict";$g();zg();Gc();jc();Cn=class{resolve(e,n,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:n.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=Jg(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Kg(r,n),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&qc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&qc(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=Hg(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>Bg(s)).join(`
777
+ `);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
761
778
  ${o}
762
- Please provide a more specific anchor or surrounding context.`}}}});var Ng=i(()=>{"use strict"});var Dg=i(()=>{"use strict";Og();Ng()});var Oc,Wg=i(()=>{"use strict";Oc=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
763
- `)});var Nc=i(()=>{"use strict"});var Fg=i(()=>{"use strict";Nc();Xr()});var Na=i(()=>{"use strict";Dg();Wg();Nc();Fg();Xr()});var Gg=i(()=>{"use strict"});import{z as W}from"zod";var jg,Kv,zv,Qv,A7,L7,Bg=i(()=>{"use strict";le();Na();Gg();jg=W.object({head:W.string().optional(),mode:W.enum(["full","head_tail"]).optional(),tail:W.string().optional(),text:W.string().optional()}).strict(),Kv=W.object({quote:W.string().optional(),sentence_id:W.string().optional()}).strict(),zv=W.union([W.object({end_anchor:W.union([W.string(),jg]).optional(),quote:W.string().optional(),sentence_id:W.string().optional(),start_anchor:W.union([W.string(),jg]).optional()}).strict(),W.array(Kv)]),Qv=W.object({confidence:W.number().min(0).max(1).optional(),evidence:zv,predicate:W.string().min(1).max(64),sourceMentionId:W.string().min(1),targetMentionId:W.string().min(1)}).strict(),A7=W.object({relations:W.array(Qv)}).strict(),L7=new kt});var Ug=i(()=>{"use strict"});var qg=i(()=>{"use strict"});var Hg=i(()=>{"use strict";Bg();Ug();qg()});var $g=i(()=>{"use strict";Hg();Aa();Rc()});var Vr,xt=i(()=>{"use strict";Vr=Object.freeze({guaranteedResponseIntent:"guaranteed-response-intent",knowledgeGraph:"knowledge-graph",readingGraphEvidenceChoice:"reading-graph-evidence-choice",readingGraphExtraction:"reading-graph-extraction",readingSummaryCompress:"reading-summary-compress",readingSummaryReview:"reading-summary-review",readingSummaryReviewGuide:"reading-summary-review-guide"})});var oee,Wc=i(()=>{"use strict";le();Gn();fg();gg();$g();zr();xt();oee=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Jg=i(()=>{"use strict"});var Kg=i(()=>{"use strict"});var zg=i(()=>{"use strict";Jg();Kg()});var Un=i(()=>{"use strict"});var Yr=i(()=>{"use strict";le()});var Xg=i(()=>{"use strict";Un();Yr()});var Vg=i(()=>{"use strict";Yr()});var Yg=i(()=>{"use strict"});import{z as I}from"zod";var Zg,Zv,eb,eC,nC,tC,rC,iC,aC,Da=i(()=>{"use strict";Un();Zg=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),Zv=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),eb=I.union([I.record(I.string(),I.unknown()),I.array(Zv)]),eC=I.object({content:I.string(),evidence:eb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),nC=I.object({chunks:I.array(eC),fragment_summary:I.string(),links:I.array(Zg)}),tC=I.object({content:I.string(),evidence:eb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),rC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),iC=I.object({chunks:I.array(tC),importance_annotations:I.array(rC),links:I.array(Zg)}),aC=I.object({choice:I.string()})});var nb=i(()=>{"use strict";le();Na();Yg();Yr();Da()});var tb=i(()=>{"use strict";le();Un();Xg();Yr();Vg();nb();Da()});var rb=i(()=>{"use strict";tb();Da()});var Mc=i(()=>{"use strict"});import{detect as sne,validateISO2 as dne}from"tinyld";var ib=i(()=>{"use strict"});var ab=i(()=>{"use strict"});import{z as Zr}from"zod";var dC,Cne,ob=i(()=>{"use strict";le();Na();rb();Mc();Mc();ib();ab();dC=Zr.object({content:Zr.string(),id:Zr.number(),label:Zr.string()}),Cne=Zr.array(dC)});var sb=i(()=>{"use strict";ob()});var db=i(()=>{"use strict";zg();sb()});var cb=i(()=>{"use strict";db()});var ub=i(()=>{"use strict"});var lb=i(()=>{"use strict"});var Gc=i(()=>{"use strict";ub();le();xt();lb()});var mb=i(()=>{"use strict"});var pb=i(()=>{"use strict"});var hb=i(()=>{"use strict";mb();pb()});var ei=i(()=>{"use strict"});var lte,mte,It=i(()=>{"use strict";Un();lte={critical:9,helpful:1,important:3},mte={detailed:9,focused:3,relevant:1,verbatim:27}});var Et=i(()=>{"use strict"});var ni=i(()=>{"use strict"});var jc=i(()=>{"use strict";Et()});var Bc=i(()=>{"use strict";It();Et();ei();ni();jc()});var Uc=i(()=>{"use strict";ei();Bc();ni()});var yb=i(()=>{"use strict";It();Et();ni()});var gb=i(()=>{"use strict";It();Et();ei();ni();jc()});var bb=i(()=>{"use strict";Uc();Et();ei();yb();Bc();gb()});var Sb=i(()=>{"use strict";bb();Uc()});var wb=i(()=>{"use strict";It()});var kb=i(()=>{"use strict";Sb();wb()});var xb=i(()=>{"use strict";hb();kb();It()});var qc=i(()=>{"use strict";Gn();xt();cb();Gc();xb()});var Ib=i(()=>{"use strict"});var Fa=i(()=>{"use strict"});var Eb=i(()=>{"use strict";Fa()});var Ma=i(()=>{"use strict"});var jre,vb=i(()=>{"use strict";Fa();Ma();jre=Object.freeze({critical:9,major:3,minor:1})});import{detect as qre,validateISO2 as Hre}from"tinyld";var Cb=i(()=>{"use strict";Ma()});var Tb=i(()=>{"use strict"});var _b=i(()=>{"use strict";Un()});var Hc=i(()=>{"use strict";_b()});var Pb=i(()=>{"use strict"});import{z as Rt}from"zod";var bC,SC,die,Ab=i(()=>{"use strict";le();Fa();Hc();Ma();bC=["critical","major","minor"],SC=Rt.object({problem:Rt.string(),severity:Rt.enum(bC),suggestion:Rt.string().default("")}),die=Rt.object({issues:Rt.array(SC)})});var Lb=i(()=>{"use strict";Ib();Eb();vb();Cb();Tb();Hc();Pb();Ab()});var $c=i(()=>{"use strict";Gn();xt();Un();Gc();Lb()});var Ob=i(()=>{"use strict";yc();Gn();bc();Wc();qc();$c()});import{z as M}from"zod";var vt,wC,kC,xC,IC,Zie,Nb=i(()=>{"use strict";vt=M.number().finite().nonnegative(),wC=M.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),kC=M.enum(["candidate","char","item","page","qid","record","sentence","window"]),xC=M.object({cacheReadTokens:vt.optional(),inputTokens:vt.optional(),outputTokens:vt.optional()}),IC=M.object({done:vt,force:M.boolean().optional(),phase:wC,phaseDetail:M.string().optional(),total:vt,unit:kC}),Zie=M.discriminatedUnion("event",[M.object({characters:vt,event:M.literal("output-characters")}),M.object({event:M.literal("token-usage"),usage:xC}),M.object({event:M.literal("progress"),progress:IC}),M.object({event:M.literal("artifact"),record:M.unknown()}),M.object({event:M.literal("complete"),revision:M.number().int().nonnegative()}),M.object({event:M.literal("error"),message:M.string()})])});var Db=i(()=>{"use strict"});var Wb=i(()=>{"use strict"});var ti=i(()=>{"use strict";Qy();Xy();Ob();bc();yc();Gn();Wc();qc();$c();xt();Nb();Db();Wb();fc()});var Fb=i(()=>{"use strict";ti();vr()});import{z as T}from"zod";var EC,RC,Iae,Eae,Rae,Mb=i(()=>{"use strict";y();EC="wikg-index-output/v1",RC=T.enum(["fts","embedding-source","embedding-summary"]),Iae=T.object({artifactKind:RC,chapterId:T.number().int().nonnegative(),embedding:T.object({dimensions:T.number().int().nonnegative(),identity:T.string().optional(),model:T.string()}).optional(),inputRevision:T.number().int().nonnegative(),protocol:T.literal(EC),type:T.literal("manifest")}),Eae=T.object({metadata:T.record(T.string(),T.unknown()).optional(),objectId:T.string().min(1),objectKind:T.string().min(1),rowId:T.string().min(1),sentenceIndex:T.number().int().nonnegative().optional(),text:T.string(),tokens:T.array(T.string()),type:T.literal("lexical-row")}),Rae=T.object({endSentenceIndex:T.number().int().nonnegative(),segmentIndex:T.number().int().nonnegative(),startSentenceIndex:T.number().int().nonnegative(),text:T.string(),vector:T.array(T.number()),wordsCount:T.number().int().nonnegative(),type:T.literal("segment")})});var qn=i(()=>{"use strict";Fb();Mb()});var Gb=i(()=>{"use strict";De();dn()});var jb=i(()=>{"use strict";_();ga()});var Ub=i(()=>{"use strict";y();_();Y();gt();wt();qn();Gb();jb()});var Ga=i(()=>{"use strict"});var qb=i(()=>{"use strict";Ga()});var Hb=i(()=>{"use strict"});var $b=i(()=>{"use strict";Ga()});var Jb=i(()=>{"use strict";Ga()});var Kb=i(()=>{"use strict";qb();Hb();$b();Jb()});import{z as h}from"zod";var zb,FC,MC,GC,jC,BC,UC,qC,HC,$C,JC,Qb=i(()=>{"use strict";ve();zb=h.tuple([h.number(),h.number()]),FC=h.object({text:h.string(),wordsCount:h.number()}),MC=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(FC)}),GC=h.object({documentOrder:h.number().optional(),id:h.number(),knowledgeGraphReady:h.boolean(),knowledgeGraphParameterHash:h.string().optional(),revision:h.number().optional(),topologyParameterHash:h.string().optional(),topologyReady:h.boolean()}).transform(n=>({documentOrder:n.documentOrder??n.id,id:n.id,knowledgeGraphReady:n.knowledgeGraphReady,...n.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:n.knowledgeGraphParameterHash},revision:n.revision??0,topologyReady:n.topologyReady,...n.topologyParameterHash===void 0?{}:{topologyParameterHash:n.topologyParameterHash}})),jC=h.object({id:h.number(),generation:h.number(),sentenceId:zb,label:h.string(),content:h.string(),sentenceIds:h.array(zb),retention:h.enum(he).optional(),importance:h.enum(Re).optional(),wordsCount:h.number(),weight:h.number()}),BC=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),UC=h.object({id:h.number(),serialId:h.number(),groupId:h.number(),localSnakeId:h.number(),size:h.number(),firstLabel:h.string(),lastLabel:h.string(),wordsCount:h.number(),weight:h.number()}),qC=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),HC=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),$C=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),JC=h.object({chunks:h.array(jC),fragmentGroups:h.array($C),fragments:h.array(MC),readingEdges:h.array(BC),serial:GC,snakeChunks:h.array(qC),snakeEdges:h.array(HC),snakes:h.array(UC)})});var Xb=i(()=>{"use strict";y();Qb()});var Vb=i(()=>{"use strict";Qn();jd();Z()});var Yb=i(()=>{"use strict";y();_();Y();Kb();Xb();_a();Vb();wt();qn()});var Zb=i(()=>{"use strict"});var ja=i(()=>{"use strict";Yb();_a();Zb()});var eS=i(()=>{"use strict";Y();ja()});var nS=i(()=>{"use strict"});var tS=i(()=>{"use strict";Ub();eS();nS()});var rS=i(()=>{"use strict";ti()});var aS=i(()=>{"use strict";ti();_();Y();qn();ja()});var oS=i(()=>{"use strict";ti();sn();Qn()});var sS=i(()=>{"use strict";tS();ja();rS();aS();oS()});import{z as $}from"zod";var Gse,zC,jse,Qc=i(()=>{"use strict";y();Gse=$.object({id:$.string().min(1),chapterId:$.number().int(),sentenceIndex:$.number().int().nonnegative().optional(),rangeStart:$.number().int().nonnegative(),rangeEnd:$.number().int().nonnegative(),surface:$.string().min(1),qid:$.string().regex(/^Q[1-9][0-9]*$/),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()}),zC=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),jse=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(zC).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var Xc=i(()=>{"use strict";y();De();wt();Qc()});var cS=i(()=>{"use strict";wt();qn();Qc()});var Ba=i(()=>{"use strict"});var uS=i(()=>{"use strict";sn();Ba()});var Vc=i(()=>{"use strict"});var lS=i(()=>{"use strict";sn()});var Yc=i(()=>{"use strict"});var Zc=i(()=>{"use strict";sn();Ba();lS();Yc()});var pS=i(()=>{"use strict";Zc()});var hS=i(()=>{"use strict";De()});var fS=i(()=>{"use strict";Dd();lt();ya()});import{z as F}from"zod";var yS,YC,ZC,eT,Pde,Ade,gS=i(()=>{"use strict";Ae();lt();fS();yS=F.object({head:F.string().optional(),mode:F.enum(["full","head_tail"]).optional(),tail:F.string().optional(),text:F.string().optional()}).strict(),YC=F.object({quote:F.string().optional(),sentence_id:F.string().optional()}).strict(),ZC=F.union([F.object({end_anchor:F.union([F.string(),yS]).optional(),quote:F.string().optional(),sentence_id:F.string().optional(),start_anchor:F.union([F.string(),yS]).optional()}).strict(),F.array(YC)]),eT=F.object({confidence:F.number().min(0).max(1).optional(),evidence:ZC,predicate:F.string().min(1).max(64),sourceMentionId:F.string().min(1),targetMentionId:F.string().min(1)}).strict(),Pde=F.object({relations:F.array(eT)}).strict(),Ade=new Nn});var bS=i(()=>{"use strict"});var SS=i(()=>{"use strict";gS();bS()});var wS=i(()=>{"use strict";SS();Ba();Yc()});var eu=i(()=>{"use strict";Y();Vc()});var IS=i(()=>{"use strict";sn();dn();Xc();uS();Vc();pS();hS();wS();eu()});var ES=i(()=>{"use strict"});var RS=i(()=>{"use strict";Xc();cS();IS();Zc();eu();ES()});var vS=i(()=>{"use strict";RS()});var ri=i(()=>{"use strict";Y()});var nu=i(()=>{"use strict";dn()});var tu=i(()=>{"use strict";De();dn();gt();ri();nu()});var _S=i(()=>{"use strict";dn();ri();tu()});var ru=i(()=>{"use strict";ye();Z()});var AS=i(()=>{"use strict";ye();Xt();xn();ru();Z()});var LS=i(()=>{"use strict";gt();ye();ri();AS();ru();Z()});import{z as Hn}from"zod";var OS,mue,NS=i(()=>{"use strict";OS=Hn.object({children:Hn.lazy(()=>Hn.array(OS)),uri:Hn.string().min(1),title:Hn.string().nullable().optional()}).strict(),mue=Hn.object({chapters:Hn.array(OS)}).strict()});var DS=i(()=>{"use strict";Y()});var WS=i(()=>{"use strict";_S();ri();tu();LS();nu();NS();DS()});var FS=i(()=>{"use strict";mr()});var Ke=i(()=>{"use strict";Ay();dt();Jy();sS();vS();dt();Qd();WS();FS();Wi()});async function gw(n="global"){let e=await lu(),t=Qe(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await b_(e),await e.run(`
779
+ Please provide a more specific anchor or surrounding context.`}}}});var Zg=i(()=>{"use strict"});var eb=i(()=>{"use strict";Yg();Zg()});var Hc,tb=i(()=>{"use strict";Hc=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
780
+ `)});var $c=i(()=>{"use strict"});var nb=i(()=>{"use strict";$c();Zr()});var ja=i(()=>{"use strict";eb();tb();$c();nb();Zr()});var ib=i(()=>{"use strict"});import{z as D}from"zod";var ab,gC,bC,SC,Mee,Fee,ob=i(()=>{"use strict";le();ja();ib();ab=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),gC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),bC=D.union([D.object({end_anchor:D.union([D.string(),ab]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),ab]).optional()}).strict(),D.array(gC)]),SC=D.object({confidence:D.number().min(0).max(1).optional(),evidence:bC,predicate:D.string().min(1).max(64),sourceMentionId:D.string().min(1),targetMentionId:D.string().min(1)}).strict(),Mee=D.object({relations:D.array(SC)}).strict(),Fee=new Cn});var sb=i(()=>{"use strict"});var db=i(()=>{"use strict"});var cb=i(()=>{"use strict";ob();sb();db()});var ub=i(()=>{"use strict";cb();Ma();Dc()});var ei,Tn=i(()=>{"use strict";ei=Object.freeze({guaranteedResponseIntent:"guaranteed-response-intent",knowledgeGraph:"knowledge-graph",readingGraphEvidenceChoice:"reading-graph-evidence-choice",readingGraphExtraction:"reading-graph-extraction",readingSummaryCompress:"reading-summary-compress",readingSummaryReview:"reading-summary-review",readingSummaryReviewGuide:"reading-summary-review-guide"})});var mte,Kc=i(()=>{"use strict";le();Ht();Ng();Dg();ub();Vr();Tn();mte=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var lb=i(()=>{"use strict"});var mb=i(()=>{"use strict"});var pb=i(()=>{"use strict";lb();mb()});var Kt=i(()=>{"use strict"});var ti=i(()=>{"use strict";le()});var fb=i(()=>{"use strict";Kt();ti()});var yb=i(()=>{"use strict";ti()});var gb=i(()=>{"use strict"});import{z as I}from"zod";var bb,IC,Sb,EC,RC,vC,CC,TC,_C,Ua=i(()=>{"use strict";Kt();bb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),IC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),Sb=I.union([I.record(I.string(),I.unknown()),I.array(IC)]),EC=I.object({content:I.string(),evidence:Sb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),RC=I.object({chunks:I.array(EC),fragment_summary:I.string(),links:I.array(bb)}),vC=I.object({content:I.string(),evidence:Sb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),CC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),TC=I.object({chunks:I.array(vC),importance_annotations:I.array(CC),links:I.array(bb)}),_C=I.object({choice:I.string()})});var wb=i(()=>{"use strict";le();ja();gb();ti();Ua()});var kb=i(()=>{"use strict";le();Kt();fb();ti();yb();wb();Ua()});var xb=i(()=>{"use strict";kb();Ua()});var Qc=i(()=>{"use strict"});import{detect as pne,validateISO2 as hne}from"tinyld";var Ib=i(()=>{"use strict"});var Eb=i(()=>{"use strict"});import{z as ni}from"zod";var LC,One,Rb=i(()=>{"use strict";le();ja();xb();Qc();Qc();Ib();Eb();LC=ni.object({content:ni.string(),id:ni.number(),label:ni.string()}),One=ni.array(LC)});var vb=i(()=>{"use strict";Rb()});var Cb=i(()=>{"use strict";pb();vb()});var Tb=i(()=>{"use strict";Cb()});var _b=i(()=>{"use strict"});var Pb=i(()=>{"use strict"});var Xc=i(()=>{"use strict";_b();le();Tn();Pb()});var Ab=i(()=>{"use strict"});var Lb=i(()=>{"use strict"});var Ob=i(()=>{"use strict";Ab();Lb()});var ri=i(()=>{"use strict"});var gre,bre,_n=i(()=>{"use strict";Kt();gre={critical:9,helpful:1,important:3},bre={detailed:9,focused:3,relevant:1,verbatim:27}});var Pn=i(()=>{"use strict"});var ii=i(()=>{"use strict"});var Vc=i(()=>{"use strict";Pn()});var Yc=i(()=>{"use strict";_n();Pn();ri();ii();Vc()});var Zc=i(()=>{"use strict";ri();Yc();ii()});var Wb=i(()=>{"use strict";_n();Pn();ii()});var Db=i(()=>{"use strict";_n();Pn();ri();ii();Vc()});var Mb=i(()=>{"use strict";Zc();Pn();ri();Wb();Yc();Db()});var Fb=i(()=>{"use strict";Mb();Zc()});var Gb=i(()=>{"use strict";_n()});var jb=i(()=>{"use strict";Fb();Gb()});var Ub=i(()=>{"use strict";Ob();jb();_n()});var eu=i(()=>{"use strict";Ht();Tn();Tb();Xc();Ub()});var Bb=i(()=>{"use strict"});var qa=i(()=>{"use strict"});var qb=i(()=>{"use strict";qa()});var Ha=i(()=>{"use strict"});var Jie,$b=i(()=>{"use strict";qa();Ha();Jie=Object.freeze({critical:9,major:3,minor:1})});import{detect as Qie,validateISO2 as Xie}from"tinyld";var Jb=i(()=>{"use strict";Ha()});var Kb=i(()=>{"use strict"});var zb=i(()=>{"use strict";Kt()});var tu=i(()=>{"use strict";zb()});var Qb=i(()=>{"use strict"});import{z as An}from"zod";var BC,qC,hae,Xb=i(()=>{"use strict";le();qa();tu();Ha();BC=["critical","major","minor"],qC=An.object({problem:An.string(),severity:An.enum(BC),suggestion:An.string().default("")}),hae=An.object({issues:An.array(qC)})});var Vb=i(()=>{"use strict";Bb();qb();$b();Jb();Kb();tu();Qb();Xb()});var nu=i(()=>{"use strict";Ht();Tn();Kt();Xc();Vb()});var Yb=i(()=>{"use strict";Cc();Ht();_c();Kc();eu();nu()});import{z as G}from"zod";var Ln,HC,$C,JC,KC,aoe,Zb=i(()=>{"use strict";Ln=G.number().finite().nonnegative(),HC=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),$C=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),JC=G.object({cacheReadTokens:Ln.optional(),inputTokens:Ln.optional(),outputTokens:Ln.optional()}),KC=G.object({done:Ln,force:G.boolean().optional(),phase:HC,phaseDetail:G.string().optional(),total:Ln,unit:$C}),aoe=G.discriminatedUnion("event",[G.object({characters:Ln,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:JC}),G.object({event:G.literal("progress"),progress:KC}),G.object({event:G.literal("artifact"),record:G.unknown()}),G.object({event:G.literal("complete"),revision:G.number().int().nonnegative()}),G.object({event:G.literal("error"),message:G.string()})])});var eS=i(()=>{"use strict"});var tS=i(()=>{"use strict"});var ai=i(()=>{"use strict";hg();fg();Yb();_c();Cc();Ht();Kc();eu();nu();Tn();Zb();eS();tS();vc()});var nS=i(()=>{"use strict";ai();Wr()});import{z as T}from"zod";var zC,QC,_oe,Poe,Aoe,rS=i(()=>{"use strict";y();zC="wikg-index-output/v1",QC=T.enum(["fts","embedding-source","embedding-summary"]),_oe=T.object({artifactKind:QC,chapterId:T.number().int().nonnegative(),embedding:T.object({dimensions:T.number().int().nonnegative(),identity:T.string().optional(),model:T.string()}).optional(),inputRevision:T.number().int().nonnegative(),protocol:T.literal(zC),type:T.literal("manifest")}),Poe=T.object({metadata:T.record(T.string(),T.unknown()).optional(),objectId:T.string().min(1),objectKind:T.string().min(1),rowId:T.string().min(1),sentenceIndex:T.number().int().nonnegative().optional(),text:T.string(),tokens:T.array(T.string()),type:T.literal("lexical-row")}),Aoe=T.object({endSentenceIndex:T.number().int().nonnegative(),segmentIndex:T.number().int().nonnegative(),startSentenceIndex:T.number().int().nonnegative(),text:T.string(),vector:T.array(T.number()),wordsCount:T.number().int().nonnegative(),type:T.literal("segment")})});var zt=i(()=>{"use strict";nS();rS()});var iS=i(()=>{"use strict";Me();pt()});var aS=i(()=>{"use strict";_();Ta()});var sS=i(()=>{"use strict";y();_();Y();Rn();vn();zt();iS();aS()});var $a=i(()=>{"use strict"});var dS=i(()=>{"use strict";$a()});var cS=i(()=>{"use strict"});var uS=i(()=>{"use strict";$a()});var lS=i(()=>{"use strict";$a()});var mS=i(()=>{"use strict";dS();cS();uS();lS()});import{z as h}from"zod";var pS,sT,dT,cT,uT,lT,mT,pT,hT,fT,yT,hS=i(()=>{"use strict";Ce();pS=h.tuple([h.number(),h.number()]),sT=h.object({text:h.string(),wordsCount:h.number()}),dT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(sT)}),cT=h.object({documentOrder:h.number().optional(),id:h.number(),knowledgeGraphReady:h.boolean(),knowledgeGraphParameterHash:h.string().optional(),revision:h.number().optional(),topologyParameterHash:h.string().optional(),topologyReady:h.boolean()}).transform(t=>({documentOrder:t.documentOrder??t.id,id:t.id,knowledgeGraphReady:t.knowledgeGraphReady,...t.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:t.knowledgeGraphParameterHash},revision:t.revision??0,topologyReady:t.topologyReady,...t.topologyParameterHash===void 0?{}:{topologyParameterHash:t.topologyParameterHash}})),uT=h.object({id:h.number(),generation:h.number(),sentenceId:pS,label:h.string(),content:h.string(),sentenceIds:h.array(pS),retention:h.enum(he).optional(),importance:h.enum(ve).optional(),wordsCount:h.number(),weight:h.number()}),lT=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),mT=h.object({id:h.number(),serialId:h.number(),groupId:h.number(),localSnakeId:h.number(),size:h.number(),firstLabel:h.string(),lastLabel:h.string(),wordsCount:h.number(),weight:h.number()}),pT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),hT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),fT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),yT=h.object({chunks:h.array(uT),fragmentGroups:h.array(fT),fragments:h.array(dT),readingEdges:h.array(lT),serial:cT,snakeChunks:h.array(pT),snakeEdges:h.array(hT),snakes:h.array(mT)})});var fS=i(()=>{"use strict";y();hS()});var yS=i(()=>{"use strict";en();yc();Z()});var gS=i(()=>{"use strict";y();_();Y();mS();fS();Wa();yS();vn();zt()});var bS=i(()=>{"use strict"});var Ja=i(()=>{"use strict";gS();Wa();bS()});var SS=i(()=>{"use strict";Y();Ja()});var wS=i(()=>{"use strict"});var kS=i(()=>{"use strict";sS();SS();wS()});var xS=i(()=>{"use strict";ai()});var ES=i(()=>{"use strict";ai();_();Y();zt();Ja()});var RS=i(()=>{"use strict";ai();mt();en()});var vS=i(()=>{"use strict";kS();Ja();xS();ES();RS()});import{z as $}from"zod";var $de,bT,Jde,ou=i(()=>{"use strict";y();$de=$.object({id:$.string().min(1),chapterId:$.number().int(),sentenceIndex:$.number().int().nonnegative().optional(),rangeStart:$.number().int().nonnegative(),rangeEnd:$.number().int().nonnegative(),surface:$.string().min(1),qid:$.string().regex(/^Q[1-9][0-9]*$/),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()}),bT=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),Jde=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(bT).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var su=i(()=>{"use strict";y();Me();vn();ou()});var TS=i(()=>{"use strict";vn();zt();ou()});var Ka=i(()=>{"use strict"});var _S=i(()=>{"use strict";mt();Ka()});var du=i(()=>{"use strict"});var PS=i(()=>{"use strict";mt()});var cu=i(()=>{"use strict"});var uu=i(()=>{"use strict";mt();Ka();PS();cu()});var LS=i(()=>{"use strict";uu()});var OS=i(()=>{"use strict";Me()});var NS=i(()=>{"use strict";lc();Sn();Ca()});import{z as M}from"zod";var WS,xT,IT,ET,Dce,Mce,DS=i(()=>{"use strict";Ne();Sn();NS();WS=M.object({head:M.string().optional(),mode:M.enum(["full","head_tail"]).optional(),tail:M.string().optional(),text:M.string().optional()}).strict(),xT=M.object({quote:M.string().optional(),sentence_id:M.string().optional()}).strict(),IT=M.union([M.object({end_anchor:M.union([M.string(),WS]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),WS]).optional()}).strict(),M.array(xT)]),ET=M.object({confidence:M.number().min(0).max(1).optional(),evidence:IT,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),Dce=M.object({relations:M.array(ET)}).strict(),Mce=new Bt});var MS=i(()=>{"use strict"});var FS=i(()=>{"use strict";DS();MS()});var GS=i(()=>{"use strict";FS();Ka();cu()});var lu=i(()=>{"use strict";Y();du()});var BS=i(()=>{"use strict";mt();pt();su();_S();du();LS();OS();GS();lu()});var qS=i(()=>{"use strict"});var HS=i(()=>{"use strict";su();TS();BS();uu();lu();qS()});var $S=i(()=>{"use strict";HS()});var oi=i(()=>{"use strict";Y()});var mu=i(()=>{"use strict";pt()});var pu=i(()=>{"use strict";Me();pt();Rn();oi();mu()});var zS=i(()=>{"use strict";pt();oi();pu()});var hu=i(()=>{"use strict";ye();Z()});var XS=i(()=>{"use strict";ye();tr();Et();hu();Z()});var VS=i(()=>{"use strict";Rn();ye();oi();XS();hu();Z()});import{z as Qt}from"zod";var YS,ble,ZS=i(()=>{"use strict";YS=Qt.object({children:Qt.lazy(()=>Qt.array(YS)),uri:Qt.string().min(1),title:Qt.string().nullable().optional()}).strict(),ble=Qt.object({chapters:Qt.array(YS)}).strict()});var ew=i(()=>{"use strict";Y()});var tw=i(()=>{"use strict";zS();oi();pu();VS();mu();ZS();ew()});var nw=i(()=>{"use strict";lr()});var ze=i(()=>{"use strict";lg();ot();Gd();vS();$S();ot();Rc();tw();nw();la()});async function Dw(t="global"){let e=await xu(),n=Xe(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await B_(e),await e.run(`
764
781
  INSERT OR IGNORE INTO gc_locks (
765
782
  scope, owner_id, owner_pid, heartbeat_at, created_at
766
783
  ) VALUES (?, ?, ?, ?, ?)
767
- `,[n,t,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[n],s=>E(s,"owner_id"))===t})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{g_(n,t).catch(()=>{})},y_);return async()=>{clearInterval(o);let s=await lu();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[n,t])}finally{await s.close()}}}async function g_(n,e){let t=await lu();try{await t.run(`
784
+ `,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>E(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{U_(t,n).catch(()=>{})},j_);return async()=>{clearInterval(o);let s=await xu();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function U_(t,e){let n=await xu();try{await n.run(`
768
785
  UPDATE gc_locks
769
786
  SET heartbeat_at = ?, owner_pid = ?
770
787
  WHERE scope = ? AND owner_id = ?
771
- `,[Date.now(),0,n,e])}finally{await t.close()}}async function b_(n){let e=await n.queryAll("SELECT * FROM gc_locks",void 0,k_);for(let{lock:t,scope:r}of e.filter(({lock:a})=>S_(a)))await n.run(`
788
+ `,[Date.now(),0,t,e])}finally{await n.close()}}async function B_(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,$_);for(let{lock:n,scope:r}of e.filter(({lock:a})=>q_(a)))await t.run(`
772
789
  DELETE FROM gc_locks
773
790
  WHERE scope = ?
774
791
  AND owner_id = ?
775
792
  AND heartbeat_at = ?
776
- `,[r,t.ownerId,t.heartbeatAt])}function S_(n){return!(Date.now()-n.heartbeatAt<f_)}async function lu(){return await X("tmp/gc.sqlite",h_)}function w_(n){return{createdAt:S(n,"created_at"),heartbeatAt:S(n,"heartbeat_at"),ownerId:E(n,"owner_id"),ownerPid:S(n,"owner_pid")}}function k_(n){return{lock:w_(n),scope:E(n,"scope")}}var h_,f_,y_,bw=i(()=>{"use strict";U();w();_();h_=`
793
+ `,[r,n.ownerId,n.heartbeatAt])}function q_(t){return!(Date.now()-t.heartbeatAt<G_)}async function xu(){return await X("tmp/gc.sqlite",F_)}function H_(t){return{createdAt:S(t,"created_at"),heartbeatAt:S(t,"heartbeat_at"),ownerId:E(t,"owner_id"),ownerPid:S(t,"owner_pid")}}function $_(t){return{lock:H_(t),scope:E(t,"scope")}}var F_,G_,j_,Mw=i(()=>{"use strict";F();w();_();F_=`
777
794
  CREATE TABLE IF NOT EXISTS gc_locks (
778
795
  scope TEXT PRIMARY KEY,
779
796
  owner_id TEXT NOT NULL,
@@ -781,8 +798,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
781
798
  heartbeat_at INTEGER NOT NULL,
782
799
  created_at INTEGER NOT NULL
783
800
  );
784
- `,f_=6e4,y_=2e4});async function Sw(n){let e=await v().library.getDirectory("tmp"),t=0,r=0,a=0;if(e===void 0)return{freedBytes:a,removed:r,scanned:t};for(let o of await I_(e)){t+=1;let s=await ze(o.value);if(!n.force&&(s===void 0||n.now-s<x_))continue;let d=await un(o.value);n.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=d}return{freedBytes:a,removed:r,scanned:t}}async function I_(n){let e=[];for(let t of await n.list())if(j(t))for(let r of await t.list())e.push({parent:t,value:r});return e}var x_,ww=i(()=>{"use strict";y();nc();x_=3600*1e3});async function Ha(n={}){let e=Date.now(),t=await gw();if(t===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};try{if(n.opportunistic===!0&&!await C_(e))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};let r={dryRun:n.dryRun===!0,force:n.force===!0,now:e},a=[];for(let s of E_)a.push(await v_(s,r));let o={finishedAt:Date.now(),freedBytes:mu(a,"freedBytes"),jobs:a,removed:mu(a,"removed"),scanned:mu(a,"scanned"),skipped:!1,startedAt:e};return await T_(o.finishedAt).catch(()=>{}),o}finally{await t()}}async function v_(n,e){try{return{name:n.name,...await n.run(e)}}catch(t){return{error:zn(t),freedBytes:0,name:n.name,removed:0,scanned:0}}}function mu(n,e){return n.reduce((t,r)=>{let a=r[e];return t+(typeof a=="number"?a:0)},0)}async function C_(n){let e=await J(v().library,"tmp/gc.last-run"),t=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(t)||n-t>=R_}async function T_(n){let e=await H(v().library,"tmp/gc.last-run");await me(e,`${n}
785
- `)}var E_,R_,kw=i(()=>{"use strict";y();dt();Ke();Be();ua();Id();pe();bw();ww();E_=[{name:"wikg-coordinator",run:da},{name:"search-cache",run:Gi},{name:"library-index",run:Hh},{name:"build-queue",run:va},{name:"wikimedia-cache",run:kd},{name:"tmp",run:Sw}],R_=600*1e3});var xw=i(()=>{"use strict";kw()});var Iw=i(()=>{"use strict";xw()});var Ew={};Tw(Ew,{tryRunWikiGraphGc:()=>__});async function __(n={}){At();let{stateDir:e,...t}=n;return await Kn(e,async()=>await Ha(t))}var Rw=i(()=>{"use strict";Iw();ce()});ce();import{AsyncLocalStorage as s_}from"async_hooks";import{randomUUID as Qpe}from"crypto";import{link as Vpe,mkdtemp as Ype,rename as Zpe,rm as ehe,stat as nhe}from"fs/promises";import{tmpdir as rhe}from"os";import{basename as ahe,dirname as ohe,join as she}from"path";import{Readable as che}from"stream";De();y();mi();import{z as Ot}from"zod";var nk=1,oP=Ot.object({completedAt:Ot.string().optional(),startedAt:Ot.string(),status:Ot.enum(["running","succeeded"]),version:Ot.literal(nk)});so();Qn();Xe();Z();uo();Tt();ua();lt();Id();sn();Ld();Ke();ye();Be();_();xn();dt();_();Xt();Ri();ki();qn();y();wn();je();rn();tn();sd();ki();ua();vr();qn();_();y();Be();y();w();w();y();w();y();Ko();y();pe();Ke();Ke();Ke();Ke();Ke();dn();sn();_();wt();y();import{rm as bpe}from"fs/promises";import{createAnthropic as jme}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as Ume}from"@ai-sdk/google";import{createOpenAI as Hme}from"@ai-sdk/openai";import{createOpenAICompatible as Jme}from"@ai-sdk/openai-compatible";ce();import{z as re}from"zod";import{AsyncLocalStorage as $T}from"async_hooks";var rw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),JT=KT();function KT(){let n=globalThis,e=n[rw];if(e!==void 0)return e;let t=new $T;return Object.defineProperty(n,rw,{configurable:!1,enumerable:!1,value:t,writable:!1}),t}async function cu(n,e){return await JT.run(n,e)}ce();import{join as npe}from"path";import{homedir as rpe}from"os";var QT=["anthropic","google","openai","openai-compatible"],iw=re.enum(QT),dpe=re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),llm:re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:iw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:iw.optional()});import{homedir as lpe}from"os";import{isAbsolute as ppe,resolve as hpe}from"path";ce();import{embed as vpe,embedMany as Cpe}from"ai";import{createOpenAI as _pe}from"@ai-sdk/openai";import{createOpenAICompatible as Ape}from"@ai-sdk/openai-compatible";import{spawn as khe}from"child_process";import{streamText as Whe}from"ai";Ke();ce();var a_=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function cw(n){let e=o_(n.env);if(n.envPolicy==="production"){let o=a_.filter(s=>e[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:e,envPolicy:n.envPolicy,stateDir:n.stateDir}}let t=e.WIKIGRAPH_DEV??e.WIKIGRAPH_STATE_DIR,r=dw(n.stateDir??t);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=dw(n.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:e,envPolicy:n.envPolicy,stateDir:r}}function o_(n){return n===void 0?{...process.env}:{...process.env,...n}}function dw(n){if(!(n===void 0||n.trim()===""))return n}ce();ce();import{mkdir as Efe}from"fs/promises";ce();import{basename as Afe}from"path";ce();ce();var d_=new s_;async function uw(n,e){return await d_.run(n,async()=>await cu({cwd:n.cwd,env:n.env,envPolicy:n.envPolicy,...n.stateDir===void 0?{}:{stateDir:n.stateDir}},e))}var lw="--wikigraph-internal-child",mw="--wikigraph-dev-project-root",pw="--wikigraph-env-policy",hw="--wikigraph-state-dir";async function fw(n,e){let t=c_(process.argv.slice(2));if(t.internalChild!==n)throw new Error("This Wiki Graph worker entry is internal.");let r=cw({argv:t.argv,devProjectRoot:t.devProjectRoot,envPolicy:t.envPolicy,stateDir:t.stateDir});return await Kn(r.stateDir,async()=>uw({argv:t.argv,cwd:process.cwd(),devProjectRoot:r.devProjectRoot,env:r.env,envPolicy:r.envPolicy,exitCode:0,queueAutostart:!1,stateDir:r.stateDir,stderr:process.stderr,stdin:process.stdin,stdout:process.stdout},async()=>await e(t)))}function c_(n){let e=[],t,r,a="production",o;for(let s=0;s<n.length;s+=1){let d=n[s];if(d===lw){if(s+1>=n.length)throw new Error(`${lw} requires a value.`);t=n[s+1],s+=1;continue}if(d===pw){let c=n[s+1];if(c!=="development"&&c!=="production")throw new Error(`${pw} requires development or production.`);a=c,s+=1;continue}if(d===mw){let c=n[s+1];if(c===void 0||c.trim()==="")throw new Error(`${mw} requires a value.`);r=c,s+=1;continue}if(d!==hw){e.push(d);continue}if(s+1>=n.length)throw new Error(`${hw} requires a value.`);o=n[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:t??"",stateDir:o}}var u_={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as Wye}from"path";import{createReadStream as Hye}from"fs";import{mkdtemp as Jye,rm as Kye}from"fs/promises";import{join as Qye}from"path";import{tmpdir as Vye}from"os";var l_=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((n,e)=>[n,e]));function yw(n){return`${JSON.stringify(uu(n),null,2)}
786
- `}function uu(n){if(n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(e=>uu(e)??null);if(typeof n=="object")return m_(n)}function m_(n){let e=Object.entries(n).map(([r,a],o)=>({index:o,key:r,priority:l_.get(r)??Number.MAX_SAFE_INTEGER,value:a})),t={};for(let r of e.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=uu(r.value);a!==void 0&&(t[r.key]=a)}return t}import{homedir as oge}from"os";import{isAbsolute as dge,relative as cge,resolve as uge}from"path";import{existsSync as fge,readFileSync as yge}from"fs";import{dirname as bge,join as Sge,parse as wge,resolve as kge}from"path";At();var{tryRunWikiGraphGc:P_}=await Promise.resolve().then(()=>(Rw(),Ew));async function A_(){await fw("gc-worker",async({argv:n})=>{let e=L_(n);process.stdout.write(yw(await P_({dryRun:e.dryRun,force:e.force})))})}function L_(n){return{dryRun:n.includes("--dry-run"),force:n.includes("--force")}}A_().catch(n=>{process.stderr.write(`${n instanceof Error?n.stack??n.message:String(n)}
801
+ `,G_=6e4,j_=2e4});async function Fw(t){let e=await v().library.getDirectory("tmp"),n=0,r=0,a=0;if(e===void 0)return{freedBytes:a,removed:r,scanned:n};for(let o of await K_(e)){n+=1;let s=await Qe(o.value);if(!t.force&&(s===void 0||t.now-s<J_))continue;let d=await ut(o.value);t.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=d}return{freedBytes:a,removed:r,scanned:n}}async function K_(t){let e=[];for(let n of await t.list())if(U(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var J_,Gw=i(()=>{"use strict";y();Rd();J_=3600*1e3});async function eo(t={}){let e=Date.now(),n=await Dw();if(n===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};try{if(t.opportunistic===!0&&!await V_(e))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};let r={dryRun:t.dryRun===!0,force:t.force===!0,now:e},a=[];for(let s of z_)a.push(await X_(s,r));let o={finishedAt:Date.now(),freedBytes:Iu(a,"freedBytes"),jobs:a,removed:Iu(a,"removed"),scanned:Iu(a,"scanned"),skipped:!1,startedAt:e};return await Y_(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function X_(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:Zt(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function Iu(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function V_(t){let e=await J(v().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=Q_}async function Y_(t){let e=await H(v().library,"tmp/gc.last-run");await me(e,`${t}
802
+ `)}var z_,Q_,jw=i(()=>{"use strict";y();ot();ze();Le();wa();Zd();pe();Mw();Gw();z_=[{name:"wikg-coordinator",run:pa},{name:"search-cache",run:Wi},{name:"library-index",run:bf},{name:"build-queue",run:ya},{name:"wikimedia-cache",run:Vd},{name:"tmp",run:Fw}],Q_=600*1e3});var Uw=i(()=>{"use strict";jw()});var Bw=i(()=>{"use strict";Uw()});var qw={};Kw(qw,{tryRunWikiGraphGc:()=>Z_});async function Z_(t={}){Mn();let{stateDir:e,...n}=t;return await Yt(e,async()=>await eo(n))}var Hw=i(()=>{"use strict";Bw();de()});de();import{AsyncLocalStorage as A_}from"async_hooks";import{randomUUID as bfe}from"crypto";import{link as wfe,mkdtemp as kfe,rename as xfe,rm as Ife,stat as Efe}from"fs/promises";import{tmpdir as vfe}from"os";import{basename as Tfe,dirname as _fe,join as Pfe}from"path";import{Readable as Lfe}from"stream";Me();y();hi();import{z as Gn}from"zod";var wk=1,PP=Gn.object({completedAt:Gn.string().optional(),startedAt:Gn.string(),status:Gn.enum(["running","succeeded"]),version:Gn.literal(wk)});bo();en();Ve();Z();wo();Nn();wa();Sn();Zd();mt();dc();ze();ye();Le();_();Et();ot();_();tr();Ci();Ii();zt();y();Ze();qe();dt();st();gd();Ii();wa();Wr();zt();_();y();Le();y();w();w();y();w();y();ns();y();pe();ze();ze();ze();ze();ze();pt();mt();_();vn();y();import{createHash as Ghe}from"crypto";import{createReadStream as Uhe}from"fs";import{rm as qhe}from"fs/promises";import{basename as $he}from"path";import{createAnthropic as Kpe}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as Qpe}from"@ai-sdk/google";import{createOpenAI as Vpe}from"@ai-sdk/openai";import{createOpenAICompatible as Zpe}from"@ai-sdk/openai-compatible";de();import{z as re}from"zod";import{AsyncLocalStorage as f_}from"async_hooks";var ww=Symbol.for("wiki-graph-sdk.runtime-context.v1"),y_=g_();function g_(){let t=globalThis,e=t[ww];if(e!==void 0)return e;let n=new f_;return Object.defineProperty(t,ww,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function bu(t,e){return await y_.run(t,e)}de();import{join as dhe}from"path";import{homedir as uhe}from"os";var S_=["anthropic","google","openai","openai-compatible"],kw=re.enum(S_),fhe=re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),llm:re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:kw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:kw.optional()});import{homedir as bhe}from"os";import{isAbsolute as whe,resolve as khe}from"path";import{realpath as Rhe,stat as vhe}from"fs/promises";import{basename as The,dirname as _he,isAbsolute as Phe,join as Ahe,relative as Lhe,resolve as Ohe}from"path";de();de();import{embed as efe,embedMany as tfe}from"ai";import{createOpenAI as rfe}from"@ai-sdk/openai";import{createOpenAICompatible as afe}from"@ai-sdk/openai-compatible";import{spawn as Kfe}from"child_process";import{streamText as dye}from"ai";ze();de();var __=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function Tw(t){let e=P_(t.env);if(t.envPolicy==="production"){let o=__.filter(s=>e[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:e,envPolicy:t.envPolicy,stateDir:t.stateDir}}let n=e.WIKIGRAPH_DEV??e.WIKIGRAPH_STATE_DIR,r=Cw(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=Cw(t.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:e,envPolicy:t.envPolicy,stateDir:r}}function P_(t){return t===void 0?{...process.env}:{...process.env,...t}}function Cw(t){if(!(t===void 0||t.trim()===""))return t}de();de();import{mkdir as ige}from"fs/promises";de();import{basename as mge}from"path";de();de();var L_=new A_;async function _w(t,e){return await L_.run(t,async()=>await bu({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var Pw="--wikigraph-internal-child",Aw="--wikigraph-dev-project-root",Lw="--wikigraph-env-policy",Ow="--wikigraph-state-dir";async function Nw(t,e){let n=O_(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=Tw({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Yt(r.stateDir,async()=>_w({argv:n.argv,cwd:process.cwd(),devProjectRoot:r.devProjectRoot,env:r.env,envPolicy:r.envPolicy,exitCode:0,queueAutostart:!1,stateDir:r.stateDir,stderr:process.stderr,stdin:process.stdin,stdout:process.stdout},async()=>await e(n)))}function O_(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===Pw){if(s+1>=t.length)throw new Error(`${Pw} requires a value.`);n=t[s+1],s+=1;continue}if(d===Lw){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${Lw} requires development or production.`);a=c,s+=1;continue}if(d===Aw){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${Aw} requires a value.`);r=c,s+=1;continue}if(d!==Ow){e.push(d);continue}if(s+1>=t.length)throw new Error(`${Ow} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var N_={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as gbe}from"path";import{createReadStream as Rbe}from"fs";import{mkdtemp as Cbe,rm as Tbe}from"fs/promises";import{join as Pbe}from"path";import{tmpdir as Lbe}from"os";var W_=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((t,e)=>[t,e]));function Ww(t){return`${JSON.stringify(ku(t),null,2)}
803
+ `}function ku(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>ku(e)??null);if(typeof t=="object")return D_(t)}function D_(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:W_.get(r)??Number.MAX_SAFE_INTEGER,value:a})),n={};for(let r of e.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=ku(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as Ube}from"os";import{isAbsolute as qbe,relative as Hbe,resolve as $be}from"path";import{existsSync as Xbe,readFileSync as Vbe}from"fs";import{dirname as Zbe,join as eSe,parse as tSe,resolve as nSe}from"path";Mn();var{tryRunWikiGraphGc:eP}=await Promise.resolve().then(()=>(Hw(),qw));async function tP(){await Nw("gc-worker",async({argv:t})=>{let e=nP(t);process.stdout.write(Ww(await eP({dryRun:e.dryRun,force:e.force})))})}function nP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}tP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
787
804
  `),process.exitCode=1});
788
805
  //# sourceMappingURL=gc-worker.js.map