@inkeep/open-knowledge 0.5.0 → 0.5.1-beta.1
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/THIRD_PARTY_NOTICES.md +150 -0
- package/dist/assets/skills/open-knowledge/SKILL.md +1 -1
- package/dist/cli.mjs +42 -42
- package/dist/config-schema.json +16 -0
- package/dist/config.user.schema.json +16 -0
- package/dist/constants-CxGUnR2R.mjs +2 -0
- package/dist/{dist-ChwYnRqt.mjs → dist-1yEbYw4s.mjs} +1 -1
- package/dist/{dist-DHj61EG5.mjs → dist-Du77nM-Z.mjs} +12 -12
- package/dist/index.mjs +1 -1
- package/dist/init-8rAVRY8c.mjs +1 -0
- package/dist/{init-gfAUbyai.mjs → init-wE_PoDlt.mjs} +4 -4
- package/dist/loader-Cx9FryMP.mjs +1 -0
- package/dist/{loader-DsGUJOWD.mjs → loader-CyRBTmf0.mjs} +2 -2
- package/dist/{preview-DWRrWnuf.mjs → preview-DIChsLP0.mjs} +2 -2
- package/dist/preview-DoBZjq8W.mjs +1 -0
- package/dist/public/assets/ActivityModeContent-BA_Hv5zU.js +2 -0
- package/dist/public/assets/DocumentContext-DLUOyqhE.js +52 -0
- package/dist/public/assets/GraphPanel-8RBGIUIt.js +46 -0
- package/dist/public/assets/SettingsDialogBody-WO4dhoz2.js +11 -0
- package/dist/public/assets/SourceEditor-DUA4Uo0Z.js +2 -0
- package/dist/public/assets/config-validation-events-BDg76Ro_.js +10 -0
- package/dist/public/assets/{doc-hash-CMD_NjP8.js → doc-hash-CO_0WoMz.js} +2 -2
- package/dist/public/assets/{index-D9afOIIc.css → index-BBU-QASR.css} +1 -1
- package/dist/public/assets/index-mEf0JUM_.js +1928 -0
- package/dist/public/assets/{target-navigation-intent-DxRtD10o.js → target-navigation-intent-BY2CtClj.js} +1 -1
- package/dist/public/assets/{toggle-group-DQWMrY_b.js → toggle-group-CJzcIZ91.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Cm3a_0Rp.js → typing-burst-detector-L-hzCd9t.js} +2 -2
- package/dist/public/index.html +8 -8
- package/dist/{repair-launch-json-CtMhcU4e.mjs → repair-launch-json-Co3PPh9L.mjs} +2 -2
- package/dist/{repair-mcp-configs-DImyCeuT.mjs → repair-mcp-configs-9moWefpg.mjs} +2 -2
- package/dist/schemas/v0/config.user.schema.json +16 -0
- package/dist/{src-7RbS1TeB.mjs → src-DD5sVihr.mjs} +2 -2
- package/dist/{start-fgy_CK47.mjs → start-Bq6io6Ey.mjs} +2 -2
- package/dist/start-By-gUCPK.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-BPsrqVcC.mjs +0 -2
- package/dist/init-LkHLm5ut.mjs +0 -1
- package/dist/loader-dMWGjY_g.mjs +0 -1
- package/dist/preview-DXHcHw7y.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-B8J4OFHO.js +0 -2
- package/dist/public/assets/DocumentContext-fSMev29P.js +0 -52
- package/dist/public/assets/GraphPanel-CbVOnaKD.js +0 -46
- package/dist/public/assets/SettingsDialogBody-8zs3jwhI.js +0 -11
- package/dist/public/assets/SourceEditor-BCHJFeGa.js +0 -2
- package/dist/public/assets/config-validation-events-BtPgkHlf.js +0 -10
- package/dist/public/assets/index-BZCMU4ot.js +0 -1918
- package/dist/start-BYmlQzPZ.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{r as diffLines,t as createPatch}from"./libesm-Cfo1LhlX.mjs";import{n as mimes,t as build_default}from"./build-BZeImWox.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";var require_identity=__commonJSMin$1((e=>{let t=Symbol.for(`yaml.alias`),S=Symbol.for(`yaml.document`),w=Symbol.for(`yaml.map`),E=Symbol.for(`yaml.pair`),D=Symbol.for(`yaml.scalar`),O=Symbol.for(`yaml.seq`),k=Symbol.for(`yaml.node.type`),j=e=>!!e&&typeof e==`object`&&e[k]===t,F=e=>!!e&&typeof e==`object`&&e[k]===S,L=e=>!!e&&typeof e==`object`&&e[k]===w,B=e=>!!e&&typeof e==`object`&&e[k]===E,H=e=>!!e&&typeof e==`object`&&e[k]===D,q=e=>!!e&&typeof e==`object`&&e[k]===O;function J(e){if(e&&typeof e==`object`)switch(e[k]){case w:case O:return!0}return!1}function Y(e){if(e&&typeof e==`object`)switch(e[k]){case t:case w:case D:case O:return!0}return!1}e.ALIAS=t,e.DOC=S,e.MAP=w,e.NODE_TYPE=k,e.PAIR=E,e.SCALAR=D,e.SEQ=O,e.hasAnchor=e=>(H(e)||J(e))&&!!e.anchor,e.isAlias=j,e.isCollection=J,e.isDocument=F,e.isMap=L,e.isNode=Y,e.isPair=B,e.isScalar=H,e.isSeq=q})),require_visit=__commonJSMin$1((e=>{var t=require_identity();let S=Symbol(`break visit`),w=Symbol(`skip children`),E=Symbol(`remove node`);function D(e,S){let w=F(S);t.isDocument(e)?O(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):O(null,e,w,Object.freeze([]))}D.BREAK=S,D.SKIP=w,D.REMOVE=E;function O(e,w,D,k){let j=L(e,w,D,k);if(t.isNode(j)||t.isPair(j))return B(e,k,j),O(e,j,D,k);if(typeof j!=`symbol`){if(t.isCollection(w)){k=Object.freeze(k.concat(w));for(let e=0;e<w.items.length;++e){let t=O(e,w.items[e],D,k);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){k=Object.freeze(k.concat(w));let e=O(`key`,w.key,D,k);if(e===S)return S;e===E&&(w.key=null);let t=O(`value`,w.value,D,k);if(t===S)return S;t===E&&(w.value=null)}}return j}async function k(e,S){let w=F(S);t.isDocument(e)?await j(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):await j(null,e,w,Object.freeze([]))}k.BREAK=S,k.SKIP=w,k.REMOVE=E;async function j(e,w,D,O){let k=await L(e,w,D,O);if(t.isNode(k)||t.isPair(k))return B(e,O,k),j(e,k,D,O);if(typeof k!=`symbol`){if(t.isCollection(w)){O=Object.freeze(O.concat(w));for(let e=0;e<w.items.length;++e){let t=await j(e,w.items[e],D,O);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){O=Object.freeze(O.concat(w));let e=await j(`key`,w.key,D,O);if(e===S)return S;e===E&&(w.key=null);let t=await j(`value`,w.value,D,O);if(t===S)return S;t===E&&(w.value=null)}}return k}function F(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function L(e,S,w,E){if(typeof w==`function`)return w(e,S,E);if(t.isMap(S))return w.Map?.(e,S,E);if(t.isSeq(S))return w.Seq?.(e,S,E);if(t.isPair(S))return w.Pair?.(e,S,E);if(t.isScalar(S))return w.Scalar?.(e,S,E);if(t.isAlias(S))return w.Alias?.(e,S,E)}function B(e,S,w){let E=S[S.length-1];if(t.isCollection(E))E.items[e]=w;else if(t.isPair(E))e===`key`?E.key=w:E.value=w;else if(t.isDocument(E))E.contents=w;else{let e=t.isAlias(E)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=D,e.visitAsync=k})),require_directives=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();let w={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},E=e=>e.replace(/[!,[\]{}]/g,e=>w[e]);var D=class e{constructor(t,S){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,S)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,S){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let w=t.trim().split(/[ \t]+/),E=w.shift();switch(E){case`%TAG`:{if(w.length!==2&&(S(0,`%TAG directive should contain exactly two parts`),w.length<2))return!1;let[e,t]=w;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,w.length!==1)return S(0,`%YAML directive should contain exactly one part`),!1;let[e]=w;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return S(6,`Unsupported YAML version ${e}`,t),!1}}default:return S(0,`Unknown directive ${E}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let S=e.slice(2,-1);return S===`!`||S===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),S)}let[,S,w]=e.match(/^(.*!)([^!]*)$/s);w||t(`The ${e} tag has no suffix`);let E=this.tags[S];if(E)try{return E+decodeURIComponent(w)}catch(e){return t(String(e)),null}return S===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,S]of Object.entries(this.tags))if(e.startsWith(S))return t+E(e.substring(S.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],E=Object.entries(this.tags),D;if(e&&E.length>0&&t.isNode(e.contents)){let w={};S.visit(e.contents,(e,S)=>{t.isNode(S)&&S.tag&&(w[S.tag]=!0)}),D=Object.keys(w)}else D=[];for(let[t,S]of E)t===`!!`&&S===`tag:yaml.org,2002:`||(!e||D.some(e=>e.startsWith(S)))&&w.push(`%TAG ${t} ${S}`);return w.join(`
|
|
1
|
+
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{r as diffLines,t as createPatch}from"./libesm-Cfo1LhlX.mjs";import{n as mimes,t as build_default}from"./build-BZeImWox.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";var require_identity=__commonJSMin$1((e=>{let t=Symbol.for(`yaml.alias`),S=Symbol.for(`yaml.document`),w=Symbol.for(`yaml.map`),E=Symbol.for(`yaml.pair`),D=Symbol.for(`yaml.scalar`),O=Symbol.for(`yaml.seq`),k=Symbol.for(`yaml.node.type`),j=e=>!!e&&typeof e==`object`&&e[k]===t,F=e=>!!e&&typeof e==`object`&&e[k]===S,L=e=>!!e&&typeof e==`object`&&e[k]===w,B=e=>!!e&&typeof e==`object`&&e[k]===E,H=e=>!!e&&typeof e==`object`&&e[k]===D,q=e=>!!e&&typeof e==`object`&&e[k]===O;function J(e){if(e&&typeof e==`object`)switch(e[k]){case w:case O:return!0}return!1}function Y(e){if(e&&typeof e==`object`)switch(e[k]){case t:case w:case D:case O:return!0}return!1}e.ALIAS=t,e.DOC=S,e.MAP=w,e.NODE_TYPE=k,e.PAIR=E,e.SCALAR=D,e.SEQ=O,e.hasAnchor=e=>(H(e)||J(e))&&!!e.anchor,e.isAlias=j,e.isCollection=J,e.isDocument=F,e.isMap=L,e.isNode=Y,e.isPair=B,e.isScalar=H,e.isSeq=q})),require_visit=__commonJSMin$1((e=>{var t=require_identity();let S=Symbol(`break visit`),w=Symbol(`skip children`),E=Symbol(`remove node`);function D(e,S){let w=F(S);t.isDocument(e)?O(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):O(null,e,w,Object.freeze([]))}D.BREAK=S,D.SKIP=w,D.REMOVE=E;function O(e,w,D,k){let j=L(e,w,D,k);if(t.isNode(j)||t.isPair(j))return B(e,k,j),O(e,j,D,k);if(typeof j!=`symbol`){if(t.isCollection(w)){k=Object.freeze(k.concat(w));for(let e=0;e<w.items.length;++e){let t=O(e,w.items[e],D,k);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){k=Object.freeze(k.concat(w));let e=O(`key`,w.key,D,k);if(e===S)return S;e===E&&(w.key=null);let t=O(`value`,w.value,D,k);if(t===S)return S;t===E&&(w.value=null)}}return j}async function k(e,S){let w=F(S);t.isDocument(e)?await j(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):await j(null,e,w,Object.freeze([]))}k.BREAK=S,k.SKIP=w,k.REMOVE=E;async function j(e,w,D,O){let k=await L(e,w,D,O);if(t.isNode(k)||t.isPair(k))return B(e,O,k),j(e,k,D,O);if(typeof k!=`symbol`){if(t.isCollection(w)){O=Object.freeze(O.concat(w));for(let e=0;e<w.items.length;++e){let t=await j(e,w.items[e],D,O);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){O=Object.freeze(O.concat(w));let e=await j(`key`,w.key,D,O);if(e===S)return S;e===E&&(w.key=null);let t=await j(`value`,w.value,D,O);if(t===S)return S;t===E&&(w.value=null)}}return k}function F(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function L(e,S,w,E){if(typeof w==`function`)return w(e,S,E);if(t.isMap(S))return w.Map?.(e,S,E);if(t.isSeq(S))return w.Seq?.(e,S,E);if(t.isPair(S))return w.Pair?.(e,S,E);if(t.isScalar(S))return w.Scalar?.(e,S,E);if(t.isAlias(S))return w.Alias?.(e,S,E)}function B(e,S,w){let E=S[S.length-1];if(t.isCollection(E))E.items[e]=w;else if(t.isPair(E))e===`key`?E.key=w:E.value=w;else if(t.isDocument(E))E.contents=w;else{let e=t.isAlias(E)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=D,e.visitAsync=k})),require_directives=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();let w={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},E=e=>e.replace(/[!,[\]{}]/g,e=>w[e]);var D=class e{constructor(t,S){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,S)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,S){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let w=t.trim().split(/[ \t]+/),E=w.shift();switch(E){case`%TAG`:{if(w.length!==2&&(S(0,`%TAG directive should contain exactly two parts`),w.length<2))return!1;let[e,t]=w;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,w.length!==1)return S(0,`%YAML directive should contain exactly one part`),!1;let[e]=w;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return S(6,`Unsupported YAML version ${e}`,t),!1}}default:return S(0,`Unknown directive ${E}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let S=e.slice(2,-1);return S===`!`||S===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),S)}let[,S,w]=e.match(/^(.*!)([^!]*)$/s);w||t(`The ${e} tag has no suffix`);let E=this.tags[S];if(E)try{return E+decodeURIComponent(w)}catch(e){return t(String(e)),null}return S===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,S]of Object.entries(this.tags))if(e.startsWith(S))return t+E(e.substring(S.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],E=Object.entries(this.tags),D;if(e&&E.length>0&&t.isNode(e.contents)){let w={};S.visit(e.contents,(e,S)=>{t.isNode(S)&&S.tag&&(w[S.tag]=!0)}),D=Object.keys(w)}else D=[];for(let[t,S]of E)t===`!!`&&S===`tag:yaml.org,2002:`||(!e||D.some(e=>e.startsWith(S)))&&w.push(`%TAG ${t} ${S}`);return w.join(`
|
|
2
2
|
`)}};D.defaultYaml={explicit:!1,version:`1.2`},D.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=D})),require_anchors=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();function w(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function E(e){let t=new Set;return S.visit(e,{Value(e,S){S.anchor&&t.add(S.anchor)}}),t}function D(e,t){for(let S=1;;++S){let w=`${e}${S}`;if(!t.has(w))return w}}function O(e,S){let w=[],O=new Map,k=null;return{onAnchor:t=>{w.push(t),k??=E(e);let O=D(S,k);return k.add(O),O},setAnchors:()=>{for(let e of w){let S=O.get(e);if(typeof S==`object`&&S.anchor&&(t.isScalar(S.node)||t.isCollection(S.node)))S.node.anchor=S.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:O}}e.anchorIsValid=w,e.anchorNames=E,e.createNodeAnchors=O,e.findNewAnchor=D})),require_applyReviver=__commonJSMin$1((e=>{function t(e,S,w,E){if(E&&typeof E==`object`)if(Array.isArray(E))for(let S=0,w=E.length;S<w;++S){let w=E[S],D=t(e,E,String(S),w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}else if(E instanceof Map)for(let S of Array.from(E.keys())){let w=E.get(S),D=t(e,E,S,w);D===void 0?E.delete(S):D!==w&&E.set(S,D)}else if(E instanceof Set)for(let S of Array.from(E)){let w=t(e,E,S,S);w===void 0?E.delete(S):w!==S&&(E.delete(S),E.add(w))}else for(let[S,w]of Object.entries(E)){let D=t(e,E,S,w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}return e.call(S,w,E)}e.applyReviver=t})),require_toJS=__commonJSMin$1((e=>{var t=require_identity();function S(e,w,E){if(Array.isArray(e))return e.map((e,t)=>S(e,String(t),E));if(e&&typeof e.toJSON==`function`){if(!E||!t.hasAnchor(e))return e.toJSON(w,E);let S={aliasCount:0,count:1,res:void 0};E.anchors.set(e,S),E.onCreate=e=>{S.res=e,delete E.onCreate};let D=e.toJSON(w,E);return E.onCreate&&E.onCreate(D),D}return typeof e==`bigint`&&!E?.keep?Number(e):e}e.toJS=S})),require_Node=__commonJSMin$1((e=>{var t=require_applyReviver(),S=require_identity(),w=require_toJS();e.NodeBase=class{constructor(e){Object.defineProperty(this,S.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:E,maxAliasCount:D,onAnchor:O,reviver:k}={}){if(!S.isDocument(e))throw TypeError(`A document argument is required`);let j={anchors:new Map,doc:e,keep:!0,mapAsMap:E===!0,mapKeyWarned:!1,maxAliasCount:typeof D==`number`?D:100},F=w.toJS(this,``,j);if(typeof O==`function`)for(let{count:e,res:t}of j.anchors.values())O(t,e);return typeof k==`function`?t.applyReviver(k,{"":F},``,F):F}}})),require_Alias=__commonJSMin$1((e=>{var t=require_anchors(),S=require_visit(),w=require_identity(),E=require_Node(),D=require_toJS(),O=class extends E.NodeBase{constructor(e){super(w.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let E;t?.aliasResolveCache?E=t.aliasResolveCache:(E=[],S.visit(e,{Node:(e,t)=>{(w.isAlias(t)||w.hasAnchor(t))&&E.push(t)}}),t&&(t.aliasResolveCache=E));let D;for(let e of E){if(e===this)break;e.anchor===this.source&&(D=e)}return D}toJSON(e,t){if(!t)return{source:this.source};let{anchors:S,doc:w,maxAliasCount:E}=t,O=this.resolve(w,t);if(!O){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let j=S.get(O);if(j||=(D.toJS(O,null,t),S.get(O)),j?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(E>=0&&(j.count+=1,j.aliasCount===0&&(j.aliasCount=k(w,O,S)),j.count*j.aliasCount>E))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return j.res}toString(e,S,w){let E=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${E} `}return E}};function k(e,t,S){if(w.isAlias(t)){let w=t.resolve(e),E=S&&w&&S.get(w);return E?E.count*E.aliasCount:0}else if(w.isCollection(t)){let w=0;for(let E of t.items){let t=k(e,E,S);t>w&&(w=t)}return w}else if(w.isPair(t)){let w=k(e,t.key,S),E=k(e,t.value,S);return Math.max(w,E)}return 1}e.Alias=O})),require_Scalar=__commonJSMin$1((e=>{var t=require_identity(),S=require_Node(),w=require_toJS();let E=e=>!e||typeof e!=`function`&&typeof e!=`object`;var D=class extends S.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:w.toJS(this.value,e,t)}toString(){return String(this.value)}};D.BLOCK_FOLDED=`BLOCK_FOLDED`,D.BLOCK_LITERAL=`BLOCK_LITERAL`,D.PLAIN=`PLAIN`,D.QUOTE_DOUBLE=`QUOTE_DOUBLE`,D.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=D,e.isScalarValue=E})),require_createNode=__commonJSMin$1((e=>{var t=require_Alias(),S=require_identity(),w=require_Scalar();let E=`tag:yaml.org,2002:`;function D(e,t,S){if(t){let e=S.filter(e=>e.tag===t),w=e.find(e=>!e.format)??e[0];if(!w)throw Error(`Tag ${t} not found`);return w}return S.find(t=>t.identify?.(e)&&!t.format)}function O(e,E,O){if(S.isDocument(e)&&(e=e.contents),S.isNode(e))return e;if(S.isPair(e)){let t=O.schema[S.MAP].createNode?.(O.schema,null,O);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:k,onAnchor:j,onTagObj:F,schema:L,sourceObjects:B}=O,H;if(k&&e&&typeof e==`object`){if(H=B.get(e),H)return H.anchor??=j(e),new t.Alias(H.anchor);H={anchor:null,node:null},B.set(e,H)}E?.startsWith(`!!`)&&(E=`tag:yaml.org,2002:`+E.slice(2));let q=D(e,E,L.tags);if(!q){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new w.Scalar(e);return H&&(H.node=t),t}q=e instanceof Map?L[S.MAP]:Symbol.iterator in Object(e)?L[S.SEQ]:L[S.MAP]}F&&(F(q),delete O.onTagObj);let J=q?.createNode?q.createNode(O.schema,e,O):typeof q?.nodeClass?.from==`function`?q.nodeClass.from(O.schema,e,O):new w.Scalar(e);return E?J.tag=E:q.default||(J.tag=q.tag),H&&(H.node=J),J}e.createNode=O})),require_Collection=__commonJSMin$1((e=>{var t=require_createNode(),S=require_identity(),w=require_Node();function E(e,S,w){let E=w;for(let e=S.length-1;e>=0;--e){let t=S[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=E,E=e}else E=new Map([[t,E]])}return t.createNode(E,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let D=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends w.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>S.isNode(t)||S.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(D(e))this.add(t);else{let[w,...D]=e,O=this.get(w,!0);if(S.isCollection(O))O.addIn(D,t);else if(O===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}deleteIn(e){let[t,...w]=e;if(w.length===0)return this.delete(t);let E=this.get(t,!0);if(S.isCollection(E))return E.deleteIn(w);throw Error(`Expected YAML collection at ${t}. Remaining path: ${w}`)}getIn(e,t){let[w,...E]=e,D=this.get(w,!0);return E.length===0?!t&&S.isScalar(D)?D.value:D:S.isCollection(D)?D.getIn(E,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!S.isPair(t))return!1;let w=t.value;return w==null||e&&S.isScalar(w)&&w.value==null&&!w.commentBefore&&!w.comment&&!w.tag})}hasIn(e){let[t,...w]=e;if(w.length===0)return this.has(t);let E=this.get(t,!0);return S.isCollection(E)?E.hasIn(w):!1}setIn(e,t){let[w,...D]=e;if(D.length===0)this.set(w,t);else{let e=this.get(w,!0);if(S.isCollection(e))e.setIn(D,t);else if(e===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}},e.collectionFromPath=E,e.isEmptyPath=D})),require_stringifyComment=__commonJSMin$1((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function S(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=S,e.lineComment=(e,t,w)=>e.endsWith(`
|
|
3
3
|
`)?S(w,t):w.includes(`
|
|
4
4
|
`)?`
|
|
@@ -151,7 +151,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
151
151
|
|
|
152
152
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let k=t.compile();return(t,S)=>k(e,t,S)},D,O=isObject$1,k=!globalConfig.jitless,j=k&&allowsEval.value,F=t.catchall,L;e._zod.parse=(B,H)=>{L??=w.value;let q=B.value;return O(q)?k&&j&&H?.async===!1&&H.jitless!==!0?(D||=E(t.shape),B=D(B,H),F?handleCatchall([],q,B,H,L,e):B):S(B,H):(B.issues.push({expected:`object`,code:`invalid_type`,input:q,inst:e}),B)}});function handleUnionResults(e,t,S,w){for(let S of e)if(S.issues.length===0)return t.value=S.value,t;let E=e.filter(e=>!aborted(e));return E.length===1?(t.value=E[0].value,E[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:S,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,w,config())))}),t)}const $ZodUnion=$constructor(`$ZodUnion`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),defineLazy(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazy(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let S=t.options.length===1,w=t.options[0]._zod.run;e._zod.parse=(E,D)=>{if(S)return w(E,D);let O=!1,k=[];for(let e of t.options){let t=e._zod.run({value:E.value,issues:[]},D);if(t instanceof Promise)k.push(t),O=!0;else{if(t.issues.length===0)return t;k.push(t)}}return O?Promise.all(k).then(t=>handleUnionResults(t,E,e,D)):handleUnionResults(k,E,e,D)}}),$ZodDiscriminatedUnion=$constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,$ZodUnion.init(e,t);let S=e._zod.parse;defineLazy(e._zod,`propValues`,()=>{let e={};for(let S of t.options){let w=S._zod.propValues;if(!w||Object.keys(w).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(S)}"`);for(let[t,S]of Object.entries(w)){e[t]||(e[t]=new Set);for(let w of S)e[t].add(w)}}return e});let w=cached(()=>{let e=t.options,S=new Map;for(let w of e){let e=w._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(w)}"`);for(let t of e){if(S.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);S.set(t,w)}}return S});e._zod.parse=(E,D)=>{let O=E.value;if(!isObject$1(O))return E.issues.push({code:`invalid_type`,expected:`object`,input:O,inst:e}),E;let k=w.value.get(O?.[t.discriminator]);return k?k._zod.run(E,D):t.unionFallback?S(E,D):(E.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,input:O,path:[t.discriminator],inst:e}),E)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,S)=>{let w=e.value,E=t.left._zod.run({value:w,issues:[]},S),D=t.right._zod.run({value:w,issues:[]},S);return E instanceof Promise||D instanceof Promise?Promise.all([E,D]).then(([t,S])=>handleIntersectionResults(e,t,S)):handleIntersectionResults(e,E,D)}});function mergeValues$1(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject$4(e)&&isPlainObject$4(t)){let S=Object.keys(t),w=Object.keys(e).filter(e=>S.indexOf(e)!==-1),E={...e,...t};for(let S of w){let w=mergeValues$1(e[S],t[S]);if(!w.valid)return{valid:!1,mergeErrorPath:[S,...w.mergeErrorPath]};E[S]=w.data}return{valid:!0,data:E}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let S=[];for(let w=0;w<e.length;w++){let E=e[w],D=t[w],O=mergeValues$1(E,D);if(!O.valid)return{valid:!1,mergeErrorPath:[w,...O.mergeErrorPath]};S.push(O.data)}return{valid:!0,data:S}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,S){let w=new Map,E;for(let S of t.issues)if(S.code===`unrecognized_keys`){E??=S;for(let e of S.keys)w.has(e)||w.set(e,{}),w.get(e).l=!0}else e.issues.push(S);for(let t of S.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)w.has(e)||w.set(e,{}),w.get(e).r=!0;else e.issues.push(t);let D=[...w].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(D.length&&E&&e.issues.push({...E,keys:D}),aborted(e))return e;let O=mergeValues$1(t.value,S.value);if(!O.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(O.mergeErrorPath)}`);return e.value=O.data,e}const $ZodRecord=$constructor(`$ZodRecord`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(S,w)=>{let E=S.value;if(!isPlainObject$4(E))return S.issues.push({expected:`record`,code:`invalid_type`,input:E,inst:e}),S;let D=[],O=t.keyType._zod.values;if(O){S.value={};let k=new Set;for(let e of O)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){k.add(typeof e==`number`?e.toString():e);let O=t.valueType._zod.run({value:E[e],issues:[]},w);O instanceof Promise?D.push(O.then(t=>{t.issues.length&&S.issues.push(...prefixIssues(e,t.issues)),S.value[e]=t.value})):(O.issues.length&&S.issues.push(...prefixIssues(e,O.issues)),S.value[e]=O.value)}let j;for(let e in E)k.has(e)||(j??=[],j.push(e));j&&j.length>0&&S.issues.push({code:`unrecognized_keys`,input:E,inst:e,keys:j})}else{S.value={};for(let O of Reflect.ownKeys(E)){if(O===`__proto__`)continue;let k=t.keyType._zod.run({value:O,issues:[]},w);if(k instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof O==`string`&&number$2.test(O)&&k.issues.length){let e=t.keyType._zod.run({value:Number(O),issues:[]},w);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(k=e)}if(k.issues.length){t.mode===`loose`?S.value[O]=E[O]:S.issues.push({code:`invalid_key`,origin:`record`,issues:k.issues.map(e=>finalizeIssue(e,w,config())),input:O,path:[O],inst:e});continue}let j=t.valueType._zod.run({value:E[O],issues:[]},w);j instanceof Promise?D.push(j.then(e=>{e.issues.length&&S.issues.push(...prefixIssues(O,e.issues)),S.value[k.value]=e.value})):(j.issues.length&&S.issues.push(...prefixIssues(O,j.issues)),S.value[k.value]=j.value)}}return D.length?Promise.all(D).then(()=>S):S}}),$ZodEnum=$constructor(`$ZodEnum`,(e,t)=>{$ZodType.init(e,t);let S=getEnumValues(t.entries),w=new Set(S);e._zod.values=w,e._zod.pattern=RegExp(`^(${S.filter(e=>propertyKeyTypes.has(typeof e)).map(e=>typeof e==`string`?escapeRegex$1(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,E)=>{let D=t.value;return w.has(D)||t.issues.push({code:`invalid_value`,values:S,input:D,inst:e}),t}}),$ZodLiteral=$constructor(`$ZodLiteral`,(e,t)=>{if($ZodType.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let S=new Set(t.values);e._zod.values=S,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?escapeRegex$1(e):e?escapeRegex$1(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(w,E)=>{let D=w.value;return S.has(D)||w.issues.push({code:`invalid_value`,values:t.values,input:D,inst:e}),w}}),$ZodTransform=$constructor(`$ZodTransform`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let E=t.transform(S.value,S);if(w.async)return(E instanceof Promise?E:Promise.resolve(E)).then(e=>(S.value=e,S));if(E instanceof Promise)throw new $ZodAsyncError;return S.value=E,S}});function handleOptionalResult(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const $ZodOptional=$constructor(`$ZodOptional`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,S)=>{if(t.innerType._zod.optin===`optional`){let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(w,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,S)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(e,t)=>{$ZodOptional.init(e,t),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,S)=>t.innerType._zod.run(e,S)}),$ZodNullable=$constructor(`$ZodNullable`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.innerType._zod.optin),defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)}|null)$`):void 0}),defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,S)=>e.value===null?e:t.innerType._zod.run(e,S)}),$ZodDefault=$constructor(`$ZodDefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);if(e.value===void 0)return e.value=t.defaultValue,e;let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(e=>handleDefaultResult(e,t)):handleDefaultResult(w,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const $ZodPrefault=$constructor(`$ZodPrefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>(S.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,S))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(S,w)=>{let E=t.innerType._zod.run(S,w);return E instanceof Promise?E.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(E,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const $ZodCatch=$constructor(`$ZodCatch`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.innerType._zod.optin),defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(w=>(e.value=w.value,w.issues.length&&(e.value=t.catchValue({...e,error:{issues:w.issues.map(e=>finalizeIssue(e,S,config()))},input:e.value}),e.issues=[]),e)):(e.value=w.value,w.issues.length&&(e.value=t.catchValue({...e,error:{issues:w.issues.map(e=>finalizeIssue(e,S,config()))},input:e.value}),e.issues=[]),e)}}),$ZodPipe=$constructor(`$ZodPipe`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>t.in._zod.values),defineLazy(e._zod,`optin`,()=>t.in._zod.optin),defineLazy(e._zod,`optout`,()=>t.out._zod.optout),defineLazy(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,S)=>{if(S.direction===`backward`){let w=t.out._zod.run(e,S);return w instanceof Promise?w.then(e=>handlePipeResult(e,t.in,S)):handlePipeResult(w,t.in,S)}let w=t.in._zod.run(e,S);return w instanceof Promise?w.then(e=>handlePipeResult(e,t.out,S)):handlePipeResult(w,t.out,S)}});function handlePipeResult(e,t,S){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},S)}const $ZodReadonly=$constructor(`$ZodReadonly`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`propValues`,()=>t.innerType._zod.propValues),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`optin`,()=>t.innerType?._zod?.optin),defineLazy(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(handleReadonlyResult):handleReadonlyResult(w)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}const $ZodCustom=$constructor(`$ZodCustom`,(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=S=>{let w=S.value,E=t.fn(w);if(E instanceof Promise)return E.then(t=>handleRefineResult(t,S,w,e));handleRefineResult(E,S,w,e)}});function handleRefineResult(e,t,S,w){if(!e){let e={code:`custom`,input:S,inst:w,path:[...w._zod.def.path??[]],continue:!w._zod.def.abort};w._zod.def.params&&(e.params=w._zod.def.params),t.issues.push(issue(e))}}var _a$2,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let S=t[0];return this._map.set(e,S),S&&typeof S==`object`&&`id`in S&&this._idmap.set(S.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let S={...this.get(t)??{}};delete S.id;let w={...S,...this._map.get(e)};return Object.keys(w).length?w:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry$1(){return new $ZodRegistry}(_a$2=globalThis).__zod_globalRegistry??(_a$2.__zod_globalRegistry=registry$1());const globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:`string`,...normalizeParams(t)})}function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}function _number(e,t){return new e({type:`number`,checks:[],...normalizeParams(t)})}function _coercedNumber(e,t){return new e({type:`number`,coerce:!0,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}function _null$1(e,t){return new e({type:`null`,...normalizeParams(t)})}function _any(e){return new e({type:`any`})}function _unknown(e){return new e({type:`unknown`})}function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:`multiple_of`,...normalizeParams(t),value:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:`overwrite`,tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _slugify(){return _overwrite(e=>slugify(e))}function _array(e,t,S){return new e({type:`array`,element:t,...normalizeParams(S)})}function _custom(e,t,S){let w=normalizeParams(S);return w.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...w})}function _refine(e,t,S){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(S)})}function _superRefine(e){let t=_check(S=>(S.addIssue=e=>{if(typeof e==`string`)S.issues.push(issue(e,S.value,t._zod.def));else{let w=e;w.fatal&&(w.continue=!1),w.code??=`custom`,w.input??=S.value,w.inst??=t,w.continue??=!t._zod.def.abort,S.issues.push(issue(w))}},e(S.value,S)));return t}function _check(e,t){let S=new $ZodCheck({check:`custom`,...normalizeParams(t)});return S._zod.check=e,S}function describe$2(e){let t=new $ZodCheck({check:`describe`});return t._zod.onattach=[t=>{let S=globalRegistry.get(t)??{};globalRegistry.add(t,{...S,description:e})}],t._zod.check=()=>{},t}function meta$2(e){let t=new $ZodCheck({check:`meta`});return t._zod.onattach=[t=>{let S=globalRegistry.get(t)??{};globalRegistry.add(t,{...S,...e})}],t._zod.check=()=>{},t}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function process$5(e,t,S={path:[],schemaPath:[]}){var w;let E=e._zod.def,D=t.seen.get(e);if(D)return D.count++,S.schemaPath.includes(e)&&(D.cycle=S.path),D.schema;let O={schema:{},count:1,cycle:void 0,path:S.path};t.seen.set(e,O);let k=e._zod.toJSONSchema?.();if(k)O.schema=k;else{let w={...S,schemaPath:[...S.schemaPath,e],path:S.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,O.schema,w);else{let S=O.schema,D=t.processors[E.type];if(!D)throw Error(`[toJSONSchema]: Non-representable type encountered: ${E.type}`);D(e,t,S,w)}let D=e._zod.parent;D&&(O.ref||=D,process$5(D,t,w),t.seen.get(D).isParent=!0)}let j=t.metadataRegistry.get(e);return j&&Object.assign(O.schema,j),t.io===`input`&&isTransforming(e)&&(delete O.schema.examples,delete O.schema.default),t.io===`input`&&O.schema._prefault&&((w=O.schema).default??(w.default=O.schema._prefault)),delete O.schema._prefault,t.seen.get(e).schema}function extractDefs(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=new Map;for(let t of e.seen.entries()){let S=e.metadataRegistry.get(t[0])?.id;if(S){let e=w.get(S);if(e&&e!==t[0])throw Error(`Duplicate schema id "${S}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);w.set(S,t[0])}}let E=t=>{let w=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let S=e.external.registry.get(t[0])?.id,E=e.external.uri??(e=>e);if(S)return{ref:E(S)};let D=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=D,{defId:D,ref:`${E(`__shared`)}#/${w}/${D}`}}if(t[1]===S)return{ref:`#`};let E=`#/${w}/`,D=t[1].schema.id??`__schema${e.counter++}`;return{defId:D,ref:E+D}},D=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:S,defId:w}=E(e);t.def={...t.schema},w&&(t.defId=w);let D=t.schema;for(let e in D)delete D[e];D.$ref=S};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
153
153
|
|
|
154
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let S of e.seen.entries()){let w=S[1];if(t===S[0]){D(S);continue}if(e.external){let w=e.external.registry.get(S[0])?.id;if(t!==S[0]&&w){D(S);continue}}if(e.metadataRegistry.get(S[0])?.id){D(S);continue}if(w.cycle){D(S);continue}if(w.count>1&&e.reused===`ref`){D(S);continue}}}function finalize(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=t=>{let S=e.seen.get(t);if(S.ref===null)return;let E=S.def??S.schema,D={...E},O=S.ref;if(S.ref=null,O){w(O);let S=e.seen.get(O),k=S.schema;if(k.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(E.allOf=E.allOf??[],E.allOf.push(k)):Object.assign(E,k),Object.assign(E,D),t._zod.parent===O)for(let e in E)e===`$ref`||e===`allOf`||e in D||delete E[e];if(k.$ref&&S.def)for(let e in E)e===`$ref`||e===`allOf`||e in S.def&&JSON.stringify(E[e])===JSON.stringify(S.def[e])&&delete E[e]}let k=t._zod.parent;if(k&&k!==O){w(k);let t=e.seen.get(k);if(t?.schema.$ref&&(E.$ref=t.schema.$ref,t.def))for(let e in E)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(E[e])===JSON.stringify(t.def[e])&&delete E[e]}e.override({zodSchema:t,jsonSchema:E,path:S.path??[]})};for(let t of[...e.seen.entries()].reverse())w(t[0]);let E={};if(e.target===`draft-2020-12`?E.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?E.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?E.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let S=e.external.registry.get(t)?.id;if(!S)throw Error("Schema is missing an `id` property");E.$id=e.external.uri(S)}Object.assign(E,S.def??S.schema);let D=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(D[e.defId]=e.def)}e.external||Object.keys(D).length>0&&(e.target===`draft-2020-12`?E.$defs=D:E.definitions=D);try{let S=JSON.parse(JSON.stringify(E));return Object.defineProperty(S,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),S}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let S=t??{seen:new Set};if(S.seen.has(e))return!1;S.seen.add(e);let w=e._zod.def;if(w.type===`transform`)return!0;if(w.type===`array`)return isTransforming(w.element,S);if(w.type===`set`)return isTransforming(w.valueType,S);if(w.type===`lazy`)return isTransforming(w.getter(),S);if(w.type===`promise`||w.type===`optional`||w.type===`nonoptional`||w.type===`nullable`||w.type===`readonly`||w.type===`default`||w.type===`prefault`)return isTransforming(w.innerType,S);if(w.type===`intersection`)return isTransforming(w.left,S)||isTransforming(w.right,S);if(w.type===`record`||w.type===`map`)return isTransforming(w.keyType,S)||isTransforming(w.valueType,S);if(w.type===`pipe`)return isTransforming(w.in,S)||isTransforming(w.out,S);if(w.type===`object`){for(let e in w.shape)if(isTransforming(w.shape[e],S))return!0;return!1}if(w.type===`union`){for(let e of w.options)if(isTransforming(e,S))return!0;return!1}if(w.type===`tuple`){for(let e of w.items)if(isTransforming(e,S))return!0;return!!(w.rest&&isTransforming(w.rest,S))}return!1}const createToJSONSchemaMethod=(e,t={})=>S=>{let w=initializeContext({...S,processors:t});return process$5(e,w),extractDefs(w,e),finalize(w,e)},createStandardJSONSchemaMethod=(e,t,S={})=>w=>{let{libraryOptions:E,target:D}=w??{},O=initializeContext({...E??{},target:D,io:t,processors:S});return process$5(e,O),extractDefs(O,e),finalize(O,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,S,w)=>{let E=S;E.type=`string`;let{minimum:D,maximum:O,format:k,patterns:j,contentEncoding:F}=e._zod.bag;if(typeof D==`number`&&(E.minLength=D),typeof O==`number`&&(E.maxLength=O),k&&(E.format=formatMap[k]??k,E.format===``&&delete E.format,k===`time`&&delete E.format),F&&(E.contentEncoding=F),j&&j.size>0){let e=[...j];e.length===1?E.pattern=e[0].source:e.length>1&&(E.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,S,w)=>{let E=S,{minimum:D,maximum:O,format:k,multipleOf:j,exclusiveMaximum:F,exclusiveMinimum:L}=e._zod.bag;typeof k==`string`&&k.includes(`int`)?E.type=`integer`:E.type=`number`,typeof L==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.minimum=L,E.exclusiveMinimum=!0):E.exclusiveMinimum=L),typeof D==`number`&&(E.minimum=D,typeof L==`number`&&t.target!==`draft-04`&&(L>=D?delete E.minimum:delete E.exclusiveMinimum)),typeof F==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.maximum=F,E.exclusiveMaximum=!0):E.exclusiveMaximum=F),typeof O==`number`&&(E.maximum=O,typeof F==`number`&&t.target!==`draft-04`&&(F<=O?delete E.maximum:delete E.exclusiveMaximum)),typeof j==`number`&&(E.multipleOf=j)},booleanProcessor=(e,t,S,w)=>{S.type=`boolean`},bigintProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,S,w)=>{t.target===`openapi-3.0`?(S.type=`string`,S.nullable=!0,S.enum=[null]):S.type=`null`},undefinedProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,S,w)=>{S.not={}},anyProcessor=(e,t,S,w)=>{},unknownProcessor=(e,t,S,w)=>{},dateProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,S,w)=>{let E=e._zod.def,D=getEnumValues(E.entries);D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),S.enum=D},literalProcessor=(e,t,S,w)=>{let E=e._zod.def,D=[];for(let e of E.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);D.push(Number(e))}else D.push(e);if(D.length!==0)if(D.length===1){let e=D[0];S.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?S.enum=[e]:S.const=e}else D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),D.every(e=>typeof e==`boolean`)&&(S.type=`boolean`),D.every(e=>e===null)&&(S.type=`null`),S.enum=D},nanProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,S,w)=>{let E=S,D=e._zod.pattern;if(!D)throw Error(`Pattern not found in template literal`);E.type=`string`,E.pattern=D.source},fileProcessor=(e,t,S,w)=>{let E=S,D={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:O,maximum:k,mime:j}=e._zod.bag;O!==void 0&&(D.minLength=O),k!==void 0&&(D.maxLength=k),j?j.length===1?(D.contentMediaType=j[0],Object.assign(E,D)):(Object.assign(E,D),E.anyOf=j.map(e=>({contentMediaType:e}))):Object.assign(E,D)},successProcessor=(e,t,S,w)=>{S.type=`boolean`},customProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def,{minimum:O,maximum:k}=e._zod.bag;typeof O==`number`&&(E.minItems=O),typeof k==`number`&&(E.maxItems=k),E.type=`array`,E.items=process$5(D.element,t,{...w,path:[...w.path,`items`]})},objectProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`,E.properties={};let O=D.shape;for(let e in O)E.properties[e]=process$5(O[e],t,{...w,path:[...w.path,`properties`,e]});let k=new Set(Object.keys(O)),j=new Set([...k].filter(e=>{let S=D.shape[e]._zod;return t.io===`input`?S.optin===void 0:S.optout===void 0}));j.size>0&&(E.required=Array.from(j)),D.catchall?._zod.def.type===`never`?E.additionalProperties=!1:D.catchall?D.catchall&&(E.additionalProperties=process$5(D.catchall,t,{...w,path:[...w.path,`additionalProperties`]})):t.io===`output`&&(E.additionalProperties=!1)},unionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=E.inclusive===!1,O=E.options.map((e,S)=>process$5(e,t,{...w,path:[...w.path,D?`oneOf`:`anyOf`,S]}));D?S.oneOf=O:S.anyOf=O},intersectionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.left,t,{...w,path:[...w.path,`allOf`,0]}),O=process$5(E.right,t,{...w,path:[...w.path,`allOf`,1]}),k=e=>`allOf`in e&&Object.keys(e).length===1;S.allOf=[...k(D)?D.allOf:[D],...k(O)?O.allOf:[O]]},tupleProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`array`;let O=t.target===`draft-2020-12`?`prefixItems`:`items`,k=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,j=D.items.map((e,S)=>process$5(e,t,{...w,path:[...w.path,O,S]})),F=D.rest?process$5(D.rest,t,{...w,path:[...w.path,k,...t.target===`openapi-3.0`?[D.items.length]:[]]}):null;t.target===`draft-2020-12`?(E.prefixItems=j,F&&(E.items=F)):t.target===`openapi-3.0`?(E.items={anyOf:j},F&&E.items.anyOf.push(F),E.minItems=j.length,F||(E.maxItems=j.length)):(E.items=j,F&&(E.additionalItems=F));let{minimum:L,maximum:B}=e._zod.bag;typeof L==`number`&&(E.minItems=L),typeof B==`number`&&(E.maxItems=B)},recordProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`;let O=D.keyType,k=O._zod.bag?.patterns;if(D.mode===`loose`&&k&&k.size>0){let e=process$5(D.valueType,t,{...w,path:[...w.path,`patternProperties`,`*`]});E.patternProperties={};for(let t of k)E.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(E.propertyNames=process$5(D.keyType,t,{...w,path:[...w.path,`propertyNames`]})),E.additionalProperties=process$5(D.valueType,t,{...w,path:[...w.path,`additionalProperties`]});let j=O._zod.values;if(j){let e=[...j].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(E.required=e)}},nullableProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.innerType,t,w),O=t.seen.get(e);t.target===`openapi-3.0`?(O.ref=E.innerType,S.nullable=!0):S.anyOf=[D,{type:`null`}]},nonoptionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},defaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.default=JSON.parse(JSON.stringify(E.defaultValue))},prefaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,t.io===`input`&&(S._prefault=JSON.parse(JSON.stringify(E.defaultValue)))},catchProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType;let O;try{O=E.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}S.default=O},pipeProcessor=(e,t,S,w)=>{let E=e._zod.def,D=t.io===`input`?E.in._zod.def.type===`transform`?E.out:E.in:E.out;process$5(D,t,w);let O=t.seen.get(e);O.ref=D},readonlyProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.readOnly=!0},promiseProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},optionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},lazyProcessor=(e,t,S,w)=>{let E=e._zod.innerType;process$5(E,t,w);let D=t.seen.get(e);D.ref=E},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if(`_idmap`in e){let S=e,w=initializeContext({...t,processors:allProcessors}),E={};for(let e of S._idmap.entries()){let[t,S]=e;process$5(S,w)}let D={};w.external={registry:S,uri:t?.uri,defs:E};for(let e of S._idmap.entries()){let[t,S]=e;extractDefs(w,S),D[t]=finalize(w,S)}return Object.keys(E).length>0&&(D.__shared={[w.target===`draft-2020-12`?`$defs`:`definitions`]:E}),{schemas:D}}let S=initializeContext({...t,processors:allProcessors});return process$5(e,S),extractDefs(S,e),finalize(S,e)}const ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodError$1=$constructor(`ZodError`,initializer),ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse$5=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse$1=_safeParse(ZodRealError),safeParseAsync$1=_safeParseAsync(ZodRealError),encode$1=_encode(ZodRealError),decode$1=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType$1=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...S)=>e.clone(mergeDefs(t,{checks:[...t.checks??[],...S.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,S)=>clone(e,t,S),e.brand=()=>e,e.register=((t,S)=>(t.add(e,S),e)),e.parse=(t,S)=>parse$5(e,t,S,{callee:e.parse}),e.safeParse=(t,S)=>safeParse$1(e,t,S),e.parseAsync=async(t,S)=>parseAsync(e,t,S,{callee:e.parseAsync}),e.safeParseAsync=async(t,S)=>safeParseAsync$1(e,t,S),e.spa=e.safeParseAsync,e.encode=(t,S)=>encode$1(e,t,S),e.decode=(t,S)=>decode$1(e,t,S),e.encodeAsync=async(t,S)=>encodeAsync(e,t,S),e.decodeAsync=async(t,S)=>decodeAsync(e,t,S),e.safeEncode=(t,S)=>safeEncode(e,t,S),e.safeDecode=(t,S)=>safeDecode(e,t,S),e.safeEncodeAsync=async(t,S)=>safeEncodeAsync(e,t,S),e.safeDecodeAsync=async(t,S)=>safeDecodeAsync(e,t,S),e.refine=(t,S)=>e.check(refine(t,S)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.exactOptional=()=>exactOptional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{let S=e.clone();return globalRegistry.add(S,{description:t}),S},Object.defineProperty(e,`description`,{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return globalRegistry.get(e);let S=e.clone();return globalRegistry.add(S,t[0]),S},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>stringProcessor(e,t,S,w);let S=e._zod.bag;e.format=S.format??null,e.minLength=S.minimum??null,e.maxLength=S.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase()),e.slugify=()=>e.check(_slugify())}),ZodString$1=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$2(e){return _string(ZodString$1,e)}const ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber$1=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>numberProcessor(e,t,S,w),e.gt=(t,S)=>e.check(_gt(t,S)),e.gte=(t,S)=>e.check(_gte(t,S)),e.min=(t,S)=>e.check(_gte(t,S)),e.lt=(t,S)=>e.check(_lt(t,S)),e.lte=(t,S)=>e.check(_lte(t,S)),e.max=(t,S)=>e.check(_lte(t,S)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,S)=>e.check(_multipleOf(t,S)),e.step=(t,S)=>e.check(_multipleOf(t,S)),e.finite=()=>e;let S=e._zod.bag;e.minValue=Math.max(S.minimum??-1/0,S.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(S.maximum??1/0,S.exclusiveMaximum??1/0)??null,e.isInt=(S.format??``).includes(`int`)||Number.isSafeInteger(S.multipleOf??.5),e.isFinite=!0,e.format=S.format??null});function number$1(e){return _number(ZodNumber$1,e)}const ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber$1.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean$1=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>booleanProcessor(e,t,S,w)});function boolean$1(e){return _boolean(ZodBoolean$1,e)}const ZodNull$1=$constructor(`ZodNull`,(e,t)=>{$ZodNull.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullProcessor(e,t,S,w)});function _null(e){return _null$1(ZodNull$1,e)}const ZodAny$1=$constructor(`ZodAny`,(e,t)=>{$ZodAny.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function any$1(){return _any(ZodAny$1)}const ZodUnknown$1=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function unknown$2(){return _unknown(ZodUnknown$1)}const ZodNever$1=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>neverProcessor(e,t,S,w)});function never(e){return _never(ZodNever$1,e)}const ZodArray$1=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>arrayProcessor(e,t,S,w),e.element=t.element,e.min=(t,S)=>e.check(_minLength(t,S)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,S)=>e.check(_maxLength(t,S)),e.length=(t,S)=>e.check(_length(t,S)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray$1,e,t)}const ZodObject$1=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>objectProcessor(e,t,S,w),defineLazy(e,`shape`,()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend$1(e,t),e.safeExtend=t=>safeExtend(e,t),e.merge=t=>merge$1(e,t),e.pick=t=>pick$2(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional$1,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object$1(e,t){return new ZodObject$1({type:`object`,shape:e??{},...normalizeParams(t)})}function looseObject(e,t){return new ZodObject$1({type:`object`,shape:e,catchall:unknown$2(),...normalizeParams(t)})}const ZodUnion$1=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>unionProcessor(e,t,S,w),e.options=t.options});function union(e,t){return new ZodUnion$1({type:`union`,options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion$1=$constructor(`ZodDiscriminatedUnion`,(e,t)=>{ZodUnion$1.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,S){return new ZodDiscriminatedUnion$1({type:`union`,options:t,discriminator:e,...normalizeParams(S)})}const ZodIntersection$1=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>intersectionProcessor(e,t,S,w)});function intersection(e,t){return new ZodIntersection$1({type:`intersection`,left:e,right:t})}const ZodRecord$1=$constructor(`ZodRecord`,(e,t)=>{$ZodRecord.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>recordProcessor(e,t,S,w),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,S){return new ZodRecord$1({type:`record`,keyType:e,valueType:t,...normalizeParams(S)})}const ZodEnum$1=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>enumProcessor(e,t,S,w),e.enum=t.entries,e.options=Object.values(t.entries);let S=new Set(Object.keys(t.entries));e.extract=(e,w)=>{let E={};for(let w of e)if(S.has(w))E[w]=t.entries[w];else throw Error(`Key ${w} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})},e.exclude=(e,w)=>{let E={...t.entries};for(let t of e)if(S.has(t))delete E[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})}});function _enum(e,t){return new ZodEnum$1({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}const ZodLiteral$1=$constructor(`ZodLiteral`,(e,t)=>{$ZodLiteral.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>literalProcessor(e,t,S,w),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral$1({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>transformProcessor(e,t,S,w),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);S.addIssue=w=>{if(typeof w==`string`)S.issues.push(issue(w,S.value,t));else{let t=w;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=S.value,t.inst??=e,S.issues.push(issue(t))}};let E=t.transform(S.value,S);return E instanceof Promise?E.then(e=>(S.value=e,S)):(S.value=E,S)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}const ZodOptional$1=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional$1({type:`optional`,innerType:e})}const ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}const ZodNullable$1=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullableProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable$1({type:`nullable`,innerType:e})}const ZodDefault$1=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>defaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault$1({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>prefaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nonoptionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const ZodCatch$1=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>catchProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch$1({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>pipeProcessor(e,t,S,w),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}const ZodReadonly$1=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>readonlyProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly$1({type:`readonly`,innerType:e})}const ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>customProcessor(e,t,S,w)});function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}const describe$1=describe$2,meta$1=meta$2;function preprocess$1(e,t){return pipe(transform(e),t)}var import_dist$1=require_dist$2();init_esm$2();const SINGLETON_KEY$1=Symbol.for(`@inkeep/open-knowledge/field-registry`),g$1=globalThis;g$1[SINGLETON_KEY$1]===void 0&&(g$1[SINGLETON_KEY$1]=registry$1());const fieldRegistry=g$1[SINGLETON_KEY$1];function getFieldMeta(e){let t=e;for(let e=0;e<16;e++){if(t==null)return;let e=isZodSchema$1(t)?fieldRegistry.get(t):void 0;if(e!==void 0)return e;let S=t._zod?.def?.innerType;if(S===void 0)return;t=S}}function isZodSchema$1(e){return typeof e==`object`&&!!e&&`_zod`in e&&`parse`in e}const FolderFrontmatterSchema=looseObject({title:string$2().optional(),description:string$2().optional(),tags:array(string$2()).optional()}),FolderRuleSchema=looseObject({match:string$2().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:FolderFrontmatterSchema}),ConfigSchema$1=looseObject({content:looseObject({dir:string$2().register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`.`)}).default({dir:`.`}),appearance:looseObject({theme:_enum([`light`,`dark`,`system`]).register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).optional(),sidebar:looseObject({showHiddenFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1),showAllFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1)}).optional()}).default({}),autoSync:looseObject({enabled:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).nullable().default(null)}).default({enabled:null})}),TRACER_NAME$1=`open-knowledge-config`;async function withConfigSpan(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,async e=>{try{return await S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withConfigSpanSync(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function addConfigSpanEvent(e,t){let S=trace.getActiveSpan();S&&S.addEvent(e,t)}function unwrapToShape(e){let t=e;for(let e=0;e<16;e++){if(t==null||t?._zod?.def?.shape!==void 0)return t;let e=t?._zod?.def?.innerType;if(e===void 0)return t;t=e}return t}function resolveLeafSchema(e,t){let S=e;for(let e of t){S=unwrapToShape(S);let t=S?._zod?.def?.shape;if(!t||(S=t[String(e)],S===void 0))return}return S}function getLeafFieldMeta(e,t){let S=resolveLeafSchema(e,t);if(S!==void 0)return getFieldMeta(S)}function isScopeCompatible(e,t){return e===`either`?!0:e===t}function validatePatchScopes(e,t){let S=null;function w(e,E){if(S!==null||e===void 0)return;if(typeof e==`object`&&e&&!Array.isArray(e)){for(let[t,D]of Object.entries(e))if(w(D,[...E,t]),S!==null)return;return}let D=getLeafFieldMeta(ConfigSchema$1,E);D?.scope!==void 0&&(isScopeCompatible(D.scope,t)||(S={code:`SCOPE_VIOLATION`,path:E,expectedScope:D.scope,actualScope:t}))}for(let[t,E]of Object.entries(e))if(w(E,[t]),S!==null)break;return S}function ensureCollectionAncestors(e,t){for(let S=1;S<t.length;S++){let w=t.slice(0,S);e.hasIn(w)&&((0,import_dist$1.isCollection)(e.getIn(w,!0))||e.deleteIn(w))}}function applyPatchToDocument(e,t){let S=[];function w(t,E){if(t!==void 0){if(t===null){e.deleteIn(E),S.push(E.join(`.`));return}if(Array.isArray(t)){ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`));return}if(typeof t==`object`){for(let[e,S]of Object.entries(t))w(S,[...E,e]);return}ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`))}}for(let[e,S]of Object.entries(t))w(S,[e]);return S}function toConfigIssue(e){return{path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}}const CONFIG_SCHEMA_MAJOR_PATH=`v0`;function resolveNode(e,t){if(t.length===0)return e.contents??null;let S=e.getIn(t,!0);if((0,import_dist$1.isNode)(S))return S;for(let S=t.length-1;S>=0;S--){let w=e.getIn(t.slice(0,S),!0);if((0,import_dist$1.isNode)(w))return w}return e.contents??null}function offsetToLineCol(e,t){let S=1,w=1,E=Math.min(t,e.length);for(let t=0;t<E;t++)e.charCodeAt(t)===10?(S++,w=1):w++;return{line:S,column:w}}function renderSnippet(e,t,S,w,E){let D=e.split(`
|
|
154
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let S of e.seen.entries()){let w=S[1];if(t===S[0]){D(S);continue}if(e.external){let w=e.external.registry.get(S[0])?.id;if(t!==S[0]&&w){D(S);continue}}if(e.metadataRegistry.get(S[0])?.id){D(S);continue}if(w.cycle){D(S);continue}if(w.count>1&&e.reused===`ref`){D(S);continue}}}function finalize(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=t=>{let S=e.seen.get(t);if(S.ref===null)return;let E=S.def??S.schema,D={...E},O=S.ref;if(S.ref=null,O){w(O);let S=e.seen.get(O),k=S.schema;if(k.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(E.allOf=E.allOf??[],E.allOf.push(k)):Object.assign(E,k),Object.assign(E,D),t._zod.parent===O)for(let e in E)e===`$ref`||e===`allOf`||e in D||delete E[e];if(k.$ref&&S.def)for(let e in E)e===`$ref`||e===`allOf`||e in S.def&&JSON.stringify(E[e])===JSON.stringify(S.def[e])&&delete E[e]}let k=t._zod.parent;if(k&&k!==O){w(k);let t=e.seen.get(k);if(t?.schema.$ref&&(E.$ref=t.schema.$ref,t.def))for(let e in E)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(E[e])===JSON.stringify(t.def[e])&&delete E[e]}e.override({zodSchema:t,jsonSchema:E,path:S.path??[]})};for(let t of[...e.seen.entries()].reverse())w(t[0]);let E={};if(e.target===`draft-2020-12`?E.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?E.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?E.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let S=e.external.registry.get(t)?.id;if(!S)throw Error("Schema is missing an `id` property");E.$id=e.external.uri(S)}Object.assign(E,S.def??S.schema);let D=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(D[e.defId]=e.def)}e.external||Object.keys(D).length>0&&(e.target===`draft-2020-12`?E.$defs=D:E.definitions=D);try{let S=JSON.parse(JSON.stringify(E));return Object.defineProperty(S,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),S}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let S=t??{seen:new Set};if(S.seen.has(e))return!1;S.seen.add(e);let w=e._zod.def;if(w.type===`transform`)return!0;if(w.type===`array`)return isTransforming(w.element,S);if(w.type===`set`)return isTransforming(w.valueType,S);if(w.type===`lazy`)return isTransforming(w.getter(),S);if(w.type===`promise`||w.type===`optional`||w.type===`nonoptional`||w.type===`nullable`||w.type===`readonly`||w.type===`default`||w.type===`prefault`)return isTransforming(w.innerType,S);if(w.type===`intersection`)return isTransforming(w.left,S)||isTransforming(w.right,S);if(w.type===`record`||w.type===`map`)return isTransforming(w.keyType,S)||isTransforming(w.valueType,S);if(w.type===`pipe`)return isTransforming(w.in,S)||isTransforming(w.out,S);if(w.type===`object`){for(let e in w.shape)if(isTransforming(w.shape[e],S))return!0;return!1}if(w.type===`union`){for(let e of w.options)if(isTransforming(e,S))return!0;return!1}if(w.type===`tuple`){for(let e of w.items)if(isTransforming(e,S))return!0;return!!(w.rest&&isTransforming(w.rest,S))}return!1}const createToJSONSchemaMethod=(e,t={})=>S=>{let w=initializeContext({...S,processors:t});return process$5(e,w),extractDefs(w,e),finalize(w,e)},createStandardJSONSchemaMethod=(e,t,S={})=>w=>{let{libraryOptions:E,target:D}=w??{},O=initializeContext({...E??{},target:D,io:t,processors:S});return process$5(e,O),extractDefs(O,e),finalize(O,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,S,w)=>{let E=S;E.type=`string`;let{minimum:D,maximum:O,format:k,patterns:j,contentEncoding:F}=e._zod.bag;if(typeof D==`number`&&(E.minLength=D),typeof O==`number`&&(E.maxLength=O),k&&(E.format=formatMap[k]??k,E.format===``&&delete E.format,k===`time`&&delete E.format),F&&(E.contentEncoding=F),j&&j.size>0){let e=[...j];e.length===1?E.pattern=e[0].source:e.length>1&&(E.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,S,w)=>{let E=S,{minimum:D,maximum:O,format:k,multipleOf:j,exclusiveMaximum:F,exclusiveMinimum:L}=e._zod.bag;typeof k==`string`&&k.includes(`int`)?E.type=`integer`:E.type=`number`,typeof L==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.minimum=L,E.exclusiveMinimum=!0):E.exclusiveMinimum=L),typeof D==`number`&&(E.minimum=D,typeof L==`number`&&t.target!==`draft-04`&&(L>=D?delete E.minimum:delete E.exclusiveMinimum)),typeof F==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.maximum=F,E.exclusiveMaximum=!0):E.exclusiveMaximum=F),typeof O==`number`&&(E.maximum=O,typeof F==`number`&&t.target!==`draft-04`&&(F<=O?delete E.maximum:delete E.exclusiveMaximum)),typeof j==`number`&&(E.multipleOf=j)},booleanProcessor=(e,t,S,w)=>{S.type=`boolean`},bigintProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,S,w)=>{t.target===`openapi-3.0`?(S.type=`string`,S.nullable=!0,S.enum=[null]):S.type=`null`},undefinedProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,S,w)=>{S.not={}},anyProcessor=(e,t,S,w)=>{},unknownProcessor=(e,t,S,w)=>{},dateProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,S,w)=>{let E=e._zod.def,D=getEnumValues(E.entries);D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),S.enum=D},literalProcessor=(e,t,S,w)=>{let E=e._zod.def,D=[];for(let e of E.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);D.push(Number(e))}else D.push(e);if(D.length!==0)if(D.length===1){let e=D[0];S.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?S.enum=[e]:S.const=e}else D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),D.every(e=>typeof e==`boolean`)&&(S.type=`boolean`),D.every(e=>e===null)&&(S.type=`null`),S.enum=D},nanProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,S,w)=>{let E=S,D=e._zod.pattern;if(!D)throw Error(`Pattern not found in template literal`);E.type=`string`,E.pattern=D.source},fileProcessor=(e,t,S,w)=>{let E=S,D={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:O,maximum:k,mime:j}=e._zod.bag;O!==void 0&&(D.minLength=O),k!==void 0&&(D.maxLength=k),j?j.length===1?(D.contentMediaType=j[0],Object.assign(E,D)):(Object.assign(E,D),E.anyOf=j.map(e=>({contentMediaType:e}))):Object.assign(E,D)},successProcessor=(e,t,S,w)=>{S.type=`boolean`},customProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def,{minimum:O,maximum:k}=e._zod.bag;typeof O==`number`&&(E.minItems=O),typeof k==`number`&&(E.maxItems=k),E.type=`array`,E.items=process$5(D.element,t,{...w,path:[...w.path,`items`]})},objectProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`,E.properties={};let O=D.shape;for(let e in O)E.properties[e]=process$5(O[e],t,{...w,path:[...w.path,`properties`,e]});let k=new Set(Object.keys(O)),j=new Set([...k].filter(e=>{let S=D.shape[e]._zod;return t.io===`input`?S.optin===void 0:S.optout===void 0}));j.size>0&&(E.required=Array.from(j)),D.catchall?._zod.def.type===`never`?E.additionalProperties=!1:D.catchall?D.catchall&&(E.additionalProperties=process$5(D.catchall,t,{...w,path:[...w.path,`additionalProperties`]})):t.io===`output`&&(E.additionalProperties=!1)},unionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=E.inclusive===!1,O=E.options.map((e,S)=>process$5(e,t,{...w,path:[...w.path,D?`oneOf`:`anyOf`,S]}));D?S.oneOf=O:S.anyOf=O},intersectionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.left,t,{...w,path:[...w.path,`allOf`,0]}),O=process$5(E.right,t,{...w,path:[...w.path,`allOf`,1]}),k=e=>`allOf`in e&&Object.keys(e).length===1;S.allOf=[...k(D)?D.allOf:[D],...k(O)?O.allOf:[O]]},tupleProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`array`;let O=t.target===`draft-2020-12`?`prefixItems`:`items`,k=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,j=D.items.map((e,S)=>process$5(e,t,{...w,path:[...w.path,O,S]})),F=D.rest?process$5(D.rest,t,{...w,path:[...w.path,k,...t.target===`openapi-3.0`?[D.items.length]:[]]}):null;t.target===`draft-2020-12`?(E.prefixItems=j,F&&(E.items=F)):t.target===`openapi-3.0`?(E.items={anyOf:j},F&&E.items.anyOf.push(F),E.minItems=j.length,F||(E.maxItems=j.length)):(E.items=j,F&&(E.additionalItems=F));let{minimum:L,maximum:B}=e._zod.bag;typeof L==`number`&&(E.minItems=L),typeof B==`number`&&(E.maxItems=B)},recordProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`;let O=D.keyType,k=O._zod.bag?.patterns;if(D.mode===`loose`&&k&&k.size>0){let e=process$5(D.valueType,t,{...w,path:[...w.path,`patternProperties`,`*`]});E.patternProperties={};for(let t of k)E.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(E.propertyNames=process$5(D.keyType,t,{...w,path:[...w.path,`propertyNames`]})),E.additionalProperties=process$5(D.valueType,t,{...w,path:[...w.path,`additionalProperties`]});let j=O._zod.values;if(j){let e=[...j].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(E.required=e)}},nullableProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.innerType,t,w),O=t.seen.get(e);t.target===`openapi-3.0`?(O.ref=E.innerType,S.nullable=!0):S.anyOf=[D,{type:`null`}]},nonoptionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},defaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.default=JSON.parse(JSON.stringify(E.defaultValue))},prefaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,t.io===`input`&&(S._prefault=JSON.parse(JSON.stringify(E.defaultValue)))},catchProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType;let O;try{O=E.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}S.default=O},pipeProcessor=(e,t,S,w)=>{let E=e._zod.def,D=t.io===`input`?E.in._zod.def.type===`transform`?E.out:E.in:E.out;process$5(D,t,w);let O=t.seen.get(e);O.ref=D},readonlyProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.readOnly=!0},promiseProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},optionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},lazyProcessor=(e,t,S,w)=>{let E=e._zod.innerType;process$5(E,t,w);let D=t.seen.get(e);D.ref=E},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if(`_idmap`in e){let S=e,w=initializeContext({...t,processors:allProcessors}),E={};for(let e of S._idmap.entries()){let[t,S]=e;process$5(S,w)}let D={};w.external={registry:S,uri:t?.uri,defs:E};for(let e of S._idmap.entries()){let[t,S]=e;extractDefs(w,S),D[t]=finalize(w,S)}return Object.keys(E).length>0&&(D.__shared={[w.target===`draft-2020-12`?`$defs`:`definitions`]:E}),{schemas:D}}let S=initializeContext({...t,processors:allProcessors});return process$5(e,S),extractDefs(S,e),finalize(S,e)}const ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodError$1=$constructor(`ZodError`,initializer),ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse$5=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse$1=_safeParse(ZodRealError),safeParseAsync$1=_safeParseAsync(ZodRealError),encode$1=_encode(ZodRealError),decode$1=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType$1=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...S)=>e.clone(mergeDefs(t,{checks:[...t.checks??[],...S.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,S)=>clone(e,t,S),e.brand=()=>e,e.register=((t,S)=>(t.add(e,S),e)),e.parse=(t,S)=>parse$5(e,t,S,{callee:e.parse}),e.safeParse=(t,S)=>safeParse$1(e,t,S),e.parseAsync=async(t,S)=>parseAsync(e,t,S,{callee:e.parseAsync}),e.safeParseAsync=async(t,S)=>safeParseAsync$1(e,t,S),e.spa=e.safeParseAsync,e.encode=(t,S)=>encode$1(e,t,S),e.decode=(t,S)=>decode$1(e,t,S),e.encodeAsync=async(t,S)=>encodeAsync(e,t,S),e.decodeAsync=async(t,S)=>decodeAsync(e,t,S),e.safeEncode=(t,S)=>safeEncode(e,t,S),e.safeDecode=(t,S)=>safeDecode(e,t,S),e.safeEncodeAsync=async(t,S)=>safeEncodeAsync(e,t,S),e.safeDecodeAsync=async(t,S)=>safeDecodeAsync(e,t,S),e.refine=(t,S)=>e.check(refine(t,S)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.exactOptional=()=>exactOptional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{let S=e.clone();return globalRegistry.add(S,{description:t}),S},Object.defineProperty(e,`description`,{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return globalRegistry.get(e);let S=e.clone();return globalRegistry.add(S,t[0]),S},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>stringProcessor(e,t,S,w);let S=e._zod.bag;e.format=S.format??null,e.minLength=S.minimum??null,e.maxLength=S.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase()),e.slugify=()=>e.check(_slugify())}),ZodString$1=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$2(e){return _string(ZodString$1,e)}const ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber$1=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>numberProcessor(e,t,S,w),e.gt=(t,S)=>e.check(_gt(t,S)),e.gte=(t,S)=>e.check(_gte(t,S)),e.min=(t,S)=>e.check(_gte(t,S)),e.lt=(t,S)=>e.check(_lt(t,S)),e.lte=(t,S)=>e.check(_lte(t,S)),e.max=(t,S)=>e.check(_lte(t,S)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,S)=>e.check(_multipleOf(t,S)),e.step=(t,S)=>e.check(_multipleOf(t,S)),e.finite=()=>e;let S=e._zod.bag;e.minValue=Math.max(S.minimum??-1/0,S.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(S.maximum??1/0,S.exclusiveMaximum??1/0)??null,e.isInt=(S.format??``).includes(`int`)||Number.isSafeInteger(S.multipleOf??.5),e.isFinite=!0,e.format=S.format??null});function number$1(e){return _number(ZodNumber$1,e)}const ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber$1.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean$1=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>booleanProcessor(e,t,S,w)});function boolean$1(e){return _boolean(ZodBoolean$1,e)}const ZodNull$1=$constructor(`ZodNull`,(e,t)=>{$ZodNull.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullProcessor(e,t,S,w)});function _null(e){return _null$1(ZodNull$1,e)}const ZodAny$1=$constructor(`ZodAny`,(e,t)=>{$ZodAny.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function any$1(){return _any(ZodAny$1)}const ZodUnknown$1=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function unknown$2(){return _unknown(ZodUnknown$1)}const ZodNever$1=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>neverProcessor(e,t,S,w)});function never(e){return _never(ZodNever$1,e)}const ZodArray$1=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>arrayProcessor(e,t,S,w),e.element=t.element,e.min=(t,S)=>e.check(_minLength(t,S)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,S)=>e.check(_maxLength(t,S)),e.length=(t,S)=>e.check(_length(t,S)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray$1,e,t)}const ZodObject$1=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>objectProcessor(e,t,S,w),defineLazy(e,`shape`,()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend$1(e,t),e.safeExtend=t=>safeExtend(e,t),e.merge=t=>merge$1(e,t),e.pick=t=>pick$2(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional$1,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object$1(e,t){return new ZodObject$1({type:`object`,shape:e??{},...normalizeParams(t)})}function looseObject(e,t){return new ZodObject$1({type:`object`,shape:e,catchall:unknown$2(),...normalizeParams(t)})}const ZodUnion$1=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>unionProcessor(e,t,S,w),e.options=t.options});function union(e,t){return new ZodUnion$1({type:`union`,options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion$1=$constructor(`ZodDiscriminatedUnion`,(e,t)=>{ZodUnion$1.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,S){return new ZodDiscriminatedUnion$1({type:`union`,options:t,discriminator:e,...normalizeParams(S)})}const ZodIntersection$1=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>intersectionProcessor(e,t,S,w)});function intersection(e,t){return new ZodIntersection$1({type:`intersection`,left:e,right:t})}const ZodRecord$1=$constructor(`ZodRecord`,(e,t)=>{$ZodRecord.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>recordProcessor(e,t,S,w),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,S){return new ZodRecord$1({type:`record`,keyType:e,valueType:t,...normalizeParams(S)})}const ZodEnum$1=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>enumProcessor(e,t,S,w),e.enum=t.entries,e.options=Object.values(t.entries);let S=new Set(Object.keys(t.entries));e.extract=(e,w)=>{let E={};for(let w of e)if(S.has(w))E[w]=t.entries[w];else throw Error(`Key ${w} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})},e.exclude=(e,w)=>{let E={...t.entries};for(let t of e)if(S.has(t))delete E[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})}});function _enum(e,t){return new ZodEnum$1({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}const ZodLiteral$1=$constructor(`ZodLiteral`,(e,t)=>{$ZodLiteral.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>literalProcessor(e,t,S,w),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral$1({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>transformProcessor(e,t,S,w),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);S.addIssue=w=>{if(typeof w==`string`)S.issues.push(issue(w,S.value,t));else{let t=w;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=S.value,t.inst??=e,S.issues.push(issue(t))}};let E=t.transform(S.value,S);return E instanceof Promise?E.then(e=>(S.value=e,S)):(S.value=E,S)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}const ZodOptional$1=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional$1({type:`optional`,innerType:e})}const ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}const ZodNullable$1=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullableProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable$1({type:`nullable`,innerType:e})}const ZodDefault$1=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>defaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault$1({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>prefaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nonoptionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const ZodCatch$1=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>catchProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch$1({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>pipeProcessor(e,t,S,w),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}const ZodReadonly$1=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>readonlyProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly$1({type:`readonly`,innerType:e})}const ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>customProcessor(e,t,S,w)});function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}const describe$1=describe$2,meta$1=meta$2;function preprocess$1(e,t){return pipe(transform(e),t)}var import_dist$1=require_dist$2();init_esm$2();const SINGLETON_KEY$1=Symbol.for(`@inkeep/open-knowledge/field-registry`),g$1=globalThis;g$1[SINGLETON_KEY$1]===void 0&&(g$1[SINGLETON_KEY$1]=registry$1());const fieldRegistry=g$1[SINGLETON_KEY$1];function getFieldMeta(e){let t=e;for(let e=0;e<16;e++){if(t==null)return;let e=isZodSchema$1(t)?fieldRegistry.get(t):void 0;if(e!==void 0)return e;let S=t._zod?.def?.innerType;if(S===void 0)return;t=S}}function isZodSchema$1(e){return typeof e==`object`&&!!e&&`_zod`in e&&`parse`in e}const FolderFrontmatterSchema=looseObject({title:string$2().optional(),description:string$2().optional(),tags:array(string$2()).optional()}),FolderRuleSchema=looseObject({match:string$2().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:FolderFrontmatterSchema}),ConfigSchema$1=looseObject({content:looseObject({dir:string$2().register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`.`)}).default({dir:`.`}),appearance:looseObject({theme:_enum([`light`,`dark`,`system`]).register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).optional(),sidebar:looseObject({showHiddenFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1),showAllFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1)}).optional()}).default({}),editor:looseObject({wordWrap:boolean$1().register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).default(!0)}).default({wordWrap:!0}),autoSync:looseObject({enabled:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).nullable().default(null)}).default({enabled:null})}),TRACER_NAME$1=`open-knowledge-config`;async function withConfigSpan(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,async e=>{try{return await S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withConfigSpanSync(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function addConfigSpanEvent(e,t){let S=trace.getActiveSpan();S&&S.addEvent(e,t)}function unwrapToShape(e){let t=e;for(let e=0;e<16;e++){if(t==null||t?._zod?.def?.shape!==void 0)return t;let e=t?._zod?.def?.innerType;if(e===void 0)return t;t=e}return t}function resolveLeafSchema(e,t){let S=e;for(let e of t){S=unwrapToShape(S);let t=S?._zod?.def?.shape;if(!t||(S=t[String(e)],S===void 0))return}return S}function getLeafFieldMeta(e,t){let S=resolveLeafSchema(e,t);if(S!==void 0)return getFieldMeta(S)}function isScopeCompatible(e,t){return e===`either`?!0:e===t}function validatePatchScopes(e,t){let S=null;function w(e,E){if(S!==null||e===void 0)return;if(typeof e==`object`&&e&&!Array.isArray(e)){for(let[t,D]of Object.entries(e))if(w(D,[...E,t]),S!==null)return;return}let D=getLeafFieldMeta(ConfigSchema$1,E);D?.scope!==void 0&&(isScopeCompatible(D.scope,t)||(S={code:`SCOPE_VIOLATION`,path:E,expectedScope:D.scope,actualScope:t}))}for(let[t,E]of Object.entries(e))if(w(E,[t]),S!==null)break;return S}function ensureCollectionAncestors(e,t){for(let S=1;S<t.length;S++){let w=t.slice(0,S);e.hasIn(w)&&((0,import_dist$1.isCollection)(e.getIn(w,!0))||e.deleteIn(w))}}function applyPatchToDocument(e,t){let S=[];function w(t,E){if(t!==void 0){if(t===null){e.deleteIn(E),S.push(E.join(`.`));return}if(Array.isArray(t)){ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`));return}if(typeof t==`object`){for(let[e,S]of Object.entries(t))w(S,[...E,e]);return}ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`))}}for(let[e,S]of Object.entries(t))w(S,[e]);return S}function toConfigIssue(e){return{path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}}const CONFIG_SCHEMA_MAJOR_PATH=`v0`;function resolveNode(e,t){if(t.length===0)return e.contents??null;let S=e.getIn(t,!0);if((0,import_dist$1.isNode)(S))return S;for(let S=t.length-1;S>=0;S--){let w=e.getIn(t.slice(0,S),!0);if((0,import_dist$1.isNode)(w))return w}return e.contents??null}function offsetToLineCol(e,t){let S=1,w=1,E=Math.min(t,e.length);for(let t=0;t<E;t++)e.charCodeAt(t)===10?(S++,w=1):w++;return{line:S,column:w}}function renderSnippet(e,t,S,w,E){let D=e.split(`
|
|
155
155
|
`),O=w-1;if(O<0||O>=D.length)return``;let k=D[O]??``,j=t-(E-1)+k.length,F=Math.max(1,Math.min(S,j)-t),L=[],B=String(O+2).length;for(let e=Math.max(0,O-1);e<=Math.min(D.length-1,O+1);e++){let t=e===O,S=t?`>`:` `,w=String(e+1).padStart(B,` `);if(L.push(`${S} ${w} | ${D[e]??``}`),t){let e=` `.repeat(2+B+3+E-1);L.push(`${e}${`^`.repeat(F)}`)}}return L.join(`
|
|
156
156
|
`)}function locateIssue(e){let t=resolveNode(e.doc,e.path);if(!t)return;let S=t.range;if(!S)return;let[w,,E=w]=S,{line:D,column:O}=offsetToLineCol(e.source,w),k=(0,import_dist$1.isCollection)(t)?renderSnippet(e.source,w,w+1,D,O):renderSnippet(e.source,w,E,D,O);return{file:e.file,line:D,column:O,snippet:k.length>0?k:void 0}}const OK_PROJECT_MARKER=`.ok/config.yml`,LOCAL_DIR=`local`;function stringifyPosition(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?position$1(e.position):`start`in e||`end`in e?position$1(e):`line`in e||`column`in e?point$2(e):``}function point$2(e){return index(e&&e.line)+`:`+index(e&&e.column)}function position$1(e){return point$2(e&&e.start)+`-`+point$2(e&&e.end)}function index(e){return e&&typeof e==`number`?e:1}var VFileMessage=class extends Error{constructor(e,t,S){super(),typeof t==`string`&&(S=t,t=void 0);let w=``,E={},D=!1;if(t&&(E=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?w=e:!E.cause&&e&&(D=!0,w=e.message,E.cause=e),!E.ruleId&&!E.source&&typeof S==`string`){let e=S.indexOf(`:`);e===-1?E.ruleId=S:(E.source=S.slice(0,e),E.ruleId=S.slice(e+1))}if(!E.place&&E.ancestors&&E.ancestors){let e=E.ancestors[E.ancestors.length-1];e&&(E.place=e.position)}let O=E.place&&`start`in E.place?E.place.start:E.place;this.ancestors=E.ancestors||void 0,this.cause=E.cause||void 0,this.column=O?O.column:void 0,this.fatal=void 0,this.file=``,this.message=w,this.line=O?O.line:void 0,this.name=stringifyPosition(E.place)||`1:1`,this.place=E.place||void 0,this.reason=this.message,this.ruleId=E.ruleId||void 0,this.source=E.source||void 0,this.stack=D&&E.cause&&typeof E.cause.stack==`string`?E.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};VFileMessage.prototype.file=``,VFileMessage.prototype.name=``,VFileMessage.prototype.reason=``,VFileMessage.prototype.message=``,VFileMessage.prototype.stack=``,VFileMessage.prototype.column=void 0,VFileMessage.prototype.line=void 0,VFileMessage.prototype.ancestors=void 0,VFileMessage.prototype.cause=void 0,VFileMessage.prototype.fatal=void 0,VFileMessage.prototype.place=void 0,VFileMessage.prototype.ruleId=void 0,VFileMessage.prototype.source=void 0;var require_diff_match_patch=__commonJSMin$1(((e,t)=>{var S=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},w=-1,E=1,D=0;S.Diff=function(e,t){return[e,t]},S.prototype.diff_main=function(e,t,w,E){E===void 0&&(E=this.Diff_Timeout<=0?Number.MAX_VALUE:new Date().getTime()+this.Diff_Timeout*1e3);var O=E;if(e==null||t==null)throw Error(`Null input. (diff_main)`);if(e==t)return e?[new S.Diff(D,e)]:[];w===void 0&&(w=!0);var k=w,j=this.diff_commonPrefix(e,t),F=e.substring(0,j);e=e.substring(j),t=t.substring(j),j=this.diff_commonSuffix(e,t);var L=e.substring(e.length-j);e=e.substring(0,e.length-j),t=t.substring(0,t.length-j);var B=this.diff_compute_(e,t,k,O);return F&&B.unshift(new S.Diff(D,F)),L&&B.push(new S.Diff(D,L)),this.diff_cleanupMerge(B),B},S.prototype.diff_compute_=function(e,t,O,k){var j;if(!e)return[new S.Diff(E,t)];if(!t)return[new S.Diff(w,e)];var F=e.length>t.length?e:t,L=e.length>t.length?t:e,B=F.indexOf(L);if(B!=-1)return j=[new S.Diff(E,F.substring(0,B)),new S.Diff(D,L),new S.Diff(E,F.substring(B+L.length))],e.length>t.length&&(j[0][0]=j[2][0]=w),j;if(L.length==1)return[new S.Diff(w,e),new S.Diff(E,t)];var H=this.diff_halfMatch_(e,t);if(H){var q=H[0],J=H[1],Y=H[2],ee=H[3],te=H[4],ne=this.diff_main(q,Y,O,k),ae=this.diff_main(J,ee,O,k);return ne.concat([new S.Diff(D,te)],ae)}return O&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,k):this.diff_bisect_(e,t,k)},S.prototype.diff_lineMode_=function(e,t,O){var k=this.diff_linesToChars_(e,t);e=k.chars1,t=k.chars2;var j=k.lineArray,F=this.diff_main(e,t,!1,O);this.diff_charsToLines_(F,j),this.diff_cleanupSemantic(F),F.push(new S.Diff(D,``));for(var L=0,B=0,H=0,q=``,J=``;L<F.length;){switch(F[L][0]){case E:H++,J+=F[L][1];break;case w:B++,q+=F[L][1];break;case D:if(B>=1&&H>=1){F.splice(L-B-H,B+H),L=L-B-H;for(var Y=this.diff_main(q,J,!1,O),ee=Y.length-1;ee>=0;ee--)F.splice(L,0,Y[ee]);L+=Y.length}H=0,B=0,q=``,J=``;break}L++}return F.pop(),F},S.prototype.diff_bisect_=function(e,t,D){for(var O=e.length,k=t.length,j=Math.ceil((O+k)/2),F=j,L=2*j,B=Array(L),H=Array(L),q=0;q<L;q++)B[q]=-1,H[q]=-1;B[F+1]=0,H[F+1]=0;for(var J=O-k,Y=J%2!=0,ee=0,te=0,ne=0,ae=0,oe=0;oe<j&&!(new Date().getTime()>D);oe++){for(var se=-oe+ee;se<=oe-te;se+=2){for(var ce=F+se,ue=se==-oe||se!=oe&&B[ce-1]<B[ce+1]?B[ce+1]:B[ce-1]+1,de=ue-se;ue<O&&de<k&&e.charAt(ue)==t.charAt(de);)ue++,de++;if(B[ce]=ue,ue>O)te+=2;else if(de>k)ee+=2;else if(Y){var fe=F+J-se;if(fe>=0&&fe<L&&H[fe]!=-1){var me=O-H[fe];if(ue>=me)return this.diff_bisectSplit_(e,t,ue,de,D)}}}for(var ge=-oe+ne;ge<=oe-ae;ge+=2){for(var fe=F+ge,me=ge==-oe||ge!=oe&&H[fe-1]<H[fe+1]?H[fe+1]:H[fe-1]+1,_e=me-ge;me<O&&_e<k&&e.charAt(O-me-1)==t.charAt(k-_e-1);)me++,_e++;if(H[fe]=me,me>O)ae+=2;else if(_e>k)ne+=2;else if(!Y){var ce=F+J-ge;if(ce>=0&&ce<L&&B[ce]!=-1){var ue=B[ce],de=F+ue-ce;if(me=O-me,ue>=me)return this.diff_bisectSplit_(e,t,ue,de,D)}}}}return[new S.Diff(w,e),new S.Diff(E,t)]},S.prototype.diff_bisectSplit_=function(e,t,S,w,E){var D=e.substring(0,S),O=t.substring(0,w),k=e.substring(S),j=t.substring(w),F=this.diff_main(D,O,!1,E),L=this.diff_main(k,j,!1,E);return F.concat(L)},S.prototype.diff_linesToChars_=function(e,t){var S=[],w={};S[0]=``;function E(e){for(var t=``,E=0,O=-1,k=S.length;O<e.length-1;){O=e.indexOf(`
|
|
157
157
|
`,E),O==-1&&(O=e.length-1);var j=e.substring(E,O+1);(w.hasOwnProperty?w.hasOwnProperty(j):w[j]!==void 0)?t+=String.fromCharCode(w[j]):(k==D&&(j=e.substring(E),O=e.length),t+=String.fromCharCode(k),w[j]=k,S[k++]=j),E=O+1}return t}var D=4e4,O=E(e);return D=65535,{chars1:O,chars2:E(t),lineArray:S}},S.prototype.diff_charsToLines_=function(e,t){for(var S=0;S<e.length;S++){for(var w=e[S][1],E=[],D=0;D<w.length;D++)E[D]=t[w.charCodeAt(D)];e[S][1]=E.join(``)}},S.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var S=0,w=Math.min(e.length,t.length),E=w,D=0;S<E;)e.substring(D,E)==t.substring(D,E)?(S=E,D=S):w=E,E=Math.floor((w-S)/2+S);return E},S.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var S=0,w=Math.min(e.length,t.length),E=w,D=0;S<E;)e.substring(e.length-E,e.length-D)==t.substring(t.length-E,t.length-D)?(S=E,D=S):w=E,E=Math.floor((w-S)/2+S);return E},S.prototype.diff_commonOverlap_=function(e,t){var S=e.length,w=t.length;if(S==0||w==0)return 0;S>w?e=e.substring(S-w):S<w&&(t=t.substring(0,S));var E=Math.min(S,w);if(e==t)return E;for(var D=0,O=1;;){var k=e.substring(E-O),j=t.indexOf(k);if(j==-1)return D;O+=j,(j==0||e.substring(E-O)==t.substring(0,O))&&(D=O,O++)}},S.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var S=e.length>t.length?e:t,w=e.length>t.length?t:e;if(S.length<4||w.length*2<S.length)return null;var E=this;function D(e,t,S){for(var w=e.substring(S,S+Math.floor(e.length/4)),D=-1,O=``,k,j,F,L;(D=t.indexOf(w,D+1))!=-1;){var B=E.diff_commonPrefix(e.substring(S),t.substring(D)),H=E.diff_commonSuffix(e.substring(0,S),t.substring(0,D));O.length<H+B&&(O=t.substring(D-H,D)+t.substring(D,D+B),k=e.substring(0,S-H),j=e.substring(S+B),F=t.substring(0,D-H),L=t.substring(D+B))}return O.length*2>=e.length?[k,j,F,L,O]:null}var O=D(S,w,Math.ceil(S.length/4)),k=D(S,w,Math.ceil(S.length/2)),j;if(!O&&!k)return null;j=k?O&&O[4].length>k[4].length?O:k:O;var F,L,B,H;e.length>t.length?(F=j[0],L=j[1],B=j[2],H=j[3]):(B=j[0],H=j[1],F=j[2],L=j[3]);var q=j[4];return[F,L,B,H,q]},S.prototype.diff_cleanupSemantic=function(e){for(var t=!1,O=[],k=0,j=null,F=0,L=0,B=0,H=0,q=0;F<e.length;)e[F][0]==D?(O[k++]=F,L=H,B=q,H=0,q=0,j=e[F][1]):(e[F][0]==E?H+=e[F][1].length:q+=e[F][1].length,j&&j.length<=Math.max(L,B)&&j.length<=Math.max(H,q)&&(e.splice(O[k-1],0,new S.Diff(w,j)),e[O[k-1]+1][0]=E,k--,k--,F=k>0?O[k-1]:-1,L=0,B=0,H=0,q=0,j=null,t=!0)),F++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),F=1;F<e.length;){if(e[F-1][0]==w&&e[F][0]==E){var J=e[F-1][1],Y=e[F][1],ee=this.diff_commonOverlap_(J,Y),te=this.diff_commonOverlap_(Y,J);ee>=te?(ee>=J.length/2||ee>=Y.length/2)&&(e.splice(F,0,new S.Diff(D,Y.substring(0,ee))),e[F-1][1]=J.substring(0,J.length-ee),e[F+1][1]=Y.substring(ee),F++):(te>=J.length/2||te>=Y.length/2)&&(e.splice(F,0,new S.Diff(D,J.substring(0,te))),e[F-1][0]=E,e[F-1][1]=Y.substring(0,Y.length-te),e[F+1][0]=w,e[F+1][1]=J.substring(te),F++),F++}F++}},S.prototype.diff_cleanupSemanticLossless=function(e){function t(e,t){if(!e||!t)return 6;var w=e.charAt(e.length-1),E=t.charAt(0),D=w.match(S.nonAlphaNumericRegex_),O=E.match(S.nonAlphaNumericRegex_),k=D&&w.match(S.whitespaceRegex_),j=O&&E.match(S.whitespaceRegex_),F=k&&w.match(S.linebreakRegex_),L=j&&E.match(S.linebreakRegex_),B=F&&e.match(S.blanklineEndRegex_),H=L&&t.match(S.blanklineStartRegex_);return B||H?5:F||L?4:D&&!k&&j?3:k||j?2:D||O?1:0}for(var w=1;w<e.length-1;){if(e[w-1][0]==D&&e[w+1][0]==D){var E=e[w-1][1],O=e[w][1],k=e[w+1][1],j=this.diff_commonSuffix(E,O);if(j){var F=O.substring(O.length-j);E=E.substring(0,E.length-j),O=F+O.substring(0,O.length-j),k=F+k}for(var L=E,B=O,H=k,q=t(E,O)+t(O,k);O.charAt(0)===k.charAt(0);){E+=O.charAt(0),O=O.substring(1)+k.charAt(0),k=k.substring(1);var J=t(E,O)+t(O,k);J>=q&&(q=J,L=E,B=O,H=k)}e[w-1][1]!=L&&(L?e[w-1][1]=L:(e.splice(w-1,1),w--),e[w][1]=B,H?e[w+1][1]=H:(e.splice(w+1,1),w--))}w++}},S.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,S.whitespaceRegex_=/\s/,S.linebreakRegex_=/[\r\n]/,S.blanklineEndRegex_=/\n\r?\n$/,S.blanklineStartRegex_=/^\r?\n\r?\n/,S.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,O=[],k=0,j=null,F=0,L=!1,B=!1,H=!1,q=!1;F<e.length;)e[F][0]==D?(e[F][1].length<this.Diff_EditCost&&(H||q)?(O[k++]=F,L=H,B=q,j=e[F][1]):(k=0,j=null),H=q=!1):(e[F][0]==w?q=!0:H=!0,j&&(L&&B&&H&&q||j.length<this.Diff_EditCost/2&&L+B+H+q==3)&&(e.splice(O[k-1],0,new S.Diff(w,j)),e[O[k-1]+1][0]=E,k--,j=null,L&&B?(H=q=!0,k=0):(k--,F=k>0?O[k-1]:-1,H=q=!1),t=!0)),F++;t&&this.diff_cleanupMerge(e)},S.prototype.diff_cleanupMerge=function(e){e.push(new S.Diff(D,``));for(var t=0,O=0,k=0,j=``,F=``,L;t<e.length;)switch(e[t][0]){case E:k++,F+=e[t][1],t++;break;case w:O++,j+=e[t][1],t++;break;case D:O+k>1?(O!==0&&k!==0&&(L=this.diff_commonPrefix(F,j),L!==0&&(t-O-k>0&&e[t-O-k-1][0]==D?e[t-O-k-1][1]+=F.substring(0,L):(e.splice(0,0,new S.Diff(D,F.substring(0,L))),t++),F=F.substring(L),j=j.substring(L)),L=this.diff_commonSuffix(F,j),L!==0&&(e[t][1]=F.substring(F.length-L)+e[t][1],F=F.substring(0,F.length-L),j=j.substring(0,j.length-L))),t-=O+k,e.splice(t,O+k),j.length&&(e.splice(t,0,new S.Diff(w,j)),t++),F.length&&(e.splice(t,0,new S.Diff(E,F)),t++),t++):t!==0&&e[t-1][0]==D?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,k=0,O=0,j=``,F=``;break}e[e.length-1][1]===``&&e.pop();var B=!1;for(t=1;t<e.length-1;)e[t-1][0]==D&&e[t+1][0]==D&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),B=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),B=!0)),t++;B&&this.diff_cleanupMerge(e)},S.prototype.diff_xIndex=function(e,t){var S=0,D=0,O=0,k=0,j;for(j=0;j<e.length&&(e[j][0]!==E&&(S+=e[j][1].length),e[j][0]!==w&&(D+=e[j][1].length),!(S>t));j++)O=S,k=D;return e.length!=j&&e[j][0]===w?k:k+(t-O)},S.prototype.diff_prettyHtml=function(e){for(var t=[],S=/&/g,O=/</g,k=/>/g,j=/\n/g,F=0;F<e.length;F++){var L=e[F][0],B=e[F][1].replace(S,`&`).replace(O,`<`).replace(k,`>`).replace(j,`¶<br>`);switch(L){case E:t[F]=`<ins style="background:#e6ffe6;">`+B+`</ins>`;break;case w:t[F]=`<del style="background:#ffe6e6;">`+B+`</del>`;break;case D:t[F]=`<span>`+B+`</span>`;break}}return t.join(``)},S.prototype.diff_text1=function(e){for(var t=[],S=0;S<e.length;S++)e[S][0]!==E&&(t[S]=e[S][1]);return t.join(``)},S.prototype.diff_text2=function(e){for(var t=[],S=0;S<e.length;S++)e[S][0]!==w&&(t[S]=e[S][1]);return t.join(``)},S.prototype.diff_levenshtein=function(e){for(var t=0,S=0,O=0,k=0;k<e.length;k++){var j=e[k][0],F=e[k][1];switch(j){case E:S+=F.length;break;case w:O+=F.length;break;case D:t+=Math.max(S,O),S=0,O=0;break}}return t+=Math.max(S,O),t},S.prototype.diff_toDelta=function(e){for(var t=[],S=0;S<e.length;S++)switch(e[S][0]){case E:t[S]=`+`+encodeURI(e[S][1]);break;case w:t[S]=`-`+e[S][1].length;break;case D:t[S]=`=`+e[S][1].length;break}return t.join(` `).replace(/%20/g,` `)},S.prototype.diff_fromDelta=function(e,t){for(var O=[],k=0,j=0,F=t.split(/\t/g),L=0;L<F.length;L++){var B=F[L].substring(1);switch(F[L].charAt(0)){case`+`:try{O[k++]=new S.Diff(E,decodeURI(B))}catch{throw Error(`Illegal escape in diff_fromDelta: `+B)}break;case`-`:case`=`:var H=parseInt(B,10);if(isNaN(H)||H<0)throw Error(`Invalid number in diff_fromDelta: `+B);var q=e.substring(j,j+=H);F[L].charAt(0)==`=`?O[k++]=new S.Diff(D,q):O[k++]=new S.Diff(w,q);break;default:if(F[L])throw Error(`Invalid diff operation in diff_fromDelta: `+F[L])}}if(j!=e.length)throw Error(`Delta length (`+j+`) does not equal source text length (`+e.length+`).`);return O},S.prototype.match_main=function(e,t,S){if(e==null||t==null||S==null)throw Error(`Null input. (match_main)`);return S=Math.max(0,Math.min(S,e.length)),e==t?0:e.length?e.substring(S,S+t.length)==t?S:this.match_bitap_(e,t,S):-1},S.prototype.match_bitap_=function(e,t,S){if(t.length>this.Match_MaxBits)throw Error(`Pattern too long for this browser.`);var w=this.match_alphabet_(t),E=this;function D(e,w){var D=e/t.length,O=Math.abs(S-w);return E.Match_Distance?D+O/E.Match_Distance:O?1:D}var O=this.Match_Threshold,k=e.indexOf(t,S);k!=-1&&(O=Math.min(D(0,k),O),k=e.lastIndexOf(t,S+t.length),k!=-1&&(O=Math.min(D(0,k),O)));var j=1<<t.length-1;k=-1;for(var F,L,B=t.length+e.length,H,q=0;q<t.length;q++){for(F=0,L=B;F<L;)D(q,S+L)<=O?F=L:B=L,L=Math.floor((B-F)/2+F);B=L;var J=Math.max(1,S-L+1),Y=Math.min(S+L,e.length)+t.length,ee=Array(Y+2);ee[Y+1]=(1<<q)-1;for(var te=Y;te>=J;te--){var ne=w[e.charAt(te-1)];if(q===0?ee[te]=(ee[te+1]<<1|1)&ne:ee[te]=(ee[te+1]<<1|1)&ne|(H[te+1]|H[te])<<1|1|H[te+1],ee[te]&j){var ae=D(q,te-1);if(ae<=O)if(O=ae,k=te-1,k>S)J=Math.max(1,2*S-k);else break}}if(D(q+1,S)>O)break;H=ee}return k},S.prototype.match_alphabet_=function(e){for(var t={},S=0;S<e.length;S++)t[e.charAt(S)]=0;for(var S=0;S<e.length;S++)t[e.charAt(S)]|=1<<e.length-S-1;return t},S.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error(`patch not initialized`);for(var w=t.substring(e.start2,e.start2+e.length1),E=0;t.indexOf(w)!=t.lastIndexOf(w)&&w.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)E+=this.Patch_Margin,w=t.substring(e.start2-E,e.start2+e.length1+E);E+=this.Patch_Margin;var O=t.substring(e.start2-E,e.start2);O&&e.diffs.unshift(new S.Diff(D,O));var k=t.substring(e.start2+e.length1,e.start2+e.length1+E);k&&e.diffs.push(new S.Diff(D,k)),e.start1-=O.length,e.start2-=O.length,e.length1+=O.length+k.length,e.length2+=O.length+k.length}},S.prototype.patch_make=function(e,t,O){var k,j;if(typeof e==`string`&&typeof t==`string`&&O===void 0)k=e,j=this.diff_main(k,t,!0),j.length>2&&(this.diff_cleanupSemantic(j),this.diff_cleanupEfficiency(j));else if(e&&typeof e==`object`&&t===void 0&&O===void 0)j=e,k=this.diff_text1(j);else if(typeof e==`string`&&t&&typeof t==`object`&&O===void 0)k=e,j=t;else if(typeof e==`string`&&typeof t==`string`&&O&&typeof O==`object`)k=e,j=O;else throw Error(`Unknown call format to patch_make.`);if(j.length===0)return[];for(var F=[],L=new S.patch_obj,B=0,H=0,q=0,J=k,Y=k,ee=0;ee<j.length;ee++){var te=j[ee][0],ne=j[ee][1];switch(!B&&te!==D&&(L.start1=H,L.start2=q),te){case E:L.diffs[B++]=j[ee],L.length2+=ne.length,Y=Y.substring(0,q)+ne+Y.substring(q);break;case w:L.length1+=ne.length,L.diffs[B++]=j[ee],Y=Y.substring(0,q)+Y.substring(q+ne.length);break;case D:ne.length<=2*this.Patch_Margin&&B&&j.length!=ee+1?(L.diffs[B++]=j[ee],L.length1+=ne.length,L.length2+=ne.length):ne.length>=2*this.Patch_Margin&&B&&(this.patch_addContext_(L,J),F.push(L),L=new S.patch_obj,B=0,J=Y,H=q);break}te!==E&&(H+=ne.length),te!==w&&(q+=ne.length)}return B&&(this.patch_addContext_(L,J),F.push(L)),F},S.prototype.patch_deepCopy=function(e){for(var t=[],w=0;w<e.length;w++){var E=e[w],D=new S.patch_obj;D.diffs=[];for(var O=0;O<E.diffs.length;O++)D.diffs[O]=new S.Diff(E.diffs[O][0],E.diffs[O][1]);D.start1=E.start1,D.start2=E.start2,D.length1=E.length1,D.length2=E.length2,t[w]=D}return t},S.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var S=this.patch_addPadding(e);t=S+t+S,this.patch_splitMax(e);for(var O=0,k=[],j=0;j<e.length;j++){var F=e[j].start2+O,L=this.diff_text1(e[j].diffs),B,H=-1;if(L.length>this.Match_MaxBits?(B=this.match_main(t,L.substring(0,this.Match_MaxBits),F),B!=-1&&(H=this.match_main(t,L.substring(L.length-this.Match_MaxBits),F+L.length-this.Match_MaxBits),(H==-1||B>=H)&&(B=-1))):B=this.match_main(t,L,F),B==-1)k[j]=!1,O-=e[j].length2-e[j].length1;else{k[j]=!0,O=B-F;var q=H==-1?t.substring(B,B+L.length):t.substring(B,H+this.Match_MaxBits);if(L==q)t=t.substring(0,B)+this.diff_text2(e[j].diffs)+t.substring(B+L.length);else{var J=this.diff_main(L,q,!1);if(L.length>this.Match_MaxBits&&this.diff_levenshtein(J)/L.length>this.Patch_DeleteThreshold)k[j]=!1;else{this.diff_cleanupSemanticLossless(J);for(var Y=0,ee,te=0;te<e[j].diffs.length;te++){var ne=e[j].diffs[te];ne[0]!==D&&(ee=this.diff_xIndex(J,Y)),ne[0]===E?t=t.substring(0,B+ee)+ne[1]+t.substring(B+ee):ne[0]===w&&(t=t.substring(0,B+ee)+t.substring(B+this.diff_xIndex(J,Y+ne[1].length))),ne[0]!==w&&(Y+=ne[1].length)}}}}}return t=t.substring(S.length,t.length-S.length),[t,k]},S.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,w=``,E=1;E<=t;E++)w+=String.fromCharCode(E);for(var E=0;E<e.length;E++)e[E].start1+=t,e[E].start2+=t;var O=e[0],k=O.diffs;if(k.length==0||k[0][0]!=D)k.unshift(new S.Diff(D,w)),O.start1-=t,O.start2-=t,O.length1+=t,O.length2+=t;else if(t>k[0][1].length){var j=t-k[0][1].length;k[0][1]=w.substring(k[0][1].length)+k[0][1],O.start1-=j,O.start2-=j,O.length1+=j,O.length2+=j}if(O=e[e.length-1],k=O.diffs,k.length==0||k[k.length-1][0]!=D)k.push(new S.Diff(D,w)),O.length1+=t,O.length2+=t;else if(t>k[k.length-1][1].length){var j=t-k[k.length-1][1].length;k[k.length-1][1]+=w.substring(0,j),O.length1+=j,O.length2+=j}return w},S.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,O=0;O<e.length;O++)if(!(e[O].length1<=t)){var k=e[O];e.splice(O--,1);for(var j=k.start1,F=k.start2,L=``;k.diffs.length!==0;){var B=new S.patch_obj,H=!0;for(B.start1=j-L.length,B.start2=F-L.length,L!==``&&(B.length1=B.length2=L.length,B.diffs.push(new S.Diff(D,L)));k.diffs.length!==0&&B.length1<t-this.Patch_Margin;){var q=k.diffs[0][0],J=k.diffs[0][1];q===E?(B.length2+=J.length,F+=J.length,B.diffs.push(k.diffs.shift()),H=!1):q===w&&B.diffs.length==1&&B.diffs[0][0]==D&&J.length>2*t?(B.length1+=J.length,j+=J.length,H=!1,B.diffs.push(new S.Diff(q,J)),k.diffs.shift()):(J=J.substring(0,t-B.length1-this.Patch_Margin),B.length1+=J.length,j+=J.length,q===D?(B.length2+=J.length,F+=J.length):H=!1,B.diffs.push(new S.Diff(q,J)),J==k.diffs[0][1]?k.diffs.shift():k.diffs[0][1]=k.diffs[0][1].substring(J.length))}L=this.diff_text2(B.diffs),L=L.substring(L.length-this.Patch_Margin);var Y=this.diff_text1(k.diffs).substring(0,this.Patch_Margin);Y!==``&&(B.length1+=Y.length,B.length2+=Y.length,B.diffs.length!==0&&B.diffs[B.diffs.length-1][0]===D?B.diffs[B.diffs.length-1][1]+=Y:B.diffs.push(new S.Diff(D,Y))),H||e.splice(++O,0,B)}}},S.prototype.patch_toText=function(e){for(var t=[],S=0;S<e.length;S++)t[S]=e[S];return t.join(``)},S.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var O=e.split(`
|
|
@@ -362,7 +362,7 @@ $2`).split(`
|
|
|
362
362
|
`;return F.join(H)},table(e,t,S,w){let E=` `,D=S.enter(`table`),O=[],k=[],j=e.children??[];for(let e of j){let t=e.children??[],E=[],D=[];for(let e of t){let t=S.enter(`tableCell`),O=S.enter(`phrasing`),k=S.containerPhrasing(e,{...w,before:` `,after:` `});O(),t(),E.push(k);let j=e.data?.sourcePadding;D.push(j&&typeof j.left==`number`&&typeof j.right==`number`?{left:j.left,right:j.right}:null)}O.push(E),k.push(D)}D();let F=e.align??[],L=e.data?.sourceDashCounts,B=O[0]?.length??0,H=O.slice(1).reduce((e,t)=>Math.max(e,t.length),0),q=Math.max(B,H,F.length),J=[];for(let e=0;e<q;e++){let t=F[e],S=``,w=``;t===`center`?(S=`:`,w=`:`):t===`left`?S=`:`:t===`right`&&(w=`:`);let E=L?.[e],D=typeof E==`number`&&E>=1?E:1;J.push(S+`-`.repeat(D)+w)}let Y=(e,t)=>{let S=[];for(let w=0;w<q;w++){let E=e[w]??``,D=t[w]??{left:1,right:1};S.push(` `.repeat(D.left)+E+` `.repeat(D.right))}return`|${S.join(`|`)}|`},ee=Array.from({length:q},()=>null);if(O.length===0)return Y(J,ee);let te=[];te.push(Y(O[0],k[0]??[])),te.push(Y(J,ee));for(let e=1;e<O.length;e++)te.push(Y(O[e],k[e]??[]));return te.join(`
|
|
363
363
|
`)},mdxJsxFlowElement(e,t,S,w){let E=e,D=E.data?.sourceRaw;if(typeof D==`string`)return D;let O=E.data?.htmlBoundary;if(O&&typeof O.opener==`string`&&typeof O.closer==`string`){let e=S.containerFlow({type:`root`,children:E.children??[]},w);return`${O.opener}\n\n${e}\n\n${O.closer}`}let k=E.name??``,j=serializeMdxJsxAttrs(E.attributes??[]);if(!E.children||E.children.length===0)return k?j?`<${k} ${j} />`:`<${k} />`:``;let F=j?`<${k} ${j}>`:`<${k}>`,L=`</${k}>`;return`${F}\n\n${S.containerFlow({type:`root`,children:E.children},w)}\n\n${L}`},mark(e,t,S,w){let E=S.createTracker(w),D=S.enter(`mark`),O=E.move(`==`);return O+=S.containerPhrasing(e,{before:O,after:`==`,...E.current()}),O+=E.move(`==`),D(),O},comment(e,t,S,w){let E=e.data?.sourceForm,D=E===`html`?`<!-- `:`%%`,O=E===`html`?` -->`:`%%`,k=S.createTracker(w),j=S.enter(`comment`),F=k.move(D);return F+=S.containerPhrasing(e,{before:F,after:O,...k.current()}),F+=k.move(O),j(),F},commentBlock(e,t,S,w){let E=S.createTracker(w),D=S.enter(`commentBlock`),O=e.children??[],k=e.data?.sourceForm,j=e.data?.sourceLayout,F=O.length===1&&O[0]?.type===`paragraph`;if(k===`html`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`<!-- `,after:` -->`,...E.current()});return D(),`<!-- ${t} -->`}if(j===`inline`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`%% `,after:` %%`,...E.current()});return D(),`%% ${t} %%`}let L=S.containerFlow(e,E.current());return D(),`%%\n\n${L}\n\n%%`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;if(typeof t==`string`)return t;let S=e.name??``,w=serializeMdxJsxAttrs(e.attributes??[]);return w?`<${S} ${w} />`:`<${S}/>`},rawMdxFallback(e){return e.value??``},blockquote(e,t,S,w){let E=S.enter(`blockquote`),D=S.createTracker(w);D.move(`> `),D.shift(2);let O=S.containerFlow(e,D.current());E();let k=e.data?.sourceMarkerSpacings,j=0;return S.indentLines(O,(e,t,S)=>S?`>`:k?.[j++]===`none`?`>${e}`:`> ${e}`)}};function serializeMdxJsxAttrs(e){let t=[];for(let S of e){if(S.type===`mdxJsxExpressionAttribute`){t.push(`{${S.value}}`);continue}let e=S.name;if(S.value===null||S.value===void 0){t.push(e);continue}if(typeof S.value==`string`){if(S.value.includes(`"`)){let w=S.value.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t.push(`${e}={"${w}"}`)}else t.push(`${e}="${S.value}"`);continue}t.push(`${e}={${S.value.value}}`)}return t.join(` `)}function emitLinkTitle(e,t,S=` `){return t===`single`?`${S}'${e.replace(/'/g,`\\'`)}'`:t===`paren`?`${S}(${e.replace(/[()]/g,`\\$&`)})`:`${S}"${e.replace(/"/g,`\\"`)}"`}function formatLinkUrl(e){if(!e)return``;let t=0,S=!0;for(let w of e)w===`(`?t++:w===`)`&&(t--,t<0&&(S=!1));return t!==0&&(S=!1),S?e:e.replace(/[\\()]/g,`\\$&`)}function escapeEntityAmpersands(e){return e.replace(/(?<!\\)&(?=[A-Za-z][A-Za-z0-9]*;|#[0-9]+;|#[xX][0-9A-Fa-f]+;)/g,`\\&`)}function safeText(e,t,S){let w=e.unsafe;e.unsafe=w.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`||e.character==="`"));let E;try{E=e.safe(t,S)}finally{e.unsafe=w}return escapeEntityAmpersands(E)}function formatFileSize(e){if(!Number.isFinite(e)||e<0)return``;if(e<1024)return`${e} B`;let t=[`KiB`,`MiB`,`GiB`,`TiB`],S=e/1024,w=0;for(;S>=1024&&w<t.length-1;)S/=1024,w+=1;return`${S.toFixed(1).replace(/\.0$/,``)} ${t[w]}`}var MarkdownManager=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;parseCtx={current:{}};constructor(e){this.schema=getSchema(e.extensions),this.handlers=buildMdastToPmHandlers(this.schema,this.parseCtx);let{nodeHandlers:t,markHandlers:S}=buildPmToMdastHandlers(this.schema);this.pmNodeHandlers=t,this.pmMarkHandlers=S,this.parseProcessor=createParseProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=createSerializeProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers,toMarkdownHandlers})}parse(e,t){if(!e.trim())return{type:`doc`,content:[{type:`paragraph`,content:[]}]};this.parseCtx.current=t??{};try{return parseMd(e,this.parseProcessor).toJSON()}finally{this.parseCtx.current={}}}parseToMdast(e){return e.trim()?parseMdToMdast(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e,t){return e.trim()?parseWithFallback(e,{parse:e=>this.parse(e,t)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e){let t;try{t=this.schema.nodeFromJSON(e)}catch(t){let S=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(S,{cause:t})}return serializeMd(t,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}};const registry=createRegistry();function destructureAttrs(e,t){let S=new Map;for(let e of t)S.set(e.name,e);let w={};for(let t of e){if(t.type===`mdxJsxExpressionAttribute`)continue;let e=t.name,E=S.get(e);if(t.value===null||t.value===void 0){w[e]=!0;continue}if(typeof t.value==`string`){if(E?.type===`number`){let S=Number(t.value);w[e]=Number.isNaN(S)?t.value:S}else E?.type===`boolean`?w[e]=t.value===`true`:w[e]=t.value;continue}let D=t.value.value;try{w[e]=JSON.parse(D)}catch{w[e]=D}}return w}function hasDirtyDescendant(e){let t=!1;return e.descendants(e=>t||e.type.name===`jsxInline`?!1:e.type.name===`jsxComponent`&&e.attrs.sourceDirty?(t=!0,!1):!0),t}function effectiveDirty(e){return e.attrs.sourceDirty||hasDirtyDescendant(e)}function isEmptyMdastParagraph(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0?!0:t.every(e=>e.type===`text`&&e.value===``)}function withInlineCodeData(e,t){if(!t)return e;let S={};return t.sourceFenceChar&&(S.sourceFenceChar=t.sourceFenceChar),typeof t.sourceFenceLength==`number`&&(S.sourceFenceLength=t.sourceFenceLength),Object.keys(S).length===0?e:{...e,data:S}}function wrapAsInlineCode(e,t){if(e.length===0)return withInlineCodeData({type:`inlineCode`,value:``},t);if(e.every(e=>e.type===`text`))return withInlineCodeData({type:`inlineCode`,value:e.map(e=>e.value).join(``)},t);if(e.length===1&&`children`in e[0]){let S=e[0];return{...S,children:[wrapAsInlineCode(S.children,t)]}}return withInlineCodeData({type:`inlineCode`,value:extractTextFromMdastNodes(e)},t)}function extractTextFromMdastNodes(e){let t=``;for(let S of e)S.type===`text`?t+=S.value:`children`in S&&Array.isArray(S.children)?t+=extractTextFromMdastNodes(S.children):`value`in S&&typeof S.value==`string`&&(t+=S.value);return t}const WIKI_EMBED_IMAGE_EXTS=IMAGE_EXTENSIONS;function buildMdastToPmHandlers(e,t){let S=e.nodes,w=e.marks,E={};S.paragraph&&(E.paragraph=(e,t,w)=>{let E=w.all(e).flat(),D=E.some(e=>e?.isBlock&&!e?.isInline),O=E.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(D&&!O)return E.length===1?E[0]:E;if(D&&O){let e=E.filter(e=>!e?.isBlock||e?.isInline),t=E.filter(e=>e?.isBlock&&!e?.isInline),w=[],D=S.paragraph.createAndFill(null,e.length>0?e:null);return D&&w.push(D),w.push(...t),w.length===1?w[0]:w}return S.paragraph.createAndFill(null,E.length>0?E:null)}),S.blockquote&&(E.blockquote=toPmNode(S.blockquote,e=>({sourceMarkerSpacings:e.data?.sourceMarkerSpacings??null}))),S.tableCell&&(E.tableCell=(e=>(t,w,E)=>{let D=E.all(t).flat();if(D.length>0&&S.paragraph){let t=S.paragraph.create(null,D);return e.createAndFill(null,[t])}return e.createAndFill(null,null)})(S.tableCell)),S.tableRow&&(E.tableRow=toPmNode(S.tableRow)),S.table&&S.tableRow&&S.tableCell&&(E.table=(e,t,w)=>{let E=e.align??[],D=e.children??[],O=[];for(let e=0;e<D.length;e++){let t=D[e];if(t.type!==`tableRow`)continue;let k=t.children??[],j=[];for(let t=0;t<k.length;t++){let D=k[t];if(D.type!==`tableCell`)continue;let O=w.all(D).flat(),F=O.length>0&&S.paragraph?[S.paragraph.create(null,O)]:null,L=E[t]??null,B=e===0&&S.tableHeader?S.tableHeader:S.tableCell,H=D.data?.sourcePadding??null,q=B.createAndFill({align:L,sourcePadding:H},F);q&&j.push(q)}let F=S.tableRow.createAndFill(null,j.length>0?j:null);F&&O.push(F)}let k=e.data?.sourceDashCounts??null;return S.table.createAndFill({sourceDashCounts:k},O.length>0?O:null)}),S.image&&(E.image=e=>{let w=e.url??``,E=normalizeDocRelativeAssetUrl(w,t.current.sourcePath);return S.image.createAndFill({src:E,alt:e.alt??null,title:e.title??null,sourceUrl:E===w?null:w})},S.imageReference?E.imageReference=e=>S.imageReference.createAndFill({alt:e.alt??``,label:e.label??e.identifier??``,identifier:e.identifier??``,referenceType:e.referenceType??`shortcut`}):E.imageReference=e=>S.image.createAndFill({src:``,alt:e.alt??null,title:null})),w.escapeMark&&(E.text=t=>{let S=t.value??``,E=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!S&&!E)return null;if(E){let t=S.replaceAll(`\xA0`,` `);return w.sourceLiteral?e.text(t,[w.sourceLiteral.create({sourceRaw:E})]):e.text(t)}let D=t.data?.escapedChars,O=t.data?.entityRefSpans;if(!D?.length&&!O?.length)return e.text(S.replaceAll(`\xA0`,` `));let k=[...(D??[]).map(e=>({kind:`escape`,offset:e.offset,length:1})),...(O??[]).map(e=>({kind:`entity`,offset:e.offset,length:e.length,raw:e.raw}))];k.sort((e,t)=>e.offset-t.offset);let j=[],F=0;for(let t of k){if(t.offset>F){let w=S.slice(F,t.offset).replaceAll(`\xA0`,` `);w&&j.push(e.text(w))}if(t.offset<S.length){let E=S.slice(t.offset,t.offset+t.length).replaceAll(`\xA0`,` `);E&&(t.kind===`escape`?j.push(e.text(E,[w.escapeMark.create()])):w.sourceLiteral?j.push(e.text(E,[w.sourceLiteral.create({sourceRaw:t.raw})])):j.push(e.text(E))),F=t.offset+t.length}}if(F<S.length){let t=S.slice(F).replaceAll(`\xA0`,` `);t&&j.push(e.text(t))}return j.length===1?j[0]:j}),w.code&&(E.inlineCode=t=>e.text(t.value,[w.code.create({sourceFenceChar:t.data?.sourceFenceChar??"`",sourceFenceLength:typeof t.data?.sourceFenceLength==`number`?t.data.sourceFenceLength:1})]));let D=w.strike??w.delete;if(D&&(E.delete=toPmMark(D)),w.highlight&&(E.mark=toPmMark(w.highlight)),w.comment&&(E.comment=toPmMark(w.comment,e=>({sourceForm:e.data?.sourceForm??`percent`}))),S.commentBlock&&(E.commentBlock=toPmNode(S.commentBlock,e=>({sourceForm:e.data?.sourceForm??`percent`,sourceLayout:e.data?.sourceLayout??`block`}))),w.emphasis&&(E.emphasis=toPmMark(w.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),w.strong&&(E.strong=toPmMark(w.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),S.heading&&(E.heading=toPmNode(S.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`,sourceTrailingHashes:e.data?.sourceTrailingHashes??null,sourceUnderlineLength:e.data?.sourceUnderlineLength??null,sourceContiguousNext:e.data?.sourceContiguousNext??!1}))),S.codeBlock&&(E.code=t=>{let w=t.value?[e.text(t.value)]:[];return S.codeBlock.createAndFill({language:t.lang??null,meta:t.meta??null,fenceDelimiter:t.data?.sourceFenceChar??"`",fenceLength:t.data?.sourceFenceLength??3,sourceStyle:t.data?.sourceStyle??`fenced`},w)}),S.thematicBreak&&(E.thematicBreak=e=>S.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),S.hardBreak&&(E.break=e=>S.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`})),S.list&&(E.list=toPmNode(S.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),S.listItem&&(E.listItem=toPmNode(S.listItem,e=>({checked:e.checked??null,spread:!!e.spread}))),w.link){let t=w.sourceLiteral;E.link=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[](${S.url??``})`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:S.url??``,title:S.title??null,linkStyle:S.data?.sourceStyle??`inline`,refLabel:null,sourceUrlForm:S.data?.sourceUrlForm??null,sourceTitleMarker:S.data?.sourceTitleMarker??null});return O.map(e=>e.mark(k.addToSet(e.marks)))},E.linkReference=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[${S.label??``}][${S.identifier??``}]`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:``,title:null,linkStyle:S.referenceType??`shortcut`,refLabel:S.label??S.identifier??null});return O.map(e=>e.mark(k.addToSet(e.marks)))}}S.htmlBlock&&(E.html=e=>S.htmlBlock.createAndFill({content:e.value??``}));let O=S.linkDefinition??S.linkRefDef;if(O){let e=!!O.spec.attrs?.url,t=!!O.spec.attrs?.href,S=!!O.spec.attrs?.identifier,w=!!O.spec.attrs?.sourceLayout,D=!!O.spec.attrs?.sourceTitleMarker;E.definition=E=>{let k={title:E.title??null};return S&&(k.identifier=E.identifier??``),k.label=E.label??E.identifier??``,e?k.url=E.url??``:t&&(k.href=E.url??``),w&&(k.sourceLayout=E.data?.sourceLayout??null),D&&(k.sourceTitleMarker=E.data?.sourceTitleMarker??null),O.createAndFill(k)}}if(S.jsxComponent){let w=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};E.mdxJsxFlowElement=(e,E,D)=>{let O=e.name??``,k=registry.getOrWildcard(O),j=destructureAttrs(e.attributes,k.props);if(O===`CommonMarkImage`&&typeof j.src==`string`){let e=j.src,S=normalizeDocRelativeAssetUrl(e,t.current.sourcePath);S!==e&&(j.src=S,j.sourceUrl=e)}let F=D.all(e).flat();return S.jsxComponent.createAndFill({componentName:O,kind:`element`,attributes:e.attributes,sourceRaw:w(e.data)??``,sourceDirty:!1,props:j},F.length?F:void 0)};let D=(e,t)=>{let S=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return S&&typeof S.value==`string`?S.value:null};E.mdxJsxTextElement=t=>{if(t.name===`InlineMath`&&S.mathInline){let e=D(t,`formula`)??``,w=D(t,`id`);return S.mathInline.create({formula:e,id:w??null})}if(t.name===`Tag`&&S.tag){let e=D(t,`value`)??``;return S.tag.create({value:e})}if(S.jsxInline){let E=w(t.data)??``;return S.jsxInline.createAndFill({},E?[e.text(E)]:null)}return S.jsxComponent.createAndFill({sourceRaw:w(t.data)??``})},E.mdxFlowExpression=e=>{let t=w(e.data)??`{${e.value??``}}`;return S.jsxComponent.createAndFill({kind:`expression`,sourceRaw:t,sourceDirty:!1})},E.mdxTextExpression=t=>{let S=w(t.data)??`{${t.value??``}}`;return e.text(S)}}return S.wikiLink&&(E.wikiLink=e=>S.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null})),S.tag&&(E.tag=e=>S.tag.createAndFill({value:e.value})),S.wikiLinkEmbed&&(E.wikiLinkEmbed=(E,D)=>{let O=E.data?.target??``,k=E.data?.alias??null,j=E.data?.anchor??null,F=extensionOf(O),{resolveEmbed:L,sourcePath:B}=t.current,H=L&&B?L(O,B)??null:null,q=H?`/${H}`:O,J=D?.type===`paragraph`&&Array.isArray(D.children)&&D.children.length===1;if(J&&WIKI_EMBED_IMAGE_EXTS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedImage`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedImage`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,alt:k??O,target:O,anchor:j,alias:k}});if(J&&VIDEO_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedVideo`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedVideo`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&AUDIO_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedAudio`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedAudio`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&FILE_ATTACHMENT_EXTENSIONS.has(F)&&S.jsxComponent&®istry.has(`WikiEmbedFile`)){let{resolveSize:e}=t.current,w=e&&B?e(O,B)??null:null,E=w===null?null:formatFileSize(w);return S.jsxComponent.createAndFill({componentName:`WikiEmbedFile`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,target:O,anchor:j,alias:k,size:E}})}let Y=k||(j?`${O}#${j}`:O);if(WIKI_EMBED_EXTENSIONS.has(F)&&w.link){let t=w.link.create({href:q,title:null,linkStyle:`inline`,refLabel:null,sourceForm:`wikiembed`,target:O,anchor:j,alias:k});return e.text(Y,[t])}if(w.link){let t=w.link.create({href:O,title:null,linkStyle:`inline`,refLabel:null});return e.text(Y,[t])}throw Error("[wikiLinkEmbed handler] schema lacks `link` mark — cannot dispatch without violating the STOP rule against emitting PM wikiLinkEmbed server-side")}),S.mathInline&&(E.inlineMath=e=>S.mathInline.create({formula:e.value??``})),E.math||=t=>{let w=t.value==null?`«unknown:${t.type}»`:t.value;return S.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled block mdast: ${t.type}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${t.type}`},w?[e.text(w)]:null)):null},E.inlineMath||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),t.value==null?e.text(`«unknown:${t.type}»`):e.text(t.value)),S.footnoteReference?E.footnoteReference=e=>S.footnoteReference.create({identifier:e.identifier,label:e.label??e.identifier}):E.footnoteReference||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteReference`,reason:`FootnoteReference extension missing — recovering [^id] source`})),e.text(`[^${t.label??t.identifier}]`)),S.footnoteDefinition?E.footnoteDefinition=toPmNode(S.footnoteDefinition,e=>{let t=e;return{identifier:t.identifier,label:t.label??t.identifier}}):E.footnoteDefinition||=t=>{console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteDefinition`,reason:`FootnoteDefinition extension missing — recovering [^id]: marker`}));let w=`[^${t.label??t.identifier}]: `;return S.paragraph?S.paragraph.create(null,e.text(w)):null},E.rawMdxFallbackMdast=t=>{if(!S.rawMdxFallback)return null;let w=t.position?{start:t.position.start?.offset??0,end:t.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.originalType,reason:`Unhandled mdast: ${t.originalType}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${t.originalType}`,originalSpan:w},t.value?[e.text(t.value)]:null)},E}function buildPmToMdastHandlers(e){let t={},S={},w=e.nodes,E=e.marks;w.paragraph&&(t.paragraph=fromPmNode(`paragraph`)),w.blockquote&&(t.blockquote=fromPmNode(`blockquote`,e=>{let t=e.attrs.sourceMarkerSpacings,S={};return Array.isArray(t)&&t.length>0&&(S.sourceMarkerSpacings=t),Object.keys(S).length>0?{data:S}:{}})),w.heading&&(t.heading=fromPmNode(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle,sourceTrailingHashes:e.attrs.sourceTrailingHashes??void 0,sourceUnderlineLength:e.attrs.sourceUnderlineLength??void 0,sourceContiguousNext:e.attrs.sourceContiguousNext===!0?!0:void 0}}))),w.codeBlock&&(t.codeBlock=e=>{let t=e.attrs.sourceStyle===`indented`?`indented`:`fenced`;return{type:`code`,lang:t===`indented`?null:e.attrs.language??null,meta:t===`indented`?null:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength,sourceStyle:t}}}),w.thematicBreak&&(t.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),w.hardBreak&&(t.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle}})),w.list&&(t.list=fromPmNode(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),w.listItem&&(t.listItem=(e,t,S)=>{let w=S.all(e),E=w.length>1&&isEmptyMdastParagraph(w[0])?w.slice(1):w;return{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,children:E}}),w.table&&(t.table=(e,t,S)=>{let w=S.all(e),E=[],D=e.firstChild;D&&D.forEach(e=>{let t=e.attrs.align;E.push(t===`left`||t===`right`||t===`center`?t:null)});let O=w.filter(e=>e.type===`tableRow`),k=e.attrs.sourceDashCounts,j=Array.isArray(k)&&k.length>0?{sourceDashCounts:k}:void 0,F={type:`table`,align:E,children:O};return j&&(F.data=j),F}),w.tableRow&&(t.tableRow=fromPmNode(`tableRow`));let D=e=>{let t=e.attrs.sourcePadding,S={};return typeof t==`object`&&t&&typeof t.left==`number`&&typeof t.right==`number`&&(S.sourcePadding=t),Object.keys(S).length>0?{data:S}:{}};if(w.tableCell&&(t.tableCell=fromPmNode(`tableCell`,D)),w.tableHeader&&(t.tableHeader=fromPmNode(`tableCell`,D)),w.image&&(t.image=e=>({type:`image`,url:e.attrs.sourceUrl??e.attrs.src,alt:e.attrs.alt,title:e.attrs.title})),w.imageReference&&(t.imageReference=e=>{let t=e.attrs.label??``,S=e.attrs.identifier??t;return{type:`imageReference`,alt:e.attrs.alt??``,identifier:S,label:t||S,referenceType:e.attrs.referenceType??`shortcut`}}),w.htmlBlock&&(t.htmlBlock=e=>({type:`html`,value:e.attrs.content})),w.linkDefinition??w.linkRefDef){let e=w.linkDefinition?`linkDefinition`:`linkRefDef`;t[e]=e=>{let t={},S=e.attrs.sourceLayout;(S===`multiline`||S===`inline`)&&(t.sourceLayout=S);let w=e.attrs.sourceTitleMarker;(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w);let E={type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title};return Object.keys(t).length>0&&(E.data=t),E}}if(w.jsxComponent&&(t.jsxComponent=(e,t,S)=>{if(e.attrs.kind===`expression`)return{type:`html`,value:e.attrs.sourceRaw??``};let w=e.attrs.componentName||null,E=Array.isArray(e.attrs.attributes)?e.attrs.attributes:[];return!effectiveDirty(e)&&e.attrs.sourceRaw?{type:`mdxJsxFlowElement`,name:w,attributes:E,children:[],data:{sourceRaw:String(e.attrs.sourceRaw)}}:registry.getOrWildcard(w??`*`).serialize(e,{all:e=>S.all(e),registry,serializeChildren:()=>{throw Error(`SerializeContext.serializeChildren is not available in the PM→mdast handler. Compat descriptors that need markdown-byte body rendering must emit a marker mdast node and let the to-markdown handler render the body via state.containerFlow.`)}})}),w.rawMdxFallback&&(t.rawMdxFallback=e=>{let t=e.textContent??``,S=typeof e.attrs.reason==`string`?e.attrs.reason:``,w=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:S,originalSpan:w&&typeof w==`object`&&`start`in w&&`end`in w?{start:Number(w.start)||0,end:Number(w.end)||0}:{start:0,end:0}}}}),w.jsxInline&&(t.jsxInline=e=>{let t=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(t)}}}),w.mathInline&&(t.mathInline=e=>{let t=e.attrs.formula??``,S=e.attrs.id;return typeof S==`string`&&S.length>0?{type:`mdxJsxTextElement`,name:`InlineMath`,attributes:[{type:`mdxJsxAttribute`,name:`formula`,value:t},{type:`mdxJsxAttribute`,name:`id`,value:S}],children:[]}:{type:`inlineMath`,value:t}}),w.wikiLink&&(t.wikiLink=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLink`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),w.tag&&(t.tag=e=>({type:`tag`,value:String(e.attrs.value??``)})),w.wikiLinkEmbed&&(t.wikiLinkEmbed=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),E.emphasis&&(S.emphasis=fromPmMark(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.strong&&(S.strong=fromPmMark(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.code&&(S.code=(e,t,S)=>{let w=e.attrs.sourceFenceChar,E=e.attrs.sourceFenceLength;return wrapAsInlineCode(S,{sourceFenceChar:w,sourceFenceLength:E})}),E.strike??E.delete){let e=E.strike?`strike`:`delete`;S[e]=fromPmMark(`delete`)}return E.highlight&&(S.highlight=fromPmMark(`mark`)),E.comment&&(S.comment=fromPmMark(`comment`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`}}))),w.commentBlock&&(t.commentBlock=fromPmNode(`commentBlock`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`,sourceLayout:e.attrs.sourceLayout===`inline`?`inline`:`block`}}))),w.footnoteReference&&(t.footnoteReference=e=>{let t=String(e.attrs.identifier??``);return{type:`footnoteReference`,identifier:t,label:e.attrs.label?String(e.attrs.label):t}}),w.footnoteDefinition&&(t.footnoteDefinition=fromPmNode(`footnoteDefinition`,e=>({identifier:String(e.attrs.identifier??``),label:e.attrs.label?String(e.attrs.label):String(e.attrs.identifier??``)}))),E.link&&(S.link=(e,t,S)=>{if(e.attrs.sourceForm===`wikiembed`){let t=typeof e.attrs.target==`string`&&e.attrs.target.length>0?e.attrs.target:e.attrs.href??``,S=typeof e.attrs.anchor==`string`&&e.attrs.anchor.length>0?e.attrs.anchor:null,w=typeof e.attrs.alias==`string`&&e.attrs.alias.length>0?e.attrs.alias:null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}let w=e.attrs.linkStyle;if(w===`autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`autolink`}};if(w===`gfm-autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`gfm-autolink`}};if(w===`inline`||!w){let t={};e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let w=e.attrs.sourceTitleMarker;return(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w),{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:S,...Object.keys(t).length>0?{data:t}:{}}}return{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:w,children:S}}),E.escapeMark&&(S.escapeMark=(e,t,S)=>{for(let e of S)if(e.type===`text`&&e.value){let t=e;t.data=t.data??{},t.data.escapedChars=t.data.escapedChars??[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return S.length===1?S[0]:S}),E.sourceLiteral&&(S.sourceLiteral=(e,t,S)=>{let w=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(S.length===1&&S[0]?.type===`text`){let e=S[0],t=w||e.value;return isValidSourceLiteralRaw(t,e.value)&&(e.data=e.data??{},e.data.sourceRaw=t),e}return{type:`text`,value:S.filter(e=>e.type===`text`).map(e=>e.value??``).join(``)||w}}),{nodeHandlers:t,markHandlers:S}}const COMBINING_MARK_RE=/\p{M}+/gu,NON_LETTER_OR_NUMBER_RE=/[^\p{L}\p{N}]+/gu,EDGE_HYPHENS_RE=/^-+|-+$/g;function toWikiLinkSlug(e){return e.trim().normalize(`NFKD`).replace(COMBINING_MARK_RE,``).toLowerCase().replace(NON_LETTER_OR_NUMBER_RE,`-`).replace(EDGE_HYPHENS_RE,``)}function disambiguateSlug(e,t){let S=t.get(e)??0;return t.set(e,S+1),S===0?e:`${e}-${S}`}function getHeadingSlug(e,t){let S=toWikiLinkSlug(e);return S?disambiguateSlug(S,t):``}const MICROMARK_MDX_EXT=mdx(),FROM_MARKDOWN_MDX_EXT=mdxFromMarkdown(),TO_MARKDOWN_MDX_EXT=mdxToMarkdown(),PLACEHOLDER_BODY=`Body content here.`,PLACEHOLDER_MERMAID_FENCE_BODY=`graph LR
|
|
364
364
|
A --> B`;function getCanonicalDescriptors(){return builtInComponents.filter(e=>e.surface===`canonical`&&e.name!==`*`)}function getAgentCanonicalDescriptors(){return getCanonicalDescriptors().filter(e=>resolveKind(e)!==`fence`)}function resolveKind(e){return e.name===`MermaidFence`?`fence`:e.hasChildren?`jsx-block`:`jsx-void`}function projectLite(e){return{id:e.name,displayName:e.displayName??e.name,description:e.description??``,kind:resolveKind(e)}}function exampleValueFor(e){if(e.hidden!==!0&&e.type!==`reactnode`){if(`defaultValue`in e&&e.defaultValue!==void 0)return e.defaultValue;if(e.type===`enum`)return e.enumValues[0];if(e.type===`string`)return``;if(e.type===`number`)return 0;if(e.type===`boolean`)return!1}}function shouldEmitProp(e,t){return!(e.omitOnDefault===!0&&`defaultValue`in e&&Object.is(e.defaultValue,t)||e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&t===``)}function buildAttributes(e){let t=[];for(let S of e.props){let e=exampleValueFor(S);e!==void 0&&shouldEmitProp(S,e)&&t.push(propToMdxJsxAttribute(S.name,e))}return t}function buildBodyChildren(e){return fromMarkdown(e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_BODY,{extensions:[MICROMARK_MDX_EXT],mdastExtensions:[FROM_MARKDOWN_MDX_EXT]}).children}function synthesizeExample(e){let t=resolveKind(e),S;if(t===`fence`)S={type:`code`,lang:`mermaid`,meta:null,value:e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_MERMAID_FENCE_BODY};else{let w=buildAttributes(e),E=t===`jsx-block`?buildBodyChildren(e):[];S={type:`mdxJsxFlowElement`,name:e.name,attributes:w,children:E}}return toMarkdown({type:`root`,children:[S]},{extensions:[TO_MARKDOWN_MDX_EXT]}).trimEnd()}function projectParams(e){let t=[];for(let S of e.props){if(S.hidden===!0)continue;let e={name:S.name,type:S.type,required:S.required};S.description!==void 0&&(e.description=S.description),S.advanced===!0&&(e.advanced=!0),S.omitOnDefault===!0&&(e.omitOnDefault=!0),S.type===`enum`&&(e.values=S.enumValues,S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue)),S.type===`string`&&(S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.language!==void 0&&(e.language=S.language),S.accept!==void 0&&(e.accept=S.accept)),S.type===`boolean`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.type===`number`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),t.push(e)}return t}function projectFull(e){return{...projectLite(e),example:synthesizeExample(e),params:projectParams(e)}}function renderInventoryFooter(){return[``,"**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `get_components({ ids })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",``,...getAgentCanonicalDescriptors().map(projectLite).map(e=>`- \`${e.id}\` (${e.kind}) — ${e.description}`)].join(`
|
|
365
|
-
`)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`,`audio`,`pdf`,`text`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionPrincipalSchema=object$1({name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({message:string$2().optional(),writers:array(SaveVersionWriterSchema).optional(),principal:SaveVersionPrincipalSchema.optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1),versionTag:string$2().min(1).optional()}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1)}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),versionTag:string$2().optional(),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),error:string$2().optional(),pausedReason:string$2().optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]??`bot`:`bot`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
365
|
+
`)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`,`audio`,`pdf`,`text`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionPrincipalSchema=object$1({name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({message:string$2().optional(),writers:array(SaveVersionWriterSchema).optional(),principal:SaveVersionPrincipalSchema.optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1),versionTag:string$2().min(1).optional()}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),DuplicatePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),DuplicatePathSuccessSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),duplicatedDocNames:array(string$2().min(1))}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1)}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),versionTag:string$2().optional(),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),error:string$2().optional(),pausedReason:string$2().optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]??`bot`:`bot`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
366
366
|
`)){let e=S.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let S=JSON.parse(e.slice(17));if(typeof S==`object`&&S&&`id`in S&&typeof S.id==`string`&&`name`in S&&typeof S.name==`string`&&`docs`in S&&Array.isArray(S.docs)&&S.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in S)||typeof S.colorSeed==`string`)){let e=S;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(S)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
|
|
367
367
|
`)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let S;try{S=JSON.parse(e.slice(18))}catch{return null}if(typeof S!=`object`||!S)return null;let w=S,E=w.kind,D=w.metadata;if(typeof D!=`object`||!D)return null;let O=typeof w.docName==`string`?w.docName:null,k=typeof w.size==`number`&&Number.isFinite(w.size)?w.size:null;if(E===`bridge-merge-loss`){let e=D;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:O,size:k,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(E===`external-change-rescue`){let e=D;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:O,size:k,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:S,...w}=e,E={...w};return t&&t.length>0&&(E.summaries=t),S&&S.length>0&&(E.previous_paths=S),`${OK_ACTOR_PREFIX}${JSON.stringify(E)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,S=typeof e.agent_session==`string`?e.agent_session:null,w;if(typeof e.writer_id==`string`&&e.writer_id.length>0)w=e.writer_id;else if(S)w=`agent-${S}`;else if(t)w=t;else switch(e.display_name){case`File System`:w=`file-system`;break;case`Git (upstream)`:w=`git-upstream`;break;default:w=`openknowledge-service`}let E=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,D=parsePreviousPaths(e);return{v:1,writer_id:w,principal:t,agent_session:S,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...E&&E.length>0?{summaries:E}:{},...D&&D.length>0?{previous_paths:D}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let S of e.previous_paths){if(typeof S!=`object`||!S)continue;let e=S;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
368
368
|
`)){let e=S.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let w;try{w=JSON.parse(e.slice(10))}catch{continue}if(typeof w!=`object`||!w)continue;let E=parseOkActorObject(w);E&&t.push(E)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let S=stripLineBreaks(e);if(t.length===0)return S;if(t.length>=2)return`${S} (${t.length} edits)`;let[w]=t;if(w===void 0)return S;let E=stripLineBreaks(w),D=`${S} — ${E}`;if(D.length<=72)return D;let O=`${S} — `,k=72-O.length-1;return k<=0?D.slice(0,72):`${O}${E.slice(0,k)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_err_helpers=__commonJSMin$1(((e,t)=>{let S=e=>e&&typeof e.message==`string`,w=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return S(t)?t:void 0}else return S(t)?t:void 0},E=(e,t)=>{if(!S(e))return``;let D=e.stack||``;if(t.has(e))return D+`
|
|
@@ -1133,7 +1133,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
|
|
|
1133
1133
|
`)),E.removeListener(`error`,ae),q.setSocket(E,j,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(q),q.on(`close`,()=>{this.clients.delete(q),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ne,this)})),F(q,w)}};function te(e,t){for(let S of Object.keys(t))e.on(S,t[S]);return function(){for(let S of Object.keys(t))e.removeListener(S,t[S])}}function ne(e){e._state=2,e.emit(`close`)}function ae(){this.destroy()}function oe(e,t,S,E){S||=w.STATUS_CODES[t],E={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(S),...E},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${w.STATUS_CODES[t]}\r\n`+Object.keys(E).map(e=>`${e}: ${E[e]}`).join(`\r
|
|
1134
1134
|
`)+`\r
|
|
1135
1135
|
\r
|
|
1136
|
-
`+S)}function se(e,t,S,w,E,D){if(e.listenerCount(`wsClientError`)){let w=Error(E);Error.captureStackTrace(w,se),e.emit(`wsClientError`,w,S,t)}else oe(S,w,E,D)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM(require_websocket_server(),1);init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1),import_src=require_src$14(),import_src$1=require_src$13(),import_src$2=require_src$4(),import_src$3=require_src$3(),import_src$4=require_src$2(),import_src$5=require_src$1(),import_src$6=require_src();init_esm$1();var import_lib=__toESM$1(require_lib(),1),import_yazl=__toESM$1(require_yazl(),1),import_shell_quote=__toESM$1(require_shell_quote(),1),import_ignore=__toESM$1(require_ignore(),1);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let S;return S=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,S),S}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(S=>({...S,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:S,...w}=t;return w})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let S=t.getLocalState()??{},w=e(S.agentFocus??{});t.setLocalState({...S,agentFocus:w})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let S=0;this.mutateAgentPresence(w=>{let E=Date.now(),D={};for(let[t,O]of Object.entries(w)){if(E-O.ts>=2e4&&t!==e){S++;continue}D[t]=O}return D[e]=t,D})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),S>0&&this.log.info({evictedCount:S,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(S=>{if(!S[e])return S;t=!0;let{[e]:w,...E}=S;return E})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let S=[],w=!1,E=this.mutateAgentPresence(E=>{let D=E[e];if(!D)return E;w=!0;let O=Date.now();return S.push({currentDoc:D.currentDoc,ts:O}),{...E,[e]:{...D,mode:t,ts:O}}}),D=S[0];E&&D?this.log.debug({agentId:e,action:`touchMode`,currentDoc:D.currentDoc,ts:D.ts,mode:t},`[agent-presence] touchMode`):w||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;let E=Date.now();return t=E,{...S,[e]:{...w,ts:E}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let S=t.getLocalState()??{},w=e(S.agentPresence??{});return t.setLocalState({...S,agentPresence:w}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics$1.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$4.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let S=new import_src$6.BasicTracerProvider({resource:e,spanProcessors:[new import_src$6.BatchSpanProcessor(new import_src$3.OTLPTraceExporter)]});trace.setGlobalTracerProvider(S),propagation.setGlobalPropagator(new import_src$1.W3CTraceContextPropagator);let w=new import_src$5.MeterProvider({resource:e,readers:[new import_src$5.PeriodicExportingMetricReader({exporter:new import_src$2.OTLPMetricExporter})]});metrics$1.setGlobalMeterProvider(w),tracerProvider=S,meterProvider=w,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics$1.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics$1.getMeter(TRACER_NAME)}async function withSpan(e,t,S){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await S(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,S){return getTracer().startActiveSpan(e,t??{},e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,S,w){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:S,"body.bytes":t.length,"doc.name":e.guid}},()=>{let S=e.getXmlFragment(`default`),E=e.getText(`source`),D=E.toString(),{body:O}=stripFrontmatter(t),k=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":O.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(O,buildParseOpts(w))),j=schema.nodeFromJSON(k);D!==t&&applyFastDiff(E,D,t),updateYFragment(e,S,j,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,S){let w=e.getXmlFragment(`default`),E=e.getText(`source`),{body:D}=stripFrontmatter(t),O=mdManager.parseWithFallback(D,buildParseOpts(S)),k=schema.nodeFromJSON(O),j=E.toString();j!==t&&(E.delete(0,j.length),E.insert(0,t)),updateYFragment(e,w,k,{mapping:new Map,isOMark:new Map})}function deriveFragmentFromYtext(e,t){let S=e.getXmlFragment(`default`),{body:w}=stripFrontmatter(e.getText(`source`).toString()),E=mdManager.parseWithFallback(w,buildParseOpts(t));updateYFragment(e,S,schema.nodeFromJSON(E),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(e)??0)+1;this.seqs.set(e,S);let w=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:S});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(e,S),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let w=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});S.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,S);let w=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:S,branch:e});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,S)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,w);let E=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:w,docName:e,sv:Buffer.from(t).toString(`base64`)});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,S]of this.latestDiskAckSVs)e[t]=Buffer.from(S).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w);let E=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:w,docName:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w);let E=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:w,path:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$8=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function applyAgentMarkdownWrite(e,t,S,w){withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":S,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,S,w))}function applyAgentMarkdownWriteInner(e,t,S,w){try{let{frontmatter:E,body:D}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:O,body:k}=stripFrontmatter(t),j,F;switch(S){case`replace`:j=O||E,F=k;break;case`prepend`:j=E,F=D.length>0?`${k}\n\n${D}`:k;break;case`append`:j=E,F=D.length>0?`${D}\n\n${k}`:k;break}j!==E&&recordFrontmatterEditSurface(`mcp-write`),composeAndWriteRawBody(e,prependFrontmatter(j,F),`agent`,w)}catch(w){throw log$8.error({err:w,docName:e.name,position:S,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),w}}function applyAgentUndo(e,t,S){return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let w=applyAgentUndoInner(e,t,S);return setActiveSpanAttributes({"agent.undo_effective":w}),w})}function applyAgentUndoInner(e,t,S){let{dc:w,um:E,undoOrigin:D}=e,O=w.document,k=!1;return O.transact(()=>{if(t===`last`){if(E.undoStack.length===0)return;E.undo(),k=!0}else for(;E.undoStack.length>0;)E.undo(),k=!0;deriveFragmentFromYtext(O,S)},D),k}function createSessionOrigin(e,t,S,w,E){let D={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(D.agent_type=t),S!==void 0&&(D.principal=S),w!==void 0&&(D.display_name=w),E!==void 0&&(D.color_seed=E),Object.freeze(D);let O={source:`local`,skipStoreHooks:!1,context:D};return Object.freeze(O),O}function createUndoOrigin(e,t){let S={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(S.agent_type=t),Object.freeze(S);let w={source:`local`,skipStoreHooks:!1,context:S};return Object.freeze(w),w}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,S]of this.sessions)e.endsWith(t)&&(yield S)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,S){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let w=this.sessionKey(e,t),E=this.sessions.get(w);if(E)return E;let D=this.pendingSessions.get(w);if(D)return D;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let O=this._createSession(e,t,S);this.pendingSessions.set(w,O);try{let e=await O;return this.sessions.set(w,e),e}finally{this.pendingSessions.delete(w)}}async _createSession(e,t,S){let w=S?.clientName,E=t.startsWith(`agent-`)?t.slice(6):t,D=createSessionOrigin(E,w,S?.principalId,S?.displayName,S?.colorSeed),O=createUndoOrigin(E,w),k={session_id:E,...w===void 0?{}:{agent_type:w},...S?.clientName===void 0?{}:{client_name:S.clientName},...S?.principalId===void 0?{}:{principalId:S.principalId}},j=await this.hocuspocus.openDirectConnection(e,k),F=new UndoManager([j.document.getText(`source`),j.document.getMap(`agent-flash`)],{trackedOrigins:new Set([D]),captureTimeout:500,captureTransaction:e=>e.origin!==O,ignoreRemoteMapChanges:!0}),L=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return F.on(`stack-item-added`,L),F.on(`stack-item-updated`,L),log$8.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:j,origin:D,undoOrigin:O,um:F,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,S){try{try{t.um.destroy()}catch(e){log$8.error({err:e,...S},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$8.error({err:e,...S},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let S=this.sessionKey(e,t),w=this.sessions.get(S);w&&(await this.cleanupSession(S,w,{docName:e,agentId:t}),log$8.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,S=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));S.length>0&&await Promise.allSettled(S.map(e=>this.pendingSessions.get(e)));let w=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of w){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,S=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of S){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,S,w){let E=e.doc;if(!E)return;let D=++_effectCounter,O=E.getMap(`agent-effects`),k=F=>{e.unobserve(k),E.off(`destroy`,j);let L=`${t}:${D}`,B={sessionId:t,timestamp:Date.now(),delta:F.delta,agent_type:w??`agent`,color_seed:S??t};try{E.transact(()=>{if(O.set(L,B),O.size>RING_BUFFER_LIMIT){let e=[...O.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,O.size-RING_BUFFER_LIMIT))O.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let S=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:S})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},j=()=>{e.unobserve(k)};e.observe(k),E.once(`destroy`,j)}function collectItemsInDeleteSet(e,t,S){iterateDeletedStructs(e,t,e=>{e instanceof Item&&S.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let S=[],w=[],E=t.doc,D=new Set,O=new Set;E&&E.transact(t=>{collectItemsInDeleteSet(t,e.insertions,D),collectItemsInDeleteSet(t,e.deletions,O)});let k=``,j=``,F=0,L=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,E=t.length,B=D.has(e),H=O.has(e);e.deleted?H&&(w.push({position:F,content:t,length:E}),k+=t,F+=E):(j+=t,B?S.push({position:L,content:t,length:E}):(k+=t,F+=E),L+=E)}return{insertions:S,deletions:w,before:k,after:j}}function synthesizeStackItemDiffText(e,t,S){let{before:w,after:E}=synthesizeStackItemDiff(e,t);return w===E?``:createPatch(S,w,E,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=0,O=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&w.has(e)&&(D+=t),E.has(e)&&(O+=t)}return{additions:D,deletions:O}}function listAgentActivity(e,t){let S=[],w=null,E=!1;for(let D of e.sessionsForConnection(t)){if(E=!0,!w){let e=D.origin.context,S=typeof e?.agent_type==`string`?e.agent_type:void 0,E=typeof e?.color_seed==`string`?e.color_seed:t,O=iconFromClientName(S),k=AGENT_ICON_COLORS[O]??colorFromSeed(E);w={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:k,icon:O,connectionId:t}}let e=D.docName,O=D.um,k=D.dc.document.getText(`source`),j=[];for(let e=0;e<O.undoStack.length;e++){let t=O.undoStack[e],S=getBurstTs(t),{additions:w,deletions:E}=countStackItemChanges(t,k);j.push({stackIndex:e,ts:S,additions:w,deletions:E})}if(j.length===0)continue;j.sort((e,t)=>t.stackIndex-e.stackIndex);let F=j.reduce((e,t)=>e+t.additions,0),L=j.reduce((e,t)=>e+t.deletions,0),B=Math.max(...j.map(e=>e.ts));S.push({docName:e,additionsTotal:F,deletionsTotal:L,lastTs:B,bursts:j})}return E?(S.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:w,files:S}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let S=getCounters(e);S.lastUserTxGen=++globalCounter,S.lastUserTxAtMs=Date.now()},S=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,S),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,S)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let S=counters.get(e);return S?S.settledGen>S.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let S=counters.get(e);return!S||S.lastUserTxAtMs===null?null:Math.max(0,t-S.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,S=Date.now()){let w=rateKey(e,t),E=lastEmitMs.get(w),D=readDebounceMs();if(E!==void 0&&S-E<D)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)S-t>=D&&lastEmitMs.delete(e);return lastEmitMs.set(w,S),!0}function shouldEmitBridgeToleranceApplied(e,t,S=Date.now()){let w=toleranceRateKey(e,t),E=lastToleranceEmitMs.get(w),D=readDebounceMs();return E!==void 0&&S-E<D?!1:(lastToleranceEmitMs.set(w,S),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let S=e??`__nodoc__`,w=lastPathBEmitMs.get(S),E=readDebounceMs();if(w!==void 0&&t-w<E)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,S]of lastPathBEmitMs)t-S>=E&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(S,t),!0}function emitObserverAPathBFired(e,t){let S=shouldEmitObserverAPathBFired(e,t);return S||incrementObserverAPathBFiresSuppressed(),S}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,S){let w=normalizeBridge(e),E=normalizeBridge(t);if(w===E){if(e!==t){let w=detectAppliedToleranceClasses(e,t);for(let e of w)shouldEmitBridgeToleranceApplied(S.site,e,S.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:S.site,class:e})))}return!0}let D={site:S.site,origin:S.origin,docName:S.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${w.slice(0,300)}\n frag: ${E.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!S.suppressDevThrow)throw new BridgeInvariantViolationError(D);if(!shouldEmitBridgeInvariantViolation(S.site,S.docName,S.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let O=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(D,{verbose:O}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,S){let w={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return S&&Object.assign(w,S),w}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,S){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,S)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,S){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,S)})}function tracedAppendFileSync(e,t,S){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,S)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
1136
|
+
`+S)}function se(e,t,S,w,E,D){if(e.listenerCount(`wsClientError`)){let w=Error(E);Error.captureStackTrace(w,se),e.emit(`wsClientError`,w,S,t)}else oe(S,w,E,D)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM(require_websocket_server(),1);init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1),import_src=require_src$14(),import_src$1=require_src$13(),import_src$2=require_src$4(),import_src$3=require_src$3(),import_src$4=require_src$2(),import_src$5=require_src$1(),import_src$6=require_src();init_esm$1();var import_lib=__toESM$1(require_lib(),1),import_yazl=__toESM$1(require_yazl(),1),import_shell_quote=__toESM$1(require_shell_quote(),1),import_ignore=__toESM$1(require_ignore(),1);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let S;return S=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,S),S}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(S=>({...S,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:S,...w}=t;return w})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let S=t.getLocalState()??{},w=e(S.agentFocus??{});t.setLocalState({...S,agentFocus:w})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let S=0;this.mutateAgentPresence(w=>{let E=Date.now(),D={};for(let[t,O]of Object.entries(w)){if(E-O.ts>=2e4&&t!==e){S++;continue}D[t]=O}return D[e]=t,D})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),S>0&&this.log.info({evictedCount:S,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(S=>{if(!S[e])return S;t=!0;let{[e]:w,...E}=S;return E})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let S=[],w=!1,E=this.mutateAgentPresence(E=>{let D=E[e];if(!D)return E;w=!0;let O=Date.now();return S.push({currentDoc:D.currentDoc,ts:O}),{...E,[e]:{...D,mode:t,ts:O}}}),D=S[0];E&&D?this.log.debug({agentId:e,action:`touchMode`,currentDoc:D.currentDoc,ts:D.ts,mode:t},`[agent-presence] touchMode`):w||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;let E=Date.now();return t=E,{...S,[e]:{...w,ts:E}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let S=t.getLocalState()??{},w=e(S.agentPresence??{});return t.setLocalState({...S,agentPresence:w}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics$1.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$4.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let S=new import_src$6.BasicTracerProvider({resource:e,spanProcessors:[new import_src$6.BatchSpanProcessor(new import_src$3.OTLPTraceExporter)]});trace.setGlobalTracerProvider(S),propagation.setGlobalPropagator(new import_src$1.W3CTraceContextPropagator);let w=new import_src$5.MeterProvider({resource:e,readers:[new import_src$5.PeriodicExportingMetricReader({exporter:new import_src$2.OTLPMetricExporter})]});metrics$1.setGlobalMeterProvider(w),tracerProvider=S,meterProvider=w,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics$1.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics$1.getMeter(TRACER_NAME)}async function withSpan(e,t,S){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await S(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,S){return getTracer().startActiveSpan(e,t??{},e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,S,w){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:S,"body.bytes":t.length,"doc.name":e.guid}},()=>{let S=e.getXmlFragment(`default`),E=e.getText(`source`),D=E.toString(),{body:O}=stripFrontmatter(t),k=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":O.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(O,buildParseOpts(w))),j=schema.nodeFromJSON(k);D!==t&&applyFastDiff(E,D,t),updateYFragment(e,S,j,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,S){let w=e.getXmlFragment(`default`),E=e.getText(`source`),{body:D}=stripFrontmatter(t),O=mdManager.parseWithFallback(D,buildParseOpts(S)),k=schema.nodeFromJSON(O),j=E.toString();j!==t&&(E.delete(0,j.length),E.insert(0,t)),updateYFragment(e,w,k,{mapping:new Map,isOMark:new Map})}function deriveFragmentFromYtext(e,t){let S=e.getXmlFragment(`default`),{body:w}=stripFrontmatter(e.getText(`source`).toString()),E=mdManager.parseWithFallback(w,buildParseOpts(t));updateYFragment(e,S,schema.nodeFromJSON(E),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(e)??0)+1;this.seqs.set(e,S);let w=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:S});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(e,S),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let w=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});S.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,S);let w=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:S,branch:e});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,S)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,w);let E=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:w,docName:e,sv:Buffer.from(t).toString(`base64`)});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,S]of this.latestDiskAckSVs)e[t]=Buffer.from(S).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w);let E=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:w,docName:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w);let E=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:w,path:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$8=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function applyAgentMarkdownWrite(e,t,S,w){withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":S,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,S,w))}function applyAgentMarkdownWriteInner(e,t,S,w){try{let{frontmatter:E,body:D}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:O,body:k}=stripFrontmatter(t),j,F;switch(S){case`replace`:j=O||E,F=k;break;case`prepend`:j=E,F=D.length>0?`${k}\n\n${D}`:k;break;case`append`:j=E,F=D.length>0?`${D}\n\n${k}`:k;break}j!==E&&recordFrontmatterEditSurface(`mcp-write`),composeAndWriteRawBody(e,prependFrontmatter(j,F),`agent`,w)}catch(w){throw log$8.error({err:w,docName:e.name,position:S,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),w}}function applyAgentUndo(e,t,S){return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let w=applyAgentUndoInner(e,t,S);return setActiveSpanAttributes({"agent.undo_effective":w}),w})}function applyAgentUndoInner(e,t,S){let{dc:w,um:E,undoOrigin:D}=e,O=w.document,k=!1;return O.transact(()=>{if(t===`last`){if(E.undoStack.length===0)return;E.undo(),k=!0}else for(;E.undoStack.length>0;)E.undo(),k=!0;deriveFragmentFromYtext(O,S)},D),k}function createSessionOrigin(e,t,S,w,E){let D={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(D.agent_type=t),S!==void 0&&(D.principal=S),w!==void 0&&(D.display_name=w),E!==void 0&&(D.color_seed=E),Object.freeze(D);let O={source:`local`,skipStoreHooks:!1,context:D};return Object.freeze(O),O}function createUndoOrigin(e,t){let S={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(S.agent_type=t),Object.freeze(S);let w={source:`local`,skipStoreHooks:!1,context:S};return Object.freeze(w),w}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,S]of this.sessions)e.endsWith(t)&&(yield S)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,S){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let w=this.sessionKey(e,t),E=this.sessions.get(w);if(E)return E;let D=this.pendingSessions.get(w);if(D)return D;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let O=this._createSession(e,t,S);this.pendingSessions.set(w,O);try{let e=await O;return this.sessions.set(w,e),e}finally{this.pendingSessions.delete(w)}}async _createSession(e,t,S){let w=S?.clientName,E=t.startsWith(`agent-`)?t.slice(6):t,D=createSessionOrigin(E,w,S?.principalId,S?.displayName,S?.colorSeed),O=createUndoOrigin(E,w),k={session_id:E,...w===void 0?{}:{agent_type:w},...S?.clientName===void 0?{}:{client_name:S.clientName},...S?.principalId===void 0?{}:{principalId:S.principalId}},j=await this.hocuspocus.openDirectConnection(e,k),F=new UndoManager([j.document.getText(`source`),j.document.getMap(`agent-flash`)],{trackedOrigins:new Set([D]),captureTimeout:500,captureTransaction:e=>e.origin!==O,ignoreRemoteMapChanges:!0}),L=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return F.on(`stack-item-added`,L),F.on(`stack-item-updated`,L),log$8.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:j,origin:D,undoOrigin:O,um:F,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,S){try{try{t.um.destroy()}catch(e){log$8.error({err:e,...S},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$8.error({err:e,...S},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let S=this.sessionKey(e,t),w=this.sessions.get(S);w&&(await this.cleanupSession(S,w,{docName:e,agentId:t}),log$8.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,S=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));S.length>0&&await Promise.allSettled(S.map(e=>this.pendingSessions.get(e)));let w=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of w){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,S=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of S){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,S,w){let E=e.doc;if(!E)return;let D=++_effectCounter,O=E.getMap(`agent-effects`),k=F=>{e.unobserve(k),E.off(`destroy`,j);let L=`${t}:${D}`,B={sessionId:t,timestamp:Date.now(),delta:F.delta,agent_type:w??`agent`,color_seed:S??t};try{E.transact(()=>{if(O.set(L,B),O.size>RING_BUFFER_LIMIT){let e=[...O.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,O.size-RING_BUFFER_LIMIT))O.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let S=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:S})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},j=()=>{e.unobserve(k)};e.observe(k),E.once(`destroy`,j)}function collectItemsInDeleteSet(e,t,S){iterateDeletedStructs(e,t,e=>{e instanceof Item&&S.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let S=[],w=[],E=t.doc,D=new Set,O=new Set;E&&E.transact(t=>{collectItemsInDeleteSet(t,e.insertions,D),collectItemsInDeleteSet(t,e.deletions,O)});let k=``,j=``,F=0,L=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,E=t.length,B=D.has(e),H=O.has(e);e.deleted?H&&(w.push({position:F,content:t,length:E}),k+=t,F+=E):(j+=t,B?S.push({position:L,content:t,length:E}):(k+=t,F+=E),L+=E)}return{insertions:S,deletions:w,before:k,after:j}}function synthesizeStackItemDiffText(e,t,S){let{before:w,after:E}=synthesizeStackItemDiff(e,t);return w===E?``:createPatch(S,w,E,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=0,O=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&w.has(e)&&(D+=t),E.has(e)&&(O+=t)}return{additions:D,deletions:O}}function listAgentActivity(e,t){let S=[],w=null,E=!1;for(let D of e.sessionsForConnection(t)){if(E=!0,!w){let e=D.origin.context,S=typeof e?.agent_type==`string`?e.agent_type:void 0,E=typeof e?.color_seed==`string`?e.color_seed:t,O=iconFromClientName(S),k=AGENT_ICON_COLORS[O]??colorFromSeed(E);w={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:k,icon:O,connectionId:t}}let e=D.docName,O=D.um,k=D.dc.document.getText(`source`),j=[];for(let e=0;e<O.undoStack.length;e++){let t=O.undoStack[e],S=getBurstTs(t),{additions:w,deletions:E}=countStackItemChanges(t,k);j.push({stackIndex:e,ts:S,additions:w,deletions:E})}if(j.length===0)continue;j.sort((e,t)=>t.stackIndex-e.stackIndex);let F=j.reduce((e,t)=>e+t.additions,0),L=j.reduce((e,t)=>e+t.deletions,0),B=Math.max(...j.map(e=>e.ts));S.push({docName:e,additionsTotal:F,deletionsTotal:L,lastTs:B,bursts:j})}return E?(S.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:w,files:S}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let S=getCounters(e);S.lastUserTxGen=++globalCounter,S.lastUserTxAtMs=Date.now()},S=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,S),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,S)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let S=counters.get(e);return S?S.settledGen>S.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let S=counters.get(e);return!S||S.lastUserTxAtMs===null?null:Math.max(0,t-S.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,S=Date.now()){let w=rateKey(e,t),E=lastEmitMs.get(w),D=readDebounceMs();if(E!==void 0&&S-E<D)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)S-t>=D&&lastEmitMs.delete(e);return lastEmitMs.set(w,S),!0}function shouldEmitBridgeToleranceApplied(e,t,S=Date.now()){let w=toleranceRateKey(e,t),E=lastToleranceEmitMs.get(w),D=readDebounceMs();return E!==void 0&&S-E<D?!1:(lastToleranceEmitMs.set(w,S),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let S=e??`__nodoc__`,w=lastPathBEmitMs.get(S),E=readDebounceMs();if(w!==void 0&&t-w<E)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,S]of lastPathBEmitMs)t-S>=E&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(S,t),!0}function emitObserverAPathBFired(e,t){let S=shouldEmitObserverAPathBFired(e,t);return S||incrementObserverAPathBFiresSuppressed(),S}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,S){let w=normalizeBridge(e),E=normalizeBridge(t);if(w===E){if(e!==t){let w=detectAppliedToleranceClasses(e,t);for(let e of w)shouldEmitBridgeToleranceApplied(S.site,e,S.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:S.site,class:e})))}return!0}let D={site:S.site,origin:S.origin,docName:S.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${w.slice(0,300)}\n frag: ${E.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!S.suppressDevThrow)throw new BridgeInvariantViolationError(D);if(!shouldEmitBridgeInvariantViolation(S.site,S.docName,S.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let O=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(D,{verbose:O}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,S){let w={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return S&&Object.assign(w,S),w}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,S){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,S)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,S){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,S)})}function tracedAppendFileSync(e,t,S){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,S)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,S){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,S)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
1137
1137
|
`);for(let e=0;e<t.length;e++){let S=t[e]??``;if(S.length!==0&&/^\s+$/.test(S))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function validateConfigContent(e,t){return e===`__config__/okignore`?validateOkignore(t):validateConfigYaml(t)}function defaultLkgFor(e){return e===`__config__/okignore`?``:serializedDefaults()}function validateConfigYaml(e){let t=(0,import_dist$1.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let S=t.toJSON()??{},w=ConfigSchema$1.safeParse(S);return w.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:w.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function loadConfigDoc(e,t,S){let w=e.getText(`source`);if(w.length>0)return;let E=configDocAbsPath(t,S),D=``;if(existsSync(E))try{D=readFileSync(E,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[config] Could not read ${E}: ${t}. Seeding with empty content.`),D=``}let O=validateConfigContent(t,D);!O.ok&&D.length>0&&getLogger(`config-persistence`).warn({docName:t,path:E},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{D.length>0&&w.insert(0,D)},CONFIG_VALIDATION_REVERT_ORIGIN),O.ok&&D.length>0?S.lkgCache.set(t,D):S.lkgCache.set(t,defaultLkgFor(t))}async function atomicWriteConfig(e,t){await tracedMkdir(dirname(e),{recursive:!0});let S=`${e}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(S,t,`utf-8`),await tracedRename(S,e)}catch(e){try{tracedUnlinkSync(S)}catch{}throw e}}async function storeConfigDoc(e,t,S,w){return withConfigSpan(`config.persist`,{"config.scope":configScopeAttr(t),"config.transport":`fs`},async E=>{let D=await storeConfigDocInner(e,t,S,w);return E.setAttribute(`config.outcome`,persistOutcomeAttr(D)),D})}function persistOutcomeAttr(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function storeConfigDocInner(e,t,S,w){if(S===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let E=e.getText(`source`),D=E.toString();if(D.length===0)return`no-op`;let O=w.lkgCache.get(t);if(O!==void 0&&D===O)return`no-op`;let k=configScopeAttr(t),j=withConfigSpanSync(`config.validate`,{"config.scope":k,"config.validation.layer":`L3`},e=>{let S=validateConfigContent(t,D);return e.setAttribute(`config.outcome`,S.ok?`success`:`rejected`),S.ok||emitSchemaInvalidIssueEvents(S.error),S});if(!j.ok)return await withConfigSpan(`config.revert`,{"config.scope":k,"config.outcome":`reverted`},async()=>{let S=O??defaultLkgFor(t);e.transact(()=>{E.length>0&&E.delete(0,E.length),E.insert(0,S)},CONFIG_VALIDATION_REVERT_ORIGIN),O===void 0&&w.lkgCache.set(t,S),t===`__config__/okignore`&&isKnownConfigError(j.error)&&okignoreRejectionCounter().add(1,{"error.code":j.error.code}),w.onConfigRejected?.(t,j.error)}),`reverted`;let F=configDocAbsPath(t,w);try{await tracedMkdir(dirname(F),{recursive:!0})}catch(e){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] could not create parent dir for ${F}: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${F}: ${S}`}),`write-failed`}try{return await withFileLock(`${F}.lock`,async()=>{let S=null;try{S=readFileSync(F,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] could not read config for reconciliation: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${F}: ${S}`}),`write-failed`}}if(S!==null&&O!==void 0&&S!==O){if(validateConfigContent(t,S).ok)return e.transact(()=>{E.length>0&&E.delete(0,E.length),E.insert(0,S)},CONFIG_FILE_WATCHER_ORIGIN),w.lkgCache.set(t,S),getLogger(`config-persistence`).info({docName:t,path:F},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:F},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(F,D)}catch(e){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] write-failed at ${F}: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${F}: ${S}`}),`write-failed`}return w.lkgCache.set(t,D),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] lock timeout at ${F}: ${e.message}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,S,w){if(!e)return`no-op`;let E=w.lkgCache.get(t);if(E!==void 0&&E===S)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let w=validateConfigContent(t,S);return e.setAttribute(`config.outcome`,w.ok?`success`:`rejected`),w.ok||emitSchemaInvalidIssueEvents(w.error),w});if(!O.ok)return t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),w.onConfigRejected?.(t,O.error),`rejected`;let k=e.getText(`source`);return e.transact(()=>{k.length>0&&k.delete(0,k.length),k.insert(0,S)},CONFIG_FILE_WATCHER_ORIGIN),w.lkgCache.set(t,S),`applied`}let pendingContributors=new Map;function recordContributor(e,t,S,w,E,D,O,k){let j=pendingContributors.get(t);if(j||(j={writerId:t,displayName:S,colorSeed:w??S,docs:new Set,subjectOverride:E,actor:D,summaries:[],previousPaths:[]},pendingContributors.set(t,j)),j.docs.add(e),E!==void 0&&(j.subjectOverride=E),D!==void 0){let e=j.actor??{};D.principalId!==void 0&&(e.principalId=D.principalId),D.agentType!==void 0&&(e.agentType=D.agentType),D.clientName!==void 0&&(e.clientName=D.clientName),D.clientVersion!==void 0&&(e.clientVersion=D.clientVersion),D.label!==void 0&&(e.label=D.label),j.actor=e}if(typeof O==`string`&&O.length>0&&j.summaries.push(O),k&&k.length>0)for(let e of k)j.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,S]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:S.displayName,colorSeed:S.colorSeed,docs:new Set,actor:S.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of S.docs)e.docs.add(t);S.summaries.length>0&&(e.summaries=[...S.summaries,...e.summaries]),S.previousPaths.length>0&&(e.previousPaths=[...S.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let S of e.values()){let e={v:1,id:S.writerId,name:S.displayName,colorSeed:S.colorSeed,docs:[...S.docs]};S.summaries.length>0&&(e.summaries=[...S.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1138
1138
|
`)}function formatContributors(){return formatContributorsFrom(pendingContributors)}function restoreContributorEntry(e,t){let S=pendingContributors.get(e);S||(S={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},pendingContributors.set(e,S));for(let e of t.docs)S.docs.add(e);t.summaries.length>0&&(S.summaries=[...t.summaries,...S.summaries]),t.previousPaths.length>0&&(S.previousPaths=[...t.previousPaths,...S.previousPaths])}function clearContributors(){pendingContributors.clear()}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let S=extname(e).slice(1).toLowerCase();return S.length>0&&t.has(S)}function stripDocExtension(e){let t=e.toLowerCase();for(let S of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(S))return e.slice(0,-S.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let S=canonicalize(t);if(!S)throw Error(`registerDocExtension: unsupported extension "${t}"`);let w=docExtensionByName.get(e);if(!w)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let E=canonicalize(w);return E?E===S?{effective:w,changed:!1,shadowed:null}:rank(S)<rank(E)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w}):{effective:w,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}function acquireLock(e,t){let S=resolve(e,`lock`);if(existsSync(S)){let t=null;try{t=JSON.parse(readFileSync(S,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${S} — replacing`)}if(t&&!isValidLockPid(t.pid)&&(console.warn(`[shadow-lock] Invalid lock pid (${String(t.pid)}) at ${S} — replacing`),t=null),t){let S=t.hostname===hostname();if(!(S&&t.pid===process.pid)){if(S&&isProcessAlive(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let w={pid:process.pid,hostname:hostname(),startedAt:new Date().toISOString(),worktreeRoot:t};return writeFileSync(S,JSON.stringify(w,null,2),`utf-8`),S}function releaseLock(e){let t=resolve(e,`lock`);try{unlinkSync(t)}catch{}}const GIT_TIMEOUT_MS$3=(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})();function shadowGit(e){return esm_default({baseDir:e.workTree,timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function initShadowRepo(e){let t=resolveShadowDir(e),S=resolve(e,`.git/openknowledge`),w=existsSync(S),E=existsSync(t);if(w&&!E?tracedRenameSync(S,t):w&&E&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!existsSync(resolve(t,`HEAD`))){tracedMkdirSync(t,{recursive:!0}),await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$3}}).raw(`init`,`--bare`,t);let S=esm_default({timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:t});await S.raw(`config`,`--unset`,`core.bare`),await S.raw(`config`,`core.worktree`,e),await S.raw(`config`,`user.name`,`openknowledge`),await S.raw(`config`,`user.email`,`noreply@openknowledge.local`)}let D={gitDir:t,workTree:e};return await sweepLegacyShadowRefs(D),sweepOrphanedTmpIndexFiles(D),acquireLock(t,e),D}function destroyShadowRepo(e){releaseLock(e.gitDir)}async function sweepLegacyShadowRefs(e){let t=shadowGit(e),S;try{S=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
|
|
1139
1139
|
`).filter(e=>e.length>0)}catch{return 0}let w=[],E={server:0,"human-":0,upstream:0};for(let e of S){let t=e.split(`/`);if(t.length<4)continue;let S=t.slice(3).join(`/`);parseWriterId(S).classification===`unknown`&&(S===`server`?(w.push(e),E.server++):S.startsWith(`human-`)?(w.push(e),E[`human-`]++):S===`upstream`&&(w.push(e),E.upstream++))}if(w.length===0)return 0;for(let e of w)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let D=w.length;return incrementShadowMigrationLegacyRefsDeleted(D),console.warn(`[shadow-migration] deleted ${D} legacy refs: server=${E.server} human-=${E[`human-`]} upstream=${E.upstream}`),D}async function commitWip(e,t,S,w,E=`main`){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":E}},async()=>commitWipInner(e,t,S,w,E))}async function commitWipInner(e,t,S,w,E=`main`){let D=resolve(e.gitDir,`index-wip-${t.id}`),O=`refs/wip/${E}/${t.id}`,k=shadowGit(e),j=S||`.`;try{try{let t=(await k.raw(`rev-parse`,`${O}^{tree}`)).trim();await k.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:D}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${O}:`,e),e}await k.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:D}).raw(`add`,j);let S=(await k.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:D}).raw(`write-tree`)).trim(),E=null;try{E=(await k.raw(`rev-parse`,O)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${O}:`,e),e}let F=[`commit-tree`,S,`-m`,w];E&&F.push(`-p`,E);let L=(await k.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await k.raw(`update-ref`,O,L),L}finally{try{rmSync(D)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let S of readdirSync(e.gitDir))if(S.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,S)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let S=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),w=shadowGit(e),E=t||`.`;try{return await w.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:S}).raw(`add`,E),(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:S}).raw(`write-tree`)).trim()}finally{try{rmSync(S)}catch{}}}async function commitWipFromTree(e,t,S,w,E=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":E,"shadow.tree":S.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,S,w,E))}async function commitWipFromTreeInner(e,t,S,w,E=`main`){let D=`refs/wip/${E}/${t.id}`,O=shadowGit(e),k=null;try{k=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,S,`-m`,w];k&&j.push(`-p`,k);let F=(await O.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...j)).trim();return await O.raw(`update-ref`,D,F),F}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,S,w,E=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":E,"shadow.new_head":w.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,S,w,E))}async function commitUpstreamImportInner(e,t,S,w,E=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(S,w)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,E)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,S,w=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${S.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,w)}async function saveInMemoryCheckpoint(e,t,S){let w=S.branch??`main`,E=shadowGit(e),D=randomUUID(),O=resolve(e.gitDir,`index-checkpoint-${D}`),k=resolve(e.gitDir,`tmp-checkpoint-blob-${D}`),j=t?`${t.replace(/\/$/,``)}/${S.docName}`:S.docName,F=Buffer.byteLength(S.contents,`utf-8`),L=formatCheckpointBodyLine(S.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:S.docName,size:F,metadata:S.metadata}:{kind:`external-change-rescue`,docName:S.docName,size:F,metadata:S.metadata}),B=`checkpoint: ${S.label}\n\n${L}`;try{tracedWriteFileSync(k,S.contents,`utf-8`);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`hash-object`,`-w`,k)).trim();await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${j}`);let D=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),F=(await E.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,D,`-m`,B)).trim();return await E.raw(`update-ref`,`refs/checkpoints/${w}/${F}`,F),F}finally{try{rmSync(O)}catch{}try{rmSync(k)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let S=shadowGit(e),w;try{w=await S.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let E=w.trim().split(`
|
|
@@ -1145,7 +1145,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
|
|
|
1145
1145
|
`).trim()),E=[]):E.push(e)}if(E.length>0){let e=E.join(`
|
|
1146
1146
|
`).trim();e&&w.push(e)}return w}function reconcile(e){if(isSystemDoc(e.docName)||isConfigDoc(e.docName))return{kind:`noop`};let{base:t,ours:S,theirs:w}=e;if(containsConflictMarkers(w))return{kind:`refused`,reason:`conflict-markers`};if(w===t)return{kind:`noop`};if(S===t)return{kind:`clean`,newContent:w};let E=splitMarkdownBlocks(t),D=splitMarkdownBlocks(S),O=splitMarkdownBlocks(w);return(E.length+1)*(D.length+1)>4e6||(E.length+1)*(O.length+1)>4e6?{kind:`refused`,reason:`too-large`}:mergeBlocks(E,D,O)}function mergeBlocks(e,t,S){let w=computeEditOps(e,t),E=computeEditOps(e,S),D=[],O=[];for(let t=0;t<e.length;t++){let S=e[t],k=w.get(t),j=E.get(t),F=k?.insertsBefore??[],L=j?.insertsBefore??[];D.push(...F,...L);let B=k?.action??`keep`,H=j?.action??`keep`;if(B===`keep`&&H===`keep`)D.push(S);else if(B===`keep`&&H!==`keep`)H===`modify`&&j?.newContent!==void 0&&D.push(j.newContent);else if(B!==`keep`&&H===`keep`)B===`modify`&&k?.newContent!==void 0&&D.push(k.newContent);else{let e=B===`modify`?k?.newContent:null,w=H===`modify`?j?.newContent:null;e===w||O.push({blockIndex:t,base:S,ours:e??``,theirs:w??``}),e!=null&&D.push(e)}}let k=w.get(e.length),j=E.get(e.length);k?.insertsBefore&&D.push(...k.insertsBefore),j?.insertsBefore&&D.push(...j.insertsBefore);let F=D.length>0?`${D.join(`
|
|
1147
1147
|
|
|
1148
|
-
`)}\n`:``;return O.length>0?{kind:`conflicts`,newContent:F,conflicts:O}:{kind:`merged`,newContent:F,mergedBlocks:D.length}}function computeEditOps(e,t){let S=new Map,w=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)S.set(t,{action:`keep`,insertsBefore:[]});let E=new Set,D=new Set;for(let[e,t]of w)E.add(e),D.add(t);let O=-1;for(let k=0;k<e.length;k++)if(E.has(k)){let e=w.find(e=>e[0]===k)?.[1]??-1,E=[];for(let S=O+1;S<e;S++)D.has(S)||E.push(t[S]);let j=S.get(k);j&&(j.insertsBefore=E),O=e}else{let e=w.find(e=>e[0]>k),E=e?e[1]:t.length,j=[];for(let e=O+1;e<E;e++)D.has(e)||j.push(e);if(j.length>0){let e=j[0];D.add(e);let w=S.get(k);w&&(w.action=`modify`,w.newContent=t[e])}else{let e=S.get(k);e&&(e.action=`delete`)}}let k=[];for(let e=O+1;e<t.length;e++)D.has(e)||k.push(t[e]);let j=S.get(e.length);return j&&(j.insertsBefore=k),S}function longestCommonSubsequence(e,t){let S=e.length,w=t.length,E=w+1,D=new Uint32Array((S+1)*E);for(let O=1;O<=S;O++){let S=O*E,k=(O-1)*E;for(let E=1;E<=w;E++)if(e[O-1]===t[E-1])D[S+E]=D[k+(E-1)]+1;else{let e=D[k+E],t=D[S+(E-1)];D[S+E]=e>t?e:t}}let O=[],k=S,j=w;for(;k>0&&j>0;)e[k-1]===t[j-1]?(O.push([k-1,j-1]),k--,j--):D[(k-1)*E+j]>=D[k*E+(j-1)]?k--:j--;return O.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let S=writeTracker.get(e)??[];S.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,S)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,S]of writeTracker){let w=S.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);w.length===0?writeTracker.delete(t):w.length!==S.length&&writeTracker.set(t,w)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let S;try{S=lstatSync(e)}catch(t){let S=t.code;return S===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${S}), dropping event`),!0)}if(!S.isSymbolicLink())return!1;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${S}), dropping event`),!0}return!isWithinContentDir(w,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function contentRelativePath(e,t){let S=relative(e,t).replaceAll(`\\`,`/`);return!S||S===`.`||S===`..`||S.startsWith(`../`)?null:S}function upsertFolderIndexEntry(e,t,S,w,E=S){let D=contentRelativePath(t,S);return D?(e.set(D,{size:0,modified:w.mtime.toISOString(),canonicalPath:E,inode:Number(w.ino)}),D):null}function removeFolderIndexEntries(e,t){let S=!1;for(let w of e.keys())(w===t||w.startsWith(`${t}/`))&&(e.delete(w),S=!0);return S}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let S=t.toLowerCase();return S===`.mdx`||S===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,S,w){let E=[],D=[],O=[];for(let w of e)if(isSupportedDocFile(w.path)){if(S){let e=relative(t,w.path);if(S.isExcluded(e))continue}switch(w.type){case`delete`:E.push(w);break;case`create`:lastKnownHash.has(w.path)?O.push(w):D.push(w);break;case`update`:O.push(w);break}}let k=new Map,j=new Map;for(let e of D)try{k.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of O)try{j.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function F(e){let S=pathToDocName(e,t);if(!w)return S;let E=null;try{E=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),w.has(S)&&w.delete(S),S}if(!E.isSymbolicLink())return w.has(S)&&w.delete(S),S;let D;try{D=realpathSync(e)}catch(t){let E=t.code;return E!==`ENOENT`&&E!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),w.delete(S),S}if(!isWithinContentDir(D,t))return w.delete(S),S;let O=pathToDocName(D,t);return O===S?S:(w.set(S,O),O)}let L=[],B=new Set,H=new Set;for(let e of E){let t=removeLastKnownHash(e.path);if(t)for(let S of D){if(B.has(S.path))continue;let w=k.get(S.path);if(w===void 0)continue;let E=contentHash(w);if(E===t){B.add(S.path),H.add(e.path),updateLastKnownHash(S.path,E),L.push({kind:`rename`,oldPath:e.path,newPath:S.path,oldDocName:F(e.path),newDocName:F(S.path),content:w});break}}}for(let e of E)H.has(e.path)||(removeLastKnownHash(e.path),L.push({kind:`delete`,path:e.path,docName:F(e.path)}));for(let e of D){if(B.has(e.path))continue;let t=k.get(e.path);if(t===void 0)continue;let S=contentHash(t);updateLastKnownHash(e.path,S),containsConflictMarkers(t)?L.push({kind:`conflict`,path:e.path,docName:F(e.path),content:t}):L.push({kind:`create`,path:e.path,docName:F(e.path),content:t})}for(let e of O){let t=j.get(e.path);if(t===void 0)continue;let S=contentHash(t);updateLastKnownHash(e.path,S),containsConflictMarkers(t)?L.push({kind:`conflict`,path:e.path,docName:F(e.path),content:t}):L.push({kind:`update`,path:e.path,docName:F(e.path),content:t})}return L}function isSelfWrite(e,t){let S=writeTracker.get(e);if(!S)return!1;let w=S.findIndex(e=>e.hash===t);return w<0?!1:(S.splice(w,1),S.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,S,w,E,D,O){let k=O??new Set;try{let O=readdirSync(e,{withFileTypes:!0});for(let j of O){let O=join(e,j.name),F;try{F=lstatSync(O)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${O}, skipping:`,e);continue}if(F.isSymbolicLink()){let e;try{e=realpathSync(O)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${O}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${O}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${O} → ${e}, skipping`);continue}try{let F=statSync(e);if(k.has(F.ino)){if(F.isFile()&&isSupportedDocFile(j.name)){let S=pathToDocName(O,t),E=pathToDocName(e,t);D.set(S,E);let k=w.get(E);k&&!k.aliases.includes(S)&&k.aliases.push(S)}continue}if(k.add(F.ino),F.isDirectory()){let j=contentRelativePath(t,O);if(S&&(!j||S.isDirExcluded(j)))continue;upsertFolderIndexEntry(E,t,O,F,e),seedLastKnownHashes(e,t,S,w,E,D,k)}else if(F.isFile()&&isSupportedDocFile(j.name)){if(S){let w=relative(t,e);if(S.isExcluded(w))continue}let E=pathToDocName(O,t),k=pathToDocName(e,t);D.set(E,k);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let S=extractDocExtension(e);if(S){let e=registerDocExtension(k,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${k}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}w.set(k,{size:F.size,modified:F.mtime.toISOString(),canonicalPath:e,inode:F.ino,aliases:[E]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(F.isDirectory()){let e=contentRelativePath(t,O);if(S&&(!e||S.isDirExcluded(e)))continue;upsertFolderIndexEntry(E,t,O,F),seedLastKnownHashes(O,t,S,w,E,D,k)}else if(F.isFile()&&isSupportedDocFile(j.name)){if(k.has(F.ino))continue;if(k.add(F.ino),S){let e=relative(t,O);if(S.isExcluded(e))continue}try{let e=readFileSync(O,`utf-8`);lastKnownHash.set(O,contentHash(e));let S=pathToDocName(O,t),E=extractDocExtension(O);if(E){let e=registerDocExtension(S,E);if(e.shadowed&&(console.warn(`[file-watcher] docName "${S}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}w.set(S,{size:F.size,modified:F.mtime.toISOString(),canonicalPath:O,inode:F.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${O}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${O}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)return;let S=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(S)||isConfigDoc(S)))switch(e.kind){case`create`:case`update`:case`conflict`:{let S=e.docName,w=t.get(S),E=extractDocExtension(e.path);E&®isterDocExtension(S,E),t.set(S,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:w?.canonicalPath??e.path,inode:w?.inode??0,aliases:w?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,S]of t){let t=S.aliases.indexOf(e.docName);if(t!==-1){S.aliases.splice(t,1);break}}break;case`rename`:{let S=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let w=extractDocExtension(e.newPath);w&®isterDocExtension(e.newDocName,w),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:S?.canonicalPath??e.newPath,inode:S?.inode??0,aliases:S?.aliases??[]});break}default:assertNeverDiskEvent(e)}}function updateFolderIndexFromRawEvents(e,t,S,w){let E=[];for(let D of e){let e=contentRelativePath(t,D.path);if(!e)continue;if(D.type===`delete`){removeFolderIndexEntries(w,e)&&E.push({kind:`folder-delete`,path:D.path,relativePath:e});continue}let O;try{O=lstatSync(D.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${D.path} (${t})`);continue}let k=null,j=D.path;if(O.isDirectory())k=O;else if(O.isSymbolicLink())try{if(j=realpathSync(D.path),!isWithinContentDir(j,t))continue;let e=statSync(j);e.isDirectory()&&(k=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${D.path} (${t})`),k=null}if(!k||S?.isDirExcluded(e))continue;let F=w.has(e);upsertFolderIndexEntry(w,t,D.path,k,j),F||(E.push({kind:`folder-create`,path:D.path,relativePath:e}),scanForUntrackedSubfolders(j,t,S,w,E))}return E}function scanForUntrackedSubfolders(e,t,S,w,E){let D=[e];for(;D.length>0;){let e=D.shift();if(e===void 0)continue;let O;try{O=readdirSync(e,{withFileTypes:!0})}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${S})`);continue}for(let k of O){if(!k.isDirectory())continue;let O=join(e,k.name),j=contentRelativePath(t,O);if(!j||S?.isDirExcluded(j))continue;let F;try{F=lstatSync(O)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${O} (${t})`);continue}F.isDirectory()&&(w.has(j)||(upsertFolderIndexEntry(w,t,O,F),E.push({kind:`folder-create`,path:O,relativePath:j})),D.push(O))}}}async function handleRawEvents(e,t,S,w,E,D,O){let k=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),j=k.filter(e=>isSupportedDocFile(e.path)),F=k.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS)),L=updateFolderIndexFromRawEvents(k,t,S,E);if(j.length===0&&F.length===0&&L.length===0)return;let B=j.length>0?await classifyEvents(j,t,S,O):[];for(let e of B){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let S=contentHash(e.content),w=e.path;try{w=realpathSync(e.path)}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${S})`)}t=isSelfWrite(w,S)}else if(e.kind===`rename`){let S=contentHash(e.content),w=e.newPath;try{w=realpathSync(e.newPath)}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${S})`)}t=isSelfWrite(w,S)}if(updateFileIndex(e,w),S&&!t)switch(e.kind){case`create`:S.incrementMdDir(dirname(e.docName));break;case`delete`:S.decrementMdDir(dirname(e.docName));break;case`rename`:S.decrementMdDir(dirname(e.oldDocName)),S.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let E=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(E),"disk.path.role":classifyFsPath(E)}},async()=>D(e))}for(let e of L)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>D(e));for(let e of F){if(S){let w=relative(t,e.path);if(S.isExcluded(w))continue}let w=relative(t,e.path);await D(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:w}:{kind:`asset-create`,path:e.path,relativePath:w})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,S,w,E,D){let O;try{O=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let k=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await O.subscribe(e,async(O,k)=>{if(O){console.error(`[file-watcher]`,O);return}try{await handleRawEvents(k.map(e=>({type:e.type,path:e.path})),e,t,S,w,E,D)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},k)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,S,w,E,D){let{watch:O}=await import(`./chokidar-CxU7f6JW.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let k=O(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(S,w)=>{let E=relative(e,S);return E===``||E===`.`?!1:w?.isDirectory()?t.isDirExcluded(E):t.isExcluded(E)}:void 0});k.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let j=50,F=[],L=null;function B(O,k){F.push({type:O,path:k}),L||=setTimeout(()=>{let O=F;F=[],L=null,handleRawEvents(O,e,t,S,w,E,D).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return k.on(`add`,e=>B(`create`,e)),k.on(`change`,e=>B(`update`,e)),k.on(`unlink`,e=>B(`delete`,e)),k.on(`addDir`,e=>B(`create`,e)),k.on(`unlinkDir`,e=>B(`delete`,e)),{unsubscribe:()=>(L&&(clearTimeout(L),L=null,F=[]),k.close())}}async function startWatcher(e,t,S){let w;try{w=realpathSync(e)}catch{w=e}let E=new Map,D=new Map,O=new Map;seedLastKnownHashes(w,w,S,E,D,O);let k=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),j,F;try{let e=await startParcelWatcher(w,S,E,D,t,O);e?(j=e,F=`parcel`):(j=await startChokidarWatcher(w,S,E,D,t,O),F=`chokidar`)}catch(e){throw clearInterval(k),e}let L=j.unsubscribe.bind(j);return console.log(`[file-watcher] Watching ${w} for external .md changes (backend: ${F})`),{async unsubscribe(){return clearInterval(k),writeTracker.clear(),lastKnownHash.clear(),L()},getFileIndex(){return E},getFolderIndex(){return D},getAliasMap(){return O},pruneFileIndexNowExcluded(){if(!S)return 0;let e=0;for(let[t,D]of E){let O=relative(w,D.canonicalPath);S.isExcluded(O)&&(E.delete(t),e++)}return e},rescanFromDisk(){seedLastKnownHashes(w,w,S,E,D,O)}}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
1148
|
+
`)}\n`:``;return O.length>0?{kind:`conflicts`,newContent:F,conflicts:O}:{kind:`merged`,newContent:F,mergedBlocks:D.length}}function computeEditOps(e,t){let S=new Map,w=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)S.set(t,{action:`keep`,insertsBefore:[]});let E=new Set,D=new Set;for(let[e,t]of w)E.add(e),D.add(t);let O=-1;for(let k=0;k<e.length;k++)if(E.has(k)){let e=w.find(e=>e[0]===k)?.[1]??-1,E=[];for(let S=O+1;S<e;S++)D.has(S)||E.push(t[S]);let j=S.get(k);j&&(j.insertsBefore=E),O=e}else{let e=w.find(e=>e[0]>k),E=e?e[1]:t.length,j=[];for(let e=O+1;e<E;e++)D.has(e)||j.push(e);if(j.length>0){let e=j[0];D.add(e);let w=S.get(k);w&&(w.action=`modify`,w.newContent=t[e])}else{let e=S.get(k);e&&(e.action=`delete`)}}let k=[];for(let e=O+1;e<t.length;e++)D.has(e)||k.push(t[e]);let j=S.get(e.length);return j&&(j.insertsBefore=k),S}function longestCommonSubsequence(e,t){let S=e.length,w=t.length,E=w+1,D=new Uint32Array((S+1)*E);for(let O=1;O<=S;O++){let S=O*E,k=(O-1)*E;for(let E=1;E<=w;E++)if(e[O-1]===t[E-1])D[S+E]=D[k+(E-1)]+1;else{let e=D[k+E],t=D[S+(E-1)];D[S+E]=e>t?e:t}}let O=[],k=S,j=w;for(;k>0&&j>0;)e[k-1]===t[j-1]?(O.push([k-1,j-1]),k--,j--):D[(k-1)*E+j]>=D[k*E+(j-1)]?k--:j--;return O.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let S=writeTracker.get(e)??[];S.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,S)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,S]of writeTracker){let w=S.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);w.length===0?writeTracker.delete(t):w.length!==S.length&&writeTracker.set(t,w)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let S;try{S=lstatSync(e)}catch(t){let S=t.code;return S===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${S}), dropping event`),!0)}if(!S.isSymbolicLink())return!1;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${S}), dropping event`),!0}return!isWithinContentDir(w,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function contentRelativePath(e,t){let S=relative(e,t).replaceAll(`\\`,`/`);return!S||S===`.`||S===`..`||S.startsWith(`../`)?null:S}function upsertFolderIndexEntry(e,t,S,w,E=S){let D=contentRelativePath(t,S);return D?(e.set(D,{size:0,modified:w.mtime.toISOString(),canonicalPath:E,inode:Number(w.ino)}),D):null}function removeFolderIndexEntries(e,t){let S=!1;for(let w of e.keys())(w===t||w.startsWith(`${t}/`))&&(e.delete(w),S=!0);return S}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let S=t.toLowerCase();return S===`.mdx`||S===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,S,w){let E=[],D=[],O=[];for(let w of e)if(isSupportedDocFile(w.path)){if(S){let e=relative(t,w.path);if(S.isExcluded(e))continue}switch(w.type){case`delete`:E.push(w);break;case`create`:lastKnownHash.has(w.path)?O.push(w):D.push(w);break;case`update`:O.push(w);break}}let k=new Map,j=new Map;for(let e of D)try{k.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of O)try{j.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function F(e){let S=pathToDocName(e,t);if(!w)return S;let E=null;try{E=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),w.has(S)&&w.delete(S),S}if(!E.isSymbolicLink())return w.has(S)&&w.delete(S),S;let D;try{D=realpathSync(e)}catch(t){let E=t.code;return E!==`ENOENT`&&E!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),w.delete(S),S}if(!isWithinContentDir(D,t))return w.delete(S),S;let O=pathToDocName(D,t);return O===S?S:(w.set(S,O),O)}let L=[],B=new Set,H=new Set;for(let e of E){let t=removeLastKnownHash(e.path);if(t)for(let S of D){if(B.has(S.path))continue;let w=k.get(S.path);if(w===void 0)continue;let E=contentHash(w);if(E===t){B.add(S.path),H.add(e.path),updateLastKnownHash(S.path,E),L.push({kind:`rename`,oldPath:e.path,newPath:S.path,oldDocName:F(e.path),newDocName:F(S.path),content:w});break}}}for(let e of E)H.has(e.path)||(removeLastKnownHash(e.path),L.push({kind:`delete`,path:e.path,docName:F(e.path)}));for(let e of D){if(B.has(e.path))continue;let t=k.get(e.path);if(t===void 0)continue;let S=contentHash(t);updateLastKnownHash(e.path,S),containsConflictMarkers(t)?L.push({kind:`conflict`,path:e.path,docName:F(e.path),content:t}):L.push({kind:`create`,path:e.path,docName:F(e.path),content:t})}for(let e of O){let t=j.get(e.path);if(t===void 0)continue;let S=contentHash(t);updateLastKnownHash(e.path,S),containsConflictMarkers(t)?L.push({kind:`conflict`,path:e.path,docName:F(e.path),content:t}):L.push({kind:`update`,path:e.path,docName:F(e.path),content:t})}return L}function isSelfWrite(e,t){let S=writeTracker.get(e);if(!S)return!1;let w=S.findIndex(e=>e.hash===t);return w<0?!1:(S.splice(w,1),S.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,S,w,E,D,O){let k=O??new Set;try{let O=readdirSync(e,{withFileTypes:!0});for(let j of O){let O=join(e,j.name),F;try{F=lstatSync(O)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${O}, skipping:`,e);continue}if(F.isSymbolicLink()){let e;try{e=realpathSync(O)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${O}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${O}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${O} → ${e}, skipping`);continue}try{let F=statSync(e);if(k.has(F.ino)){if(F.isFile()&&isSupportedDocFile(j.name)){let S=pathToDocName(O,t),E=pathToDocName(e,t);D.set(S,E);let k=w.get(E);k&&!k.aliases.includes(S)&&k.aliases.push(S)}continue}if(k.add(F.ino),F.isDirectory()){let j=contentRelativePath(t,O);if(S&&(!j||S.isDirExcluded(j)))continue;upsertFolderIndexEntry(E,t,O,F,e),seedLastKnownHashes(e,t,S,w,E,D,k)}else if(F.isFile()&&isSupportedDocFile(j.name)){if(S){let w=relative(t,e);if(S.isExcluded(w))continue}let E=pathToDocName(O,t),k=pathToDocName(e,t);D.set(E,k);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let S=extractDocExtension(e);if(S){let e=registerDocExtension(k,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${k}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}w.set(k,{size:F.size,modified:F.mtime.toISOString(),canonicalPath:e,inode:F.ino,aliases:[E]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(F.isDirectory()){let e=contentRelativePath(t,O);if(S&&(!e||S.isDirExcluded(e)))continue;upsertFolderIndexEntry(E,t,O,F),seedLastKnownHashes(O,t,S,w,E,D,k)}else if(F.isFile()&&isSupportedDocFile(j.name)){if(k.has(F.ino))continue;if(k.add(F.ino),S){let e=relative(t,O);if(S.isExcluded(e))continue}try{let e=readFileSync(O,`utf-8`);lastKnownHash.set(O,contentHash(e));let S=pathToDocName(O,t),E=extractDocExtension(O);if(E){let e=registerDocExtension(S,E);if(e.shadowed&&(console.warn(`[file-watcher] docName "${S}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}w.set(S,{size:F.size,modified:F.mtime.toISOString(),canonicalPath:O,inode:F.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${O}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${O}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)return;let S=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(S)||isConfigDoc(S)))switch(e.kind){case`create`:case`update`:case`conflict`:{let S=e.docName,w=t.get(S),E=extractDocExtension(e.path);E&®isterDocExtension(S,E),t.set(S,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:w?.canonicalPath??e.path,inode:w?.inode??0,aliases:w?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,S]of t){let t=S.aliases.indexOf(e.docName);if(t!==-1){S.aliases.splice(t,1);break}}break;case`rename`:{let S=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let w=extractDocExtension(e.newPath);w&®isterDocExtension(e.newDocName,w),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:S?.canonicalPath??e.newPath,inode:S?.inode??0,aliases:S?.aliases??[]});break}default:assertNeverDiskEvent(e)}}function updateFolderIndexFromRawEvents(e,t,S,w){let E=[];for(let D of e){let e=contentRelativePath(t,D.path);if(!e)continue;if(D.type===`delete`){removeFolderIndexEntries(w,e)&&E.push({kind:`folder-delete`,path:D.path,relativePath:e});continue}let O;try{O=lstatSync(D.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${D.path} (${t})`);continue}let k=null,j=D.path;if(O.isDirectory())k=O;else if(O.isSymbolicLink())try{if(j=realpathSync(D.path),!isWithinContentDir(j,t))continue;let e=statSync(j);e.isDirectory()&&(k=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${D.path} (${t})`),k=null}if(!k||S?.isDirExcluded(e))continue;let F=w.has(e);upsertFolderIndexEntry(w,t,D.path,k,j),F||(E.push({kind:`folder-create`,path:D.path,relativePath:e}),scanForUntrackedSubfolders(j,t,S,w,E))}return E}function scanForUntrackedSubfolders(e,t,S,w,E){let D=[e];for(;D.length>0;){let e=D.shift();if(e===void 0)continue;let O;try{O=readdirSync(e,{withFileTypes:!0})}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${S})`);continue}for(let k of O){if(!k.isDirectory())continue;let O=join(e,k.name),j=contentRelativePath(t,O);if(!j||S?.isDirExcluded(j))continue;let F;try{F=lstatSync(O)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${O} (${t})`);continue}F.isDirectory()&&(w.has(j)||(upsertFolderIndexEntry(w,t,O,F),E.push({kind:`folder-create`,path:O,relativePath:j})),D.push(O))}}}async function handleRawEvents(e,t,S,w,E,D,O){let k=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),j=k.filter(e=>isSupportedDocFile(e.path)),F=k.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS)),L=updateFolderIndexFromRawEvents(k,t,S,E);if(j.length===0&&F.length===0&&L.length===0)return;let B=j.length>0?await classifyEvents(j,t,S,O):[];for(let e of B){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let S=contentHash(e.content),w=e.path;try{w=realpathSync(e.path)}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${S})`)}t=isSelfWrite(w,S)}else if(e.kind===`rename`){let S=contentHash(e.content),w=e.newPath;try{w=realpathSync(e.newPath)}catch(t){let S=t.code;S!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${S})`)}t=isSelfWrite(w,S)}if(updateFileIndex(e,w),S&&!t)switch(e.kind){case`create`:S.incrementMdDir(dirname(e.docName));break;case`delete`:S.decrementMdDir(dirname(e.docName));break;case`rename`:S.decrementMdDir(dirname(e.oldDocName)),S.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let E=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(E),"disk.path.role":classifyFsPath(E)}},async()=>D(e))}for(let e of L)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>D(e));for(let e of F){if(S){let w=relative(t,e.path);if(S.isExcluded(w))continue}let w=relative(t,e.path);await D(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:w}:{kind:`asset-create`,path:e.path,relativePath:w})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,S,w,E,D){let O;try{O=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let k=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await O.subscribe(e,async(O,k)=>{if(O){console.error(`[file-watcher]`,O);return}try{await handleRawEvents(k.map(e=>({type:e.type,path:e.path})),e,t,S,w,E,D)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},k)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,S,w,E,D){let{watch:O}=await import(`./chokidar-CxU7f6JW.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let k=O(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(S,w)=>{let E=relative(e,S);return E===``||E===`.`?!1:w?.isDirectory()?t.isDirExcluded(E):t.isExcluded(E)}:void 0});k.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let j=50,F=[],L=null;function B(O,k){F.push({type:O,path:k}),L||=setTimeout(()=>{let O=F;F=[],L=null,handleRawEvents(O,e,t,S,w,E,D).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return k.on(`add`,e=>B(`create`,e)),k.on(`change`,e=>B(`update`,e)),k.on(`unlink`,e=>B(`delete`,e)),k.on(`addDir`,e=>B(`create`,e)),k.on(`unlinkDir`,e=>B(`delete`,e)),{unsubscribe:()=>(L&&(clearTimeout(L),L=null,F=[]),k.close())}}async function startWatcher(e,t,S){let w;try{w=realpathSync(e)}catch{w=e}let E=new Map,D=new Map,O=new Map;seedLastKnownHashes(w,w,S,E,D,O);let k=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),j,F;try{let e=await startParcelWatcher(w,S,E,D,t,O);e?(j=e,F=`parcel`):(j=await startChokidarWatcher(w,S,E,D,t,O),F=`chokidar`)}catch(e){throw clearInterval(k),e}let L=j.unsubscribe.bind(j);return console.log(`[file-watcher] Watching ${w} for external .md changes (backend: ${F})`),{async unsubscribe(){return clearInterval(k),writeTracker.clear(),lastKnownHash.clear(),L()},getFileIndex(){return E},getFolderIndex(){return D},getAliasMap(){return O},pruneFileIndexNowExcluded(){if(!S)return 0;let e=0;for(let[t,D]of E){let O=relative(w,D.canonicalPath);S.isExcluded(O)&&(E.delete(t),e++)}return e},pruneFolderIndexNowExcluded(){if(!S)return 0;let e=0;for(let t of D.keys())S.isDirExcluded(t)&&(D.delete(t),e++);return e},rescanFromDisk(){seedLastKnownHashes(w,w,S,E,D,O)}}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
1149
1149
|
`||e===` `||e===`\r`}function classifyDuplication(e,t){let S=normalizeBody(t);if(S.length===0)return{kind:`allow`,reason:`empty-base`};let w=normalizeBody(e);if(w===S)return{kind:`allow`,reason:`identical`};if(w.length<S.length*2)return{kind:`allow`,reason:`too-short`};let E=0,D=0;for(;E<w.length;){if(w.slice(E,E+S.length)!==S)return{kind:`allow`,reason:`not-integer-multiple`};for(E+=S.length,D++;E<w.length&&isWhitespace(w[E]??``);)E++}return D>=2?{kind:`block`,reason:`structural-duplication`,copies:D}:{kind:`allow`,reason:`single-copy`}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let S=t.actor;return typeof S.writerId!=`string`||S.writerId.length===0||typeof S.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:S.writerId,displayName:S.displayName}}}function removeFromByFrom(e,t){let S=e.byFrom.get(t.from);if(!S)return;let w=S.filter(e=>e!==t);w.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,w)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let S=e.byTo.get(t.to);S&&removeFromByFrom(e,S),e.byTo.set(t.to,t);let w=e.byFrom.get(t.from);w?w.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),S=renameLogPath(e);if(!existsSync(S))return t;let w;try{w=readFileSync(S,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${S}, treating as empty:`,e),t}if(w.length===0)return t;let E=w.split(`
|
|
1150
1150
|
`),D=E[E.length-1];D!==``&&console.warn(`[rename-log] WARN: trailing line missing newline (${D.length} bytes); dropped`);let O=E.slice(0,-1);for(let e=0;e<O.length;e++){let S=O[e];if(S.length===0)continue;let w;try{w=JSON.parse(S)}catch(t){let w=S.slice(0,80),E=t.message;console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped (${E}): ${w}${S.length>80?`…`:``}`);continue}let E=validateEntry(w);if(!E){console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped`);continue}indexInsert(t,E)}return t.byTo.size>0&&liveEntriesGauge().add(t.byTo.size),t}function appendRenameLogEntry(e,t,S,w){let E=validateEntry(t);if(!E)throw Error(`[rename-log] refusing to append malformed entry`);let D=`${JSON.stringify(E)}\n`;if(Buffer.byteLength(D,`utf-8`)>RENAME_LOG_MAX_LINE_BYTES)throw Error(`[rename-log] entry exceeds max line size (${RENAME_LOG_MAX_LINE_BYTES} bytes)`);let O=renameLogPath(e),k=!1;if(existsSync(O))try{let e=statSync(O).size;e>5242880&&(k=!0,console.warn(`[rename-log] WARN: file size ${e} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`))}catch{}tracedAppendFileSync(O,D,{flag:`a`}),indexInsert(S,E),liveEntriesGauge().add(1),k&&w&&scheduleHardCapGc(w,S)}const gcPending=new Set;function scheduleHardCapGc(e,t){queueMicrotask(()=>{gcRenameLog(e,t).catch(e=>{console.warn(`[rename-log] WARN: hard-cap forced GC failed:`,e)})})}let _moduleIndex=null;function setRenameLogIndex(e,t){_moduleIndex={shadowDir:e,index:t}}function getOrLoadRenameLogIndex(e){if(_moduleIndex&&_moduleIndex.shadowDir===e)return _moduleIndex.index;let t=loadRenameLogIndex(e);return _moduleIndex={shadowDir:e,index:t},t}function serializeIndexToString(e){let t=[];for(let S of e.byTo.values())t.push(JSON.stringify(S));return t.length>0?`${t.join(`
|
|
1151
1151
|
`)}\n`:``}function parseGitTimeoutMs(){let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4}function expandPredecessors(e,t,S){let w=[],E=new Set,D=e,O=0;for(;;){if(w.length>=100){console.warn(`[rename-log] WARN: predecessor chain depth exceeded 100 while expanding "${e}"; truncating`);break}if(E.has(D)){console.warn(`[rename-log] WARN: cycle detected at "${D}" while expanding predecessors of "${e}"; truncating`);break}E.add(D);let k=S.byTo.get(D);if(!k||k.branch!==t)break;if(k.commitSha===``){O+=1;break}w.push({path:k.from,renameCommit:k.commitSha}),D=k.from}return w.reverse(),w.push({path:e,renameCommit:null}),{chain:w,skipped:O}}function createAncestorShaSetCache(){return new Map}function createSeedsCache(){return new Map}async function buildSeeds(e,t,S,w){return withSpan(`rename.buildSeeds`,void 0,async E=>{if(w){let e=w.get(`${S}:${t}`);if(e)return E.setAttribute(`rename.seeds_count`,e.length),E.setAttribute(`rename.cache_hit`,!0),e}let D=shadowGit(e),O;try{O=(await D.raw(`show`,`-s`,`--format=%aI`,t)).trim()}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: git show failed for rename commit ${t}; falling back to single-seed:`,e),E.setAttribute(`rename.seeds_count`,1),[t]}if(!O)return E.setAttribute(`rename.seeds_count`,1),[t];let k;try{k=await D.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(creatordate:iso8601-strict) %(objectname)`,`refs/checkpoints/${S}/`)}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${S}; falling back to single-seed:`,e),E.setAttribute(`rename.seeds_count`,1),[t]}let j=[t];for(let e of k.split(`
|
|
@@ -2099,7 +2099,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2099
2099
|
`).filter(e=>e.length===40);ne.push(...e)}catch{}let se=[];if(oe)try{se=(await te.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
|
|
2100
2100
|
`).filter(e=>e.length===40)}catch{}try{let e=(await te.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${E}/`)).trim().split(`
|
|
2101
2101
|
`).filter(Boolean);ae.push(...e)}catch{}if(oe&&ae.length===0)try{let e=(await te.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
|
|
2102
|
-
`).filter(Boolean);ae.push(...e)}catch{}if(ae.length===0&&ne.length===0&&se.length===0)return EMPTY;let ce=[...ne,...se],ue=[];if(ce.length>0){let t=parseGitLogOutput(await te.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce)).map(e=>({...e,type:`checkpoint`}));if(H&&(t=await filterEntriesByChain(e,t,L,E,B,ee,Y)),oe&&ne.length>0&&se.length>0){let e=new Set(ne),S=t.filter(t=>e.has(t.sha)),w=t.filter(t=>!e.has(t.sha)),E=S.reduce((e,t)=>{let S=new Date(t.timestamp).getTime();return S<e?S:e},1/0);ue=[...S,...w.filter(e=>new Date(e.timestamp).getTime()<E)]}else ue=t}let de=[...ae];for(let e of ce)de.push(e);let fe=[];if(de.length>0&&(fe=parseGitLogOutput(await te.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...de,...H?[`--`,H]:[])),J))for(let t=0;t<L.length-1;t++){let S=L[t];if(S.renameCommit!==null)try{let t=await buildSeeds(e,S.renameCommit,E,Y);if(t.length===0)continue;let w=B(S.path),D=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,w);fe=[...fe,...parseGitLogOutput(D)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${S.path}); skipping:`,e)}}let me=[...ue,...fe],ge=new Set,_e=[];for(let e of me)ge.has(e.sha)||(ge.add(e.sha),_e.push(e));let ve=_e;_e.length>0&&L.length>0&&(ve=filterEntriesByOkActorDocs(_e,L,await Promise.all(L.map(async t=>{if(t.renameCommit===null)return null;let S=await buildSeeds(e,t.renameCommit,E,Y);return S.length===0?new Set:buildAncestorShaSet(e,S,E,ee)})))),ve.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let ye=ve;ye=ye.filter(e=>e.type!==`park`),k.length>0&&(ye=ye.filter(e=>k.includes(e.type))),j.length>0&&(ye=ye.filter(e=>matchesAuthor(e,j))),F.length>0&&(ye=ye.filter(e=>!matchesAuthor(e,F)));let Ce=ye.length;return{entries:ye.slice(O,O+D).map(({rawBody:e,...t})=>t),total:Ce,hasMore:O+D<Ce}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$2=getLogger(`api`);function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let S=t===`.`?``:t.replace(/^\.\//,``),w=getDocExtension(e);return{path:S?`${S}/${e}${w}`:`${e}${w}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let S=255,w=new TextEncoder;if(w.encode(t).length>255){let e=t.lastIndexOf(`.`),S=e>=0?t.slice(e):``,E=e>=0?t.slice(0,e):t;for(;w.encode(E+S).length>255&&E.length>0;)E=E.slice(0,-1);t=(E||`upload`)+S,w.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,S){let w=t.trim();return w===``||w===`./`?resolve(S,dirname(e)):w===`/`?S:w.startsWith(`./`)?resolve(S,dirname(e),w.slice(2)):resolve(S,w)}function readTempFileHead(e,t){let S=openSync(e,`r`);try{let e=Buffer.alloc(t),w=readSync(S,e,0,t,0);return e.subarray(0,w)}finally{closeSync(S)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,S){let w;try{w=await readdir(e)}catch{return null}let E=getLogger(`upload`),D=0;for(let O of w){let w=extname(O).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(w))continue;let k=resolve(e,O),j;try{j=await stat$1(k)}catch{continue}if(!j.isFile()||j.size!==S)continue;if(D++,D>MAX_DEDUP_SCAN_CANDIDATES)return E.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:S},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let F;try{F=await streamingHashFile(k)}catch(e){let t=e.code;t!==`ENOENT`&&E.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:O},`[upload-dedup] skipped candidate — read failed`);continue}if(F===t)return O}return null}function readUploadBody(e,t){return new Promise((S,w)=>{let E;try{E=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){w(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let D=!1,O=`upload`,k=``,j=``,F,L,B=!1,H=(e,t)=>{if(!D){if(D=!0,F)try{unlinkSync(F)}catch{}w(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},q=classifyUploadErrno;E.on(`field`,(e,t)=>{e===`parentDocName`&&(j=t)}),E.on(`file`,(e,w,E)=>{B=!0,O=E.filename||`upload`,k=E.mimeType||``;let J;try{J=mintTempUploadPath(t)}catch(e){H(q(e),e),w.resume();return}F=J;let Y=new HashingPassThrough;pipeline(w,Y,createWriteStream(J)).then(()=>{D||(D=!0,S({filename:O,mimeType:k,parentDocName:j,tempPath:J,sha:Y.digest(),byteLength:Y.byteLength()}))}).catch(e=>{L=e,H(q(e),e)})}),E.on(`error`,e=>{H(`urn:ok:error:malformed-upload`,e)}),E.on(`close`,()=>{D||L||B||(D=!0,S({filename:``,mimeType:``,parentDocName:j,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{D||L||e.complete||H(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(E)})}function safeSubdir(e,t){let S=resolve(e,t);if(S!==e&&!S.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return S}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}async function walkContentDirForShowAll(e){let{contentDir:t,contentFilter:S,dirFilter:w,documents:E,getDocExtension:D}=e,O=e=>w?e===w||e.startsWith(`${w}/`):!0,k;try{k=await realpath(t)}catch{k=t}let j=e=>e===k?!0:e.startsWith(`${k}/`);async function F(e,t){let w;try{w=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let k of w){let w=t?`${t}/${k.name}`:k.name;if(k.isDirectory()){if(S.isDirExcluded(w,{bypassFilters:!0}))continue;let t=`${e}/${k.name}`,D;try{D=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!j(D)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${D}`);continue}if(O(w)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}E.push({kind:`folder`,path:w,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null})}await F(t,w);continue}if(!k.isFile()||S.isExcluded(w,{bypassFilters:!0})||!O(w))continue;let L=null;try{L=await stat$1(`${e}/${k.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${k.name}:`,t);continue}if(isSupportedDocFile(k.name)){let e=w.replace(/\.(md|mdx)$/i,``),t=D(e);E.push({kind:`document`,docName:e,docExt:t,size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null});continue}let B=synthesizeShowAllAssetExt(k.name),H=ASSET_EXTENSIONS.has(B)?mediaKindForSidebarAssetExtension(B):null;E.push({kind:`asset`,docName:w,docExt:B,path:w,assetExt:B,mediaKind:H,referencedBy:[],size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null})}}await F(w?`${t}/${w}`:t,w??``)}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function listAffectedDocNames(e,t,S){let w=[...e.keys()].filter(e=>t===`file`?e===S:e===S||e.startsWith(`${S}/`));return w.sort((e,t)=>e.localeCompare(t)),w}function remapDocNameForRename(e,t,S,w){return t===`file`||e===S?w:`${w}${e.slice(S.length)}`}function assertNoSymlinkEscape(e,t){let S;try{S=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let w=e;for(;;)try{if(!isWithinContentDir(realpathSync(w),S))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let S=e.code;if(S===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(S!==`ENOENT`)throw e;let E=dirname(w);if(E===w||E!==t&&!E.startsWith(`${t}${sep}`))throw e;w=E}}function resolveContentEntryPath(e,t,S){if(!isValidRelativeContentPath(S))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,t===`file`?isSupportedDocFile(S)?S:`${S}${getDocExtension(S)}`:S);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let S=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let w=resolve(S,`${t}${e}`);if(!(w!==S&&!w.startsWith(`${S}${sep}`))&&existsSync(w)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let S=resolve(e),w=resolve(t);return w!==S&&!w.startsWith(`${S}${sep}`)?null:relative(S,w).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,S){if(!e)return!1;let w=toGitRelativePath(e,t),E=toGitRelativePath(e,S);return!w||!E?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}}),D=``;try{D=(await t.raw(`ls-files`,`--`,w)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!D)return!1;mkdirSync(dirname(S),{recursive:!0});try{return await t.raw(`mv`,`--`,w,E),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
|
|
2102
|
+
`).filter(Boolean);ae.push(...e)}catch{}if(ae.length===0&&ne.length===0&&se.length===0)return EMPTY;let ce=[...ne,...se],ue=[];if(ce.length>0){let t=parseGitLogOutput(await te.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce)).map(e=>({...e,type:`checkpoint`}));if(H&&(t=await filterEntriesByChain(e,t,L,E,B,ee,Y)),oe&&ne.length>0&&se.length>0){let e=new Set(ne),S=t.filter(t=>e.has(t.sha)),w=t.filter(t=>!e.has(t.sha)),E=S.reduce((e,t)=>{let S=new Date(t.timestamp).getTime();return S<e?S:e},1/0);ue=[...S,...w.filter(e=>new Date(e.timestamp).getTime()<E)]}else ue=t}let de=[...ae];for(let e of ce)de.push(e);let fe=[];if(de.length>0&&(fe=parseGitLogOutput(await te.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...de,...H?[`--`,H]:[])),J))for(let t=0;t<L.length-1;t++){let S=L[t];if(S.renameCommit!==null)try{let t=await buildSeeds(e,S.renameCommit,E,Y);if(t.length===0)continue;let w=B(S.path),D=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,w);fe=[...fe,...parseGitLogOutput(D)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${S.path}); skipping:`,e)}}let me=[...ue,...fe],ge=new Set,_e=[];for(let e of me)ge.has(e.sha)||(ge.add(e.sha),_e.push(e));let ve=_e;_e.length>0&&L.length>0&&(ve=filterEntriesByOkActorDocs(_e,L,await Promise.all(L.map(async t=>{if(t.renameCommit===null)return null;let S=await buildSeeds(e,t.renameCommit,E,Y);return S.length===0?new Set:buildAncestorShaSet(e,S,E,ee)})))),ve.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let ye=ve;ye=ye.filter(e=>e.type!==`park`),k.length>0&&(ye=ye.filter(e=>k.includes(e.type))),j.length>0&&(ye=ye.filter(e=>matchesAuthor(e,j))),F.length>0&&(ye=ye.filter(e=>!matchesAuthor(e,F)));let Ce=ye.length;return{entries:ye.slice(O,O+D).map(({rawBody:e,...t})=>t),total:Ce,hasMore:O+D<Ce}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$2=getLogger(`api`);function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let S=t===`.`?``:t.replace(/^\.\//,``),w=getDocExtension(e);return{path:S?`${S}/${e}${w}`:`${e}${w}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let S=255,w=new TextEncoder;if(w.encode(t).length>255){let e=t.lastIndexOf(`.`),S=e>=0?t.slice(e):``,E=e>=0?t.slice(0,e):t;for(;w.encode(E+S).length>255&&E.length>0;)E=E.slice(0,-1);t=(E||`upload`)+S,w.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,S){let w=t.trim();return w===``||w===`./`?resolve(S,dirname(e)):w===`/`?S:w.startsWith(`./`)?resolve(S,dirname(e),w.slice(2)):resolve(S,w)}function readTempFileHead(e,t){let S=openSync(e,`r`);try{let e=Buffer.alloc(t),w=readSync(S,e,0,t,0);return e.subarray(0,w)}finally{closeSync(S)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,S){let w;try{w=await readdir(e)}catch{return null}let E=getLogger(`upload`),D=0;for(let O of w){let w=extname(O).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(w))continue;let k=resolve(e,O),j;try{j=await stat$1(k)}catch{continue}if(!j.isFile()||j.size!==S)continue;if(D++,D>MAX_DEDUP_SCAN_CANDIDATES)return E.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:S},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let F;try{F=await streamingHashFile(k)}catch(e){let t=e.code;t!==`ENOENT`&&E.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:O},`[upload-dedup] skipped candidate — read failed`);continue}if(F===t)return O}return null}function readUploadBody(e,t){return new Promise((S,w)=>{let E;try{E=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){w(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let D=!1,O=`upload`,k=``,j=``,F,L,B=!1,H=(e,t)=>{if(!D){if(D=!0,F)try{unlinkSync(F)}catch{}w(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},q=classifyUploadErrno;E.on(`field`,(e,t)=>{e===`parentDocName`&&(j=t)}),E.on(`file`,(e,w,E)=>{B=!0,O=E.filename||`upload`,k=E.mimeType||``;let J;try{J=mintTempUploadPath(t)}catch(e){H(q(e),e),w.resume();return}F=J;let Y=new HashingPassThrough;pipeline(w,Y,createWriteStream(J)).then(()=>{D||(D=!0,S({filename:O,mimeType:k,parentDocName:j,tempPath:J,sha:Y.digest(),byteLength:Y.byteLength()}))}).catch(e=>{L=e,H(q(e),e)})}),E.on(`error`,e=>{H(`urn:ok:error:malformed-upload`,e)}),E.on(`close`,()=>{D||L||B||(D=!0,S({filename:``,mimeType:``,parentDocName:j,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{D||L||e.complete||H(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(E)})}function safeSubdir(e,t){let S=resolve(e,t);if(S!==e&&!S.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return S}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}async function walkContentDirForShowAll(e){let{contentDir:t,contentFilter:S,dirFilter:w,documents:E,getDocExtension:D}=e,O=e=>w?e===w||e.startsWith(`${w}/`):!0,k;try{k=await realpath(t)}catch{k=t}let j=e=>e===k?!0:e.startsWith(`${k}/`);async function F(e,t){let w;try{w=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let k of w){let w=t?`${t}/${k.name}`:k.name;if(k.isDirectory()){if(S.isDirExcluded(w,{bypassFilters:!0}))continue;let t=`${e}/${k.name}`,D;try{D=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!j(D)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${D}`);continue}if(O(w)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}E.push({kind:`folder`,path:w,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null})}await F(t,w);continue}if(!k.isFile()||S.isExcluded(w,{bypassFilters:!0})||!O(w))continue;let L=null;try{L=await stat$1(`${e}/${k.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${k.name}:`,t);continue}if(isSupportedDocFile(k.name)){let e=w.replace(/\.(md|mdx)$/i,``),t=D(e);E.push({kind:`document`,docName:e,docExt:t,size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null});continue}let B=synthesizeShowAllAssetExt(k.name),H=ASSET_EXTENSIONS.has(B)?mediaKindForSidebarAssetExtension(B):null;E.push({kind:`asset`,docName:w,docExt:B,path:w,assetExt:B,mediaKind:H,referencedBy:[],size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null})}}await F(w?`${t}/${w}`:t,w??``)}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,S){let w=[...e.keys()].filter(e=>t===`file`?e===S:e===S||e.startsWith(`${S}/`));return w.sort((e,t)=>e.localeCompare(t)),w}function remapDocNameForRename(e,t,S,w){return t===`file`||e===S?w:`${w}${e.slice(S.length)}`}function assertNoSymlinkEscape(e,t){let S;try{S=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let w=e;for(;;)try{if(!isWithinContentDir(realpathSync(w),S))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let S=e.code;if(S===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(S!==`ENOENT`)throw e;let E=dirname(w);if(E===w||E!==t&&!E.startsWith(`${t}${sep}`))throw e;w=E}}function resolveContentEntryPath(e,t,S){if(!isValidRelativeContentPath(S))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,t===`file`?isSupportedDocFile(S)?S:`${S}${getDocExtension(S)}`:S);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(S=>existsSync(resolve(e,`${t}${S}`)))}function resolveDuplicateDocPath(e,t,S){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,`${t}${S}`);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function nextAvailableDuplicateDocName(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!docNameExistsWithAnySupportedExtension(e,E))return{docName:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!existsSync(resolveContentEntryPath(e,`folder`,E)))return{folderPath:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){E(D,O);continue}!S.isFile()||!isSupportedDocFile(O)||w.push({docName:stripDocExtension(O),fullPath:D,content:readFileSync(D,`utf-8`)})}}return E(S,t),w.sort((e,t)=>e.docName.localeCompare(t.docName)),w}function collectFolderPaths(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[t];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){if(!S.isDirectory())continue;let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;w.push(O),E(D,O)}}return E(S,t),w.sort((e,t)=>e.localeCompare(t)),w}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let S=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let w=resolve(S,`${t}${e}`);if(!(w!==S&&!w.startsWith(`${S}${sep}`))&&existsSync(w)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let S=resolve(e),w=resolve(t);return w!==S&&!w.startsWith(`${S}${sep}`)?null:relative(S,w).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,S){if(!e)return!1;let w=toGitRelativePath(e,t),E=toGitRelativePath(e,S);return!w||!E?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}}),D=``;try{D=(await t.raw(`ls-files`,`--`,w)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!D)return!1;mkdirSync(dirname(S),{recursive:!0});try{return await t.raw(`mv`,`--`,w,E),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
|
|
2103
2103
|
`)||e.startsWith(`---\r
|
|
2104
2104
|
`)){let S=e.indexOf(`
|
|
2105
2105
|
---`,3);S!==-1&&(t=e.slice(S+4))}let S=[],w=new Map,E=createCodeFenceTracker();for(let e of t.split(`
|
|
@@ -2107,10 +2107,10 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2107
2107
|
`)}let Re=createInstalledAgentsProbe({probe:ge??createOsProbe(process.platform)});function ze(e){if(!isSafeDocName(e))return null;let t=resolve(w),S=resolve(t,`${e}${getDocExtension(e)}`);return!S.startsWith(`${t}/`)&&S!==t?null:S}function Be(e){let t=ze(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Ve(e,t){return t.has(e)?Be(e):e}let Ue={cluster:void 0,category:void 0,tags:void 0};function We(e){try{let S=t.documents.get(e);if(S){let e=readFmMap(S.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,S=typeof e.category==`string`?e.category:void 0,w;return Array.isArray(e.tags)?w=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(w=[e.tags]),{cluster:t,category:S,tags:w}}}}catch{}try{let t=ze(e);if(!t||!existsSync(t))return Ue;let{frontmatter:S}=stripFrontmatter(readFileSync(t,`utf-8`));return S?parseFrontmatterMetadata(S):Ue}catch{return Ue}}function Ge(e,t){return t.has(e)?We(e):Ue}function Ke(e){if(ee)try{if(ee.getBacklinks(e).length>0)return;let t=performance.now(),S=findHubCandidates(e,D()),w=performance.now()-t;return w>5&&log$2.debug({docName:e,elapsedMs:w,candidateCount:S.length},`[orphan-hint] findHubCandidates slow`),S.length===0?void 0:[{type:`orphan`,parentCandidates:S,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${S.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function Xe(e){return k?.().get(e)??e}function $e(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function nt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function rt(e,S){let w=`onStoreDocument-${e}`;(t.debouncer.isDebounced(w)?t.debouncer.executeNow(w):Promise.resolve()).then(()=>B?.()).catch(e=>{log$2.warn({err:e},`[${S}] post-write flush failed`)})}function it(){let e=new Set;for(let[t,S]of D()){e.add(t);for(let t of S.aliases)e.add(t)}return e}function at(){let e=Promise.resolve();return async function(t){let S=e,w=()=>{};e=new Promise(e=>{w=e}),await S;try{return await t()}finally{w()}}}let st=at(),vt=e=>e.endsWith(`.`)?e:`${e}.`;function Tt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:vt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError?{status:400,type:`urn:ok:error:invalid-request`,error:vt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:vt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:vt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:vt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Et(e){let w=new Map;for(let S of e){let e=t.documents.get(S);e&&w.set(S,e.getText(`source`).toString())}for(let t of e)await S.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let S of e){let e=t.documents.get(S);deleteReconciledBase(S),e&&(t.closeConnections(S),await(_e??t.unloadDocument.bind(t))(e))}return w}function Dt(e,t){for(let{fromDocName:S,toDocName:E}of e){let e=safeContentPath(E,w),D=t.get(S);typeof D==`string`&&tracedWriteFileSync(e,D,`utf-8`);let O=typeof D==`string`?D:existsSync(e)?readFileSync(e,`utf-8`):null;typeof O==`string`&®isterWrite(e,contentHash(O))}}function jt(e,t){return e.map(e=>{let S=t.get(e);if(typeof S==`string`)return{docName:e,content:S};let E=safeContentPath(e,w);if(!existsSync(E))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(E,`utf-8`)}})}function Mt(e){let S=t.documents.get(e);if(S)return S.getText(`source`).toString();let E=resolveContentEntryPath(w,`file`,e);return existsSync(E)?readFileSync(E,`utf-8`):null}function Ft(e,t){let S=resolveContentEntryPath(w,`file`,e);tracedMkdirSync(dirname(S),{recursive:!0}),tracedWriteFileSync(S,t,`utf-8`),registerWrite(S,contentHash(t)),setReconciledBase(e,t);let E=D();E instanceof Map&&updateFileIndex({kind:`update`,path:S,docName:e,content:t},E)}function It(e,S){let w=t.documents.get(e);if(!w)throw Error(`Document is not loaded: ${e}`);let E={markdown:``,rewrites:0};return w.transact(()=>{E=applyRenameMap(w.getText(`source`).toString(),e,S),E.rewrites!==0&&composeAndWriteRawBody(w,E.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),E}async function Lt(e,S,E,O){return st(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":E}},async k=>{if(!ee)throw new BacklinkIndexRequiredError;let j=resolveContentEntryPath(w,E,e),F=resolveContentEntryPath(w,E,S);if(j===F)return{renamed:[],rewrittenDocs:[]};if(!existsSync(j))throw new ManagedRenameSourceNotFoundError(E);if(existsSync(F))throw new ManagedRenameDestinationExistsError;let B=statSync(j);if(E===`file`&&!B.isFile()||E===`folder`&&!B.isDirectory())throw new ManagedRenameSourceTypeMismatchError(E);let H=(E===`file`?[stripDocExtension(e)]:listAffectedDocNames(D(),E,e)).map(t=>({from:t,to:E===`file`?stripDocExtension(S):remapDocNameForRename(t,E,e,S)}));if(k.setAttribute(`rename.affected_docs`,H.length),H.length===0)return E===`folder`&&(await renameTrackedPathInGit(de,j,F)||(tracedMkdirSync(dirname(F),{recursive:!0}),tracedRenameSync(j,F)),Pe(e,S),ne?.(`files`)),{renamed:[],rewrittenDocs:[]};let J=buildRenameMap(H),Y=H.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),te=new Set;for(let{from:e}of H)for(let t of ee.getBacklinks(e))J.has(t.source)||te.add(t.source);let ae=[...te].sort((e,t)=>e.localeCompare(t)),oe=new Map,se=[],ce=[];for(let e of[...J.keys(),...ae]){if(oe.has(e))continue;if(!J.has(e)&&!existsSync(resolveContentEntryPath(w,`file`,e))){ce.push(e);continue}let t=Mt(e);typeof t==`string`?(oe.set(e,t),J.has(e)||se.push(e)):J.has(e)||ce.push(e)}for(let{from:e}of H)if(typeof oe.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:S,affectedDocs:[...H],snapshots:jt([...oe.keys()],oe)}),fe=[];return await withManagedRenameRecovery(de??w,ue,async()=>{for(let e of ce)ee.deleteDocument(e);for(let e of se){let S=t.documents.get(e)?It(e,J):applyRenameMap(oe.get(e)??``,e,J);S.rewrites>0&&(Ft(e,S.markdown),fe.push({docName:e,rewrites:S.rewrites})),ee.updateDocumentFromMarkdown(e,S.markdown)}if(ye)for(let{from:e,to:t}of H)isSystemDoc(e)||isConfigDoc(e)||(ye.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let k=resolveContentEntryPath(w,E,e),j=resolveContentEntryPath(w,E,S);await renameTrackedPathInGit(de,k,j)||(tracedMkdirSync(dirname(j),{recursive:!0}),tracedRenameSync(k,j)),E===`folder`&&Pe(e,S);let F=await Et([...J.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(L?.current){let e=L.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":E}},t=>{let S=randomUUID(),w=new Date().toISOString(),D=q?.()??`main`,k=getOrLoadRenameLogIndex(e.gitDir),j=O?.actor?{writerId:O.actor.writerId,displayName:O.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},F=0;for(let{from:t,to:L}of H){let B={v:1,from:t,to:L,at:w,commitSha:``,branch:D,groupId:S,kind:E,actor:j};appendRenameLogEntry(e.gitDir,B,k,e),F+=1,O?.actor?recordContributor(L,O.actor.writerId,O.actor.displayName,O.actor.colorSeed,formatRenameSubject(t,L),O.actor.actorMetadata,void 0,[{from:t,to:L}]):recordContributor(L,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,L),void 0,void 0,[{from:t,to:L}])}t.setAttribute(`rename.entries_appended`,F)})}let B=E===`file`&&isSupportedDocFile(S)?extname(S):null;for(let{from:e,to:t}of H){let S=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,B??S)}let Y=[...H].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of Y){let S=resolveContentEntryPath(w,`file`,e),E=resolveContentEntryPath(w,`file`,t),O=applyRenameMap(F.get(e)??oe.get(e)??readFileSync(E,`utf-8`),e,J);Dt([{fromDocName:e,toDocName:t}],new Map([[e,O.markdown]])),setReconciledBase(t,O.markdown);let k=D();k instanceof Map&&updateFileIndex({kind:`rename`,oldPath:S,newPath:E,oldDocName:e,newDocName:t,content:O.markdown},k),ee.renameDocument(e,t,O.markdown),O.rewrites>0&&fe.push({docName:t,rewrites:O.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ee.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ne?.(`files`),ne?.(`backlinks`),ne?.(`graph`),fe.sort((e,t)=>e.docName.localeCompare(t.docName)),k.setAttribute(`rename.rewrite_count`,fe.length),{renamed:Y,rewrittenDocs:fe}}))}function Rt(e){let t=parseAgentBodyFields(e),S=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:S,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??S,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function zt(e){return{principalId:fe?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Bt(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function Vt(e){return{value:e.value}}function Ht(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}let Ut=withValidation(AgentWriteRequestSchema,async(t,w,E)=>{try{let t=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:D,agentName:O,colorSeed:k,clientName:j,clientVersion:F,label:L}=Rt(E);if(isSystemDoc(t)||isConfigDoc(t)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-write`});return}let B=normalizeSummary(E.summary),H=await S.getSession(t,D,{displayName:O,colorSeed:k,clientName:j}),q=new Date().toISOString(),J=typeof E.content==`string`?E.content:`Hello from the agent! ${q}`,{response:Y,stored:ee}=Bt(B);try{let S=iconFromClientName(j),w=AGENT_ICON_COLORS[S]??colorFromSeed(k??D);oe?.setPresence(D,{displayName:O,icon:S,color:w,currentDoc:t,mode:`writing`,ts:Date.now()}),captureEffect(H.dc.document.getText(`source`),D,k,j),H.dc.document.transact(()=>{applyAgentMarkdownWrite(H.dc.document,`${J}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:t}:void 0),H.dc.document.getMap(`agent-flash`).set(D,{agentId:D,timestamp:Date.now(),type:`insert`,description:`Added (${O}): ${J.slice(0,50)}`})},H.origin),recordContributor(t,D,O,k,void 0,zt({clientName:j,clientVersion:F,label:L}),ee),incrementAgentWriteCalls(),Ht(B)}finally{oe?.touchMode(D,`idle`)}rt(t,`agent-write`),se?.(),successResponse(w,200,AgentWriteSuccessSchema,{timestamp:q,...Y?{summary:Y}:{}},{handler:`agent-write`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Wt=withValidation(AgentWriteMdRequestSchema,async(t,w,E)=>{try{let t=E.position??`append`,D=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Rt(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write-md`});return}let H=normalizeSummary(E.summary),{response:q,stored:J}=Bt(H),Y=await S.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=new Date().toISOString();try{let S=iconFromClientName(F),w=AGENT_ICON_COLORS[S]??colorFromSeed(j??O);oe?.setPresence(O,{displayName:k,icon:S,color:w,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),O,j,F),Y.dc.document.transact(()=>{applyAgentMarkdownWrite(Y.dc.document,E.markdown,t,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),Y.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),recordContributor(D,O,k,j,void 0,zt({clientName:F,clientVersion:L,label:B}),J),incrementAgentWriteCalls(),Ht(H)}finally{oe?.touchMode(O,`idle`)}rt(D,`agent-write-md`),ae?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),se?.();let te=Ke(D),ne=$e(D),ce=nt();ce===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)}),successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ee,subscriberCount:ne,systemSubscriberCount:ce,...te?{hints:te}:{},...q?{summary:q}:{}},{handler:`agent-write-md`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Kt=withValidation(FrontmatterPatchRequestSchema,async(e,t,w)=>{try{let e=Xe(w.docName!==void 0&&w.docName.length>0?w.docName:`test-doc`),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Rt(w);if(isSystemDoc(e)||isConfigDoc(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${e}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let L=w.patch??{},B=Object.keys(L),H=normalizeSummary(w.summary),{response:q,stored:J}=Bt(H),Y=await S.getSession(e,E,{displayName:D,colorSeed:O,clientName:k}),ee=new Date().toISOString(),te,ne=!1,ce=[];try{let t=iconFromClientName(k),S=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);oe?.setPresence(E,{displayName:D,icon:t,color:S,currentDoc:e,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":e,"frontmatter_patch.keys":B.length}},()=>{Y.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(Y.dc.document.getText(`source`).toString()),S=applyPatchToFm(e,L);if(!S.ok){te=S.error;return}for(let e of Object.keys(L))ce.push(e);if(S.nextFenced!==e){let e=S.nextFenced+t;composeAndWriteRawBody(Y.dc.document,e,`agent`),recordFrontmatterEditSurface(`mcp-write`)}ne=!0},Y.origin)})}finally{oe?.touchMode(E,`idle`)}if(te){let e;switch(te.kind){case`invalid_value`:e={[te.key]:te.reason};break;case`reserved_key`:e={[te.key]:`'${te.key}' is reserved`};break;case`unknown_key`:e={[te.key]:`'${te.key}' is not a recognized key`};break;case`duplicate_target`:e={[te.key]:`'${te.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${te.expected.join(`, `)}; got: ${te.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${te.bytes} > ${te.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${te.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(te)})`}}errorResponse(t,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}ne&&ce.length>0&&(recordContributor(e,E,D,O,void 0,zt({clientName:k,clientVersion:j,label:F}),J),incrementAgentWriteCalls(),Ht(H),rt(e,`frontmatter-patch`)),ae?.setFocus(E,{agentName:D,currentDoc:e,writeKind:`write`,ts:Date.now()}),se?.();let ue=$e(e),de=nt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(k)}),successResponse(t,200,FrontmatterPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,appliedKeys:ce,...q?{summary:q}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(t,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`}),$t=withValidation(EmptyRequestSchema,async(e,S)=>{try{let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(E)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let D=Xe(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`document-read`});return}let O=t.documents.get(D);if(O){successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:O.getText(`source`).toString()},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(w,`file`,D))){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document not found: ${D}.`,{handler:`document-read`});return}let k=await t.openDirectConnection(D);try{let e=k.document;if(!e){errorResponse(S,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:e.getText(`source`).toString()},{handler:`document-read`})}finally{await k.disconnect()}}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),en=withValidation(EmptyRequestSchema,async(e,t)=>{try{ve&&await ve.catch(e=>{log$2.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=S.searchParams.get(`dir`),k=S.searchParams.get(`showAll`)===`true`;if(E)try{safeSubdir(w,E)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(k&&me){let e=[];try{await walkContentDirForShowAll({contentDir:w,contentFilter:me,dirFilter:E,documents:e,getDocExtension}),e.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:e},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}return}let j=D(),F=O?.()??new Map,L=[];for(let[e,t]of F)E&&!e.startsWith(`${E}/`)&&e!==E||L.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of j){if(E&&!e.startsWith(`${E}/`)&&e!==E)continue;let S=getDocExtension(e);L.push({kind:`document`,docName:e,docExt:S,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let D of t.aliases){if(E&&!D.startsWith(`${E}/`)&&D!==E)continue;let O=relative(w,t.canonicalPath);L.push({kind:`document`,docName:D,docExt:S,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:O})}}let B=[];try{let e=Ie(j);we?.signature!==e&&(we={signature:e,assets:collectReferencedAssets({contentDir:w,fileIndex:j,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:me?e=>me.isPathIgnored(e):void 0})}),B=we?.assets??[]}catch(e){we=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of B)E&&!e.path.startsWith(`${E}/`)&&e.path!==E||L.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});L.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:L},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),jr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:S,backlinks:ee.getBacklinks(S).map(e=>({source:e.source,anchor:e.anchor,title:Be(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Mr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let w={};for(let e of S.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(w[t]=ee.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:w},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Fr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let w=it();successResponse(t,200,ForwardLinksSuccessSchema,{docName:S,forwardLinks:ee.getForwardLinkEntries(S).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ve(e.target,w),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Ir=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`docName`);if(w&&!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let E=S.searchParams.get(`degrees`);if(E&&!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let D,O;if(E&&w){let e=Number.parseInt(E,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:D,links:O}=ee.getLinkGraphNeighborhood(w,e))}else ({nodes:D,links:O}=ee.getLinkGraph());let k=it();successResponse(t,200,LinkGraphSuccessSchema,{nodes:D.map(e=>{if(e.kind===`doc`){let t=Ge(e.docName,k);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ve(e.docName,k),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:O},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Lr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ee.getOrphans([...D().keys()],S).map(e=>({docName:e,title:Be(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),zr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),w=S?Number.parseInt(S,10):20,E=Number.isFinite(w)&&w>0?w:20,D=it();successResponse(t,200,HubsSuccessSchema,{hubs:ee.getHubs(E).map(e=>({docName:e.docName,title:Ve(e.docName,D),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Br=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(S.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let w=S.length?[...new Set(S.map(e=>Xe(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ee.getDeadLinks(it(),w).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Be(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Vr=withValidation(AgentPatchRequestSchema,async(t,w,E)=>{try{let{find:t,replace:D,offset:O}=E,k=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:j,agentName:F,colorSeed:L,clientName:B,clientVersion:H,label:q}=Rt(E);if(findLooksLikeFrontmatter(t)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await S.getSession(k,j,{displayName:F,colorSeed:L,clientName:B}),ee=new Date().toISOString(),te=!1,ne=!1,ce=!1;try{let S=iconFromClientName(B),w=AGENT_ICON_COLORS[S]??colorFromSeed(L??j);if(oe?.setPresence(j,{displayName:F,icon:S,color:w,currentDoc:k,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),j,L,B),Y.dc.document.transact(()=>{let{frontmatter:S,body:w}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),E=prependFrontmatter(S,w),L=O==null?E.indexOf(t):E.slice(O,O+t.length)===t?O:-1;if(L===-1){O==null?te=!0:ne=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":k,findLength:t.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(L<S.length){ce=!0;return}let{body:B}=stripFrontmatter(E.slice(0,L)+D+E.slice(L+t.length));applyAgentMarkdownWrite(Y.dc.document,B,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0),Y.dc.document.getMap(`agent-flash`).set(j,{agentId:j,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${t.slice(0,50)}`})},Y.origin),!te&&!ne&&!ce){let{stored:e}=Bt(J);recordContributor(k,j,F,L,void 0,zt({clientName:B,clientVersion:H,label:q}),e),incrementAgentWriteCalls(),Ht(J)}}finally{oe?.touchMode(j,`idle`)}if(ne){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(te){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ce){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}rt(k,`agent-patch`),ae?.setFocus(j,{agentName:F,currentDoc:k,writeKind:`edit`,ts:Date.now()}),se?.();let ue=$e(k),de=nt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(B)});let{response:fe}=Bt(J);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,...fe?{summary:fe}:{}},{handler:`agent-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$2.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Hr=withValidation(AgentUndoRequestSchema,async(t,w,E)=>{try{let{agentId:t,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Rt(E),L=Xe(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`);if(isSystemDoc(L)||isConfigDoc(L)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${L}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:B}=E,H=E.scope===`session`||E.scope===`file`?`session`:`last`;if(!S.hasSession(L,B)){errorResponse(w,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let q=await S.getSession(L,B),J=!1;try{let S=iconFromClientName(k),w=AGENT_ICON_COLORS[S]??colorFromSeed(O??t);oe?.setPresence(t,{displayName:D,icon:S,color:w,currentDoc:L,mode:`writing`,ts:Date.now()}),J=applyAgentUndo(q,H,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:L}:void 0),J&&recordContributor(L,B,D,O,void 0,zt({clientName:k,clientVersion:j,label:F}))}finally{oe?.touchMode(t,`idle`)}J&&rt(L,`agent-undo`),ae?.setFocus(B,{agentName:B,currentDoc:L,writeKind:`undo`,ts:Date.now()}),successResponse(w,200,AgentUndoSuccessSchema,{docName:L,scope:H,undone:J},{handler:`agent-undo`})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Ur=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(S,w),{handler:`agent-activity`})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Wr=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=validateAgentId(w.searchParams.get(`agentId`)),D=w.searchParams.get(`docName`),O=w.searchParams.get(`stackIndex`);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!D||D.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let k=Xe(D);if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!O||Number.isNaN(Number(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let j=Number(O);if(!Number.isInteger(j)||j<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let F=S.getLiveSession(k,E);if(!F){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let L=F.um;if(j>=L.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${j} out of range (stack has ${L.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let B=L.undoStack[j];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(B,F.dc.document.getText(`source`),k),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Gr=withValidation(EmptyRequestSchema,async(e,E)=>{try{let D=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),O=Xe(D.searchParams.get(`docName`)??`test-doc`),k;try{k=safeContentPath(O,w)}catch(e){log$2.error({err:e,docName:O},`[test-reset] safeContentPath rejected docName`),errorResponse(E,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await S.closeAll(O),t.closeConnections(O);let j=`onStoreDocument-${O}`;t.debouncer.isDebounced(j)&&await t.debouncer.executeNow(j);let F=t.documents.get(O);if(F&&await(_e??t.unloadDocument.bind(t))(F),writeFileSync(k,``,`utf-8`),ee&&(ee.deleteDocument(O),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${O}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),D.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(w,`.okignore`),S=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(S){let e=S.getText(`source`);e.length>0&&S.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),me&&await me.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}ne?.(`files`),successResponse(E,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Kr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ee.rebuildFromDisk(),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),ne?.(`backlinks`),ne?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),qr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!j){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}j(),ne?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Jr=withValidation(SaveVersionRequestSchema,async(e,t,S)=>{try{let{rawAgentId:e,agentId:w,agentName:E,clientName:D}=Rt(S),O=L?.current;if(!O){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let k=/^[a-zA-Z0-9_-]+$/,j=[],F,B,H;if(typeof S.message==`string`&&S.message.trim()&&(F=S.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(S.writers))try{j=S.writers.map(e=>{let t=e.id??`unknown`;if(!k.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}S.principal&&(typeof S.principal.name==`string`&&S.principal.name.trim()&&(B=sanitizeGitIdentity(S.principal.name.trim())),typeof S.principal.email==`string`&&S.principal.email.trim()&&(H=sanitizeGitIdentity(S.principal.email.trim()))),j.length===0&&(j=e===void 0?[SERVICE_WRITER]:[{id:w,name:D?`${E} (${D})`:E,email:`${w}@openknowledge.local`}]);let q=Y??`.`,J=await saveVersion(O,q,j);console.log(`[history] checkpoint ${J.checkpointRef}`);try{await gcRenameLog(O,getOrLoadRenameLogIndex(O.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}let ee=swapContributors(),te;if(de){let e=!1;try{await esm_default({baseDir:de,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{te=await withParentLock(async()=>{let e=esm_default({baseDir:de,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,S=`ok/v${t}`,w=`openknowledge`,E=`noreply@openknowledge.local`;if(B&&H)w=B,E=H;else try{let e=await resolveGitIdentity(de);e&&(w=e.name,E=e.email)}catch{}let D=[];for(let e of ee.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;D.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let O=formatCheckpointSubject(F??`Checkpoint v${t}`),k=D.length>0?`${O}\n\n${D.join(`
|
|
2108
2108
|
`)}`:O,j=q||`.`;return await e.add(j),await e.env({GIT_AUTHOR_NAME:w,GIT_AUTHOR_EMAIL:E,GIT_COMMITTER_NAME:w,GIT_COMMITTER_EMAIL:E}).commit(k,[`--allow-empty`]),await e.addTag(S),console.log(`[checkpoint] parent-git commit + tag ${S}`),S})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:J.checkpointRef,...te?{versionTag:te}:{}},{handler:`save-version`})}catch(e){log$2.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),Yr=withValidation(EmptyRequestSchema,async(e,t)=>{let S=L?.current;if(!S){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`docName`)??``,D=w.searchParams.get(`branch`)??q?.()??`main`;if(!E){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName query parameter is required.`,{handler:`history`});return}if(D.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}let O=Y??`.`,k=safeDocPath(E,O);if(`error`in k){errorResponse(t,400,`urn:ok:error:invalid-request`,k.error,{handler:`history`});return}let j=Number(w.searchParams.get(`limit`)??`50`),F=Number(w.searchParams.get(`offset`)??`0`),B=Math.min(200,Number.isFinite(j)?j:50),H=Number.isFinite(F)?F:0,J=w.searchParams.get(`type`)??void 0,ee=w.searchParams.get(`author`)??void 0,te=w.searchParams.get(`excludeAuthor`)??void 0,ne=Date.now();try{let e=await getDocumentHistory(S,{docName:E,branch:D,limit:B,offset:H,type:J,author:ee,excludeAuthor:te},O),w=Date.now()-ne;console.log(`[timeline] query docName=${E} entries=${e.entries.length} duration=${w}ms`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Xr(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let w=L?.current;if(!w){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,D=Y??`.`,O=safeDocPath(E,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history-version`});return}let k=shadowGit(w),j=q?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(w,E,S,j,getOrLoadRenameLogIndex(w.gitDir),e=>{let t=safeDocPath(e,D);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let O=await k.raw(`show`,`${S}:${e}`),[F=``,L=``]=(await k.raw(`log`,`-1`,`--format=%aI%x00%an`,S)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:S,content:O,timestamp:F,author:L},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let Zr=withValidation(EmptyRequestSchema,async(e,S)=>{let w=L?.current;if(!w){errorResponse(S,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),D=E.searchParams.get(`docName`)??``,O=E.searchParams.get(`from`)??``,k=E.searchParams.get(`to`)??``;if(!k||!/^[0-9a-f]{40}$/i.test(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let j=Y??`.`,F=safeDocPath(D,j);if(`error`in F){errorResponse(S,400,`urn:ok:error:invalid-request`,F.error,{handler:`diff`});return}let B=shadowGit(w),H=q?.()??`main`,J=getOrLoadRenameLogIndex(w.gitDir),ee=createAncestorShaSetCache(),te=e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(w,D,k,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let E=await B.raw(`show`,`${k}:${e}`),j;if(O&&/^[0-9a-f]{40}$/i.test(O)){let e=await resolveDocPathAtCommit(w,D,O,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}j=await B.raw(`show`,`${O}:${e}`)}else{let e=t.documents.get(D);if(!e){errorResponse(S,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}j=e.getText(`source`).toString()}let F=stripFrontmatter(j).body,L=stripFrontmatter(E).body,q=diffLines(F,L),Y=[],ne=0,ae=0;for(let e of q){let t=e.value.replace(/\n$/,``).split(`
|
|
2109
2109
|
`),S=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:S,text:e});e.added&&(ne+=t.length),e.removed&&(ae+=t.length)}successResponse(S,200,DiffSuccessSchema,{lines:Y,additions:ne,deletions:ae},{handler:`diff`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Qr=withValidation(RollbackRequestSchema,async(S,w,E)=>{let D=extractActorIdentity(E,fe);if(D.kind===`invalid-summary`){errorResponse(w,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let O=L?.current;if(!O){errorResponse(w,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:k,commitSha:j,versionTag:F}=E,B=Y??`.`,H=safeDocPath(k,B);if(`error`in H){errorResponse(w,400,`urn:ok:error:invalid-request`,H.error,{handler:`rollback`});return}let J=shadowGit(O),ee=Date.now();try{let S=getOrLoadRenameLogIndex(O.gitDir),E=createAncestorShaSetCache(),L=await resolveDocPathAtCommit(O,k,j,q?.()??`main`,S,e=>{let t=safeDocPath(e,B);return`error`in t?`${e}.md`:t.path},E);if(L===null){errorResponse(w,404,`urn:ok:error:doc-not-found`,`Commit ${j.slice(0,7)} does not contain document ${k} at any known historical path.`,{handler:`rollback`});return}let H=await J.raw(`show`,`${j}:${L}`),te=new Date().toISOString();await safetyCheckpoint(O,B,{action:`rollback`,context:{docName:k,targetSha:j}});let ne=t.documents.get(k);if(!ne){errorResponse(w,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let oe=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0;ne.transact(()=>{replaceRawBody(ne,H,oe)},ROLLBACK_ORIGIN);let se;switch(D.kind){case`agent`:{let e=j.slice(0,8),t=D.summary.kind===`value`,S=t?D.summary:normalizeSummary(`Restored to ${e}`),w=Bt(S);se=t||!w.response?w.response:Vt(w.response),recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,w.stored),incrementAgentWriteCalls(),Ht(S,!t);break}case`principal`:{let e=Bt(D.summary);se=e.response,recordContributor(k,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(k,j),D.actor,e.stored),Ht(D.summary,!1);break}case`anonymous`:log$2.debug({docName:k,commitSha:j.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(D.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:D.kind}),rt(k,`rollback`);let ce=Date.now()-ee;if(console.log(`[rollback] docName=${k} from=${j.slice(0,8)} duration=${ce}ms`),de){let e=`Restored to ${F??j.slice(0,8)}: ${k}`,t=Y??`.`;withParentLock(async()=>{let S=esm_default({baseDir:de,timeout:{block:15e3}}),w=t||`.`;await S.add(w),await S.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}D.kind===`agent`&&ae?.setFocus(D.writerId,{agentName:D.displayName,currentDoc:k,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(w,200,RollbackSuccessSchema,{restoredFrom:j,timestamp:te,...se?{summary:se}:{}},{handler:`rollback`})}catch(e){errorResponse(w,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ji=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$2.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),Hi=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$2.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Ui=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=getActiveBranch(),S=J?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:E,currentBranch:e,...S===void 0?{}:{currentDiskAckSVs:S}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function Gi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let S=fe?.()??null;if(!S){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,S,{handler:`principal`})}async function Ki(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=oe?.getPresenceMap()??{},S=Date.now(),w={};for(let[t,E]of Object.entries(e))S-E.ts<2e4&&(w[t]=E);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:w},{handler:`metrics-agent-presence`})}catch(e){log$2.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Yi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let S=resolve(w),E=S,D=!0;try{E=realpathSync(S)}catch(e){let w=e?.code;if(w===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:S}),D=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:S,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:w??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:E,pathSeparator:sep,symlinkResolved:D},{handler:`workspace`})}let Xi=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let E=assetContentTypeForPath(S),D=extname(S).slice(1).toLowerCase();if(!E||!ASSET_EXTENSIONS.has(D)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let O=realpathSync(w),k=resolve(O,S),j;try{j=realpathSync(k)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(j,O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let F;try{F=statSync(j)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!F.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let L=toContentRelativePath(O,j);if(L!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(me?.isPathIgnored(L)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let B={"Content-Type":E,"Content-Length":String(F.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(D)?`inline`:`attachment`,"Cache-Control":`no-store`};D===`svg`&&(B[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,B);try{await pipeline(createReadStream(j),t)}catch(e){log$2.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:S,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Zi=1048576,ka=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let E=realpathSync(w),D=resolve(E,S),O;try{O=realpathSync(D)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let k;try{k=statSync(O)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(E,O)!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(k.size>Zi){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Zi}-byte text-viewer cap.`,{handler:`asset-text`});return}let j=(await readFile$1(O)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(j)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),_s=1440*60*1e3,xs=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!L?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),S=[],w=resolve(L.current.gitDir,`rescue`);if(existsSync(w))try{let t=readdirSync(w).filter(e=>isSupportedDocFile(e));for(let E of t){let t=resolve(w,E),D=statSync(t);if(e-D.mtimeMs>_s){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}S.push({docName:stripDocExtension(E),timestamp:D.mtime.toISOString(),size:D.size,source:`flat`})}}catch(e){log$2.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=q?.()??`main`,t=await listRescueCheckpoints(L.current,e);for(let e of t)S.push({...e,source:`timeline`})}catch(e){log$2.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,S,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0});async function Cs(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!L?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let w=resolve(L.current.gitDir,`rescue`),E=resolve(w,`${S}${getDocExtension(S)}`);if(!E.startsWith(`${w}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(E)){let e=statSync(E);if(Date.now()-e.mtimeMs>_s)try{unlinkSync(E)}catch{}else{let e=readFileSync(E,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=q?.()??`main`,w=(await listRescueCheckpoints(L.current,e)).filter(e=>e.docName===S).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(w){let e=shadowGit(L.current),S=((await e.raw(`ls-tree`,`-r`,w.sha)).trim().split(`
|
|
2110
|
-
`)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let Ts=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(ye?.delete(H),me&&me.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),ee&&(ee.updateDocumentFromMarkdown(H,L),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Ds=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(me?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),je(e),ne?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Os=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=ze(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),ks=withValidation(RenamePathRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:E,fromPath:D,toPath:O}=S;if(!isValidRelativeContentPath(D)||!isValidRelativeContentPath(O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(E===`file`&&(isSystemDoc(D)||isSystemDoc(O)||isConfigDoc(D)||isConfigDoc(O))){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||O===`.ok`||O.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(D===O){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(D.toLowerCase()===O.toLowerCase()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(E===`file`&&probeAndRegisterSourceFileExtension(w,D),me&&(E===`file`?me.isExcluded(isSupportedDocFile(O)?O:`${O}${getDocExtension(D)}`):me.isDirExcluded(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination ${E===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let k=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,j;try{j=await Lt(D,O,E,k?{actor:k}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(t,409,`urn:ok:error:doc-already-exists`,vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(j.renamed.length===0){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let F;switch(e.kind){case`agent`:{let t=e.summary.kind===`value`,S=t?e.summary:normalizeSummary(`Renamed ${D} → ${O}`),w=Bt(S);F=t||!w.response?w.response:Vt(w.response);for(let t=0;t<j.renamed.length;t++){let{fromDocName:S,toDocName:E}=j.renamed[t];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(S,E),e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Ht(S,!t);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`principal`:{let t=Bt(e.summary);F=t.response;for(let S=0;S<j.renamed.length;S++){let{fromDocName:w,toDocName:E}=j.renamed[S];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(w,E),e.actor,S===0?t.stored:void 0)}Ht(e.summary,!1);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:E,fromPath:D,toPath:O,affectedDocs:j.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(e.kind)}`)}if(renameAttributionCounter().add(1,{kind:`rename-${E}`,attribution_kind:e.kind}),H)try{await H()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(t,200,RenamePathSuccessSchema,{renamed:j.renamed,rewrittenDocs:j.rewrittenDocs,...F?{summary:F}:{}},{handler:`rename-path`})}catch(e){let{status:S,type:w,error:E}=Tt(e);errorResponse(t,S,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),As=withValidation(DeletePathRequestSchema,async(e,t,S)=>{try{Rt(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let O=resolveContentEntryPath(w,e,E);if(!existsSync(O)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let k=statSync(O);if(e===`file`&&!k.isFile()||e===`folder`&&!k.isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let j=e===`file`?[E]:listAffectedDocNames(D(),e,E);if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`?unlinkSync(O):(rmSync(O,{recursive:!0,force:!1}),Me(E));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);successResponse(t,200,DeletePathSuccessSchema,{deletedDocNames:j},{handler:`delete-path`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ns=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&(E===`__system__`||E===`__config__`||E===`__user__`||E===`__local__`||E.startsWith(`__system__/`)||E.startsWith(`__config__/`)||E.startsWith(`__user__/`)||E.startsWith(`__local__/`));if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}let k=D(),j=e===`file`?k.has(E)?[E]:[]:listAffectedDocNames(k,e,E);if(j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Me(E),ne?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(w,`${t}${D}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:D,size:E.size,modified:E.modified})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Rs(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,de??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=Rt(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$2.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(e.code!==`EEXIST`){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let $s=`/api/local-op/clone`,ec=`/api/local-op/open`,tc=600*1e3,nc=45e3,rc=`local-op-clone`,ic=withValidation(LocalOpCloneRequestSchema,ac,{handler:rc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:rc})});async function ac(e,t,S){let{url:w,dir:E}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:rc,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:rc,cause:Error(`dir=${E}`)});return}if(!Ce.tryAcquire($s)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:rc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let D=createStreamingErrorWriter(t,rc),O=null,k=runCloneSubprocess({cliArgs:ue,url:w,dir:E,timeoutMs:tc,onEvent:e=>{if(e.type===`complete`){O=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),D(500,`urn:ok:error:clone-failed`,`Clone subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await k.done,O&&!t.writableEnded&&!t.destroyed){let e=await oc(O);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:O})}\n`):D(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?D(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$2.error({err:e,handler:rc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ce.release($s)}})(),t.on(`close`,()=>{k.cancel()})}async function oc(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=ue,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$2.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let sc=`local-op-open`,cc=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:sc,cause:Error(`dir=${w}`)});return}if(!Ce.tryAcquire(ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:sc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await oc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:sc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:sc,cause:Error(e.error)})}finally{Ce.release(ec)}},{handler:sc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:sc})}),lc=`/api/local-op/auth/login`,uc=`/api/local-op/auth/status`,dc=`/api/local-op/auth/repos`,fc=`/api/local-op/auth/signout`,pc=`/api/local-op/auth/pat`,mc=`local-op-auth-login`,hc=withValidation(LocalOpAuthHostRequestSchema,gc,{handler:mc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:mc})});async function gc(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(lc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:mc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,mc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:tc,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}}),O=()=>{D.cancel()};t.on(`close`,O),D.done.finally(()=>{t.off(`close`,O),t.writableEnded||t.end(),Ce.release(lc)})}let _c=`local-op-auth-status`,vc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(uc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:_c,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2111
|
-
`).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:
|
|
2112
|
-
`);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ce.release(
|
|
2113
|
-
`).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:wc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:wc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:wc,cause:e})}finally{Ce.release(pc)}},{handler:wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:wc})}),Ec=`local-op-auth-identity`;async function Dc(e,t){if(checkLocalOpSecurity(e,t,{handler:Ec})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Ec,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ec});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Ec})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Ec,cause:e})}}}let Oc=`/api/local-op/auth/set-identity`,kc=`local-op-auth-set-identity`,Ac=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:kc});return}if(!Ce.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:kc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:kc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:kc,cause:e})}finally{Ce.release(Oc)}},{handler:kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:kc})});async function jc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Mc=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Nc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Pc=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Fc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=esm_default({baseDir:de,timeout:{block:15e3}});async function E(e){try{return await w.raw([`show`,`:${e}:${S}`])}catch{return``}}try{let[e,w,D]=await Promise.all([E(1),E(2),E(3)]);successResponse(t,200,SyncConflictContentSuccessSchema,{file:S,base:e,ours:w,theirs:D},{handler:`sync-conflict-content`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Ic(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Lc=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Rc(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let zc=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Bc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Re.probeAll)}catch(e){t.headersSent||(log$2.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Vc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ce?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Hc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:te.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Uc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=te.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:Be(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Wc(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let Gc=/^[A-Za-z0-9_-]+$/;function Kc(e,t,S=`template`){return!e||!Gc.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function qc(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}async function Jc(e,t){if(e.method===`GET`)return Yc(e,t);if(e.method===`PUT`)return Xc(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Wc(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`,`frontmatter.yml`),D=null;if(existsSync(E))try{let e=(0,import_dist$1.parse)(await readFile$1(E,`utf-8`));D=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${E}: ${t}`),D=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:D},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Xc=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Wc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:qc(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:E.applied},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});async function Zc(e,t){if(e.method===`GET`)return nl(e,t);if(e.method===`PUT`)return il(e,t);if(e.method===`DELETE`)return al(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Qc=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,$c=e=>{let t=e.match(Qc),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},nl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Kc(w,t,`template-get`))return;let E=Wc(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=$c(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),il=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Kc(e,t,`template-put`))return;let w=Wc(S.folder,t,`folder`,`template-put`);if(!w)return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:qc(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),al=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Kc(w,t,`template-delete`))return;let E=Wc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E)return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function cl(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function ll(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function ul(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function dl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function fl(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,...cl(e)]}function pl(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function ml(){let e=`${w}${de??``}`,t=pl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=fl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function hl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{ml().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}hl();async function gl(e,t){if(e.method===`GET`)return _l(e,t);if(e.method===`POST`)return vl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let _l=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=ul(S.searchParams.get(`intent`)),O=dl(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await ml(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ll(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),vl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=ul(S.intent),D=dl(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await ml(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ll(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function xl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let Tl=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!de){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(de);if(e===null){if(readOriginGitHubRepo(de).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(de);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(de,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})});async function El(e){let[t,...S]=ue,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Dl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await El([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Ol=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ce.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await El([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),kl=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!de){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ce.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,de,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await El(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),jl={"/api/asset":Xi,"/api/asset-text":ka,"/api/document":$t,"/api/documents":en,"/api/backlinks":jr,"/api/backlink-counts":Mr,"/api/forward-links":Fr,"/api/link-graph":Ir,"/api/dead-links":Br,"/api/orphans":Lr,"/api/hubs":zr,"/api/tags":Hc,"/api/pages":Ps,"/api/folder-config":Jc,"/api/template":Zc,"/api/search":gl,"/api/suggest-links":Is,"/api/page-headings":Os,"/api/create-page":Ts,"/api/create-folder":Ds,"/api/rename-path":ks,"/api/delete-path":As,"/api/trash/cleanup":Ns,"/api/upload":Rs,"/api/agent-write":Ut,"/api/agent-write-md":Wt,"/api/frontmatter-patch":Kt,"/api/agent-patch":Vr,"/api/agent-undo":Hr,"/api/agent-activity":Ur,"/api/agent-burst-diff":Wr,"/api/save-version":Jr,"/api/history":Yr,"/api/diff":Zr,"/api/rollback":Qr,"/api/metrics/reconciliation":ji,"/api/metrics/parse-health":Hi,"/api/metrics/agent-presence":Ki,"/api/server-info":Ui,"/api/share/construct-url":Tl,"/api/share/publish/owners":Dl,"/api/share/publish/name-check":Ol,"/api/share/publish":kl,"/api/principal":Gi,"/api/rescue":xs,"/api/workspace":Yi,"/api/sync/status":jc,"/api/sync/trigger":Mc,"/api/sync/conflicts":Nc,"/api/sync/conflict-content":Fc,"/api/sync/resolve-conflict":Pc,"/api/sync/abort-merge":Vc,"/api/local-op/clone":ic,"/api/local-op/open":cc,"/api/local-op/auth/login":hc,"/api/local-op/auth/status":vc,"/api/local-op/auth/repos":bc,"/api/local-op/auth/signout":Cc,"/api/local-op/auth/pat":Tc,"/api/local-op/auth/identity":Dc,"/api/local-op/auth/set-identity":Ac,"/api/installed-agents":Bc,"/api/spawn-cursor":Cl,"/api/handoff":xl,"/api/install-skill":zc,"/api/skill/install-state":yl,"/api/seed/plan":Ic,"/api/seed/apply":Lc,"/api/seed/packs":Rc};F&&(jl[`/api/test-reset`]=Gr,jl[`/api/test-rescan-backlinks`]=Kr,jl[`/api/test-rescan-files`]=qr);let Ml=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Pl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ml.has(S)||Pl.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:jl[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=jl[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await Cs(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Xr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Uc(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `list_documents({ dir })`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search` / `grep`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` / `grep` / `read_document` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir. Prefer `-A` over plain `ls`: OK projects carry dot-prefixed entries (`.ok/`, nested `.ok/`, `.okignore`) that plain `ls` omits. `-A` shows hidden entries without the noisy `.`/`..` rows that `-a` adds, and without the verbose long-format columns that `-la` adds (the per-child enrichment already carries the useful metadata `-l` would surface).\n- Search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files\n- Typed tools (`read_document`, `search`, `grep`, `list_documents`) remain available — prefer them when a structured `structuredContent` shape is useful (e.g., passing results to another tool). For interactive reads, `exec` is lighter. **Pick the right search:** `search` for ranked retrieval (cmd-K parity — title boost + body BM25 + recency); `grep` for every literal-string occurrence grouped by file with frontmatter enrichment.\n\n## Preview — open the browser at session start\n\n**The invariant.** If OK Electron is open for this project OR `ok ui` is running for it, every OK tool response carries the preview URL — plain HTTP, no custom URL schemes, works in any browser including agent in-app browsers (Claude Desktop, Cursor, Codex, Cowork). Read tools (`exec`, `grep`, `search`, `list_documents`, `read_document`) carry it in `ui.baseUrl` (top-level) and per-doc `previewUrl` fields; write tools carry it in `previewUrl` + the optional `warning` shape. Never construct this URL; always read it from the latest tool response.\n\n**The default agent move.** Make your first OK tool call (any read works — `list_documents`, `exec("ls -A")`, or `read_document` is enough). The response carries the preview URL. Navigate to it immediately, then proceed with your real work. The user watches edits land live; you can re-navigate later to verify a CRDT edit landed when a response looks ambiguous. Per host:\n\n- **In-app browser hosts** (Claude Desktop, Cursor, Codex, Cowork): navigate the in-app browser to the `previewUrl`. Default.\n- **Claude Code Desktop**: call `preview_start("open-knowledge-ui")` (host tool, not OK MCP).\n- **Stdio-only hosts**: surface the URL in chat; `open <url>` (macOS) if the host can shell out.\n\n**Four signals to check if it\'s already open** (you usually can\'t pre-check, so read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot.\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `frontmatter_patch`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename_document` / `rename_folder` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings.\n\n**Always read `previewUrl` from the latest write response.** Don\'t cache the session-start value — Electron quit/reopen (or `ok ui` restart) can change the port; the resolver picks up the new port automatically.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry. NEVER construct preview URLs by hand.\n\nOK Electron and `ok ui` cannot serve the same project at once — they share `ui.lock`. A UI-lock collision means the other is running for that project (use that one, or quit it first).\n\n**The preview is read-only for the agent.** Navigate to verify edits landed; you cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots after every edit.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after every write. Trust the response. Screenshot only when (a) debugging a visual issue, (b) a response looks ambiguous, or (c) the user asks.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
2110
|
+
`)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let Ts=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(ye?.delete(H),me&&me.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),ee&&(ee.updateDocumentFromMarkdown(H,L),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Ds=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(me?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),je(e),ne?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Os=withValidation(DuplicatePathRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:E}=S,O=E===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(O===`.ok`||O.startsWith(`.ok/`)||E===`file`&&(isSystemDoc(O)||isConfigDoc(O))||E===`folder`&&isReservedSyntheticFolderPath(O)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}E===`file`&&probeAndRegisterSourceFileExtension(w,O);let k=resolveContentEntryPath(w,E,O);if(!existsSync(k)){if(E===`file`){let e=resolveContentEntryPath(w,`folder`,O);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}}errorResponse(t,404,`urn:ok:error:doc-not-found`,`${E} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(E===`file`&&!j.isFile()||E===`folder`&&!j.isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}let F=typeof D==`function`?D():null,L,B=[];if(E===`file`){let e=extname(k);if(L=nextAvailableDuplicateDocName(w,O).docName,isSystemDoc(L)||isConfigDoc(L)||me?.isExcluded(`${L}${e}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let S=resolveDuplicateDocPath(w,L,e),E=readFileSync(k,`utf-8`),D=dirname(S),j=existsSync(D);try{tracedMkdirSync(D,{recursive:!0}),tracedWriteFileSync(S,E,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!j)try{tracedRmdirSync(D)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:D,err:e})}throw e}let H=!1;try{registerDocExtension(L,e),ye?.delete(L),me&&(me.incrementMdDir(dirname(L)),H=!0),registerWrite(S,contentHash(E)),F instanceof Map&&updateFileIndex({kind:`create`,path:S,docName:L,content:E},F),ee?.updateDocumentFromMarkdown(L,E),B=[L]}catch(e){try{tracedRmSync(S,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:S,err:e})}throw forgetDocExtension(L),me&&H&&me.decrementMdDir(dirname(L)),F instanceof Map&&updateFileIndex({kind:`delete`,path:S,docName:L},F),e}}else{if(L=nextAvailableDuplicateFolderPath(w,O).folderPath,me?.isDirExcluded(L)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(w,`folder`,L);try{tracedCpSync(k,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(w,L))je(e);let e=collectMarkdownCopies(w,L);B=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),ye?.delete(t.docName),me&&me.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),F instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},F),ee?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of B)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ee&&B.length>0&&(ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),successResponse(t,200,DuplicatePathSuccessSchema,{kind:E,path:L,duplicatedDocNames:B},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let S=classifyDuplicatePathFilesystemProblem(e);if(S){errorResponse(t,S.status,S.type,S.title,{handler:`duplicate-path`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),ks=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=ze(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),As=withValidation(RenamePathRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:E,fromPath:D,toPath:O}=S;if(!isValidRelativeContentPath(D)||!isValidRelativeContentPath(O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(E===`file`&&(isSystemDoc(D)||isSystemDoc(O)||isConfigDoc(D)||isConfigDoc(O))){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||O===`.ok`||O.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(D===O){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(D.toLowerCase()===O.toLowerCase()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(E===`file`&&probeAndRegisterSourceFileExtension(w,D),me&&(E===`file`?me.isExcluded(isSupportedDocFile(O)?O:`${O}${getDocExtension(D)}`):me.isDirExcluded(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination ${E===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let k=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,j;try{j=await Lt(D,O,E,k?{actor:k}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(t,409,`urn:ok:error:doc-already-exists`,vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(j.renamed.length===0){successResponse(t,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let F;switch(e.kind){case`agent`:{let t=e.summary.kind===`value`,S=t?e.summary:normalizeSummary(`Renamed ${D} → ${O}`),w=Bt(S);F=t||!w.response?w.response:Vt(w.response);for(let t=0;t<j.renamed.length;t++){let{fromDocName:S,toDocName:E}=j.renamed[t];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(S,E),e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Ht(S,!t);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`principal`:{let t=Bt(e.summary);F=t.response;for(let S=0;S<j.renamed.length;S++){let{fromDocName:w,toDocName:E}=j.renamed[S];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(w,E),e.actor,S===0?t.stored:void 0)}Ht(e.summary,!1);for(let{toDocName:e}of j.renamed)rt(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:E,fromPath:D,toPath:O,affectedDocs:j.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(e.kind)}`)}if(renameAttributionCounter().add(1,{kind:`rename-${E}`,attribution_kind:e.kind}),H)try{await H()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(t,200,RenamePathSuccessSchema,{renamed:j.renamed,rewrittenDocs:j.rewrittenDocs,...F?{summary:F}:{}},{handler:`rename-path`})}catch(e){let{status:S,type:w,error:E}=Tt(e);errorResponse(t,S,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Ns=withValidation(DeletePathRequestSchema,async(e,t,S)=>{try{Rt(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let O=resolveContentEntryPath(w,e,E);if(!existsSync(O)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let k=statSync(O);if(e===`file`&&!k.isFile()||e===`folder`&&!k.isDirectory()){errorResponse(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let j=e===`file`?[E]:listAffectedDocNames(D(),e,E);if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`?unlinkSync(O):(tracedRmSync(O,{recursive:!0,force:!1}),Me(E));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);successResponse(t,200,DeletePathSuccessSchema,{deletedDocNames:j},{handler:`delete-path`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ps=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&isReservedSyntheticFolderPath(E);if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}let k=D(),j=e===`file`?k.has(E)?[E]:[]:listAffectedDocNames(k,e,E);if(j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Et(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Me(E),ne?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(w,`${t}${D}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:D,size:E.size,modified:E.modified})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function $s(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,de??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=Rt(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$2.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let ec=`/api/local-op/clone`,tc=`/api/local-op/open`,nc=600*1e3,rc=45e3,ic=`local-op-clone`,ac=withValidation(LocalOpCloneRequestSchema,oc,{handler:ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ic})});async function oc(e,t,S){let{url:w,dir:E}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ic,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ic,cause:Error(`dir=${E}`)});return}if(!Ce.tryAcquire(ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ic,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let D=createStreamingErrorWriter(t,ic),O=null,k=runCloneSubprocess({cliArgs:ue,url:w,dir:E,timeoutMs:nc,onEvent:e=>{if(e.type===`complete`){O=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),D(500,`urn:ok:error:clone-failed`,`Clone subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await k.done,O&&!t.writableEnded&&!t.destroyed){let e=await sc(O);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:O})}\n`):D(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?D(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$2.error({err:e,handler:ic},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ce.release(ec)}})(),t.on(`close`,()=>{k.cancel()})}async function sc(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=ue,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$2.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let cc=`local-op-open`,lc=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:cc,cause:Error(`dir=${w}`)});return}if(!Ce.tryAcquire(tc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:cc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await sc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:cc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:cc,cause:Error(e.error)})}finally{Ce.release(tc)}},{handler:cc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:cc})}),uc=`/api/local-op/auth/login`,dc=`/api/local-op/auth/status`,fc=`/api/local-op/auth/repos`,pc=`/api/local-op/auth/signout`,mc=`/api/local-op/auth/pat`,hc=`local-op-auth-login`,gc=withValidation(LocalOpAuthHostRequestSchema,_c,{handler:hc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:hc})});async function _c(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(uc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:hc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,hc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:nc,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}}),O=()=>{D.cancel()};t.on(`close`,O),D.done.finally(()=>{t.off(`close`,O),t.writableEnded||t.end(),Ce.release(uc)})}let vc=`local-op-auth-status`,yc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:vc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2111
|
+
`).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:vc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:vc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:vc,cause:e})}finally{Ce.release(dc)}},{handler:vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vc})}),bc=`local-op-auth-repos`,xc=withValidation(LocalOpAuthHostRequestSchema,Sc,{handler:bc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bc})});async function Sc(e,t,S){let w=S.host??`github.com`;if(!Ce.tryAcquire(fc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:bc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,bc),[D,...O]=ue,k=[...O,`auth`,`repos`,`--json`,`--host`,w],j=!1,F=``,L=spawn(D,k,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),B=setTimeout(()=>{L.kill(`SIGTERM`)},nc);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
|
|
2112
|
+
`);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ce.release(fc))}),L.on(`error`,e=>{clearTimeout(B),j||(j=!0,t.writableEnded||(E(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ce.release(fc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),Ce.release(fc))})}let Cc=`local-op-auth-signout`,wc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Ce.tryAcquire(pc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Cc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`signout`,`--host`,w];await new Promise((t,S)=>{let w=spawn(e,E,{stdio:`ignore`,env:{...process.env}}),D=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.on(`close`,()=>{clearTimeout(D),t()}),w.on(`error`,e=>{clearTimeout(D),S(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Cc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Cc,cause:e})}finally{Ce.release(pc)}},{handler:Cc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cc})}),Tc=`local-op-auth-pat`,Ec=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!Ce.tryAcquire(mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Tc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`pat`,`--json`,`--host`,D],O=(await new Promise((t,S)=>{let D=spawn(e,E,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),O=setTimeout(()=>{D.kill(`SIGTERM`)},3e4);D.stdin.write(`${w}\n`),D.stdin.end();let k=[];D.stdout.on(`data`,e=>k.push(e)),D.on(`close`,e=>{clearTimeout(O),e===0?t(Buffer.concat(k).toString(`utf-8`)):S(Error(`auth pat exited with code ${e}`))}),D.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2113
|
+
`).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:Tc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Tc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Tc,cause:e})}finally{Ce.release(mc)}},{handler:Tc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Tc})}),Dc=`local-op-auth-identity`;async function Oc(e,t){if(checkLocalOpSecurity(e,t,{handler:Dc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Dc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Dc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Dc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Dc,cause:e})}}}let kc=`/api/local-op/auth/set-identity`,Ac=`local-op-auth-set-identity`,jc=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ac});return}if(!Ce.tryAcquire(kc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ac,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Ac})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ac,cause:e})}finally{Ce.release(kc)}},{handler:Ac,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ac})});async function Mc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Nc=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Pc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Fc=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ic(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=esm_default({baseDir:de,timeout:{block:15e3}});async function E(e){try{return await w.raw([`show`,`:${e}:${S}`])}catch{return``}}try{let[e,w,D]=await Promise.all([E(1),E(2),E(3)]);successResponse(t,200,SyncConflictContentSuccessSchema,{file:S,base:e,ours:w,theirs:D},{handler:`sync-conflict-content`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Lc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Rc=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function zc(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Bc=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Vc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Re.probeAll)}catch(e){t.headersSent||(log$2.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Hc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ce?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Uc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:te.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Wc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=te.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:Be(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Gc(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let Kc=/^[A-Za-z0-9_-]+$/;function qc(e,t,S=`template`){return!e||!Kc.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function Jc(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}async function Yc(e,t){if(e.method===`GET`)return Xc(e,t);if(e.method===`PUT`)return Zc(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Xc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Gc(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`,`frontmatter.yml`),D=null;if(existsSync(E))try{let e=(0,import_dist$1.parse)(await readFile$1(E,`utf-8`));D=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${E}: ${t}`),D=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:D},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Zc=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Gc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:Jc(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:E.applied},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});async function Qc(e,t){if(e.method===`GET`)return il(e,t);if(e.method===`PUT`)return al(e,t);if(e.method===`DELETE`)return cl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let $c=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,nl=e=>{let t=e.match($c),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},il=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!qc(w,t,`template-get`))return;let E=Gc(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=nl(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),al=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!qc(e,t,`template-put`))return;let w=Gc(S.folder,t,`folder`,`template-put`);if(!w)return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:Jc(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),cl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!qc(w,t,`template-delete`))return;let E=Gc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E)return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function ll(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function ul(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function dl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function fl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function pl(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,...ll(e)]}function ml(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function hl(){let e=`${w}${de??``}`,t=ml(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=pl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function gl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{hl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}gl();async function _l(e,t){if(e.method===`GET`)return vl(e,t);if(e.method===`POST`)return yl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let vl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=dl(S.searchParams.get(`intent`)),O=fl(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await hl(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ul(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),yl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=dl(S.intent),D=fl(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await hl(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?ul(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),xl=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function Tl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let El=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!de){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(de);if(e===null){if(readOriginGitHubRepo(de).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(de);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(de,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})});async function Dl(e){let[t,...S]=ue,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Ol=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dl([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),kl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ce.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dl([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),jl=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!de){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ce.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,de,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await Dl(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ce.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Ml={"/api/asset":Xi,"/api/asset-text":ka,"/api/document":$t,"/api/documents":en,"/api/backlinks":jr,"/api/backlink-counts":Mr,"/api/forward-links":Fr,"/api/link-graph":Ir,"/api/dead-links":Br,"/api/orphans":Lr,"/api/hubs":zr,"/api/tags":Uc,"/api/pages":Is,"/api/folder-config":Yc,"/api/template":Qc,"/api/search":_l,"/api/suggest-links":Rs,"/api/page-headings":ks,"/api/create-page":Ts,"/api/create-folder":Ds,"/api/duplicate-path":Os,"/api/rename-path":As,"/api/delete-path":Ns,"/api/trash/cleanup":Ps,"/api/upload":$s,"/api/agent-write":Ut,"/api/agent-write-md":Wt,"/api/frontmatter-patch":Kt,"/api/agent-patch":Vr,"/api/agent-undo":Hr,"/api/agent-activity":Ur,"/api/agent-burst-diff":Wr,"/api/save-version":Jr,"/api/history":Yr,"/api/diff":Zr,"/api/rollback":Qr,"/api/metrics/reconciliation":ji,"/api/metrics/parse-health":Hi,"/api/metrics/agent-presence":Ki,"/api/server-info":Ui,"/api/share/construct-url":El,"/api/share/publish/owners":Ol,"/api/share/publish/name-check":kl,"/api/share/publish":jl,"/api/principal":Gi,"/api/rescue":xs,"/api/workspace":Yi,"/api/sync/status":Mc,"/api/sync/trigger":Nc,"/api/sync/conflicts":Pc,"/api/sync/conflict-content":Ic,"/api/sync/resolve-conflict":Fc,"/api/sync/abort-merge":Hc,"/api/local-op/clone":ac,"/api/local-op/open":lc,"/api/local-op/auth/login":gc,"/api/local-op/auth/status":yc,"/api/local-op/auth/repos":xc,"/api/local-op/auth/signout":wc,"/api/local-op/auth/pat":Ec,"/api/local-op/auth/identity":Oc,"/api/local-op/auth/set-identity":jc,"/api/installed-agents":Vc,"/api/spawn-cursor":Tl,"/api/handoff":Cl,"/api/install-skill":Bc,"/api/skill/install-state":xl,"/api/seed/plan":Lc,"/api/seed/apply":Rc,"/api/seed/packs":zc};F&&(Ml[`/api/test-reset`]=Gr,Ml[`/api/test-rescan-backlinks`]=Kr,Ml[`/api/test-rescan-files`]=qr);let Pl=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Fl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Pl.has(S)||Fl.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:Ml[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=Ml[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await Cs(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Xr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Wc(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `list_documents({ dir })`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search` / `grep`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` / `grep` / `read_document` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir. Prefer `-A` over plain `ls`: OK projects carry dot-prefixed entries (`.ok/`, nested `.ok/`, `.okignore`) that plain `ls` omits. `-A` shows hidden entries without the noisy `.`/`..` rows that `-a` adds, and without the verbose long-format columns that `-la` adds (the per-child enrichment already carries the useful metadata `-l` would surface).\n- Search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files\n- Typed tools (`read_document`, `search`, `grep`, `list_documents`) remain available — prefer them when a structured `structuredContent` shape is useful (e.g., passing results to another tool). For interactive reads, `exec` is lighter. **Pick the right search:** `search` for ranked retrieval (cmd-K parity — title boost + body BM25 + recency); `grep` for every literal-string occurrence grouped by file with frontmatter enrichment.\n\n## Preview — open the browser at session start\n\n**The invariant.** If OK Electron is open for this project OR `ok ui` is running for it, every OK tool response carries the preview URL — plain HTTP, no custom URL schemes, works in any browser including agent in-app browsers (Claude Desktop, Cursor, Codex, Cowork). Read tools (`exec`, `grep`, `search`, `list_documents`, `read_document`) carry it in `ui.baseUrl` (top-level) and per-doc `previewUrl` fields; write tools carry it in `previewUrl` + the optional `warning` shape. Never construct this URL; always read it from the latest tool response.\n\n**The default agent move.** Make your first OK tool call (any read works — `list_documents`, `exec("ls -A")`, or `read_document` is enough). The response carries the preview URL. Navigate to it immediately, then proceed with your real work. The user watches edits land live; you can re-navigate later to verify a CRDT edit landed when a response looks ambiguous. Per host:\n\n- **In-app browser hosts** (Claude Desktop, Cursor, Codex, Cowork): navigate the in-app browser to the `previewUrl`. Default.\n- **Claude Code Desktop**: call `preview_start("open-knowledge-ui")` (host tool, not OK MCP).\n- **Stdio-only hosts**: surface the URL in chat; `open <url>` (macOS) if the host can shell out.\n\n**Four signals to check if it\'s already open** (you usually can\'t pre-check, so read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot.\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `frontmatter_patch`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename_document` / `rename_folder` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings.\n\n**Always read `previewUrl` from the latest write response.** Don\'t cache the session-start value — Electron quit/reopen (or `ok ui` restart) can change the port; the resolver picks up the new port automatically.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry. NEVER construct preview URLs by hand.\n\nOK Electron and `ok ui` cannot serve the same project at once — they share `ui.lock`. A UI-lock collision means the other is running for that project (use that one, or quit it first).\n\n**The preview is read-only for the agent.** Navigate to verify edits landed; you cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots after every edit.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after every write. Trust the response. Screenshot only when (a) debugging a visual issue, (b) a response looks ambiguous, or (c) the user asks.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
2114
2114
|
`).length};let S=e===`command`?240:120;return t.length<=S?t:{type:`string`,length:t.length,preview:`${t.slice(0,S)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let S of COMMON_SCALAR_KEYS)S in e&&(t[S]=e[S]);for(let S of COMMON_ARRAY_KEYS){let w=e[S];Array.isArray(w)&&(t[`${S}Count`]=w.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),isPlainObject(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,S){let w=S.logger;return w?async(...E)=>{let D=w.child(),O=Date.now(),{toolArgs:k,extra:j}=splitInvocationArgs(E);D.info(`tool start`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},...j?.sessionId?{transportSessionId:j.sessionId}:{},...S.identityRef?.current?{agent:summarizeIdentityForLog(S.identityRef.current)}:{},...k===void 0?{}:{args:summarizeArgsForLog(e,k)}});try{let S=await runWithMcpLogger(D,async()=>await t(...E));return D.info(`tool finish`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O,result:summarizeToolResultForLog(S)}),S}catch(t){throw D.error(`tool error`,t,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let S=e.tool.bind(e),w=e.registerTool,E=typeof w==`function`?w.bind(e):void 0,D=Object.create(e);return D.tool=((...e)=>{let w=String(e[0]),E=e.at(-1);if(typeof E!=`function`)return S(...e);let D=[...e];return D[D.length-1]=wrapToolHandlerForLogging(w,E,t),S(...D)}),E&&(D.registerTool=((e,S,w)=>typeof w==`function`?E(e,S,wrapToolHandlerForLogging(e,w,t)):E(e,S,w))),D}function buildBody$2(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
|
|
2115
2115
|
|
|
2116
2116
|
Topic: ${e}
|
|
@@ -3226,6 +3226,6 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3226
3226
|
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let S=[],w=[];for(let e of t){let t=join(this.projectDir,e),E=relative(this.contentDir,t);!E.startsWith(`..`)&&!this.contentFilter.isExcluded(E)?S.push(e):w.push(e)}for(let t of w)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),S.push(t)}if(S.length>0){for(let e of S)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:S},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason;let S=t.inflightConflicts??[];if(S.length>0){for(let e of S)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let S=t?.get(`mountId`)??void 0,w={"doc.name":e};S!==void 0&&MOUNT_ID_PATTERN.test(S)&&(w[`mount.id`]=S);try{withSpanSync(`sync.handshake`,{attributes:w},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
3227
3227
|
`,`
|
|
3228
3228
|
`).split(`
|
|
3229
|
-
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Rt?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){let t=e.getMap(`lifecycle`);t.get(`status`)===`conflict`&&(t.delete(`status`),t.delete(`reason`))}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3229
|
+
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Rt?.pruneFileIndexNowExcluded()??0,t=Rt?.pruneFolderIndexNowExcluded()??0,S=e+t;S>0&&getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] pruned now-excluded entries from file indexes`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){let t=e.getMap(`lifecycle`);t.get(`status`)===`conflict`&&(t.delete(`status`),t.delete(`reason`))}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3230
3230
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir})}catch(e){throw await Y().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:ge}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;w!==null&&(ye=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})}));try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(t){if(e.reactShellDistDir)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),t}let Ce=fe.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ue=we,j(ne,we),e.reactShellDistDir&&updateUiLockPort(ne,we),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return ve=async()=>{if(Te)return;Te=!0;let t=[],S=async(e,S)=>{try{await De(e,S)}catch(S){t.push(S),E.warn({err:S,step:e},`bootServer destroy step failed`)}};try{ye?.detach()}catch(e){t.push(e),E.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await S(`mount.shutdown`,()=>_e.shutdown()),await S(`mcpHttpHandler.close`,()=>de.close()),await S(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(S=>S?t(S):e())})),await S(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await S(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await S(`destroyHocuspocus`,()=>Y()),e.reactShellDistDir&&await S(`releaseUiLock`,async()=>releaseUiLock(ne)),await S(`shutdownTelemetry`,()=>shutdownTelemetry()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ve,lockDir:ne,contentDir:e.contentDir,port:we,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,ALL_EDITOR_IDS as $r,incrementServerObserverFire as $t,MissingOkConfigError as A,_coercedNumber as Ai,readServerPackageVersion as An,tracedWriteFile as Ar,createStreamingErrorWriter as At,STARTER_PACK_IDS as B,registerWrite as Bn,writeTargetVersion as Br,formatAuthRejectionWire as Bt,LOG_MD_TEMPLATE as C,boolean$1 as Ci,parseAuthRejectionWire as Cn,tracedMkdir as Cr,createExternalChangeHandler as Ct,MCP_SERVER_NAME as D,object$1 as Di,planSeed as Dn,tracedRmSync as Dr,createPersistenceExtension as Dt,MCP_CONNECTION_ID_HEADER as E,number$1 as Ei,pathToDocName as En,tracedRenameSync as Er,createOsProbe as Et,SERVICE_WRITER as F,readUiLock as Fn,validateCloneInputs as Fr,errorResponse as Ft,StateManifestError as G,resolveContentDir as Gn,isInitializedNotification as Gr,getLocalDir as Gt,STATE_MANIFEST_FILENAME as H,removeLastKnownHash as Hn,McpServer as Hr,formatContributorsFrom as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,reconcile as In,validateSkillZip as Ir,evictStaleTrackerEntries as It,acquireUiLock as J,resolveLockDir as Jn,readConfigSafely as Jr,getMetrics as Jt,TagIndex as K,resolveCursorBinaryDefault as Kn,isJSONRPCRequest as Kr,getLogger as Kt,STARTER_FOLDERS as L,recordContributor as Ln,withSpan as Lr,extractWikiLinksFromMarkdown as Lt,PinoLogger as M,require_dist$2 as Mi,readStateManifest as Mn,updateLastKnownHash as Mr,detectClaudeDesktopPresence as Mt,ProjectGitInitError as N,readTargetRecordedAt as Nn,updateUiLockPort as Nr,detectProjectShape as Nt,MISSING_OK_CONFIG_MESSAGE as O,string$2 as Oi,readAllTargets as On,tracedRmdirSync as Or,createServer$1 as Ot,ROLLBACK_ORIGIN as P,readTargetVersion as Pn,validateAgentId as Pr,ensureProjectGit as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,MalformedGitPointerError as Qr,incrementCollabSocketFilteredError as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,recordSkillInstallEvent as Rn,withSpanSync as Rr,findEnclosingGitRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,array as Si,normalizeFsPath as Sn,tracedLinkSync as Sr,createContentFilterAsync as St,MAX_AGENT_SESSIONS as T,looseObject as Ti,parseKeepaliveConnectionId as Tn,tracedRename as Tr,createMcpHttpHandler as Tt,SeedPrerequisiteError as U,resetMetrics as Un,JSONRPCMessageSchema as Ur,gcCheckpointRefs as Ut,STARTER_TEMPLATES as V,releaseUiLock as Vn,writeTracker as Vr,formatContributors as Vt,SeedRootDirError as W,resolveBundledSkillDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getCurrentMcpLogger as Wt,applyExternalChange as X,resolvePackageVersion as Xn,writeConfigPatch as Xr,handleCollabSocketError as Xt,applyAgentMarkdownWrite as Y,resolvePack as Yn,resolveConfigPath as Yr,getTracer as Yt,applySeed as Z,restoreContributors as Zn,GitDirAccessError as Zr,handleSpawnCursor as Zt,GIT_UPSTREAM_WRITER as _,LOCAL_DIR as _i,listRescueCheckpoints as _n,startWatcher as _r,contentHash as _t,AgentPresenceBroadcaster as a,EXECUTABLE_BLOCKLIST_EXTENSIONS as ai,isAllowedApiOrigin as an,safeContentPath as ar,buildReadResult as at,HocuspocusAuthTokenSchema as b,ZodNumber$1 as bi,loggerFactory as bn,toBroadcasterKey as br,createAssetServeMiddleware as bt,BacklinkIndex as c,ProblemDetailsSchema as ci,isHocuspocusAuthRejectionReason as cn,sanitizeClientName as cr,buildWipTree as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,colorFromSeed as di,isPairedWriteOrigin as dn,seedBasenameIndex as dr,clearContributors as dt,ASSET_EXTENSIONS as ei,initShadowRepo as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,defaultScheduler as fi,isPathWithinDir as fn,setActiveSpanAttributes as fr,coercePackId as ft,FILE_WATCHER_ORIGIN as g,CONFIG_SCHEMA_MAJOR_PATH as gi,lastKnownHash as gn,splitMarkdownBlocks as gr,containsConflictMarkers as gt,FILE_SYSTEM_WRITER as h,isOrphanMode as hi,isSystemDoc as hn,spawnDetached as hr,commitWipFromTree as ht,AgentFocusBroadcaster as i,EDITOR_LABELS as ii,installUserSkill as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,NEVER as ji,readSkillInstallStateSnapshot as jn,tracedWriteFileSync as jr,createTestLogger as jt,McpLogger as k,url as ki,readBranchFromHead as kn,tracedUnlinkSync as kr,createServerObserverExtension as kt,CC1Broadcaster as l,SKILL_STATE_TARGETS as li,isKnownPackId as ln,saveInMemoryCheckpoint as lr,classifyEvents as lt,DEFAULT_PACK_ID as m,iconFromClientName as mi,isSelfWrite as mn,shutdownTelemetry as mr,commitWip as mt,AGENT_ID_RE as n,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ni,installPrettyZodErrors as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,INLINE_RENDERABLE_EXTENSIONS as oi,isAllowedWorkspaceHostHeader as on,safeSubdir as or,buildSkillZip as ot,DEFAULT_CHECKPOINT_RETENTION as p,humanFormat as pi,isProjectRoot as pn,shadowGit as pr,commitUpstreamImport as pt,UiLockCollisionError as q,resolveCursorSpawnInvocation as qn,isJSONRPCResultResponse as qr,getMeter as qt,AGENT_WRITE_ORIGIN as r,DEFAULT_SERVER_HOST as ri,installTestLoggers as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,ORPHAN_MODES as si,isConfigDoc as sn,safetyCheckpoint as sr,buildStarterFolderFrontmatterYaml as st,AGENT_ID_MAX_LEN as t,CC1_CONTRACT_VERSION as ti,initTelemetry as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,SYSTEM_DOC_NAME as ui,isLoopbackAddress as un,saveVersion as ur,classifyFsPath as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,OK_PROJECT_MARKER as vi,listStarterPacks as vn,streamingProblemEvent as vr,contributorCount as vt,MANAGED_RENAME_ORIGIN as w,literal as wi,parseHocuspocusAuthToken as wn,tracedMkdirSync as wr,createLiveDerivedIndexExtension as wt,INSTALLED_AGENTS_SCHEMES as x,any$1 as xi,mountMcpAndApi as xn,tracedAppendFileSync as xr,createContentFilter as xt,HocuspocusAuthRejection as y,locateIssue as yi,loadPrincipal as yn,swapContributors as yr,createApiExtension as yt,STARTER_PACKS as z,registerAllTools as zn,writeStateManifest as zr,findEnclosingProjectRoot as zt};
|
|
3231
|
-
//# sourceMappingURL=dist-
|
|
3231
|
+
//# sourceMappingURL=dist-Du77nM-Z.mjs.map
|