@inkeep/open-knowledge 0.8.0-beta.20 → 0.8.0-beta.21
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/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +2 -1
- package/dist/cli.mjs +4 -4
- package/dist/config-schema.json +21 -1
- package/dist/config.project-local.schema.json +5 -1
- package/dist/config.user.schema.json +21 -1
- package/dist/constants-C2aYjymb.mjs +2 -0
- package/dist/{dist-4x_d-0GF.mjs → dist-BRdwpvRU.mjs} +1 -1
- package/dist/{dist-BWAKwlW9.mjs → dist-Ca54A9UG.mjs} +13 -13
- package/dist/{gh-detect-CSW5IRNM.mjs → gh-detect-CauEoJLn.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-thuZWJ1y.mjs → init-BsIzz_tj.mjs} +4 -4
- package/dist/init-DitdFLbU.mjs +1 -0
- package/dist/{loader-BOSnqU2v.mjs → loader-BOFezBgk.mjs} +2 -2
- package/dist/loader-DrX7HBax.mjs +1 -0
- package/dist/{preview-BbpC7NzU.mjs → preview-CfMgJxEQ.mjs} +2 -2
- package/dist/preview-qRSE5P9s.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-D8YR6SMv.js → ActivityModeContent-CngtcPpo.js} +1 -1
- package/dist/public/assets/{DocumentContext-ChHEoqaV.js → DocumentContext-C4-J37Ox.js} +1 -1
- package/dist/public/assets/{GraphPanel-Dzx3Zg0v.js → GraphPanel-CAKYBrh_.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-CcDcbViP.js → SettingsDialogBody-Du4i_Cr7.js} +2 -2
- package/dist/public/assets/{SourceEditor-dd-Qcqkz.js → SourceEditor-BW3Wow6y.js} +1 -1
- package/dist/public/assets/{config-validation-events-D8fQSuEW.js → config-validation-events-CcfTH-z4.js} +1 -1
- package/dist/public/assets/{index-BcU2S6Nn.js → index-B_zbJvsu.js} +7 -7
- package/dist/public/assets/{prop-types-Cyh4p-YX.js → prop-types-vr6qWjMf.js} +2 -2
- package/dist/public/assets/{target-navigation-intent-gvCIKhvh.js → target-navigation-intent-BTTe7RwN.js} +1 -1
- package/dist/public/assets/{toggle-group-6WLbf3-e.js → toggle-group-BKjtvTFY.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-DgfXa9sF.js → typing-burst-detector-DDFQ4-NK.js} +1 -1
- package/dist/public/index.html +7 -7
- package/dist/{repair-launch-json-xn4cdXuq.mjs → repair-launch-json-BBNdyDOQ.mjs} +2 -2
- package/dist/{repair-mcp-configs-B40aAdEh.mjs → repair-mcp-configs-5E5yZSYG.mjs} +2 -2
- package/dist/repair-skills-BlQp9JSE.mjs +1 -0
- package/dist/{repair-skills-ClqjW2ic.mjs → repair-skills-Cjs7REOr.mjs} +2 -2
- package/dist/schemas/v0/config.project-local.schema.json +5 -1
- package/dist/schemas/v0/config.user.schema.json +21 -1
- package/dist/{src-C3n7feZn.mjs → src-Cja5R8Lf.mjs} +2 -2
- package/dist/{start-Bs05_Fdd.mjs → start-BSZnlCB4.mjs} +2 -2
- package/dist/start-DccrZYde.mjs +1 -0
- package/dist/{write-project-skill-C3aYUp9w.mjs → write-project-skill-yR3pYdTj.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-DgOkqYR5.mjs +0 -2
- package/dist/init-BasVjE6u.mjs +0 -1
- package/dist/loader-DhfiO_1K.mjs +0 -1
- package/dist/preview-B3dGmHaF.mjs +0 -1
- package/dist/repair-skills-BGSggwrg.mjs +0 -1
- package/dist/start-Crf5DM7q.mjs +0 -1
|
@@ -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$1();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:`.`}),preview:looseObject({scriptSrc:_enum([`cdn-allowlist`,`inline-only`]).register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`cdn-allowlist`)}).default({scriptSrc:`cdn-allowlist`}),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(`
|
|
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$1();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:`.`}),preview:looseObject({scriptSrc:_enum([`cdn-allowlist`,`inline-only`]).register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`cdn-allowlist`)}).default({scriptSrc:`cdn-allowlist`}),appearance:looseObject({theme:_enum([`light`,`dark`,`system`]).register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).optional(),preview:looseObject({autoOpen:boolean$1().register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).default(!0)}).default({autoOpen:!0}),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({preview:{autoOpen:!0}}),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(`
|
|
@@ -2378,7 +2378,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2378
2378
|
`).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:wc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:wc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:wc,cause:e})}finally{we.release(gc)}},{handler:wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:wc})}),Ec=`local-op-auth-repos`,Dc=withValidation(LocalOpAuthHostRequestSchema,Oc,{handler:Ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ec})});async function Oc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(_c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Ec,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,Ec),[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`)},ac);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
|
|
2379
2379
|
`);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$3.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(),we.release(_c))}),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()),we.release(_c))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),we.release(_c))})}let kc=`local-op-auth-signout`,Ac=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:kc,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:kc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:kc,cause:e})}finally{we.release(vc)}},{handler:kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:kc})}),jc=`local-op-auth-pat`,Mc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!we.tryAcquire(yc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:jc,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(`
|
|
2380
2380
|
`).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:jc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:jc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:jc,cause:e})}finally{we.release(yc)}},{handler:jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jc})}),Nc=`local-op-auth-identity`;async function Pc(e,t){if(checkLocalOpSecurity(e,t,{handler:Nc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Nc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Nc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Nc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Nc,cause:e})}}}let Fc=`/api/local-op/auth/set-identity`,Ic=`local-op-auth-set-identity`,Lc=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:Ic});return}if(!we.tryAcquire(Fc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ic,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Ic})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ic,cause:e})}finally{we.release(Fc)}},{handler:Ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ic})});async function Rc(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,remote:null},{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 zc=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 Bc(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 Vc=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,detail:e instanceof Error?e.message:void 0})}},{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 Hc(e,S){if(!checkLocalOpSecurity(e,S,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(S,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`file`);if(!E){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(E.includes(`..`)||E.startsWith(`/`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let D=stripDocExtension(E),O=t.documents.get(D)?.getMap(`lifecycle`).get(`status`)===`conflict`,k=ce?.(),j=k?k.getConflicts().some(e=>e.file===E):!1;if(!O&&!j){errorResponse(S,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:E}});return}let F=w.searchParams.get(`source`),L=esm_default({baseDir:de,timeout:{block:15e3}});async function B(e){try{return{present:!0,content:await L.raw([`show`,`:${e}:${E}`])}}catch(t){let S=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(S))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:E,detail:S,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=e.present?e.content:``,k=D.present?D.content:``,j=w.present&&D.present?`both-modified`:!w.present&&D.present?`delete-modify`:w.present&&!D.present?`modify-delete`:`both-modified`,L=w.present?w.content:``,H=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);if(H=typeof t==`string`&&t.length>0?t:null,j!==`delete-modify`){let t=Ce?Ce(e):null;t!==null&&!ytextHasConflictMarkers(t)?L=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(S,200,SyncConflictContentSuccessSchema,{file:E,base:O,ours:L,theirs:k,kind:j,lifecycleStatus:H},{handler:`sync-conflict-content`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Uc(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 Wc=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 Gc(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 Kc=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 qc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,ze.probeAll)}catch(e){t.headersSent||(log$3.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 Jc(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 Yc=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 Xc(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:Ve(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 Zc(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 Qc=/^[A-Za-z0-9_-]+$/;function $c(e,t,S=`template`){return!e||!Qc.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 nl(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}function il(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return{patch:t,badField:null};for(let[S,w]of Object.entries(e)){if(w===void 0)continue;if(w===null){t[S]=null;continue}let e=DeclarationSchema.safeParse(w);if(!e.success)return{patch:null,badField:S};t[S]=e.data}return{patch:t,badField:null}}async function al(e,t){if(e.method===`GET`)return cl(e,t);if(e.method===`PUT`)return ll(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let cl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Zc(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`),D=resolve(E,`frontmatter.yml`),O=null;if(existsSync(D))try{let e=(0,import_dist$1.parse)(await readFile$1(D,`utf-8`));O=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 ${D}: ${t}`),O=null}let k=resolveNestedFrontmatterWithSources(S.resolvedContentDir,S.folderRel),j=resolve(E,`schema.yml`),F=null;if(existsSync(j))try{let e=(0,import_dist$1.parse)(await readFile$1(j,`utf-8`)),t=FolderSchemaSchema.safeParse(e);t.success?F=t.data.declarations:(console.warn(`[ok-folder-schema] invalid shape at ${j}: ${t.error.message}`),F=null)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[ok-folder-schema] malformed YAML in ${j}: ${t}`),F=null}let L=Object.keys(k.declarations).length>0;successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:O,...Object.keys(k.sources).length>0?{frontmatter_sources:k.sources}:{},...L?{schema_declarations:k.declarations,schema_sources:k.declarationSources}:{},schema_local:F},{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}),ll=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Zc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E;if(S.declarations!==void 0){let e=il(S.declarations);if(e.patch===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid declaration for field "${e.badField}": must be { type: text|number|boolean|date|list } or null.`,{handler:`folder-config-put`,detail:`INVALID_DECLARATION`});return}E=e.patch}let D=[];if(S.frontmatter!==void 0){let E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:nl(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}D.push(...E.applied)}if(E!==void 0&&Object.keys(E).length>0){let S=applyNestedFolderSchemaUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,declarations:E}]});if(!S.ok){let e=S.error.code===`WRITE_ERROR`||S.error.code===`BAD_PROJECT_DIR`?500:400,w=e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,E=e===500?`Failed to write folder schema.`:`Invalid folder schema request.`,O=D.length>0?{partiallyApplied:D}:void 0;errorResponse(t,e,w,E,{handler:`folder-config-put`,detail:S.error.code,cause:Error(S.error.message),...O?{extensions:O}:{}});return}D.push(...S.applied)}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:D},{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`});function ul(e,S,w,E){if(!S)return!1;let D=e===``?`.ok/templates/${S}`:`${e.replace(/\/$/,``)}/.ok/templates/${S}`,O=t.documents.get(D);return O&&isDocInConflict(O)?(respondDocInConflict(E,new DocInConflictError({file:`${D}.md`}),w),!0):!1}async function dl(e,t){if(e.method===`GET`)return ml(e,t);if(e.method===`PUT`)return hl(e,t);if(e.method===`DELETE`)return gl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let fl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,pl=e=>{let t=e.match(fl),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}},ml=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!$c(w,t,`template-get`))return;let E=Zc(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}=pl(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}),hl=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!$c(e,t,`template-put`))return;let w=Zc(S.folder,t,`folder`,`template-put`);if(!w||ul(w.folderRel,e,`template-put`,t))return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:nl(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`}),gl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!$c(w,t,`template-delete`))return;let E=Zc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||ul(E.folderRel,w,`template-delete`,t))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 _l(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 vl(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 yl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function xl(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 Cl(){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,..._l(e)]}function Tl(){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 El(){let e=`${w}${de??``}`,t=Tl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=Cl().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 Dl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{El().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Dl();async function Ol(e,t){if(e.method===`GET`)return kl(e,t);if(e.method===`POST`)return jl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let kl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=yl(S.searchParams.get(`intent`)),O=xl(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 El(),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`?vl(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}),jl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=yl(S.intent),D=xl(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 El(),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`?vl(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`}),Ml=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 Pl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.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 Fl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.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 Il=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})}),Ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`branch`),E=S.searchParams.get(`path`);if(!isValidBranchName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoDocPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(de,w,E),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Rl=withValidation(CheckoutRequestSchema,async(e,t,S)=>{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(de,S.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function zl(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 Bl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!we.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 zl([`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{we.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})}),Vl=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(!we.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 zl([`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{we.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})}),Hl=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(!we.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 zl(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{we.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Ul={"/api/asset":ka,"/api/asset-text":xs,"/api/document":jr,"/api/documents":Mr,"/api/backlinks":Fr,"/api/backlink-counts":Ir,"/api/forward-links":Lr,"/api/link-graph":zr,"/api/dead-links":Hr,"/api/orphans":Br,"/api/hubs":Vr,"/api/tags":Yc,"/api/pages":$s,"/api/folder-config":al,"/api/template":dl,"/api/search":Ol,"/api/suggest-links":ec,"/api/page-headings":Ns,"/api/create-page":Os,"/api/create-folder":ks,"/api/duplicate-path":As,"/api/rename-path":Ps,"/api/delete-path":Is,"/api/trash/cleanup":Rs,"/api/upload":tc,"/api/agent-write":Wt,"/api/agent-write-md":Kt,"/api/frontmatter-patch":$t,"/api/agent-patch":Ur,"/api/agent-undo":Wr,"/api/agent-activity":Gr,"/api/agent-burst-diff":Kr,"/api/save-version":Xr,"/api/history":Zr,"/api/diff":ji,"/api/rollback":Hi,"/api/metrics/reconciliation":Ui,"/api/metrics/parse-health":Gi,"/api/metrics/agent-presence":Xi,"/api/server-info":Ki,"/api/share/construct-url":Il,"/api/git/branch-info":Ll,"/api/git/checkout":Rl,"/api/share/publish/owners":Bl,"/api/share/publish/name-check":Vl,"/api/share/publish":Hl,"/api/principal":Yi,"/api/rescue":Ts,"/api/workspace":Zi,"/api/sync/status":Rc,"/api/sync/trigger":zc,"/api/sync/conflicts":Bc,"/api/sync/conflict-content":Hc,"/api/sync/resolve-conflict":Vc,"/api/sync/abort-merge":Jc,"/api/local-op/clone":cc,"/api/local-op/open":fc,"/api/local-op/ok-init":mc,"/api/local-op/auth/login":Sc,"/api/local-op/auth/status":Tc,"/api/local-op/auth/repos":Dc,"/api/local-op/auth/signout":Ac,"/api/local-op/auth/pat":Mc,"/api/local-op/auth/identity":Pc,"/api/local-op/auth/set-identity":Lc,"/api/installed-agents":qc,"/api/spawn-cursor":Fl,"/api/handoff":Pl,"/api/install-skill":Kc,"/api/skill/install-state":Ml,"/api/seed/plan":Uc,"/api/seed/apply":Wc,"/api/seed/packs":Gc};F&&(Ul[`/api/test-reset`]=qr,Ul[`/api/test-rescan-backlinks`]=Jr,Ul[`/api/test-rescan-files`]=Yr);let Wl=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/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Gl=[`/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(Wl.has(S)||Gl.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`:Ul[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=Ul[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 Ds(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Qr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Xc(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 log$2=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$2.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$2.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$2.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-CjyGVy33-lwHYMDQ0.mjs`).then(e=>e.n),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}case`delete`:await D.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$2.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
2381
|
-
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$2.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$2.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};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 `exec("ls -A <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`. 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` 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, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — including Codex\'s built-in browser, and any host tool whose contract is "navigate to a URL" (`browser`, `view_url`, `open_url`, `web.browse`, host-specific names, etc.) → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) 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 (`preview_start`, or `get_preview_url` → in-app browser).\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` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\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(`
|
|
2381
|
+
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$2.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$2.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};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 `exec("ls -A <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`. 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` 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, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — including Codex\'s built-in browser, and any host tool whose contract is "navigate to a URL" (`browser`, `view_url`, `open_url`, `web.browse`, host-specific names, etc.) → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `get_preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) 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 (`preview_start`, or `get_preview_url` → in-app browser).\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` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\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(`
|
|
2382
2382
|
`).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)),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.
|
|
2383
2383
|
|
|
2384
2384
|
Topic: ${e}
|
|
@@ -2527,7 +2527,7 @@ superseded_by: <path-to-new-canonical-article>.md
|
|
|
2527
2527
|
- **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
|
|
2528
2528
|
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
|
|
2529
2529
|
`}const DESCRIPTION$22=[`Returns a step-by-step plan to promote stabilized research into a canonical article. Does NOT write — you execute the plan after a STOP gate confirms a real decision was made.`,"Canonical, not provisional — the output becomes the source of truth, with a `supersedes` trail back to the research.",`Use when a team has decided after research and wants the outcome committed as authoritative knowledge.`].join(`
|
|
2530
|
-
`);function register$22(e,t){e.registerTool(`consolidate`,{description:DESCRIPTION$22,inputSchema:{topic:string$2().describe(`The topic to consolidate into a canonical article`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE=`No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.`;function buildPreviewAttachWarning(e){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,S){return resolvePreviewUrl(e,{lockDir:resolveLockDir(S??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function buildListResolver(e,t){let S={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,S)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let S=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:S,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$21=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — A single document to delete, typically extension-less. A trailing `.md` or `.mdx` is stripped automatically.","- `docNames` — Batch form: an array of documents to delete in one call. Mutually exclusive with `docName`. Each is deleted independently; the response reports per-doc status.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `links({ kind: "backlinks", docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.','- Deletion is irreversible from this tool. Use `version({ action: "save" })` beforehand if you may need to roll back.',"- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
|
|
2530
|
+
`);function register$22(e,t){e.registerTool(`consolidate`,{description:DESCRIPTION$22,inputSchema:{topic:string$2().describe(`The topic to consolidate into a canonical article`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE=`No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.`;function buildPreviewAttachWarning(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE,autoOpen:t}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE,autoOpen:t}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,S){return resolvePreviewUrl(e,{lockDir:resolveLockDir(S??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function buildListResolver(e,t){let S={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,S)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let S=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:S,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$21=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — A single document to delete, typically extension-less. A trailing `.md` or `.mdx` is stripped automatically.","- `docNames` — Batch form: an array of documents to delete in one call. Mutually exclusive with `docName`. Each is deleted independently; the response reports per-doc status.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `links({ kind: "backlinks", docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.','- Deletion is irreversible from this tool. Use `version({ action: "save" })` beforehand if you may need to roll back.',"- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
|
|
2531
2531
|
`);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function deleteOne(e,t,S,w){let E=normalizeDocName(e);if(!E.ok)return{docName:e,ok:!1,error:E.error};let D=w.identityRef?.current,O=await httpPost(t,`/api/delete-path`,{kind:`file`,path:E.docName,...D?{agentId:D.connectionId,agentName:D.displayName,clientName:D.clientInfo?.name,colorSeed:D.colorSeed}:{}});if(!O.ok)return{docName:E.docName,ok:!1,error:O.error};let k=parseDeletedDocNames(O.deletedDocNames),j=await resolvePreviewUrlForTool(E.docName,{config:w.config,resolveCwd:w.resolveCwd},S);return{docName:E.docName,ok:!0,deletedDocNames:k.length>0?k:[E.docName],...j?{previousPreviewUrl:j.url}:{}}}function register$21(e,t){e.registerTool(`delete_document`,{description:DESCRIPTION$21,inputSchema:{docName:string$2().optional().describe(`A single document to delete.`),docNames:array(string$2()).min(1).optional().describe("Batch: documents to delete in one call. Mutually exclusive with `docName`."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.docName===void 0&&e.docNames===void 0)return textResult("Error: provide `docName` (single) or `docNames` (batch).",!0);if(e.docName!==void 0&&e.docNames!==void 0)return textResult("Error: `docName` and `docNames` are mutually exclusive.",!0);if(e.docNames!==void 0){let S=await Promise.all(e.docNames.map(e=>deleteOne(e,E,w,t))),D=S.filter(e=>e.ok).length,O=D===S.length,k=S.map(e=>e.ok?`Deleted ${e.docName}.`:`Failed ${e.docName}: ${e.error}`);return textPlusStructured(`${D}/${S.length} deleted.\n${k.join(`
|
|
2532
2532
|
`)}`,{ok:O,documents:S},!O)}let D=await deleteOne(e.docName,E,w,t);if(!D.ok){let e={ok:!1,error:D.error??`unknown error`};return textPlusStructured(`Error: ${e.error}`,e,!0)}let O=D.deletedDocNames??[D.docName],k={ok:!0,deletedDocNames:O,...D.previousPreviewUrl?{previousPreviewUrl:D.previousPreviewUrl}:{}};return textPlusStructured(O.length===1?`Deleted ${O[0]}.`:`Deleted ${O.length} documents: ${O.join(`, `)}.`,k)})}function buildDiscoverBody(e){return`# Discover — Project Convention Extraction + Link Graph Activation
|
|
2533
2533
|
|
|
@@ -2843,11 +2843,11 @@ Link-graph activation:
|
|
|
2843
2843
|
- **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
|
|
2844
2844
|
`}const DESCRIPTION$20=[`Returns a step-by-step plan for setting up an existing repo: extract folder conventions, write folder frontmatter + templates, activate the link graph. Does NOT execute the plan — you run it, with per-phase user confirmation.`,``,"Invoke on first arrival at a repo that has markdown content but no folder frontmatter / templates (an `exec` listing shows empty `frontmatter_defaults` + `templates_available`). Skip empty repos (use `ok seed`) and already-configured ones. One-shot per project; idempotent on re-run (extends, never re-proposes).",``,"Phases 1-4 run fs-direct; Phase 5 (link-graph activation) needs `ok start`. Composes existing tools only — `exec`, `links`, `search`, `folder_config`, `edit_document`."].join(`
|
|
2845
2845
|
`),InputSchema$5={cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$9=outputSchemaWithText({previewUrl:_null()});function register$20(e,t){e.registerTool(`discover`,{description:DESCRIPTION$20,inputSchema:InputSchema$5,outputSchema:OutputSchema$9,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return S.ok?textPlusStructured(buildDiscoverBody(S.config.content.dir),{previewUrl:null}):textResult(`Error: ${S.error}`,!0)})}const DESCRIPTION$19=`${["[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer. The patch propagates to all connected editors in real-time. Use `offset` to target an exact occurrence; omit for first-match.",``,'**Body-only.** Frontmatter-intersecting find/replace is rejected with HTTP 400. For frontmatter: 1-2 keys → `edit_frontmatter`; full rewrite → `write_document({ position: "replace" })`.',``,`**Parameters:**`,"- `docName` — Document name, extension-less. Trailing `.md`/`.mdx` stripped.","- `find` — Text to find (exact match).","- `replace` — Replacement text.",'- `offset` — Optional JavaScript string offset of the exact occurrence to patch. Stale offsets return an error; re-fetch via `links({ kind: "suggest", docName })`.',"- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history."].join(`
|
|
2846
|
-
`)}\n${renderInventoryFooter()}`;function register$19(e,t){e.registerTool(`edit_document`,{description:DESCRIPTION$19,inputSchema:{docName:string$2().describe(`Document name to edit`),find:string$2().describe(`Text to find (exact match)`),replace:string$2().describe(`Replacement text`),offset:number$1().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:
|
|
2847
|
-
`);if(!
|
|
2848
|
-
`),PatchValueSchema=union([FrontmatterValueSchema,_null()]).describe("Property value (string|number|boolean|string[]) — `null` deletes the key");function register$18(e,t){e.registerTool(`edit_frontmatter`,{description:DESCRIPTION$18,inputSchema:{docName:string$2().describe(`Document name`),patch:record(string$2(),PatchValueSchema).describe("JSON Merge Patch — `{key: value}` sets, `{key: null}` deletes"),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional().describe(`Currently ignored (shape-validated for forward-compat but not persisted). Type is inferred from value shape on read. Will become a real per-key widget-type override (text|number|boolean|date|list) once persistence lands.`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:
|
|
2849
|
-
`)}`:`Error: ${e}`,!0)}let
|
|
2850
|
-
`);if(!
|
|
2846
|
+
`)}\n${renderInventoryFooter()}`;function register$19(e,t){e.registerTool(`edit_document`,{description:DESCRIPTION$19,inputSchema:{docName:string$2().describe(`Document name to edit`),find:string$2().describe(`Text to find (exact match)`),replace:string$2().describe(`Replacement text`),offset:number$1().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=E.appearance.preview.autoOpen,k=normalizeDocName(e.docName);if(!k.ok)return textResult(k.error,!0);let j=t.identityRef?.current,F=await httpPost(D,`/api/agent-patch`,{docName:k.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...j?{agentId:j.connectionId,agentName:j.displayName,clientName:j.clientInfo?.name,colorSeed:j.colorSeed}:{}});if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=resolveLockDir(w),B=resolvePreviewUrl(k.docName,{lockDir:L}),H=typeof F.subscriberCount==`number`?F.subscriberCount:void 0,q=(typeof F.systemSubscriberCount==`number`?F.systemSubscriberCount:void 0)===0,J=H===0,Y=F.summary&&typeof F.summary==`object`?F.summary:void 0,ee=typeof Y?.hint==`string`?Y.hint:void 0,te=[`Edit applied successfully.`];q&&!B&&te.push(START_UI_TEXT_HINT),ee&&te.push(ee);let ne=te.join(`
|
|
2847
|
+
`);if(!B&&!q&&!J&&!Y)return textResult(ne);let ae={};return B&&(ae.previewUrl=B.url,ae.previewUrlSource=B.source),q&&(ae.warning=buildPreviewAttachWarning(B,O)),Y&&(ae.summary=Y),textPlusStructured(ne,ae)})}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Set, create, or delete frontmatter properties via JSON Merge Patch (RFC 7396).`,``,`Field-level CRDT merge: concurrent patches to different keys (human form + this tool, or two agents) merge cleanly. Same-key concurrent writes resolve last-writer-wins per key.`,``,'**Use this tool — not `edit_document` — for any frontmatter change.** `edit_document` (agent-patch) targets body content; FM-intersecting `edit_document` calls return HTTP 400. For full-document rewrites (≥3-5 frontmatter keys changing), `write_document({ position: "replace" })` remains the canonical pathway.',``,`**Parameters:**`,"- `docName` — Document name. A trailing `.md` or `.mdx` is stripped automatically.","- `patch` — Object whose keys are property names. Each value is the new value (string, number, boolean, or array of strings) to **set or create** the key, or `null` to **delete** the key. Keys not present in `patch` are unchanged.","- `types` (optional) — **Currently ignored.** Shape-validated for forward-compat but not persisted server-side; type is inferred from value shape on read. Reserved for a future per-key widget-type override (`text | number | boolean | date | list`) once persistence ships.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Prefer outcome phrasing ("Marked spec as approved") over structural ("Set status field"). Avoid secrets / PII — summaries persist to git history.',``,`**Atomicity:** any value failing schema validation rejects the WHOLE patch (HTTP 400 with per-key error report). Either every change commits or none do.`,``,"**Folder schema declarations:** if the doc's parent folder declares fields via `<folder>/.ok/schema.yml` (visible on the doc's `EnrichedMeta.schema_declarations`), prefer filling those declared fields when relevant — they exist precisely because every doc in the folder should carry them. Type is advisory, not enforced."].join(`
|
|
2848
|
+
`),PatchValueSchema=union([FrontmatterValueSchema,_null()]).describe("Property value (string|number|boolean|string[]) — `null` deletes the key");function register$18(e,t){e.registerTool(`edit_frontmatter`,{description:DESCRIPTION$18,inputSchema:{docName:string$2().describe(`Document name`),patch:record(string$2(),PatchValueSchema).describe("JSON Merge Patch — `{key: value}` sets, `{key: null}` deletes"),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional().describe(`Currently ignored (shape-validated for forward-compat but not persisted). Type is inferred from value shape on read. Will become a real per-key widget-type override (text|number|boolean|date|list) once persistence lands.`),summary:summaryArgSchema,cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=E.appearance.preview.autoOpen,k=normalizeDocName(e.docName);if(!k.ok)return textResult(k.error,!0);let j=t.identityRef?.current,F=await httpPost(D,`/api/frontmatter-patch`,{docName:k.docName,patch:e.patch,...e.types?{types:e.types}:{},...e.summary===void 0?{}:{summary:e.summary},...j?{agentId:j.connectionId,agentName:j.displayName,clientName:j.clientInfo?.name,colorSeed:j.colorSeed}:{}});if(!F.ok){let e=F.error,t=F.fieldErrors&&typeof F.fieldErrors==`object`?F.fieldErrors:void 0;return textResult(t?`Error: ${e}\n${Object.entries(t).map(([e,t])=>` ${e}: ${t}`).join(`
|
|
2849
|
+
`)}`:`Error: ${e}`,!0)}let L=resolveLockDir(w),B=resolvePreviewUrl(k.docName,{lockDir:L}),H=typeof F.subscriberCount==`number`?F.subscriberCount:void 0,q=(typeof F.systemSubscriberCount==`number`?F.systemSubscriberCount:void 0)===0,J=H===0,Y=F.summary&&typeof F.summary==`object`?F.summary:void 0,ee=typeof Y?.hint==`string`?Y.hint:void 0,te=[],ne=[];for(let[t,S]of Object.entries(e.patch))S===null?ne.push(t):te.push(t);let ae=[`Frontmatter patched (${[te.length?`${te.length} set`:``,ne.length?`${ne.length} deleted`:``].filter(Boolean).join(`, `)||`${Object.keys(e.patch).length} key(s)`}).`];q&&!B&&ae.push(START_UI_TEXT_HINT),ee&&ae.push(ee);let oe=ae.join(`
|
|
2850
|
+
`);if(!B&&!q&&!J&&!Y)return textResult(oe);let se={};return B&&(se.previewUrl=B.url,se.previewUrlSource=B.source),q&&(se.warning=buildPreviewAttachWarning(B,O)),Y&&(se.summary=Y),textPlusStructured(oe,se)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let S=nonFlagArgs(argsOf(t)),w=S.length>0?S[S.length-1]:``,E=w&&w!==`.`?normalize$1(w):``,D=[];E&&D.push(E);for(let t of e.split(`
|
|
2851
2851
|
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let S=E?`${E}/${e}`:e;D.push(S)}return D}function extractFromGrep(e){let t=[];for(let S of e.split(`
|
|
2852
2852
|
`)){if(!S)continue;let e=S.indexOf(`:`);if(e<0)continue;let w=normalize$1(S.slice(0,e));isWikiPath(w)&&t.push(w)}return t}function extractFromFind(e){let t=[];for(let S of e.split(`
|
|
2853
2853
|
`)){let e=normalize$1(S);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],S=e.matchAll(PATH_FALLBACK_RE);for(let e of S)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let S=null;for(let e=t.length-1;e>=0;e--){let w=t[e];if(PRODUCER_COMMANDS.has(w.command)){S=w;break}if((w.command===`head`||w.command===`tail`)&&headTailActsAsProducer(w)){S=w;break}}let w;if(!S)w=fallback(e);else{switch(S.command){case`cat`:w=extractFromCat(S);break;case`ls`:w=extractFromLs(e,S);break;case`grep`:w=extractFromGrep(e);break;case`find`:w=extractFromFind(e);break;case`head`:case`tail`:w=extractFromHeadTail(S);break;default:w=fallback(e)}w.length===0&&(w=fallback(e))}let E=new Set,D=[];for(let e of w){let t=normalize$1(e);!t||E.has(t)||(E.add(t),D.push(t))}return D}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,S){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=S}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new xt({cwd:`/`,fs:new Ss({root:resolve(e),allowSymlinks:!1})})}async function execBash(e,t){let S=await e.exec(t);if(S.stdout.length>MAX_STDOUT_BYTES)throw new StdoutOverflowError(MAX_STDOUT_BYTES,S.stdout.length,{stdout:S.stdout.slice(0,MAX_STDOUT_BYTES),stderr:S.stderr,exitCode:S.exitCode});return{stdout:S.stdout,stderr:S.stderr,exitCode:S.exitCode}}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),S=new Map,w=0,E=!1;async function D(e){if(E)return;let O;try{O=await readdir(e,{withFileTypes:!0})}catch{return}for(let k of O){if(E)return;if(k.isDirectory()&&SKIP_DIRS.has(k.name))continue;let O=resolve(e,k.name);if(k.isDirectory()){await D(O);continue}if(k.isFile()){if(w>=SCAN_CAP){E=!0;return}try{let e=await stat$1(O);S.set(relative(t,O),e.mtimeMs),w++}catch{}}}}return await D(t),{snapshot:S,truncated:E}}function diffMtimes(e,t){let S=[];for(let[w,E]of t){let t=e.get(w);(t===void 0||t!==E)&&S.push(w)}for(let[w]of e)t.has(w)||S.push(w);return{changed:S}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let S of e)t.push(`-not`,`-path`,`*/${S}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let S=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),w=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,w),...S,...e.args.slice(w)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let S of e){if(typeof S==`string`){if(SUSPICIOUS_STRING_RE.test(S))return{error:{category:`shell_construct_blocked`,message:`Argument '${S}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(S);continue}if(!isOpToken(S))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(S.op===`glob`&&typeof S.pattern==`string`){t.push(S.pattern);continue}return typeof S.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(S)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let S;try{S=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let w=[],E=[];for(let e of S){if(isOpToken(e)&&e.op===`|`){w.push(E),E=[];continue}E.push(e)}w.push(E);let D=[];for(let e of w){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let S={command:t.args[0],args:t.args},w=checkStage(S);if(w)return{error:w};D.push(S)}return{stages:D}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=50*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$17=["**STOP — native tools on in-scope markdown (when project has `.ok/`).** When the active project contains `.ok/`, do NOT use your host's native `Read`, `Grep`, or `Glob` on `.md` / `.mdx` paths inside OK's content directory — use `exec` (this tool) instead. Native file tools skip frontmatter, backlinks, shadow-repo activity, and project git history that `exec` returns for every matched wiki file. Reserve native `Read`/`Grep`/`Glob` for source code, non-markdown paths, and projects without `.ok/`.",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
|
|
@@ -2883,7 +2883,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
|
|
|
2883
2883
|
`),InputSchema$2={path:array(string$2()).optional().describe(`Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6=outputSchemaWithText({value:unknown$2().describe(`Resolved config value at the requested path (or full config).`),exists:boolean$1().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:array(string$2()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)});function readConfigPath(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S)return;S=S[e]}return S}function register$13(e,t){e.registerTool(`get_config`,{description:DESCRIPTION$13,inputSchema:InputSchema$2,outputSchema:OutputSchema$6,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let w=e.path??[],E=w.length>0?readConfigPath(S.config,w):S.config;return w.length>0&&E===void 0?textPlusStructured(`(no value at ${w.join(`.`)})`,{value:null,exists:!1,path:w}):textPlusStructured(JSON.stringify(E,null,2),{value:E,exists:!0,path:w})})}const DESCRIPTION$12=[`[Requires: Hocuspocus server] Fetch the three merge stages (base / ours / theirs) for a doc currently in a merge-conflict state, plus the doc's lifecycle status and the conflict shape discriminator.`,`Returns 404 if no conflict is tracked for the path.`,"The `ours` field is sourced from the live Y.Text (showing any pre-conflict unflushed user edits) when the doc is loaded server-side; falls back to `git show :2:<file>` otherwise.","The `kind` field discriminates conflict shape: `both-modified` (both sides edited the file), `delete-modify` (DU — you deleted, they edited; stage 2 absent, `ours` empty), or `modify-delete` (UD — you edited, they deleted; stage 3 absent, `theirs` empty). Use it to pick the right `resolve_conflict` strategy: both-modified accepts `mine`/`theirs`/`content`; delete-modify accepts `delete` (keep deletion) or `theirs` (restore); modify-delete accepts `mine` (keep your version) or `delete` (accept their deletion).",``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH the `.md` extension (e.g. `notes/sso.md`). Mirrors the server-side wire contract."].join(`
|
|
2884
2884
|
`),OutputSchema$5=outputSchemaWithText({file:string$2(),base:string$2(),ours:string$2(),theirs:string$2(),kind:_enum([`both-modified`,`delete-modify`,`modify-delete`]),lifecycleStatus:string$2().nullable()});function register$12(e,t){e.registerTool(`get_conflict_content`,{description:DESCRIPTION$12,inputSchema:{file:string$2().min(1).describe("Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`). Server-side contract — do NOT strip the extension."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{url:w}=S;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=await httpGet(w,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!E.ok){let e=E.error,t=typeof E.detail==`string`?E.detail:void 0;return textResult(`Error: ${t?`${e} — ${t}`:e}`,!0)}let D=E,O=typeof D.file==`string`?D.file:e.file,k=typeof D.base==`string`?D.base:``,j=typeof D.ours==`string`?D.ours:``,F=typeof D.theirs==`string`?D.theirs:``,L=D.kind===`delete-modify`||D.kind===`modify-delete`?D.kind:`both-modified`,B=typeof D.lifecycleStatus==`string`?D.lifecycleStatus:null,H={file:O,base:k,ours:j,theirs:F,kind:L,lifecycleStatus:B};return textPlusStructured(`Conflict stages for ${O} (kind: ${L})${B?` (lifecycle: ${B})`:``}:\n--- base ---\n${k}\n--- ours ---\n${j}\n--- theirs ---\n${F}`,H)})}const DESCRIPTION$11=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,'Each entry includes a commit SHA that can be passed to `version({ action: "rollback" })`.',``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
|
|
2885
2885
|
`);function register$11(e,t){e.registerTool(`get_history`,{description:DESCRIPTION$11,inputSchema:{docName:string$2().describe(`Document name to query history for`),branch:string$2().optional().describe(`Branch name (default: current branch)`),limit:number$1().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number$1().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:string$2().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string$2().optional().describe(`Exclude entries by this author name or email`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=new URLSearchParams;O.set(`docName`,D.docName),e.branch&&O.set(`branch`,e.branch),e.limit!=null&&O.set(`limit`,String(e.limit)),e.offset!=null&&O.set(`offset`,String(e.offset)),e.type&&O.set(`type`,e.type),e.author&&O.set(`author`,e.author),e.excludeAuthor&&O.set(`excludeAuthor`,e.excludeAuthor);let k=await httpGet(E,`/api/history?${O.toString()}`);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{ok:j,...F}=k,L=await resolvePreviewUrlForTool(D.docName,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(JSON.stringify(F,null,2),{...F,previewUrl:L?.url??null,...L?{previewUrlSource:L.source}:{}})})}const DESCRIPTION$10=[`[Operates on disk; no running OK server required] Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc).`,``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Claude Code does NOT need this tool: it calls `preview_start("open-knowledge-ui")`, whose pane supplies its own origin.',``,"Returns `{ url, baseUrl, running: false }` and a recovery hint when no UI is running for the project (start one with `ok ui`).",``,`**Parameters:**`,"- `docName` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
2886
|
-
`),InputSchema$1={docName:string$2().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string$2().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `docName` is given, else the UI root. `null` when no UI is running."),baseUrl:string$2().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean$1().describe(`Whether a UI is running for the project.`)}),NO_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code), or open the project in OK Electron.';function register$10(e,t){e.registerTool(`get_preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$1,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{baseUrl:w}=resolveUiInfo({lockDir:resolveLockDir(S.cwd)});if(w===null)return textPlusStructured(NO_UI_MESSAGE,{url:null,baseUrl:null,running:!1});let
|
|
2886
|
+
`),InputSchema$1={docName:string$2().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string$2().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `docName` is given, else the UI root. `null` when no UI is running."),baseUrl:string$2().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean$1().describe(`Whether a UI is running for the project.`),autoOpen:boolean$1().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`.")}),NO_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code), or open the project in OK Electron.';function register$10(e,t){e.registerTool(`get_preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$1,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!S.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${S.error}`}]};let{baseUrl:w}=resolveUiInfo({lockDir:resolveLockDir(S.cwd)}),E=S.config.appearance.preview.autoOpen;if(w===null)return textPlusStructured(NO_UI_MESSAGE,{url:null,baseUrl:null,running:!1,autoOpen:E});let D=e.docName?`${w}/#/${encodeDocName(e.docName)}`:w;return textPlusStructured(`Preview URL: ${D}`,{url:D,baseUrl:w,running:!0,autoOpen:E})})}function buildBody$1(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
|
|
2887
2887
|
|
|
2888
2888
|
**Bias toward binary preservation.** When the source is a binary file (PDF, image, audio, video, Office doc, archive, dataset), preserve the raw bytes — do NOT settle for a text scrape. OK already ships a complete asset-embed surface (\`![[file.ext]]\` wiki-embed, file-watcher pickup, sha256 dedup, blocked-extension enforcement); this tool's job is to bridge \`ingest\` to it via your shell tool.
|
|
2889
2889
|
|
|
@@ -3486,9 +3486,9 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3486
3486
|
`);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved document path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal docName under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function resolveDocSharePath(e,t,S){let w=resolveWithinRoot(t,S);if(!w.ok)return null;for(let t of[`.mdx`,`.md`]){let S=`${w.abs}${t}`;if(existsSync(S)){let t=resolveWithinRoot(e,S);return t.ok?t.rel:null}}return null}const OutputSchema=outputSchemaWithText({ok:boolean$1().describe(`Success discriminator.`),shareUrl:string$2().optional().describe(`Marketing share URL (success only).`),blobUrl:string$2().optional().describe(`Unencoded GitHub blob URL (success only).`),branch:string$2().optional().describe(`Branch the share URL pins to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`doc-not-found`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string$2().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string$2().nullable().optional().describe("Route-only preview URL `/#/<doc>` (no host:port). `null` when no UI is running."),previewUrlSource:string$2().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{docName:string$2().describe("Document to share, extension-less. Trailing `.md`/`.mdx` is stripped."),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=normalizeDocName(e.docName);if(!O.ok)return textResult(O.error,!0);let k=resolveDocSharePath(w,join(w,E.content.dir),O.docName);if(k===null){let e={ok:!1,error:`doc-not-found`,message:`Document \`${O.docName}\` does not exist under the content directory (looked for \`.md\` and \`.mdx\`).`};return textPlusStructured(`Error: ${e.message}`,e,!0)}let j;try{j=await fetch(`${D}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({docPath:k}),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let F;try{F=await j.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!j.ok){let e;if(F&&typeof F==`object`){let t=F,S=typeof t.title==`string`?t.title:void 0,w=typeof t.detail==`string`?t.detail:void 0;e=S&&w?`${S}: ${w}`:S||w||`HTTP ${j.status}`}else e=`HTTP ${j.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let L=ShareConstructUrlResponseSchema.safeParse(F);if(!L.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let B=L.data;if(!B.ok){let e=messageForShareError(B.error,B.branch),t={ok:!1,error:B.error,message:e,...B.branch?{branch:B.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:H,blobUrl:q,branch:J}=B,Y={ok:!0,shareUrl:H,blobUrl:q,branch:J},ee=await resolvePreviewUrlForTool(O.docName,{config:t.config,resolveCwd:t.resolveCwd},w);return textPlusStructured(`Share link for \`${O.docName}\` on branch \`${J}\`:\n${H}`,{...Y,previewUrl:ee?.url??null,...ee?{previewUrlSource:ee.source}:{}})})}const ACTIONS=[`save`,`rollback`],DESCRIPTION$1=["[Requires: Hocuspocus server] Project version management. Dispatches on `action`:",``,'- `action: "save"` — Project-wide checkpoint of every document. No `docName`. Returns `{checkpointRef, previewUrl: null}`. Find checkpoints later via `get_history`.','- `action: "rollback"` — Restore one document to a historical version via the CRDT layer (append-only — creates a new version with the old content; all connected editors see the change in real-time). Requires `docName` and `commitSha`. Find `commitSha` via `get_history`.',``,`**Parameters:**`,"- `action` — `save` | `rollback`.","- `docName` — Required for `rollback`. Document name, typically without extension; trailing `.md`/`.mdx` is stripped.","- `commitSha` — Required for `rollback`. 40-character SHA from the shadow-repo timeline.",'- `summary` — Optional rollback summary (≤80 chars). If omitted, defaults to "Restored to <sha-short>". Avoid secrets or PII — summaries persist to git history.'].join(`
|
|
3487
3487
|
`);function register$1(e,t){e.registerTool(`version`,{description:DESCRIPTION$1,inputSchema:{action:_enum(ACTIONS).describe(`Which version action to perform.`),docName:string$2().optional().describe(`Document name. Required for action=rollback.`),commitSha:string$2().length(40).regex(/^[0-9a-f]+$/i).optional().describe(`40-character commit SHA from the shadow-repo timeline. Required for action=rollback. Find via get_history.`),summary:summaryArgSchema.describe(`Optional rollback summary (≤80 chars). Defaults to "Restored to <sha-short>". Appears as a bullet in the timeline.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,url:E}=S;if(!E)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);switch(e.action){case`save`:return handleSave(E,t);case`rollback`:return handleRollback(e,E,w,t);default:return textResult(`Error: unknown version action.`,!0)}})}async function handleSave(e,t){let S=t.identityRef?.current,w=await httpPost(e,`/api/save-version`,S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{});return w.ok?textPlusStructured(`Checkpoint saved. Checkpoint ref: ${w.checkpointRef}`,{checkpointRef:w.checkpointRef,previewUrl:null}):textResult(`Error: ${w.error}`,!0)}async function handleRollback(e,t,S,w){if(!e.docName)return textResult("Error: action=rollback requires `docName`.",!0);if(!e.commitSha)return textResult("Error: action=rollback requires `commitSha`.",!0);let E=normalizeDocName(e.docName);if(!E.ok)return textResult(E.error,!0);let D=E.docName,O=await httpGet(t,`/api/history/${e.commitSha}?docName=${encodeURIComponent(D)}`);if(!O.ok)return textResult(`Error: ${O.error??`Version not found`}`,!0);let k=w.identityRef?.current,j=await httpPost(t,`/api/rollback`,{docName:D,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...k?{agentId:k.connectionId,agentName:k.displayName,clientName:k.clientInfo?.name,colorSeed:k.colorSeed}:{}});if(!j.ok)return textResult(`Error: ${j.error}`,!0);let F=j.summary&&typeof j.summary==`object`?j.summary:void 0,L=typeof F?.hint==`string`?F.hint:void 0,B=typeof O.author==`string`?O.author:void 0,H=typeof O.timestamp==`string`?O.timestamp:void 0,q=B&&H?` (${B}, ${H})`:``,J=[`Restored "${D}" to version ${e.commitSha.slice(0,8)}${q}. The change has been applied to all connected editors.`];L&&J.push(L);let Y=await resolvePreviewUrlForTool(D,{config:w.config,resolveCwd:w.resolveCwd},S);return textPlusStructured(J.join(`
|
|
3488
3488
|
`),{previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{},...F?{summary:F}:{}})}const POSITIONS=[`append`,`prepend`,`replace`],DESCRIPTION=`${[`[Requires: Hocuspocus server] Write markdown to a document via the CRDT layer. Content propagates to all connected editors in real-time.`,``,'Frontmatter changes: 1-2 keys → prefer `edit_frontmatter` (field-level CRDT, atomic). Full rewrite (≥3-5 keys or body + frontmatter together) → this tool with `position: "replace"` and the full YAML block in the payload.',``,'Templates: `template: "<name>"` resolves against the parent folder\'s `templates_available` (see `exec("ls <folder>/")`) and becomes the new doc verbatim. `template` and `markdown` are mutually exclusive. With `template` set, `position` is forced to `"replace"`.',``,"To create several docs in one call (scaffolding a pack, seeding dossiers), pass `docs: [{docName, markdown|template, position?, summary?}, ...]` instead of the single-doc fields. Docs write in order; the response reports each.",``,`**Parameters:**`,"- `docName` — A single document, extension-less (`notes/meeting`). Trailing `.md`/`.mdx` is stripped. New docs default to `.md`.","- `docs` — Batch form: array of `{docName, markdown?|template?, position?, summary?}`. Mutually exclusive with the single-doc fields.","- `markdown` — Markdown payload. Required unless `template` is set.","- `template` — Template name. Mutually exclusive with `markdown`.","- `position` — `append` | `prepend` | `replace`. Optional for a new doc (defaults to `replace`); required for an existing doc. Forced to `replace` with `template`.","- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history.",``,"Folder schema declarations: if the target folder declares fields via `<folder>/.ok/schema.yml`, those declarations surface on each doc's `EnrichedMeta.schema_declarations` (visible through `exec(\"cat <doc>.md\")`). Prefer including declared fields in the new doc's frontmatter when their value is known. Type is advisory, not enforced."].join(`
|
|
3489
|
-
`)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit_frontmatter\` (1-2 keys) or \`write_document({ position: "replace" })\` (full rewrite).`}function docExistsOnDisk(e,t){return SUPPORTED_DOC_EXTENSIONS.some(S=>{let w=resolveWithinRoot(e,`${t}${S}`);return w.ok&&existsSync(w.abs)})}async function writeOneDoc(e,t,S,w,E){let D=normalizeDocName(e.docName);if(!D.ok)return{docName:e.docName,ok:!1,error:D.error};let O=D.docName,k=E.identityRef?.current;if(e.template===void 0&&e.markdown===void 0)return{docName:O,ok:!1,error:"either `markdown` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.markdown!==void 0)return{docName:O,ok:!1,error:"TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one; fill placeholders via subsequent `edit_document` calls."};let j=e.markdown??``,F;if(e.position!==void 0)F=e.position;else if(docExistsOnDisk(S,O))return{docName:O,ok:!1,error:`"${O}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit_document\` for a targeted change.`};else F=`replace`;if(e.template!==void 0){let S=parentFolderOf(O),w=resolveTemplatesAvailable(t,S,{depth:1}),E=w.find(t=>t.name===e.template);if(!E)return{docName:O,ok:!1,error:`template "${e.template}" not found for folder "${S||`.`}". Available: ${w.length===0?`(none)`:w.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let D;try{D=readFileSync(resolve(t,E.path),`utf-8`)}catch(e){return{docName:O,ok:!1,error:`failed to read template at ${E.path}: ${e.message}`}}let{body:L}=stripFrontmatter(D);j=applySubstitution(L,{date:todayIsoUtc(),user:k?.displayName??``}),F=`replace`}let L=await httpPost(w,`/api/agent-write-md`,{docName:O,markdown:j,position:F,...e.summary===void 0?{}:{summary:e.summary},...k?{agentId:k.connectionId,agentName:k.displayName,clientName:k.clientInfo?.name,colorSeed:k.colorSeed}:{}});return L.ok?{docName:O,ok:!0,position:F,...e.template===void 0?{}:{fromTemplate:e.template},raw:L}:{docName:O,ok:!1,error:String(L.error)}}function register(e,t){let S={docName:string$2().describe(`Document name to write to`),markdown:string$2().optional().describe("Markdown content to write. Optional when `template` is set."),template:string$2().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema};e.registerTool(`write_document`,{description:DESCRIPTION,inputSchema:{docName:string$2().optional().describe(`A single document to write to.`),markdown:string$2().optional().describe("Markdown content. Optional when `template` is set."),template:string$2().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema,docs:array(object$1(S)).min(1).optional().describe(`Batch: documents to write in one call. Mutually exclusive with the single-doc fields.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=resolveLockDir(w),k=resolveContentDir(E,w);if(e.docs!==void 0){if(e.docName!==void 0||e.markdown!==void 0||e.template!==void 0||e.position!==void 0||e.summary!==void 0)return textResult("Error: `docs` is the batch form — do not also pass top-level `docName` / `markdown` / `template` / `position` / `summary` (each `docs[]` entry carries its own).",!0);let S=[];for(let E of e.docs)S.push(await writeOneDoc(E,w,k,D,t));let E=S.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:O});return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{}}}),
|
|
3490
|
-
`),
|
|
3491
|
-
`);if(!L&&!H&&!q&&!J&&!Y)return textResult(ae);let oe={};return L&&(oe.previewUrl=L.url,oe.previewUrlSource=L.source),H&&(oe.warning=buildPreviewAttachWarning(L)),J&&(oe.hints=J),Y&&(oe.summary=Y),textPlusStructured(ae,oe)})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$17(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$9(w,{config:t.config,resolveCwd:E(`ingest`)}),register$5(w,{config:t.config,resolveCwd:E(`research`)}),register$22(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$20(w,{config:t.config,resolveCwd:E(`discover`)}),register$3(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`links`)}),register(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$19(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$21(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_frontmatter`),identityRef:t.identityRef}),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename`),identityRef:t.identityRef}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`version`),identityRef:t.identityRef}),register$14(w,{resolveCwd:E(`get_components`),config:t.config}),register$15(w,{resolveCwd:E(`get_authoring_palette`),config:t.config}),register$13(w,{config:t.config,resolveCwd:E(`get_config`)}),register$10(w,{config:t.config,resolveCwd:E(`get_preview_url`)}),register$16(w,{config:t.config,resolveCwd:E(`folder_config`)}),register$7(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_conflicts`)}),register$12(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_conflict_content`)}),register$4(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`resolve_conflict`)}),register$2(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)});installPrettyZodErrors(E);let D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j,reactShellMiddleware:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,J=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let O=(S,w,D)=>{if(S===void 0){D();return}try{S(e,t,()=>{t.writableEnded||t.headersSent||D()})}catch(e){E.error({err:e},`Unhandled ${w} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},k=e=>O(j,`content-asset`,e),L=e=>O(F,`react-shell`,e),B=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})};if(F!==void 0&&D?.startsWith(`/assets/`)){L(()=>k(B));return}if(j!==void 0||F!==void 0){k(()=>L(B));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=H.get(S);e!==void 0&&(clearTimeout(e),H.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(H.delete(S),J)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(S,e),E.info({connectionId:S,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-Drw_7KKo.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-Drw_7KKo.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}function entryMatchesDocName(e,t,S,w){let E=relative(w,join(S,e.file));return E.startsWith(`..`)?!1:stripDocExtension(E)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:S,contentDir:w}=e;return{async afterLoadDocument({documentName:e,document:E}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let D=t();if(!D)return;let O=D.getConflicts();if(O.length===0||!O.some(t=>entryMatchesDocName(t,e,S,w)))return;let k=E.getMap(`lifecycle`);if(k.get(`status`)===`conflict`)return;k.set(`status`,`conflict`),k.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let S=readGitCommonDirSync(e);if(S===null)return[];let w=[];appendExcludeFileIfExists(join(S,`info`,`exclude`),t,w,`info/exclude`);let E=resolveGlobalExcludesfileSync(e);return E&&appendExcludeFileIfExists(E,t,w,`global excludesfile`),w}async function loadGitExcludeSourcesAsync(e,t){let S=await readGitCommonDirAsync(e);if(S===null)return[];let w=[];await appendExcludeFileIfExistsAsync(join(S,`info`,`exclude`),t,w,`info/exclude`);let E=await resolveGlobalExcludesfileAsync(e);return E&&await appendExcludeFileIfExistsAsync(E,t,w,`global excludesfile`),w}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),S=t.trim();if(S)return S}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,S,w){if(existsSync(e))try{let w=readFileSync(e,`utf-8`);t.value+=w.length,S.push(...parseIgnorePatterns(w))}catch(t){console.warn(`[content-filter] Failed to read ${w} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,S,w){if(existsSync(e))try{let w=await readFile$1(e,`utf-8`);t.value+=w.length,S.push(...parseIgnorePatterns(w))}catch(t){console.warn(`[content-filter] Failed to read ${w} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O,k,j,F=0,L=0,B=0;function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[],H=0,q=0;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=readFileSync(E,`utf-8`);H+=t.length;let S=parseIgnorePatterns(t);w.push(...S),e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);H+=t.length,q++;let S=parseIgnorePatterns(t).map(e=>prefixPattern(e,E));e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let J={value:H};q+=loadNestedIgnoreFiles(S,t,e,J),H=J.value;let Y=loadGitExcludeSources(t,J);H=J.value,Y.length>0&&(w.push(...Y),e.add(Y));let ee=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return O=e,k=w,j=ee,F=w.length,L=q,B=H,{patternCount:F,nestedFileCount:L,bytes:B}}H();let q=new Map;function J(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}populateDirCount(S,``,J,q);function Y(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function ee(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:J(e)}return{isExcluded(e,t){if(Y(e))return!0;if(t?.bypassFilters)return!1;if(ee(e))return!0;if(isSupportedDocFile(e))return!1;let S=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(S)){let t=dirname(e),S=t===`.`?``:t;if((q.get(S)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let S=E?`${E}/${e}`:e;return O.ignores(S)||O.ignores(`${S}/`)},isPathIgnored(e,t){return Y(e)?!0:t?.bypassFilters?!1:ee(e)},getWatcherIgnoreGlobs(){return j},incrementMdDir(e){let t=e===`.`?``:e;q.set(t,(q.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=q.get(t)??0;S<=1?q.delete(t):q.set(t,S-1)},rebuildDirCount(){let e=new Map(q);q.clear();try{populateDirCount(S,``,J,q)}catch(t){for(let[t,S]of e)q.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,E=k,D=j,Y=F,ee=L,te=B,ne=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async ae=>{try{let t=H();q.clear(),populateDirCount(S,``,J,q);let E=Date.now()-ne;if(ae.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E},`content-filter rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E}}catch(w){O=t,k=E,j=D,F=Y,L=ee,B=te,q.clear();try{populateDirCount(S,``,J,q)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let H=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(H)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:H}}}})}}}function populateDirCount(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let D of E){let E=t?`${t}/${D.name}`:D.name;if(D.isDirectory()){if(BUILTIN_SKIP_DIRS.has(D.name)||S(E)||S(`${E}/`))continue;populateDirCount(join(e,D.name),E,S,w)}else D.isFile()&&isSupportedDocFile(D.name)&&!S(E)&&w.set(t,(w.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3489
|
+
`)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit_frontmatter\` (1-2 keys) or \`write_document({ position: "replace" })\` (full rewrite).`}function docExistsOnDisk(e,t){return SUPPORTED_DOC_EXTENSIONS.some(S=>{let w=resolveWithinRoot(e,`${t}${S}`);return w.ok&&existsSync(w.abs)})}async function writeOneDoc(e,t,S,w,E){let D=normalizeDocName(e.docName);if(!D.ok)return{docName:e.docName,ok:!1,error:D.error};let O=D.docName,k=E.identityRef?.current;if(e.template===void 0&&e.markdown===void 0)return{docName:O,ok:!1,error:"either `markdown` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.markdown!==void 0)return{docName:O,ok:!1,error:"TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one; fill placeholders via subsequent `edit_document` calls."};let j=e.markdown??``,F;if(e.position!==void 0)F=e.position;else if(docExistsOnDisk(S,O))return{docName:O,ok:!1,error:`"${O}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit_document\` for a targeted change.`};else F=`replace`;if(e.template!==void 0){let S=parentFolderOf(O),w=resolveTemplatesAvailable(t,S,{depth:1}),E=w.find(t=>t.name===e.template);if(!E)return{docName:O,ok:!1,error:`template "${e.template}" not found for folder "${S||`.`}". Available: ${w.length===0?`(none)`:w.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let D;try{D=readFileSync(resolve(t,E.path),`utf-8`)}catch(e){return{docName:O,ok:!1,error:`failed to read template at ${E.path}: ${e.message}`}}let{body:L}=stripFrontmatter(D);j=applySubstitution(L,{date:todayIsoUtc(),user:k?.displayName??``}),F=`replace`}let L=await httpPost(w,`/api/agent-write-md`,{docName:O,markdown:j,position:F,...e.summary===void 0?{}:{summary:e.summary},...k?{agentId:k.connectionId,agentName:k.displayName,clientName:k.clientInfo?.name,colorSeed:k.colorSeed}:{}});return L.ok?{docName:O,ok:!0,position:F,...e.template===void 0?{}:{fromTemplate:e.template},raw:L}:{docName:O,ok:!1,error:String(L.error)}}function register(e,t){let S={docName:string$2().describe(`Document name to write to`),markdown:string$2().optional().describe("Markdown content to write. Optional when `template` is set."),template:string$2().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema};e.registerTool(`write_document`,{description:DESCRIPTION,inputSchema:{docName:string$2().optional().describe(`A single document to write to.`),markdown:string$2().optional().describe("Markdown content. Optional when `template` is set."),template:string$2().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema,docs:array(object$1(S)).min(1).optional().describe(`Batch: documents to write in one call. Mutually exclusive with the single-doc fields.`),cwd:string$2().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let S=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{cwd:w,config:E,url:D}=S;if(!D)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=resolveLockDir(w),k=resolveContentDir(E,w),j=E.appearance.preview.autoOpen;if(e.docs!==void 0){if(e.docName!==void 0||e.markdown!==void 0||e.template!==void 0||e.position!==void 0||e.summary!==void 0)return textResult("Error: `docs` is the batch form — do not also pass top-level `docName` / `markdown` / `template` / `position` / `summary` (each `docs[]` entry carries its own).",!0);let S=[];for(let E of e.docs)S.push(await writeOneDoc(E,w,k,D,t));let E=S.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:O});return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{}}}),F=E.filter(e=>e.ok).length,L=F===E.length,B=E.map(e=>e.ok?`Wrote ${e.docName} (${e.position}).`:`Failed ${e.docName}: ${e.error}`),H=e.docs.flatMap((e,t)=>{let w=S[t];if(!w?.ok)return[];let E=frontmatterIgnoredNote(w.position,e.markdown);return E?[`${e.docName} — ${E}`]:[]}),q=[`${F}/${E.length} written.`,...B,...H].join(`
|
|
3490
|
+
`),J={ok:L,documents:E},Y=S.find(e=>e.ok);return Y&&Y.raw.systemSubscriberCount===0&&(J.warning=buildPreviewAttachWarning(resolvePreviewUrl(Y.docName,{lockDir:O}),j)),textPlusStructured(q,J,!L)}if(e.docName===void 0)return textResult("Error: provide `docName` (single) or `docs` (batch).",!0);let F=await writeOneDoc({docName:e.docName,markdown:e.markdown,template:e.template,position:e.position,summary:e.summary},w,k,D,t);if(!F.ok)return textResult(`Error: ${F.error}`,!0);let L=F.raw,B=resolvePreviewUrl(F.docName,{lockDir:O}),H=typeof L.subscriberCount==`number`?L.subscriberCount:void 0,q=(typeof L.systemSubscriberCount==`number`?L.systemSubscriberCount:void 0)===0,J=H===0,Y=Array.isArray(L.hints)?L.hints:void 0,ee=L.summary&&typeof L.summary==`object`?L.summary:void 0,te=typeof ee?.hint==`string`?ee.hint:void 0,ne=[F.fromTemplate===void 0?`Written successfully (${F.position}).`:`Written successfully (instantiated from template "${F.fromTemplate}").`],ae=frontmatterIgnoredNote(F.position,e.markdown);if(ae&&ne.push(ae),q&&!B&&ne.push(START_UI_TEXT_HINT),te&&ne.push(te),Y)for(let e of Y)e.message&&ne.push(e.message);let oe=ne.join(`
|
|
3491
|
+
`);if(!B&&!q&&!J&&!Y&&!ee)return textResult(oe);let se={};return B&&(se.previewUrl=B.url,se.previewUrlSource=B.source),q&&(se.warning=buildPreviewAttachWarning(B,j)),Y&&(se.hints=Y),ee&&(se.summary=ee),textPlusStructured(oe,se)})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$17(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$9(w,{config:t.config,resolveCwd:E(`ingest`)}),register$5(w,{config:t.config,resolveCwd:E(`research`)}),register$22(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$20(w,{config:t.config,resolveCwd:E(`discover`)}),register$3(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`links`)}),register(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$19(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$21(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_frontmatter`),identityRef:t.identityRef}),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename`),identityRef:t.identityRef}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`version`),identityRef:t.identityRef}),register$14(w,{resolveCwd:E(`get_components`),config:t.config}),register$15(w,{resolveCwd:E(`get_authoring_palette`),config:t.config}),register$13(w,{config:t.config,resolveCwd:E(`get_config`)}),register$10(w,{config:t.config,resolveCwd:E(`get_preview_url`)}),register$16(w,{config:t.config,resolveCwd:E(`folder_config`)}),register$7(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_conflicts`)}),register$12(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_conflict_content`)}),register$4(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`resolve_conflict`)}),register$2(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)});installPrettyZodErrors(E);let D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j,reactShellMiddleware:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,J=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let O=(S,w,D)=>{if(S===void 0){D();return}try{S(e,t,()=>{t.writableEnded||t.headersSent||D()})}catch(e){E.error({err:e},`Unhandled ${w} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},k=e=>O(j,`content-asset`,e),L=e=>O(F,`react-shell`,e),B=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})};if(F!==void 0&&D?.startsWith(`/assets/`)){L(()=>k(B));return}if(j!==void 0||F!==void 0){k(()=>L(B));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=H.get(S);e!==void 0&&(clearTimeout(e),H.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(H.delete(S),J)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(S,e),E.info({connectionId:S,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-Drw_7KKo.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-Drw_7KKo.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}function entryMatchesDocName(e,t,S,w){let E=relative(w,join(S,e.file));return E.startsWith(`..`)?!1:stripDocExtension(E)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:S,contentDir:w}=e;return{async afterLoadDocument({documentName:e,document:E}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let D=t();if(!D)return;let O=D.getConflicts();if(O.length===0||!O.some(t=>entryMatchesDocName(t,e,S,w)))return;let k=E.getMap(`lifecycle`);if(k.get(`status`)===`conflict`)return;k.set(`status`,`conflict`),k.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let S=readGitCommonDirSync(e);if(S===null)return[];let w=[];appendExcludeFileIfExists(join(S,`info`,`exclude`),t,w,`info/exclude`);let E=resolveGlobalExcludesfileSync(e);return E&&appendExcludeFileIfExists(E,t,w,`global excludesfile`),w}async function loadGitExcludeSourcesAsync(e,t){let S=await readGitCommonDirAsync(e);if(S===null)return[];let w=[];await appendExcludeFileIfExistsAsync(join(S,`info`,`exclude`),t,w,`info/exclude`);let E=await resolveGlobalExcludesfileAsync(e);return E&&await appendExcludeFileIfExistsAsync(E,t,w,`global excludesfile`),w}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),S=t.trim();if(S)return S}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,S,w){if(existsSync(e))try{let w=readFileSync(e,`utf-8`);t.value+=w.length,S.push(...parseIgnorePatterns(w))}catch(t){console.warn(`[content-filter] Failed to read ${w} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,S,w){if(existsSync(e))try{let w=await readFile$1(e,`utf-8`);t.value+=w.length,S.push(...parseIgnorePatterns(w))}catch(t){console.warn(`[content-filter] Failed to read ${w} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O,k,j,F=0,L=0,B=0;function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[],H=0,q=0;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=readFileSync(E,`utf-8`);H+=t.length;let S=parseIgnorePatterns(t);w.push(...S),e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);H+=t.length,q++;let S=parseIgnorePatterns(t).map(e=>prefixPattern(e,E));e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let J={value:H};q+=loadNestedIgnoreFiles(S,t,e,J),H=J.value;let Y=loadGitExcludeSources(t,J);H=J.value,Y.length>0&&(w.push(...Y),e.add(Y));let ee=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return O=e,k=w,j=ee,F=w.length,L=q,B=H,{patternCount:F,nestedFileCount:L,bytes:B}}H();let q=new Map;function J(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}populateDirCount(S,``,J,q);function Y(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function ee(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:J(e)}return{isExcluded(e,t){if(Y(e))return!0;if(t?.bypassFilters)return!1;if(ee(e))return!0;if(isSupportedDocFile(e))return!1;let S=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(S)){let t=dirname(e),S=t===`.`?``:t;if((q.get(S)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let S=E?`${E}/${e}`:e;return O.ignores(S)||O.ignores(`${S}/`)},isPathIgnored(e,t){return Y(e)?!0:t?.bypassFilters?!1:ee(e)},getWatcherIgnoreGlobs(){return j},incrementMdDir(e){let t=e===`.`?``:e;q.set(t,(q.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=q.get(t)??0;S<=1?q.delete(t):q.set(t,S-1)},rebuildDirCount(){let e=new Map(q);q.clear();try{populateDirCount(S,``,J,q)}catch(t){for(let[t,S]of e)q.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,E=k,D=j,Y=F,ee=L,te=B,ne=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async ae=>{try{let t=H();q.clear(),populateDirCount(S,``,J,q);let E=Date.now()-ne;if(ae.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E},`content-filter rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E}}catch(w){O=t,k=E,j=D,F=Y,L=ee,B=te,q.clear();try{populateDirCount(S,``,J,q)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let H=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(H)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:H}}}})}}}function populateDirCount(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let D of E){let E=t?`${t}/${D.name}`:D.name;if(D.isDirectory()){if(BUILTIN_SKIP_DIRS.has(D.name)||S(E)||S(`${E}/`))continue;populateDirCount(join(e,D.name),E,S,w)}else D.isFile()&&isSupportedDocFile(D.name)&&!S(E)&&w.set(t,(w.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3492
3492
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let D=0;for(let O of E){if(!O.isDirectory()||BUILTIN_SKIP_DIRS.has(O.name))continue;let E=join(e,O.name),k=relative(t,E);if(!k.startsWith(`..`)&&!(S.ignores(k)||S.ignores(`${k}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(E,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);w.value+=e.length;let E=parseIgnorePatterns(e).map(e=>prefixPattern(e,k));S.add(E),D++}catch(S){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,S)}}D+=loadNestedIgnoreFiles(E,t,S,w)}}return D}async function initContentDirStateAsync(e,t,S,w,E,D,O){let k;try{k=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let j of k){let k=t?`${t}/${j.name}`:j.name;if(j.isDirectory()){if(BUILTIN_SKIP_DIRS.has(j.name))continue;let t=join(e,j.name);if(!D){let e=relative(S,t);if(e.startsWith(`..`)||w.ignores(e)||w.ignores(`${e}/`))continue;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${S} at ${E}:`,e)}}}await initContentDirStateAsync(t,k,S,w,E,D,O)}else if(j.isFile()&&isSupportedDocFile(j.name)){if(!D){let e=E?`${E}/${k}`:k;if(w.ignores(e))continue}O.set(t,(O.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O=(0,import_ignore.default)(),k=[],j=new Map;function F(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[];for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=parseIgnorePatterns(await readFile$1(w,`utf-8`));e.add(t.map(e=>prefixPattern(e,E)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let F=await loadGitExcludeSourcesAsync(t,{value:0});F.length>0&&(w.push(...F),e.add(F));let L=new Map;await initContentDirStateAsync(S,``,t,e,E,D,L),O=e,k=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),j.clear();for(let[e,t]of L)j.set(e,t)}return await H(),{isExcluded(e,t){if(L(e))return!0;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let S=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(S)){let t=dirname(e),S=t===`.`?``:t;if((j.get(S)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let S=E?`${E}/${e}`:e;return O.ignores(S)||O.ignores(`${S}/`)},isPathIgnored(e,t){return L(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;j.set(t,(j.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=j.get(t)??0;S<=1?j.delete(t):j.set(t,S-1)},rebuildDirCount(){let e=new Map(j);j.clear();try{populateDirCount(S,``,F,j)}catch(t){for(let[t,S]of e)j.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,S=k,E=new Map(j),D=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async F=>{try{await H();let t=Date.now()-D;if(F.setAttributes({"ok.ignore.pattern_count":k.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:k.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(w){O=t,k=S,j.clear();for(let[e,t]of E)j.set(e,t);let D=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(D)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:D}}}})}}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let S=resolve(e,t.slice(5));try{return readFileSync(S,`utf-8`).trim()}catch{try{let S=readFileSync(resolve(e,`packed-refs`),`utf-8`),w=t.slice(5),E=S.split(`
|
|
3493
3493
|
`).find(e=>e.endsWith(` ${w}`));if(E)return E.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,S){let w=resolveGitDir(e);if(!w)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let E=w,D=!1,O=null,k=null,j=null,F=null;async function L(e){if(H&&await H,!D)return;O&&=(clearTimeout(O),null),k&&=(clearTimeout(k),null);let t=readHeadSha(E),w=j!==t,L=readBranchFromHead(E),B;B=L?.startsWith(`detached-`)?`detached-head`:F===L?`within-branch`:`cross-branch`;let q=F;try{await S({headMoved:w,oldHead:j,newHead:t,timeout:e,batchKind:B,oldBranch:q,newBranch:L})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{D=!1,j=t,F=L}}function B(){O&&clearTimeout(O),O=setTimeout(()=>{O=null,L(!1)},QUIET_WINDOW_MS)}let H=null;async function q(e){if(!D){D=!0,j=readHeadSha(E);let S=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();H=S,await S,H=null,k=setTimeout(()=>{k=null,L(!0)},BATCH_TIMEOUT_MS)}B()}let J,Y;try{Y=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await Y.subscribe(E,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){q(t);break}}});J=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return j=readHeadSha(E),F=readBranchFromHead(E),console.log(`[head-watcher] Watching ${E} for HEAD changes`),{unsubscribe:async()=>{D&&await L(!1),O&&clearTimeout(O),k&&clearTimeout(k),await J()},getLastKnownBranch:()=>F}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:S,signalChannel:w,debounceMs:E=100}=e,D=new Map;function O(e){let t=D.get(e);t&&(clearTimeout(t),D.delete(e))}function k(e,k){O(e),D.set(e,setTimeout(()=>{D.delete(e);try{let E=serializeLiveDocument(k);t.updateDocumentFromMarkdown(e,E),w?.(`backlinks`),w?.(`graph`),S&&(S.updateDocumentFromMarkdown(e,E),w?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},E))}return{async onChange({documentName:e,document:t,transactionOrigin:S}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(S)&&S.context?.origin===`file-watcher`||k(e,t)},async beforeUnloadDocument({documentName:e}){O(e)},async onDestroy(){for(let e of D.values())clearTimeout(e);D.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),S=resolve(t,PRINCIPAL_FILE),{name:w,email:E}=await readGitConfig(e);if(existsSync(S)){let e;try{e=JSON.parse(readFileSync(S,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,D=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),O=t.slice(10,18),k={id:t,display_name:w?sanitizeGitIdentity(w):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:E?sanitizeGitIdentity(E):typeof e.display_email==`string`?e.display_email:`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:D};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}mkdirSync(t,{recursive:!0});let D=`principal-${randomUUID()}`,O=D.slice(10,18),k={id:D,display_name:w?sanitizeGitIdentity(w):`Local User`,display_email:E?sanitizeGitIdentity(E):`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let S=e.resolveFilePath(t);return S!==null&&e.fileExists(S)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let S=t.recentlyRemovedDocs.get(e);if(S===void 0)return;if(S.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let w=new Set([e]),E=S.newDocName;for(;;){if(w.has(E)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:E}));return}w.add(E);let S=t.recentlyRemovedDocs.get(E);if(S===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E);if(S.kind===`deleted`)throw fileExistsForDocName(t,E)?(t.recentlyRemovedDocs.delete(E),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));E=S.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,S=new Map;return{async afterLoadDocument({documentName:w,document:E}){if(isSystemDoc(w)||isConfigDoc(w)||t.has(w))return;let D=E,O=D.getXmlFragment(`default`),k=D.getText(`source`),j=()=>{try{let S=setupServerObservers({doc:D,xmlFragment:O,ytext:k,mdManager:e.mdManager,schema:e.schema,docName:w,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(w,S),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${w}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!j()){let e=setTimeout(()=>{S.delete(w),!t.has(w)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${w}'`),j())},5e3);S.set(w,e)}},async afterUnloadDocument({documentName:e}){let w=S.get(e);w&&(clearTimeout(w),S.delete(e));let E=t.get(e);E&&(E(),t.delete(e))},async onDestroy(){for(let e of S.values())clearTimeout(e);S.clear();for(let[e,S]of t.entries())try{S()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let S=t.createdBy;return!(typeof S.runtimeVersion!=`string`||S.protocolVersion!==void 0&&typeof S.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let S;try{S=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let w;try{w=JSON.parse(S)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(w))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:w}}function writeStateManifest(e,t){let S=manifestPath(e);mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),S=e.currentStateSchemaVersion??1,w=e.currentRuntimeVersion??RUNTIME_VERSION,E=e.currentProtocolVersion??1,D=(e.now??(()=>new Date))().toISOString(),O=manifestPath(e.lockDir),k=readStateManifest(e.lockDir);if(k.status===`present`){let j=k.manifest;if(!isCompatibleSchema(j.stateSchemaVersion,S))throw new StateManifestError({kind:`incompatible`,path:O,message:`State manifest at ${O} declares stateSchemaVersion=${j.stateSchemaVersion} but this binary supports ${S}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${j.createdBy.runtimeVersion}, protocol ${j.createdBy.protocolVersion}.)`});try{let t={...j,lastWriteBy:{runtimeVersion:w,protocolVersion:E,at:D}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),j}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let k={stateSchemaVersion:S,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E}};return writeStateManifest(e.lockDir,k),t.info({path:O,stateSchemaVersion:S},`[state-manifest] fresh project — wrote manifest`),k}let j={stateSchemaVersion:0,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E,adoptedAt:D}};return writeStateManifest(e.lockDir,j),t.warn({path:O,runtimeVersion:w},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),j}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),S=extractStderr(t),w=`${t.message}\n${S}`.toLowerCase();return matchesAny(w,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:S}:matchesAny(w,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:S}:matchesAny(w,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:S}:matchesAny(w,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:S}:matchesAny(w,AUTH_PATTERNS)?/\b401\b/.test(w)||/token.*expired/i.test(w)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:S}:/\b403\b/.test(w)?matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:S}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:S}:matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:matchesAny(w,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:S}:matchesAny(w,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:S}:matchesAny(w,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:S}:matchesAny(w,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:S}:matchesAny(w,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:S}:matchesAny(w,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:S}:matchesAny(w,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:S}:matchesAny(w,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:S}:matchesAny(w,NETWORK_PATTERNS)?/timed? out/i.test(w)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:S}:/refused/i.test(w)||/econnrefused/i.test(w)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:S}:/resolve.*host/i.test(w)||/enotfound/i.test(w)||/getaddrinfo/i.test(w)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:S}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:S}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:S}}const log$1=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let S=t.push;return typeof S==`boolean`?S:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$1.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let S=readPushFlag(t);return S===null?(log$1.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):S?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$1.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,S){let w=t(e);if(w.available&&w.token)return{token:w.token,source:`gh`};if(S)try{let t=await S.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$1.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:S,host:w=`github.com`,detectGh:E=()=>({available:!1}),tokenStore:D,_fetchFn:O=fetch,_timeoutMs:k=PROBE_TIMEOUT_MS}=e,{token:j,source:F}=await resolveProbeTokenWithSource(w,E,D),L=`${githubApiBase(w)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(S)}`;log$1.info({host:w,tokenSource:F,tokenLen:j===void 0?0:j.length},`[permissions] probe starting`);let B=new AbortController,H=setTimeout(()=>B.abort(),k);try{let e=await O(L,{signal:B.signal,headers:buildHeaders(j)}),t=await classify(e,j!==void 0);return log$1.info({host:w,tokenSource:F,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return B.signal.aborted?(log$1.warn({host:w,timeoutMs:k},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$1.warn({err:e,host:w},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(H)}}async function checkPushPermission(e){let t=performance.now(),S=await runProbe(e);return recordProbeTelemetry(S,performance.now()-t),S}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let S=outcomeAttributes(e);outcomeCounter().add(1,S),durationHist().record(t,{outcome:S.outcome})}function computeRemainingMs(e,t,S=Date.now()){if(!e)return 0;let w=new Date(e).getTime();if(Number.isNaN(w))return 0;let E=w+t*1e3;return Math.max(0,E-S)}const log=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,S=t*.15*(2*Math.random()-1);return Math.round(t+S)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let S=readFileSync(t,`utf-8`).trim(),w=/^ref:\s+(refs\/.+)$/.exec(S);if(!w)return!1;let E=w[1];if(existsSync(join(e,`.git`,E)))return!1;let D=join(e,`.git`,`packed-refs`);if(existsSync(D)){let e=readFileSync(D,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${E}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;errorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),S=t?join(t,`MERGE_HEAD`):null,w=S!==null&&existsSync(S);if(this.conflictCount>0&&!w)log.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&w)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
3494
3494
|
`).map(e=>e.trim()).filter(Boolean):[]),S=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<S&&log.info({cleared:S-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(w&&this.conflictCount===0){log.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let E=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),D=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(E>0?E:void 0),this.schedulePush(D>0?D:void 0),log.info({branch:this.currentBranch,pullDelayMs:E,pushDelayMs:D},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.error=void 0,this.errorCode=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.error=void 0,this.errorCode=void 0,this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.error=void 0,this.errorCode=void 0),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,error:this.error,...this.errorCode===void 0?{}:{errorCode:this.errorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let S;try{S=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),S={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let w=pushPermissionStatusFrom(S),E=this.pushPermission;this.pushPermission=w;let D=!1;return w.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),D=!0,log.info({reason:w.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):w.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),D=!0,log.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!D&&!pushPermissionStatusEqual(E,w)&&this.cc1Broadcaster?.signal(`sync-status`),w}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),S=t?join(t,`MERGE_HEAD`):null;if(!(S!==null&&existsSync(S)))log.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),S=new Set(t?t.split(`
|
|
@@ -3504,4 +3504,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3504
3504
|
`),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{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Rt),S=e+t;S>0?getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile 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,serializeDoc:at});_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()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Bt,projectDir:S,contentDir:t}))}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){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);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)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}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 w=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 e of CONFIG_DOC_NAMES){let t=w.get(e);if(t)try{ee.info({docName:e,path:t},`[config-file-watcher] starting`);let S=await startConfigFileWatcher(t,t=>{let S=_e.documents.get(e);ee.info({docName:e,hasDocument:S!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,e,t,ge.configPersistenceCtx);if(ee.info({docName:e,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__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:e,cleanup:S}),ee.info({docName:e,path:t},`[config-file-watcher] started`)}catch(S){ee.warn({err:S,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Wt.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:S,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(S,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(E=t)}}catch{}let D=E?[e,w,E]:[e,w],O=ee;O.info({okignorePath:e,gitignorePath:w,gitInfoExcludePath:E},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let k=await startMultiPathConfigFileWatcher(D,(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);O.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){O.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let E=await ue.rebuildIgnorePatterns();if(E.ok)O.info({changedPath:relative(S,t),patternCount:E.patternCount,nestedFileCount:E.nestedFileCount,durationMs:E.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;O.warn({changedPath:e,error:E.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,E.error.message)}})().catch(e=>{O.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:k}),O.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 E=resolveGitDir(S),D=E?readBranchFromHead(E)??`main`:`main`;switchReconciledBaseScope(D),de.switchBranch(D);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`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}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++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}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(`
|
|
3505
3505
|
`))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`)}function O(e){for(let w of e)try{let e=relative(t,join(S,w));if(e.startsWith(`..`))continue;let E=stripDocExtension(e),D=_e.documents.get(E);if(!D)continue;let O=at(E);O===null?ee.warn({docName:E,file:w},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(E,O);let k=D.getMap(`lifecycle`);k.set(`status`,`conflict`),k.set(`reason`,`sync-merge-conflict`),ee.info({docName:E,file:w},`[sync] marked loaded content conflict`)}catch(e){ee.warn({err:e,file:w},`[sync] failed to mark loaded content conflict`)}}let k=J?.[0]??`open-knowledge`,j=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):k} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:j,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,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}`)},onContentConflictsDetected:O,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-BniQ3qki-D-qFWWUB.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,detectGh:e.detectGh,tokenStore:e.tokenStore}),{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,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ne},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;w!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});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(e){if(ge)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,j(ne,Te),ge&&updateUiLockPort(ne,Te),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=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 ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,S)=>{try{await je(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>Y()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(ne)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:ne,contentDir:e.contentDir,port:Te,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
|
|
3506
3506
|
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}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 OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],S=e.toLowerCase();if(t.includes(S))return S}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let S=t===1?e:`${e}.${t-1}`,w=`${e}.${t}`;try{renameSync(S,w)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),S=MAX_AGE_DAYS*24*60*60*1e3,w=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let S=statSync(join(e,t));return{name:t,mtime:S.mtimeMs,size:S.size}}catch{return null}}).filter(Boolean);for(let E of w)if(t-E.mtime>S)try{unlinkSync(join(e,E.name))}catch{}let E=w.filter(e=>t-e.mtime<=S).sort((e,t)=>e.mtime-t.mtime),D=E.reduce((e,t)=>e+t.size,0);for(let t of E){if(D<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),D-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),S=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(S),setTimeout(()=>pruneLogsDir(OK_LOGS_DIR),5e3);let w=import_pino.default.destination({dest:S,append:!0,sync:!1});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},w)}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}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}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:S}of HOME_PATH_PATTERNS)t=t.replace(e,S);return t}function serializeError(e,t=0,S=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(S.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};S.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,S)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let w=e;return{name:String(w.name??`ObjectError`),message:scrubPaths(String(w.message??``))??``,stack:scrubPaths(w.stack),code:w.code,cause:w.cause===void 0?void 0:serializeError(w.cause,t+1,S)}}return{name:`UnknownError`,message:String(e)}}export{applySeed as $,resolveCursorBinaryDefault as $n,LATEST_PROTOCOL_VERSION as $r,getMetrics as $t,McpLogger as A,OK_PROJECT_MARKER as Ai,parseAuthRejectionWire as An,tracedAppendFileSync as Ar,createPersistenceExtension as At,STARTER_FOLDER_FRONTMATTER_FILENAME as B,string$2 as Bi,readTargetRecordedAt as Bn,tracedWriteFileSync as Br,extractWikiLinksFromMarkdown as Bt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as C,SYSTEM_DOC_NAME as Ci,listRescueCheckpoints as Cn,shutdownTelemetry as Cr,createContentFilter as Ct,MCP_CONNECTION_ID_HEADER as D,iconFromClientName as Di,mountMcpAndApi as Dn,streamingProblemEvent as Dr,createLiveDerivedIndexExtension as Dt,MAX_AGENT_SESSIONS as E,humanFormat as Ei,loggerFactory as En,startWatcher as Er,createFileLogger as Et,ProjectGitInitError as F,boolean$1 as Fi,readAllTargets as Fn,tracedRenameSync as Fr,detectClaudeDesktopPresence as Ft,SeedPrerequisiteError as G,recordSkillInstallEvent as Gn,validateSkillZip as Gr,formatContributorsFrom as Gt,STARTER_PACK_IDS as H,_coercedNumber as Hi,readUiLock as Hn,updateUiLockPort as Hr,findEnclosingProjectRoot as Ht,ROLLBACK_ORIGIN as I,literal as Ii,readBranchFromHead as In,tracedRmSync as Ir,detectProjectShape as It,TagIndex as J,releaseUiLock as Jn,writeStateManifest as Jr,getLocalDir as Jt,SeedRootDirError as K,registerAllTools as Kn,withSpan as Kr,gcCheckpointRefs as Kt,SERVICE_WRITER as L,looseObject as Li,readServerPackageVersion as Ln,tracedRmdirSync as Lr,ensureProjectGit as Lt,OBSERVER_SYNC_ORIGIN as M,ZodNumber$1 as Mi,parseKeepaliveConnectionId as Mn,tracedMkdir as Mr,createServerObserverExtension as Mt,OK_OKIGNORE_TEMPLATE as N,any$1 as Ni,pathToDocName as Nn,tracedMkdirSync as Nr,createStreamingErrorWriter as Nt,MCP_SERVER_NAME as O,isBranchNotFoundGitError as Oi,normalizeFsPath as On,swapContributors as Or,createMcpHttpHandler as Ot,PinoLogger as P,array as Pi,planSeed as Pn,tracedRename as Pr,createTestLogger as Pt,applyExternalChange as Q,resolveContentDir as Qn,JSONRPCMessageSchema as Qr,getMeter as Qt,SKILL_INSTALL_EVENTS_FILE_REL as R,number$1 as Ri,readSkillInstallStateSnapshot as Rn,tracedUnlinkSync as Rr,errorResponse as Rt,INSTALLED_AGENTS_SCHEMES as S,SPAWN_ERROR_LOG as Si,lastKnownHash as Sn,shadowGit as Sr,createAssetServeMiddleware as St,MANAGED_RENAME_ORIGIN as T,defaultScheduler as Ti,loadPrincipal as Tn,splitMarkdownBlocks as Tr,createExternalChangeHandler as Tt,STARTER_TEMPLATES as U,NEVER as Ui,reconcile as Un,validateAgentId as Ur,formatAuthRejectionWire as Ut,STARTER_PACKS as V,url as Vi,readTargetVersion as Vn,updateLastKnownHash as Vr,findEnclosingGitRoot as Vt,STATE_MANIFEST_FILENAME as W,require_dist$1 as Wi,recordContributor as Wn,validateCloneInputs as Wr,formatContributors as Wt,acquireUiLock as X,resetMetrics as Xn,writeTracker as Xr,getLogger as Xt,UiLockCollisionError as Y,removeLastKnownHash as Yn,writeTargetVersion as Yr,getLogFilePath as Yt,applyAgentMarkdownWrite as Z,resolveBundledSkillDir as Zn,McpServer as Zr,getLogsDir as Zt,FILE_WATCHER_ORIGIN as _,EXECUTABLE_BLOCKLIST_EXTENSIONS as _i,isPairedWriteOrigin as _n,saveInMemoryCheckpoint as _r,commitWipFromTree as _t,AgentPresenceBroadcaster as a,resolveConfigPath as ai,initContent as an,restoreLifecycleFromConflictsJson as ar,buildConfigYmlContent as at,HocuspocusAuthRejection as b,ProblemDetailsSchema as bi,isSelfWrite as bn,serializeError as br,contributorCount as bt,BacklinkIndex as c,GitDirAccessError as ci,installPrettyZodErrors as cn,runAuthReposSubprocess as cr,buildSkillZip as ct,CONFLICT_MARKER_RE as d,ASSET_EXTENSIONS as di,isAllowedApiOrigin as dn,runDeviceFlowSubprocess as dr,classifyEvents as dt,isInitializedNotification as ei,getTracer as en,resolveCursorSpawnInvocation as er,assertCompatibleStateManifest as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,CC1_CONTRACT_VERSION as fi,isAllowedWorkspaceHostHeader as fn,runWithMcpLogger as fr,classifyFsPath as ft,FILE_SYSTEM_WRITER as g,EDITOR_LABELS as gi,isLoopbackAddress as gn,sanitizeClientName as gr,commitWip as gt,DEFAULT_PACK_ID as h,DEFAULT_SIGTERM_GRACE_MS as hi,isKnownPackId as hn,safetyCheckpoint as hr,commitUpstreamImport as ht,AgentFocusBroadcaster as i,readConfigSafely as ii,incrementServerObserverFire as in,restoreContributors as ir,buildAndOpenSkill as it,MissingOkConfigError as j,locateIssue as ji,parseHocuspocusAuthToken as jn,tracedLinkSync as jr,createServer$1 as jt,MISSING_OK_CONFIG_MESSAGE as k,isOrphanMode as ki,packageVersionMajorMinor as kn,toBroadcasterKey as kr,createOsProbe as kt,CC1Broadcaster as l,MalformedGitPointerError as li,installTestLoggers as ln,runAuthStatusSubprocess as lr,buildStarterFolderFrontmatterYaml as lt,DEFAULT_CHECKPOINT_RETENTION as m,DEFAULT_SERVER_HOST as mi,isHocuspocusAuthRejectionReason as mn,safeSubdir as mr,coercePackId as mt,AGENT_ID_RE as n,isJSONRPCResultResponse as ni,handleSpawnCursor as nn,resolvePack as nr,attachIdleShutdown as nt,AgentSessionCapacityError as o,withFileLockSync as oi,initShadowRepo as on,rewriteMarkdownLinksForDocumentRename as or,buildExecResult as ot,ConfigSchema as p,DEFAULT_GITHUB_OAUTH_CLIENT_ID as pi,isConfigDoc as pn,safeContentPath as pr,clearContributors as pt,StateManifestError as q,registerWrite as qn,withSpanSync as qr,getCurrentMcpLogger as qt,AGENT_WRITE_ORIGIN as r,atomicWriteFileSync as ri,incrementCollabSocketFilteredError as rn,resolvePackageVersion as rr,bootServer as rt,AgentSessionManager as s,writeConfigPatch as si,initTelemetry as sn,rewriteWikiLinksForDocumentRename as sr,buildInstructions as st,AGENT_ID_MAX_LEN as t,isJSONRPCRequest as ti,handleCollabSocketError as tn,resolveLockDir as tr,assertNeverDiskEvent as tt,CONFIG_FILENAME as u,ALL_EDITOR_IDS as ui,installUserSkill as un,runCloneSubprocess as ur,buildWipTree as ut,GIT_UPSTREAM_WRITER as v,INLINE_RENDERABLE_EXTENSIONS as vi,isPathWithinDir as vn,saveVersion as vr,containsConflictMarkers as vt,LOG_MD_TEMPLATE as w,colorFromSeed as wi,listStarterPacks as wn,spawnDetached as wr,createContentFilterAsync as wt,HocuspocusAuthTokenSchema as x,SKILL_STATE_TARGETS as xi,isSystemDoc as xn,setActiveSpanAttributes as xr,createApiExtension as xt,HOCUSPOCUS_AUTH_REJECTION_REASONS as y,ORPHAN_MODES as yi,isProjectRoot as yn,seedBasenameIndex as yr,contentHash as yt,STARTER_FOLDERS as z,object$1 as zi,readStateManifest as zn,tracedWriteFile as zr,evictStaleTrackerEntries as zt};
|
|
3507
|
-
//# sourceMappingURL=dist-
|
|
3507
|
+
//# sourceMappingURL=dist-Ca54A9UG.mjs.map
|