@inkeep/open-knowledge 0.73.0-beta.6 → 0.73.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-Bj8ALhwz.mjs +1 -0
  3. package/dist/{dist-D3p6jBye.mjs → dist-Bz2ulDby.mjs} +1 -1
  4. package/dist/{dist-BR_F3tPt.mjs → dist-CmkkO00A.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-CY6mjVg8.mjs +1 -0
  7. package/dist/{init-BF6LkDNO.mjs → init-RRNvrwqG.mjs} +2 -2
  8. package/dist/{launch-json-removal-xVjE7rjr.mjs → launch-json-removal-H2_LurB8.mjs} +1 -1
  9. package/dist/{loader-BPLeeRBL.mjs → loader-B5SAldnx.mjs} +1 -1
  10. package/dist/loader-DAtfirp3.mjs +1 -0
  11. package/dist/{open-browser-CsYfwgRA.mjs → open-browser-Bk-q-DTx.mjs} +1 -1
  12. package/dist/preview-C3OgrbbK.mjs +1 -0
  13. package/dist/{preview-D-QyVMJR.mjs → preview-DAkIttDa.mjs} +1 -1
  14. package/dist/public/assets/{ActivityModeContent-DZlniU4k.js → ActivityModeContent-DIokNg_1.js} +1 -1
  15. package/dist/public/assets/{AddPropertiesButton-r9pUsDp6.js → AddPropertiesButton-CTxZoKEd.js} +1 -1
  16. package/dist/public/assets/{AgentDiffPane-BSGSWUH4.js → AgentDiffPane-BPCO6N9C.js} +1 -1
  17. package/dist/public/assets/{CodeMirrorPropInput-CzEn4HIE.js → CodeMirrorPropInput-Cy9h8tVy.js} +1 -1
  18. package/dist/public/assets/{DocumentContext-B_DJRQtG.js → DocumentContext-BE-EqO42.js} +1 -1
  19. package/dist/public/assets/{EditorModeToggle-mV4rnHEf.js → EditorModeToggle-D5UCrenE.js} +1 -1
  20. package/dist/public/assets/{EnableSyncConfirmDialog-BOhmjhcs.js → EnableSyncConfirmDialog-BgN3rSZE.js} +1 -1
  21. package/dist/public/assets/{ExcalidrawDocEditor-lUs3Hi0K.js → ExcalidrawDocEditor-D1DBApsF.js} +1 -1
  22. package/dist/public/assets/FeedbackForm-Cu2MzQEe.js +1 -0
  23. package/dist/public/assets/{ImportSkillDialog-DuZKwG-j.js → ImportSkillDialog-r7h6LN1Y.js} +1 -1
  24. package/dist/public/assets/{LintConfigEditor-BINWs_Py.js → LintConfigEditor-UiBKtnrX.js} +1 -1
  25. package/dist/public/assets/ManagedArtifactProperties-BE67J54X.js +1 -0
  26. package/dist/public/assets/{ManagedArtifactProperties-BhPcKXb4.js → ManagedArtifactProperties-Cx7hf_qV.js} +1 -1
  27. package/dist/public/assets/{MermaidDocEditor-BTTRLLbG.js → MermaidDocEditor-9Ne7RN3c.js} +1 -1
  28. package/dist/public/assets/{PropertyDisplayRow-BQubidKf.js → PropertyDisplayRow-NVZRUfkZ.js} +1 -1
  29. package/dist/public/assets/{SchemaConfigEditor-ConRL1eI.js → SchemaConfigEditor-CRQtqEX6.js} +1 -1
  30. package/dist/public/assets/{SessionsHost-jOznXUUn.js → SessionsHost-BgXGDhsS.js} +2 -2
  31. package/dist/public/assets/{SettingsDialogBody-Z3N2dd_v.js → SettingsDialogBody-Bck8vtDh.js} +1 -1
  32. package/dist/public/assets/{ShareReceiveMissDialog-B68oE41T.js → ShareReceiveMissDialog-B6i4mHrK.js} +1 -1
  33. package/dist/public/assets/{SkillToolbarControls-CMXBbU--.js → SkillToolbarControls-CpKKDkFW.js} +1 -1
  34. package/dist/public/assets/{SourceEditor-DI2wBFkU.js → SourceEditor-BtLocLDr.js} +1 -1
  35. package/dist/public/assets/{TerminalWindowApp-CQV-cAHA.js → TerminalWindowApp-DK5sWW3j.js} +1 -1
  36. package/dist/public/assets/{TextDocEditor-DUdVpSlC.js → TextDocEditor-BY1uEt02.js} +1 -1
  37. package/dist/public/assets/{ThreadView-4qX5qSc_.js → ThreadView-Dz-5JQc3.js} +1 -1
  38. package/dist/public/assets/{TimelineDiffPane-CZKA5agt.js → TimelineDiffPane-C3cjU3A1.js} +1 -1
  39. package/dist/public/assets/{auth-state-cache-oi2AiNjE.js → auth-state-cache-jCDsV2dz.js} +1 -1
  40. package/dist/public/assets/{client-version-hldFhH0x.js → client-version-BUPOk8CD.js} +1 -1
  41. package/dist/public/assets/{comment-chips-Dykh1KMD.js → comment-chips-BMjTOnXD.js} +1 -1
  42. package/dist/public/assets/{config-provider-NcFOez6Z.js → config-provider-CbCQUINR.js} +1 -1
  43. package/dist/public/assets/{doc-undo-manager-mgtyFpOA.js → doc-undo-manager-Be4USElh.js} +1 -1
  44. package/dist/public/assets/{index-C5Iole39.js → index-CH4q7hfW.js} +8 -8
  45. package/dist/public/assets/{pending-receive-nav-store-DHlL6VvW.js → pending-receive-nav-store-4sJffkwT.js} +1 -1
  46. package/dist/public/assets/{progress-B58NWR1I.js → progress-CqLe3trE.js} +1 -1
  47. package/dist/public/assets/{selection-context-CVvVUryD.js → selection-context-BVwwiGPI.js} +1 -1
  48. package/dist/public/assets/{src-D1K6BZj-.js → src-BWYGI3WU.js} +1 -1
  49. package/dist/public/assets/{telemetry-impl-8ZYvwPMn.js → telemetry-impl-GCfc_-8q.js} +1 -1
  50. package/dist/public/assets/{telemetry-startup-CHI8oMpP.js → telemetry-startup-B0300RVO.js} +1 -1
  51. package/dist/public/assets/{typing-burst-detector-BxexOcMR.js → typing-burst-detector-B35v8wrR.js} +1 -1
  52. package/dist/public/assets/{use-activity-panel-Bpthmvwx.js → use-activity-panel-CimuGIWw.js} +1 -1
  53. package/dist/public/assets/{use-open-skill-DAV7LJa9.js → use-open-skill-9gXQlWGe.js} +1 -1
  54. package/dist/public/assets/{use-terminal-enabled-CmC_tzgK.js → use-terminal-enabled-DGPJ15om.js} +1 -1
  55. package/dist/public/assets/{use-timeline-entry-diff-BFYTYwwf.js → use-timeline-entry-diff-DHiHNFAi.js} +1 -1
  56. package/dist/public/index.html +17 -17
  57. package/dist/{registry-probes-CnJMJmOY.mjs → registry-probes-v9Bhe-ny.mjs} +1 -1
  58. package/dist/{removal-file-path-0HQQp3Hj.mjs → removal-file-path-BIgJ4hsT.mjs} +1 -1
  59. package/dist/{repair-launch-json-Dc3hhssu.mjs → repair-launch-json-BHF9iOKA.mjs} +1 -1
  60. package/dist/{repair-mcp-configs-DGg3ZUYM.mjs → repair-mcp-configs-CBAny7zg.mjs} +1 -1
  61. package/dist/src-gF5GjSGo.mjs +1 -0
  62. package/dist/{src-DIhnVXfu.mjs → src-vyfChLjW.mjs} +1 -1
  63. package/dist/start-COABFazN.mjs +1 -0
  64. package/dist/{start-DiFYCgE2.mjs → start-D1vujlOU.mjs} +3 -3
  65. package/package.json +5 -5
  66. package/dist/constants-CNfLm09a.mjs +0 -1
  67. package/dist/init-Bf-Px54h.mjs +0 -1
  68. package/dist/loader-y2fbtjaK.mjs +0 -1
  69. package/dist/preview-DrrBy4-s.mjs +0 -1
  70. package/dist/public/assets/FeedbackForm-DVQQ3oXB.js +0 -1
  71. package/dist/public/assets/ManagedArtifactProperties-CoP112iS.js +0 -1
  72. package/dist/src-IUqqfleT.mjs +0 -1
  73. package/dist/start-yaUoJrnV.mjs +0 -1
@@ -1007,7 +1007,7 @@ ${THe.join(`
1007
1007
  `),c=[],l=new Set,u=null,d=(e,t,n,r)=>{let i=`${r??`md`}\0${e}`;l.has(i)||(l.add(i),c.push({href:e,resolvedTo:t,reason:n,...r?{sourceForm:r}:{}}))},f=e=>{let n=e.trim();if(n.startsWith(`#`))return;let o=v(n,t);if(!o){d(n,null,`unresolvable`);return}if(o.kind===`doc`){!a.has(o.docName)&&i?.(o.docName)!==!0&&d(n,o.docName,`no-such-doc`);return}if(o.kind===`asset`){if(!r)return;let e=Ji(o.url,t,{literal:o.literal});if(e===null){d(n,null,`unresolvable`);return}r(e)||d(n,e,`no-such-file`);return}},p=(e,n)=>{if(n===``)return;if(rr(n)){d(n,null,`unresolvable`,`jsx`);return}let o=JX(e,n,t);if(o===null){d(n,null,`unresolvable`,`jsx`);return}if(pa(o)){if(!r)return;r(o)||d(n,o,`no-such-file`,`jsx`);return}!a.has(o)&&i?.(o)!==!0&&d(n,o,`no-such-doc`,`jsx`)},m,h,g={pages:a,get pagesBySlug(){return m??=vr(a,ea),m},get pagesByBasename(){return h??=ka(a,ea),h}},_=(e,t)=>{let n=en(e,t,g);n?.kind===`doc`&&ar(n.docName,g)===void 0&&i?.(n.docName)!==!0&&d(`[[${e}${t?`#${t}`:``}]]`,n.docName,`no-such-doc`)};for(let e of s){if(u){P0(e,u)&&(u=null);continue}let t=N0(e);if(t){u=t;continue}let n=F0(e);for(;n<e.length;){if(e[n]===`\\`&&n+1<e.length){n+=2;continue}if(e[n]==="`"){let t=I0(e,n);if(t){n=t.nextIndex;continue}}if(e[n]===`<`){let t=KX(e,n);if(t){for(let e of t.attrs.matchAll(qX(t.spec.attrName)))p(t.spec,e[3]??``);n+=t.matchLength;continue}}if(e[n]===`[`&&e[n+1]===`[`){let t=L0(e,n);if(t){_(t.target,t.anchor),n=t.nextIndex;continue}}if(e[n]===`[`&&e[n-1]!==`!`){let t=R0(e,n);if(t){f(t.href),n=t.nextIndex;continue}}n++}}return c}function z$e(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet,sourceForm:t.sourceForm,line:t.line,column:t.column,...t.rawWikiTarget===!0?{rawWikiTarget:!0}:{}}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))])),skillRefs:Object.fromEntries([...e.skillRefs.entries()].map(([e,t])=>[e,[...t].sort()]))}}function B$e(e){let t=new Map;for(let[n,r]of e)for(let[e,i]of r){let r=t.get(e);r||(r=new Map,t.set(e,r)),r.set(n,i)}return t}function V$e(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}function H$e(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null,sourceForm:e.sourceForm===`wiki`||e.sourceForm===`markdown`||e.sourceForm===`jsx`?e.sourceForm:void 0,line:V$e(e.line),column:V$e(e.column),rawWikiTarget:e.rawWikiTarget===!0}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:B$e(t),skillRefs:new Map(Object.entries(e.skillRefs??{}).map(([e,t])=>[e,new Set(t)])),epoch:0}}function U$e(e){let t=new Set;for(let n of e){let e=n.indexOf(`/`);for(;e!==-1;)t.add(n.slice(0,e)),e=n.indexOf(`/`,e+1)}return t}var W$e=class{projectDir;contentDir;contentFilter;getFileOracle;states=new Map;mtimesByBranch=new Map;documentLookups=new WeakMap;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.getFileOracle=e.getFileOracle??(()=>void 0),this.states.set(this.activeBranch,O0())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=O0(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let n=k0(e),r=new Set;if(!n)return r;let i=this.getState(t);if(!i.forward.has(e))return r;if(n.kind===`skill`)for(let t of i.forward.keys()){let n=k0(t);n?.kind===`reference`&&n.skillDocName===e&&r.add(t)}else i.forward.has(n.skillDocName)&&r.add(n.skillDocName);return r}skillRefNeighbors(e,t=this.activeBranch){let n=new Set,r=this.getState(t);if(!r.forward.has(e))return n;let i=k0(e);if(!i)return n;let a=e.startsWith(M),o=r.skillRefs.get(e);if(o){for(let e of o)if(e!==i.name){if(a){let t=gr(`global`,e);r.forward.has(t)&&n.add(t)}else for(let t of r.forward.keys()){let r=k0(t);r?.kind===`skill`&&r.name===e&&!t.startsWith(`__skill__/`)&&n.add(t)}}}if(i.kind===`skill`)for(let[t,o]of r.skillRefs)t===e||!o.has(i.name)||t.startsWith(`__skill__/`)===a&&r.forward.has(t)&&n.add(t);return n}bundleNeighbors(e,t=this.activeBranch){let n=this.structuralBundleNeighbors(e,t);for(let r of this.skillRefNeighbors(e,t))n.add(r);return n}recordSkillRefs(e,t,n=this.activeBranch){this.recordSkillRefsInto(this.getState(n),e,t)}recordSkillRefsInto(e,t,n){if(!k0(t))return;let r=Nne(n);r.length===0?e.skillRefs.delete(t):e.skillRefs.set(t,new Set(r))}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return W(aX(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let n=this.getState(t),r=n.forward.get(e)??new Set,i=n.externalForward.get(e)??new Map;for(let t of r){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of i.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}n.forward.set(e,new Set),n.epoch++,n.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){ji(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,n=[],r=this.activeBranch){if(rX(e))return;if(ji(e)){this.registerNodeOnly(e,r);return}let i=this.getState(r),a=i.forward.get(e)??new Set,o=i.externalForward.get(e)??new Map;for(let t of a){let n=i.backward.get(t);n&&(n.delete(e),n.size===0&&i.backward.delete(t))}for(let t of o.keys()){let n=i.externalBackward.get(t);n&&(n.delete(e),n.size===0&&i.externalBackward.delete(t))}let s=new Set,c=new Map;i.forward.set(e,s),i.epoch++,i.externalForward.set(e,c);for(let n of t){if(!n.target)continue;s.add(n.target);let t=i.backward.get(n.target);t||(t=new Map,i.backward.set(n.target,t)),t.set(e,w$e(t.get(e),{anchor:n.anchor,snippet:n.snippet,sourceForm:n.sourceForm,line:n.line,column:n.column,rawWikiTarget:n.rawWikiTarget===!0}))}for(let t of n){if(!t.url)continue;c.set(t.url,{label:t.label,snippet:t.snippet});let n=i.externalBackward.get(t.url);n||(n=new Map,i.externalBackward.set(t.url,n)),(!n.has(e)||!n.get(e)?.snippet&&t.snippet)&&n.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,n=this.activeBranch){try{let{frontmatter:r,body:i}=Dr(t),a=M$e(r),o=z0(i,e,a).map(e=>({...e,sourceForm:`wiki`})),s=N$e(i,e,a,this.getFileOracle()).map(e=>({...e,sourceForm:`markdown`})),c=j$e(i,e,a).map(e=>({...e,sourceForm:`jsx`})),l=I$e(i),u=L$e(i,e),d=new Set(o.map(e=>e.target)),f=[...o,...s.filter(e=>!d.has(e.target))];for(let e of f)d.add(e.target);f.push(...c.filter(e=>!d.has(e.target)));let p=new Set(l.map(e=>e.url)),m=[...l,...u.filter(e=>!p.has(e.url))];this.recordSkillRefs(e,i,n),this.updateDocument(e,f,m,n)}catch(t){D0.warn({docName:e,err:t},`Failed to scan ${e} for link extraction`),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(rX(e))return;let n=this.getState(t),r=n.forward.get(e)??new Set,i=n.externalForward.get(e)??new Map;for(let t of r){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of i.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}n.forward.delete(e),n.epoch++,n.externalForward.delete(e),n.skillRefs.delete(e)}renameDocument(e,t,n,r=this.activeBranch){this.deleteDocument(e,r),this.updateDocumentFromMarkdown(t,n,r)}getBacklinks(e,t=this.activeBranch){let n=this.getState(t).backward.get(e),r=new Map;if(n)for(let[e,t]of n)r.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let n of this.bundleNeighbors(e,t))r.has(n)||r.set(n,{source:n,anchor:null,snippet:null});return[...r.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let n=this.getState(t).backward.get(e),r=this.bundleNeighbors(e,t);if(r.size===0)return n?.size??0;let i=new Set(n?.keys()??[]);for(let e of r)i.add(e);return i.size}getForwardLinks(e,t=this.activeBranch){let n=this.getState(t),r=new Set(n.forward.get(e)??new Set);for(let n of this.bundleNeighbors(e,t))r.add(n);return[...r].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let n=this.getState(t),r=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:n.backward.get(t)?.get(e)?.anchor??null,snippet:n.backward.get(t)?.get(e)?.snippet??null})),i=[...(n.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...r,...i]}getOrphans(e,t=`both`,n=this.activeBranch){let r=this.getState(n),i=new Set;for(let e of r.forward.keys()){let t=k0(e);t?.kind===`reference`&&i.add(t.skillDocName)}let a=e=>{let t=k0(e);return!t||!r.forward.has(e)?!1:t.kind===`skill`?i.has(e):r.forward.has(t.skillDocName)};return[...e].filter(e=>{let n=a(e),i=n||(r.backward.get(e)?.size??0)>0,o=n||(r.forward.get(e)?.size??0)>0;return t===`incoming`?!i:(t===`outgoing`||!i)&&!o}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,n=this.activeBranch,r){let i=this.getState(n),a=new Set(e),o=t?.length?new Set(t):null,s=U$e([...a,...i.forward.keys()]);for(let e of r??[])s.add(e);return[...i.backward.entries()].filter(([e,t])=>{if(a.has(e)||i.forward.has(e)||s.has(e.replace(/\/+$/,``)))return!1;if(!o)return t.size>0;for(let e of t.keys())if(o.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([,e])=>e.rawWikiTarget!==!0).filter(([,t])=>{if(t.sourceForm!==`jsx`||!pa(e))return!0;let n=this.getFileOracle();return n!==void 0&&!n.hasFile(e)}).filter(([,t])=>t.sourceForm!==`wiki`||ar(e,this.documentLookup(n))===void 0).filter(([e])=>!o||o.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet,sourceForm:t.sourceForm,line:t.line,column:t.column})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}documentLookup(e=this.activeBranch){let t=this.getState(e),n=this.documentLookups.get(t);if(n?.epoch===t.epoch)return n.lookup;let r=new Set(t.forward.keys()),i={pages:r,pagesBySlug:vr(r,ea),pagesByBasename:ka(r,ea)};return this.documentLookups.set(t,{epoch:t.epoch,lookup:i}),i}undecidedTargetResolves(e,t=this.activeBranch){return en(e,null,this.documentLookup(t))?.kind===`doc`}getLinkGraph(e=this.activeBranch){let t=this.getState(e),n=new Map,r=[];for(let[i,a]of t.forward){n.set(i,{kind:`doc`,id:i,docName:i,anchor:A0(t.backward.get(i))});for(let o of a)C$e(t,o)&&!this.undecidedTargetResolves(o,e)||(n.set(o,{kind:`doc`,id:o,docName:o,anchor:A0(t.backward.get(o))}),r.push({source:i,target:o}))}for(let[e,i]of t.externalForward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:A0(t.backward.get(e))});for(let[t,a]of i){let i=j0(t);n.set(i,{kind:`external`,id:i,url:t,label:a.label}),r.push({source:e,target:i})}}for(let i of t.forward.keys())if(k0(i)?.kind===`skill`)for(let a of this.bundleNeighbors(i,e))t.forward.get(i)?.has(a)||t.forward.get(a)?.has(i)||(n.set(i,{kind:`doc`,id:i,docName:i,anchor:A0(t.backward.get(i))}),n.set(a,{kind:`doc`,id:a,docName:a,anchor:A0(t.backward.get(a))}),r.push({source:i,target:a}));return{nodes:[...n.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:r}}getLinkGraphNeighborhood(e,t,n=this.activeBranch){let r=this.getState(n),i=new Map;for(let e of r.externalForward.values())for(let[t,n]of e)i.has(t)||i.set(t,n.label);let a=new Set([e]),o=[{nodeId:e,degree:0}],s=0;for(;s<o.length;){let e=o[s++];if(e.degree>=t)continue;let i=T$e(e.nodeId),c=new Set;if(i)for(let e of r.externalBackward.get(i)?.keys()??[])c.add(e);else{for(let t of r.forward.get(e.nodeId)??new Set)C$e(r,t)&&!this.undecidedTargetResolves(t,n)||c.add(t);for(let t of r.externalForward.get(e.nodeId)?.keys()??[])c.add(j0(t));for(let t of r.backward.get(e.nodeId)?.keys()??[])c.add(t);for(let t of this.bundleNeighbors(e.nodeId,n))c.add(t)}for(let t of c)a.has(t)||(a.add(t),o.push({nodeId:t,degree:e.degree+1}))}let c=[];for(let[e,t]of r.forward)if(a.has(e))for(let n of t)a.has(n)&&c.push({source:e,target:n});for(let[e,t]of r.externalForward)if(a.has(e))for(let n of t.keys()){let t=j0(n);a.has(t)&&c.push({source:e,target:t})}for(let e of a)if(k0(e)?.kind===`skill`)for(let t of this.bundleNeighbors(e,n))a.has(t)&&(r.forward.get(e)?.has(t)||r.forward.get(t)?.has(e)||c.push({source:e,target:t}));return{nodes:[...a].sort().map(e=>{let t=T$e(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:A0(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);Ss(V(t),{recursive:!0});let n=this.getState(e),r=this.mtimesByBranch.get(e),i={version:3,...z$e(n),...r?{mtimes:Object.fromEntries(r)}:{}};await Zs(t,JSON.stringify(i,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!G(t))return!1;try{let n=await Ks(t,`utf-8`),r=JSON.parse(n);return r.version===3&&(this.states.set(e,H$e(r)),r.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(r.mtimes))):this.mtimesByBranch.delete(e),!0)}catch(t){return D0.warn({branch:e,err:t},`Failed to load cache for ${e}`),!1}}clear(e=this.activeBranch){this.states.set(e,O0()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){return S0(`backlink`,`full`,()=>this.rebuildFromDiskUnspanned(e))}async rebuildFromDiskUnspanned(e){let t=O0(),n=new Map,r=[];await this.walkForPaths(this.contentDir,r);let i=new Set,a=r.filter(({docName:e})=>!i.has(e)&&(i.add(e),!0));for(let e=0;e<a.length;e+=50){let r=a.slice(e,e+50),i=await Promise.allSettled(r.map(async({docName:e,filePath:t})=>{let[n,r]=await Promise.all([Xs(t),Ks(t,`utf-8`)]);return{docName:e,mtimeMs:n.mtimeMs,markdown:r}}));for(let e of i){if(e.status===`rejected`){D0.warn({err:e.reason},`Failed to rebuild entry`);continue}let{docName:r,mtimeMs:i,markdown:a}=e.value;n.set(r,i);let{frontmatter:o,body:s}=Dr(a),c=M$e(o),l=z0(s,r,c).map(e=>({...e,sourceForm:`wiki`})),u=N$e(s,r,c,this.getFileOracle()).map(e=>({...e,sourceForm:`markdown`})),d=j$e(s,r,c).map(e=>({...e,sourceForm:`jsx`})),f=I$e(s),p=L$e(s,r),m=new Set(l.map(e=>e.target)),h=[...l,...u.filter(e=>!m.has(e.target))];for(let e of h)m.add(e.target);h.push(...d.filter(e=>!m.has(e.target)));let g=new Set(f.map(e=>e.url)),_=[...f,...p.filter(e=>!g.has(e.url))],v=new Set,y=new Map;this.recordSkillRefsInto(t,r,s),t.forward.set(r,v),t.epoch++,t.externalForward.set(r,y);for(let e of h){if(!e.target)continue;v.add(e.target);let n=t.backward.get(e.target);n||(n=new Map,t.backward.set(e.target,n)),n.set(r,w$e(n.get(r),{anchor:e.anchor,snippet:e.snippet,sourceForm:e.sourceForm,line:e.line,column:e.column,rawWikiTarget:e.rawWikiTarget===!0}))}for(let e of _){if(!e.url)continue;y.set(e.url,{label:e.label,snippet:e.snippet});let n=t.externalBackward.get(e.url);n||(n=new Map,t.externalBackward.set(e.url,n)),n.set(r,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,n)}async walkForPaths(e,t){let n;try{n=await qs(e,{withFileTypes:!0})}catch(t){D0.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=bX(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(n,t)}else if(r.isFile()&&zY(r.name)){let e=bX(U(this.contentDir,n));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:VY(e),filePath:n})}}}async reconcileWithDisk(e=this.activeBranch){return S0(`backlink`,`reconcile`,()=>this.reconcileWithDiskUnspanned(e),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted}))}async reconcileWithDiskUnspanned(e){if(!G(this.contentDir))return{added:0,updated:0,deleted:0,deletedDocNames:[],changedDocs:[]};let t=this.mtimesByBranch.get(e)??new Map,n=[];await this.walkForPaths(this.contentDir,n);let r=new Set,i=n.filter(({docName:e})=>!r.has(e)&&(r.add(e),!0)),a=new Set(i.map(e=>e.docName)),o=new Map,s=0,c=0,l=[],u=await Promise.allSettled(i.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await Xs(t)).mtimeMs})));for(let e of u){if(e.status===`rejected`)continue;let{docName:n,filePath:r,mtimeMs:i}=e.value,a=t.get(n);if(a!==void 0&&a===i){o.set(n,i);continue}l.push({docName:n,filePath:r,mtimeMs:i,isNew:a===void 0})}for(let t=0;t<l.length;t+=50){let n=l.slice(t,t+50),r=await Promise.allSettled(n.map(async({docName:e,filePath:t,mtimeMs:n,isNew:r})=>({docName:e,mtimeMs:n,isNew:r,markdown:await Ks(t,`utf-8`)})));for(let t of r){if(t.status===`rejected`){D0.warn({err:t.reason},`Failed to reconcile file`);continue}let{docName:n,mtimeMs:r,isNew:i,markdown:a}=t.value;this.updateDocumentFromMarkdown(n,a,e),o.set(n,r),i?s++:c++}}let d=0,f=[],p=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of p)ji(t)||a.has(t)||(this.deleteDocument(t,e),d++,f.push(t));return this.mtimesByBranch.set(e,o),{added:s,updated:c,deleted:d,deletedDocNames:f,changedDocs:l.map(({docName:e,filePath:t})=>({docName:e,filePath:t}))}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let n=new Set;for(let r of e){if(!G(r))continue;let e;try{e=await qs(r,{withFileTypes:!0})}catch(e){D0.warn({root:r,err:e},`Failed to read global skills root ${r}`);continue}for(let i of e){if(!i.isDirectory())continue;let e=i.name,a=H(r,e),o=gr(`global`,e);if(G(H(a,`SKILL.md`))&&ji(o)){this.registerNodeOnly(o,t),n.add(o);try{let e=await Ks(H(a,`SKILL.md`),`utf-8`);this.recordSkillRefs(o,Dr(e).body,t)}catch(e){D0.warn({dir:a,err:e},`global skill ref-scan failed; edges skipped`)}}let s=[];await this.walkGlobalSkillReferences(H(a,`references`),e,``,s);for(let{docName:e}of s)this.registerNodeOnly(e,t),n.add(e)}}let r=[];for(let e of this.getState(t).forward.keys())ji(e)&&!n.has(e)&&r.push(e);for(let e of r)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,n,r){let i;try{i=await qs(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&D0.warn({dir:e,err:t},`Failed to read skill references dir ${e}`);return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;if(a.isDirectory())await this.walkGlobalSkillReferences(H(e,a.name),t,i,r);else if(a.isFile()&&zY(a.name)){let e=VY(i);r.push({docName:`${M}global/${t}/references/${e}`})}}}};function G$e(e){let t=new Set(e),n=new Map;for(let e of t){let t=ea(e);t&&!n.has(t)&&n.set(t,e)}let r=new Map;for(let e of[...t].sort((e,t)=>e.localeCompare(t))){let t=e.slice(e.lastIndexOf(`/`)+1),n=ea(t);n&&!r.has(n)&&r.set(n,e)}return e=>{let i=ea(e),a=i?n.get(i):void 0;if(a)return a;let o=`${e}/index`;if(t.has(o))return o;let s=`${e}/${e.slice(e.lastIndexOf(`/`)+1)}`;return t.has(s)?s:!e.includes(`/`)&&i?r.get(i)??null:null}}function B0(e){return e.trim().startsWith(`/`)?`root-relative`:`source-relative`}const K$e={targetKind:`unknown`,resolvedTarget:null,status:`unresolvable`,reason:`unresolvable`,resolutionMethod:`none`,fallbackTarget:null};function q$e(e,t,n,r,i){if((i??r.hasDocument(e))||r.hasFolder?.(e))return{targetKind:`document`,resolvedTarget:e,status:`exact`,reason:null,resolutionMethod:B0(t),fallbackTarget:null};let a=r.resolveTolerantDocument?.(e,n)??null;return a?{targetKind:`document`,resolvedTarget:e,status:`fallback`,reason:`no-such-doc`,resolutionMethod:`tolerant`,fallbackTarget:a}:{targetKind:`document`,resolvedTarget:e,status:`missing`,reason:`no-such-doc`,resolutionMethod:B0(t),fallbackTarget:null}}function V0(e,t,n,r,i){let a=Ji(e,n,{literal:i});return a===null?{...K$e,targetKind:`file`}:r.hasFile(a)?{targetKind:`file`,resolvedTarget:a,status:`exact`,reason:null,resolutionMethod:B0(t),fallbackTarget:null}:{targetKind:`file`,resolvedTarget:a,status:`missing`,reason:`no-such-file`,resolutionMethod:B0(t),fallbackTarget:null}}function H0(e){switch(e){case`wiki-link`:case`wiki-embed`:return!0;case`markdown-inline`:case`markdown-reference`:case`html-img`:return!1;default:return e}}function J$e(e,t,n,r,i){let a=H0(n)?pn(e,null):v(e,r);if(!a)return K$e;switch(a.kind){case`doc`:{if(t===`image`&&!H0(n))return V0(e,e,r,i,!1);let o=i.hasDocument(a.docName);if(!o&&!H0(n)){let t=V0(e,e,r,i,!1);if(t.status===`exact`)return t}return q$e(a.docName,e,r,i,o)}case`asset`:return V0(a.url,e,r,i,a.literal);case`external`:case`anchor`:return null;default:return Ete(a)}}function U0(e,t,n){let r=new Map,i=[];for(let a of e){let e=`${a.role}\0${a.sourceForm}\0${a.href}`,o=r.get(e);o===void 0&&(o=J$e(a.href,a.role,a.sourceForm,t,n),r.set(e,o)),o!==null&&i.push({occurrence:a,...o})}return i}function Y$e(e,t,n){return U0(E0(e),t,n)}function W0(e){switch(e){case`markdown-inline`:case`markdown-reference`:case`html-img`:return e;case`wiki-link`:case`wiki-embed`:return null;default:return e}}function X$e(e){return W0(e.sourceForm)!==null}function Z$e(e,t){let{occurrence:n}=e,r=W0(n.sourceForm);return r===null?null:{href:n.href,targetKind:e.targetKind,role:n.role,sourceForm:r,resolvedTarget:e.resolvedTarget,reason:t,resolutionMethod:e.resolutionMethod,...e.fallbackTarget===null?{}:{fallbackTarget:e.fallbackTarget},...n.reference?{definition:{line:n.reference.definition.line,label:n.reference.definition.label}}:{}}}function Q$e(e){let t=[];for(let n of e){let{occurrence:e}=n;if(!X$e(e)||n.targetKind!==`file`&&e.role!==`image`)continue;let r=W0(e.sourceForm);r!==null&&t.push({role:e.role,sourceForm:r,targetKind:n.targetKind,href:e.href,resolvedTarget:n.resolvedTarget,status:n.status,reason:n.reason,resolutionMethod:n.resolutionMethod,fallbackTarget:n.fallbackTarget,range:{start:e.range.start,end:e.range.end},line:e.line,column:e.column,definition:e.reference?{line:e.reference.definition.line,label:e.reference.definition.label}:null})}return t}function G0(e,t,n,r,i){let a=n instanceof Set?n:new Set(n),o=new Set;for(let e of a){let t=e.indexOf(`/`);for(;t!==-1;)o.add(e.slice(0,t)),t=e.indexOf(`/`,t+1)}let s=e=>o.has(e)||i?.(e)===!0,c=Y$e(e,t,{hasDocument:e=>a.has(e),hasFile:e=>r?r(e):!1,resolveTolerantDocument:G$e(a),hasFolder:s}),l=new Set(c.filter(({occurrence:e})=>e.sourceForm===`markdown-inline`&&e.role===`link`).map(({occurrence:e})=>e.href)),u=R$e(e,t,a,r,s).filter(e=>e.sourceForm===`jsx`||e.href.startsWith(`[[`)||l.has(e.href)),d=new Set(u.map(e=>e.href)),f=new Set;for(let e of c){if(e.reason===null||!r&&e.targetKind===`file`)continue;let{href:t,role:n,sourceForm:i,range:a,reference:o}=e.occurrence;if(n===`link`&&i===`markdown-inline`&&d.has(t))continue;let s=Z$e(e,e.reason);if(s===null)continue;let c=o?.definition.repairRange??a,l=`${c.start}:${c.end}`;f.has(l)||(f.add(l),u.push({href:t,resolvedTo:e.resolvedTarget,reason:e.reason,localTarget:s}))}return u}const $$e={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}};let e1e=null;function K0(){return e1e||=Uq().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),e1e}let t1e=null;function n1e(){return t1e||=Uq().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:"Count of agent-patch calls refused for touching the frontmatter region. Bounded labels: result ∈ {rejected, pre_deprecation_passthrough}, reason ∈ {intersect, promoted}. `intersect` is a find that MATCHED inside the existing frontmatter; `promoted` is a byte-0 replace that would CREATE frontmatter on a document that had none. They refuse for opposite reasons, so a spike in one says nothing about the other — the append/prepend surface separates the same pair via the `byte-0-promotion` class on `frontmatter-malformed-write-refused`."}),t1e}function r1e(e){let{conflicts:t,getLinkAdvisoryPolicy:n,respondStaleExternalWrite:r,requireNonEmptyDocName:i,resolveAlias:a,extractAgentIdentity:o,docNameExistsWithAnySupportedExtension:s,contentDir:c,summaryResponseFields:l,sessionManager:u,durabilityState:d,hocuspocus:f,options:p,getBridgeLossReporter:m,agentPresenceBroadcaster:h,recordContentDivergenceGate:g,buildAgentActor:_,countNormalizedSummary:v,flushDiskAndDetectOutcome:y,respondPersistenceFailure:b,respondDiskDivergence:x,flushDocToDisk:S,agentFocusBroadcaster:C,onAgentWrite:w,computeOrphanHints:T,registerWrittenDocInFileIndex:E,collectAdmittedDocNames:D,createLinkedFileExists:O,createLinkedFolderExists:A,buildReconcileWarning:ee,computeLintViolations:j,log:M,flushDocToGit:P,isSafeDocName:te,shadowRef:ne,getPrincipal:re,contentRoot:ie,safeDocPath:ae,getCurrentBranch:oe,docTreePathCandidates:se,stripDefaultPathTruncation:ce,renameAttributionCounter:le}=e,ue=qQe({getCurrentBranch:oe,contentRoot:ie});function de(e){try{return f.documents.get(e)?.connections.size??0}catch{return 0}}function fe(){try{return f.documents.get(`__system__`)?.connections.size??0}catch{return 0}}return L1({"/api/agent-write-md":Z(Mte,async(e,k,N)=>{try{let e=n(),M=N.position??`append`,P=i(N.docName,k,`agent-write-md`);if(P===null)return;let te=qY(a(P)),{agentId:ne,agentName:re,colorSeed:ie,clientName:ae,clientVersion:oe,label:se}=o(N);if(XY(te)||ZY(te)){X(k,400,`urn:ok:error:reserved-doc-name`,`'${te}' is a reserved document name.`,{handler:`agent-write-md`});return}N.extension!==void 0&&!s(c,te)&&WY(te,N.extension);let ce=S1(N.summary),{response:le,stored:ue}=l(ce),pe=await u.getSession(te,ne,{displayName:re,colorSeed:ie,clientName:ae}),me=i0(d,f,te,c,p.resolveEmbed,m?.(),t),he=p.resolveEmbed?{resolveEmbed:p.resolveEmbed,sourcePath:te}:void 0,ge=await o$(pe.dc.document,N.markdown,M,he),_e=new Date().toISOString(),ve,ye;try{let e=_n(ae),t=fa[e]??ze(ie??ne);h?.setPresence(ne,{displayName:re,icon:e,color:t,currentDoc:te,mode:`writing`,ts:Date.now()}),ye=G1(pe.dc.document.getText(`source`),ne,pe.origin,ie,ae),c$(pe.dc.document,N.markdown,M),pe.dc.document.transact(()=>{let e=u$(pe.dc.document);ve=l$(pe.dc.document,N.markdown,M,he,ge,s$(pe));let t=xn(e,u$(pe.dc.document))??void 0;pe.dc.document.getMap(`agent-flash`).set(ne,{agentId:ne,timestamp:Date.now(),type:`insert`,description:`Added (${re}): ${N.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},pe.origin),ve!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":te,position:M,intendedBytes:ve.intendedBytes,actualBytes:ve.actualBytes,byteDelta:ve.byteDelta,"agent.id":ne,"agent.client_name":ae})),g(`agent-write-md`,ve),q1(te,ne,re,ie,void 0,_({clientName:ae,clientVersion:oe,label:se}),ue),eY(),v(ce)}finally{ye?.(),h?.touchMode(ne,`idle`)}let be=await y(te);if(be?.kind===`failure`){b(k,be.failure,`agent-write-md`);return}if(be?.kind===`divergence`){x(k,`agent-write-md`);return}if(be?.kind===`stale-external-write`){r(k,`agent-write-md`,te);return}S(te,`agent-write-md`),C?.setFocus(ne,{agentName:re,currentDoc:te,writeKind:`write`,ts:Date.now()}),w?.();let xe=await T(te),Se=pe.dc.document.getText(`source`).toString();E(te,Se);let Ce=await gQe(Se,te),we=await D();we.add(te);let Te=o0(G0(Se,te,we,O(),A()),te,e.suppressLogLinkAdvisories),Ee=de(te),De=fe();De===0&&K0().add(1,{"shadow.writer":`agent`,"agent.type":Oq(ae)});let Oe=ee(me),ke=ve===void 0?void 0:cQ(ve),Ae=[...ke?[ke]:[],...Oe?[Oe]:[],...Ce??[],...await j(pe.dc.document.getText(`source`).toString(),te,e)];Q(k,200,Tte,{timestamp:_e,subscriberCount:Ee,systemSubscriberCount:De,...xe?{hints:xe}:{},...le?{summary:le}:{},...Ae.length>0?{warnings:Ae}:{},...Te},{handler:`agent-write-md`})}catch(n){if(n instanceof mX){hX(k,n,`agent-write-md`,t.findByDocName(VY(n.file)));return}if(n instanceof lQ){uQ(k,n,`agent-write-md`);return}if(n instanceof f$){X(k,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:n,extraHeaders:{"Retry-After":`10`}});return}M.error({err:n,requestId:lX(e)},`[agent-write-md] handler failed`),X(k,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:n})}},{handler:`agent-write-md`,method:`POST`}),"/api/frontmatter-patch":Z(nee,async(e,s,g)=>{try{let e=n(),T=i(g.docName,s,`frontmatter-patch`);if(T===null)return;let A=a(T),{agentId:j,agentName:M,colorSeed:N,clientName:P,clientVersion:te,label:ne}=o(g);if(XY(A)||ZY(A)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${A}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let re=g.patch??{},ie=Object.keys(re),ae=S1(g.summary),{response:oe,stored:se}=l(ae),ce=await u.getSession(A,j,{displayName:M,colorSeed:N,clientName:P}),le=i0(d,f,A,c,p.resolveEmbed,m?.(),t),ue=await Gqe(ce.dc.document,re),me=new Date().toISOString(),he,ge=!1,_e=!1,ve=[];try{let e=_n(P),t=fa[e]??ze(N??j);h?.setPresence(j,{displayName:M,icon:e,color:t,currentDoc:A,mode:`writing`,ts:Date.now()}),Gq(`ok.frontmatter_patch`,{attributes:{"doc.name":A,"frontmatter_patch.keys":ie.length}},()=>{ce.dc.document.transact(()=>{let e=ce.dc.document.getText(`source`).toString(),{fenced:t,body:n}=na(e),r=Li(t,re);if(!r.ok){he=r.error;return}for(let e of Object.keys(re))ve.push(e);if(r.nextFenced!==t){let e=t===``&&n!==``&&!n.startsWith(`
1008
1008
  `),i=k(r.nextFenced,(e?`
1009
1009
  `:``)+n).md;Zq(ce.dc.document,i,`agent`,void 0,ue),dQ(`mcp-write`),_e=!0}ge=!0},ce.origin)})}finally{h?.touchMode(j,`idle`)}if(he){let e;switch(he.kind){case`invalid_value`:e={[he.key]:he.reason};break;case`reserved_key`:e={[he.key]:`'${he.key}' is reserved`};break;case`unknown_key`:e={[he.key]:`'${he.key}' is not a recognized key`};break;case`duplicate_target`:e={[he.key]:`'${he.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${he.expected.join(`, `)}; got: ${he.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${he.bytes} > ${he.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${he.reason}`};break;case`invalid_path`:e={[he.path.map(String).join(`.`)||`__path__`]:he.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(he)})`}}X(s,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(ge&&ve.length>0){if(q1(A,j,M,N,void 0,_({clientName:P,clientVersion:te,label:ne}),se),eY(),v(ae),_e){let e=await y(A);if(e?.kind===`failure`){b(s,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){x(s,`frontmatter-patch`);return}if(e?.kind===`stale-external-write`){r(s,`frontmatter-patch`,A);return}}S(A,`frontmatter-patch`)}C?.setFocus(j,{agentName:M,currentDoc:A,writeKind:`write`,ts:Date.now()}),w?.();let ye=de(A),be=fe();be===0&&K0().add(1,{"shadow.writer":`agent`,"agent.type":Oq(P)});let xe=ee(le);E(A,ce.dc.document.getText(`source`).toString());let Se=await D();Se.add(A);let Ce=o0(G0(ce.dc.document.getText(`source`).toString(),A,Se,O()),A,e.suppressLogLinkAdvisories);Q(s,200,pe,{timestamp:me,subscriberCount:ye,systemSubscriberCount:be,appliedKeys:ve,...oe?{summary:oe}:{},...xe?{warnings:[xe]}:{},...Ce},{handler:`frontmatter-patch`})}catch(t){if(t instanceof f$){X(s,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:t,extraHeaders:{"Retry-After":`10`}});return}M.error({err:t,requestId:lX(e)},`[frontmatter-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:t})}},{handler:`frontmatter-patch`,method:`POST`}),"/api/agent-patch":Z(une,async(e,s,T)=>{try{let e=n(),{find:k,replace:A,offset:M}=T,N=i(T.docName,s,`agent-patch`);if(N===null)return;let P=a(N),{agentId:te,agentName:ne,colorSeed:re,clientName:ie,clientVersion:ae,label:oe}=o(T);if(XY(P)||ZY(P)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${P}' is a reserved document name.`,{handler:`agent-patch`});return}let se=S1(T.summary),ce=await u.getSession(P,te,{displayName:ne,colorSeed:re,clientName:ie}),le=i0(d,f,P,c,p.resolveEmbed,m?.(),t),ue=p.resolveEmbed?{resolveEmbed:p.resolveEmbed,sourcePath:P}:void 0,pe;{let e=ce.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Dr(e),r=ii(t,n),i=M==null?r.indexOf(k):r.slice(M,M+k.length)===k?M:-1;if(i!==-1&&i>=t.length){let e=r.slice(0,i)+A+r.slice(i+k.length);pe=await o$(ce.dc.document,Dr(e).body,`patch`,ue)}}let me=new Date().toISOString(),he=!1,ge=!1,_e=!1,ve=!1,ye,be;try{let e=_n(ie),t=fa[e]??ze(re??te);if(h?.setPresence(te,{displayName:ne,icon:e,color:t,currentDoc:P,mode:`writing`,ts:Date.now()}),be=G1(ce.dc.document.getText(`source`),te,ce.origin,re,ie),ce.dc.document.transact(()=>{let e=ce.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Dr(e),r=ii(t,n),i=M==null?r.indexOf(k):r.slice(M,M+k.length)===k?M:-1;if(i===-1){M==null?he=!0:ge=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":P,findLength:k.length,replaceLength:A.length,hadOffset:M!=null})),CVe();return}if(i<t.length){_e=!0;return}let a=r.slice(0,i)+A+r.slice(i+k.length);if(t===``&&Dr(a).frontmatter!==``){ve=!0;return}let{body:o}=Dr(a),s=u$(ce.dc.document);ye=l$(ce.dc.document,o,`patch`,ue,pe,s$(ce));let c=xn(s,u$(ce.dc.document))??void 0;ce.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Patched (${ne}): ${k.slice(0,50)}`,...c===void 0?{}:{changedBlocks:c}})},ce.origin),ye!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":P,position:`patch`,intendedBytes:ye.intendedBytes,actualBytes:ye.actualBytes,byteDelta:ye.byteDelta,"agent.id":te,"agent.client_name":ie})),!he&&!ge&&!_e&&!ve){let{stored:e}=l(se);q1(P,te,ne,re,void 0,_({clientName:ie,clientVersion:ae,label:oe}),e),eY(),v(se),g(`agent-patch`,ye)}}finally{be?.(),h?.touchMode(te,`idle`)}if(ge){X(s,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(he){X(s,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(_e){n1e().add(1,{result:`rejected`,reason:`intersect`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(ve){n1e().add(1,{result:`rejected`,reason:`promoted`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,"This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",{handler:`agent-patch`});return}let xe=await y(P);if(xe?.kind===`failure`){b(s,xe.failure,`agent-patch`);return}if(xe?.kind===`divergence`){x(s,`agent-patch`);return}if(xe?.kind===`stale-external-write`){r(s,`agent-patch`,P);return}S(P,`agent-patch`),C?.setFocus(te,{agentName:ne,currentDoc:P,writeKind:`edit`,ts:Date.now()}),w?.();let Se=de(P),Ce=fe();Ce===0&&K0().add(1,{"shadow.writer":`agent`,"agent.type":Oq(ie)});let{response:we}=l(se),Te=ce.dc.document.getText(`source`).toString();E(P,Te);let Ee=await gQe(Te,P),De=await D();De.add(P);let Oe=o0(G0(Te,P,De,O()),P,e.suppressLogLinkAdvisories),ke=ee(le),Ae=ye===void 0?void 0:cQ(ye),je=[...Ae?[Ae]:[],...ke?[ke]:[],...Ee??[],...await j(ce.dc.document.getText(`source`).toString(),P,e)];Q(s,200,Ore,{timestamp:me,subscriberCount:Se,systemSubscriberCount:Ce,...we?{summary:we}:{},...je.length>0?{warnings:je}:{},...Oe},{handler:`agent-patch`})}catch(n){if(n instanceof mX){hX(s,n,`agent-patch`,t.findByDocName(VY(n.file)));return}if(n instanceof lQ){uQ(s,n,`agent-patch`);return}if(n instanceof f$){X(s,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:n,extraHeaders:{"Retry-After":`10`}});return}M.error({err:n,requestId:lX(e)},`[agent-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:n})}},{handler:`agent-patch`,method:`POST`}),"/api/agent-undo":Z(cte,async(e,n,s)=>{try{let e=i(s.docName,n,`agent-undo`);if(e===null)return;let t=a(e),{agentId:c,agentName:l,colorSeed:d,clientName:f,clientVersion:m,label:g}=o(s);if(XY(t)||ZY(t)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:v}=s,S,w;if(s.scope===`count`?(S=`count`,w=s.count):S=s.scope===`session`||s.scope===`file`?`session`:`last`,!u.hasSession(t,v)){X(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let T=await u.getSession(t,v),E=!1;try{let e=_n(f),n=fa[e]??ze(d??c);h?.setPresence(c,{displayName:l,icon:e,color:n,currentDoc:t,mode:`writing`,ts:Date.now()}),E=qqe(T,S,p.resolveEmbed?{resolveEmbed:p.resolveEmbed,sourcePath:t}:void 0,w),E&&q1(t,v,l,d,void 0,_({clientName:f,clientVersion:m,label:g}))}finally{h?.touchMode(c,`idle`)}if(E){let e=await y(t);if(e?.kind===`failure`){b(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){x(n,`agent-undo`);return}if(e?.kind===`stale-external-write`){r(n,`agent-undo`,t);return}P(t,`agent-undo`)}C?.setFocus(v,{agentName:v,currentDoc:t,writeKind:`undo`,ts:Date.now()}),Q(n,200,_te,{docName:t,scope:S,undone:E},{handler:`agent-undo`})}catch(r){if(r instanceof mX){hX(n,r,`agent-undo`,t.findByDocName(VY(r.file)));return}M.error({err:r,requestId:lX(e)},`[agent-undo] handler failed`),X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:r})}},{handler:`agent-undo`,method:`POST`}),"/api/agent-activity":Z(Ii,async(e,t)=>{try{let n=Tq(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}let r=cqe(u,n);Q(t,200,Bee,r,{handler:`agent-activity`})}catch(n){M.error({err:n,requestId:lX(e)},`[agent-activity] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),"/api/agent-burst-diff":Z(Ii,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Tq(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(r===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){X(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!te(i)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=a(i);if(XY(s)||ZY(s)){X(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!o||Number.isNaN(Number(o))){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=u.getLiveSession(s,r);if(!l){X(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let d=l.um;if(c>d.undoStack.length){X(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${d.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let f=l.dc.document.getText(`source`),{diff:p,before:m,after:h,properties:g}=aqe(d.undoStack,c,f,s);Q(t,200,Pne,{diff:p,before:m,after:h,properties:g,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){M.error({err:n,requestId:lX(e)},`[agent-burst-diff] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),"/api/save-version":Z(Tre,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=o(n),s=ne?.current;if(!s){X(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let c=/^[a-zA-Z0-9_-]+$/,l=[];if(Array.isArray(n.writers))try{l=n.writers.map(e=>{let t=e.id??`unknown`;if(!c.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){X(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=e===void 0?void 0:{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`},d=S1(typeof n.summary==`string`?n.summary:void 0),f=await ue.saveCheckpoint(s,{explicitWriters:l,agentWriter:u,summary:d.kind===`value`?d.value:void 0});Q(t,200,jne,{checkpointRef:f.checkpointRef},{handler:`save-version`})}catch(n){M.error({err:n,requestId:lX(e)},`[save-version] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),"/api/rollback":Z(hie,async(e,n,i)=>{let a=C1(i,re);if(a.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=t.findByDocName(i.docName);if(o!==void 0){hX(n,new mX({file:o.file}),`rollback`,o);return}let s=ne?.current;if(!s){X(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:u}=i,d=ie??`.`,m=ae(c,d);if(`error`in m){X(n,400,`urn:ok:error:invalid-request`,m.error,{handler:`rollback`});return}let h=xY(s),_=Date.now();try{let e=m0(s.gitDir),t=g0(),i=await GQe(s,c,u,oe?.()??`main`,e,e=>se(e,d),t);if(i===null){X(n,404,`urn:ok:error:doc-not-found`,`Commit ${u.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let o=await h.raw(`show`,`${u}:${i}`),m=new Date().toISOString();await NY(s,d,{action:`rollback`,context:{docName:c,targetSha:u}});let S=f.documents.get(c);if(!S){X(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let w=p.resolveEmbed?{resolveEmbed:p.resolveEmbed,sourcePath:c}:void 0,T=await wQ(o,w),E;S.transact(()=>{Qq(S,o,w,T),E=sKe(S.getText(`source`).toString(),o,`rollback`)},$$e),E!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:E.intendedBytes,actualBytes:E.actualBytes,byteDelta:E.byteDelta,"actor.kind":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),g(`rollback`,E);let D;switch(a.kind){case`agent`:{let e=u.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:S1(`Restored to ${e}`),r=l(n);D=t||!r.response?r.response:ce(r.response),q1(c,a.writerId,a.displayName,a.colorSeed,rpe(c,u),a.actor,r.stored),eY(),v(n,!t);break}case`principal`:{let e=l(a.summary);D=e.response,q1(c,a.writerId,a.displayName,a.colorSeed,rpe(c,u),a.actor,e.stored),v(a.summary,!1);break}case`anonymous`:M.debug({docName:c,commitSha:u.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(a.kind)}`)}le().add(1,{kind:`rollback`,attribution_kind:a.kind});let O=await y(c);if(O?.kind===`failure`){b(n,O.failure,`rollback`);return}if(O?.kind===`divergence`){x(n,`rollback`);return}if(O?.kind===`stale-external-write`){r(n,`rollback`,c);return}P(c,`rollback`);let k=Date.now()-_;q(`rollback`).info({docName:c,from:u.slice(0,8),durationMs:k},`rollback`),a.kind===`agent`&&C?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let A=E===void 0?void 0:cQ(E);Q(n,200,N,{restoredFrom:u,timestamp:m,...D?{summary:D}:{},...A?{warnings:[A]}:{}},{handler:`rollback`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`})},{mutating:[`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`]})}const q0={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},i1e={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function a1e(e){let{conflicts:t,durabilityState:n,resolveAlias:r,contentDir:i,log:a,sessionManager:o,hocuspocus:s,forceUnloadDocument:c,derivedDocumentIndex:l,contentFilter:u,bumpSkillsCatalogGen:d,signalChannel:f,flushGitCommit:p,rescanFiles:m}=e;return L1({"/api/test-reset":Z(Ii,async(e,p)=>{try{let m=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),h=qY(r(m.searchParams.get(`docName`)??`test-doc`)),g;try{g=cZ(h,i)}catch(e){a.error({err:e,docName:h},`[test-reset] safeContentPath rejected docName`),X(p,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await o.closeAll(h),s.closeConnections(h);let _=`onStoreDocument-${h}`;s.debouncer.isDebounced(_)&&await s.debouncer.executeNow(_);let v=s.documents.get(h);if(v&&await(c??s.unloadDocument.bind(s))(v),n.deleteReconciledBase(h),t.dissolveReconcile(h),Fs(g,``,`utf-8`),await l?.testOnly?.resetDocumentForTest(h),m.searchParams.get(`reset-okignore`)!==`false`)try{let e=W(i,`.okignore`),t=s.documents.get(Pn);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},q0)}G(e)&&Fs(e,``,`utf-8`),u&&(d(),await u.rebuildIgnorePatterns())}catch(e){a.warn({err:e},`[test-reset] okignore reset partial failure`)}f?.(`files`),Q(p,200,kee,{},{handler:`test-reset`})}catch(e){X(p,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),"/api/test-flush-git":Z(Ii,async(e,t)=>{try{await p?.(),Q(t,200,Ot,{},{handler:`test-flush-git`})}catch(n){a.error({err:n,requestId:lX(e)},`[test-flush-git] flush failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-backlinks":Z(Ii,async(e,t)=>{try{if(!l?.testOnly){X(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await l.testOnly.rescanBacklinksForTest(),Q(t,200,Cee,{},{handler:`test-rescan-backlinks`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-files":Z(Ii,async(e,t)=>{try{if(!m){X(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await m(),f?.(`files`),Q(t,200,hee,{},{handler:`test-rescan-files`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0})},{mutating:[`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`]})}const o1e=Qte,s1e={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`},c1e={codex:()=>H(process.env.CODEX_HOME??H(Rs(),`.codex`),`auth.json`)};function l1e(e){let t=c1e[e];if(t===void 0)return`unknown`;let n;try{return n=t(),G(n)?`present`:`unknown`}catch(t){return q(`acp-harness`).warn({cli:e,credentialPath:n,err:t},`harness credential probe failed; treating as unknown`),`unknown`}}async function u1e(e,t,n=N$){let r={cmd:s1e[e],args:[],env:k$(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof O$)||i.code!==`command-not-found`)return q(`acp-harness`).warn({cli:e,err:i},`harness preflight failed before absence could be verified; availability unknown`),`unknown`;let a=null,o;try{a=await t()}catch(e){o=e}if(a===null)return q(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(dYe(r,a)),`present`}catch(t){return t instanceof O$&&t.code===`command-not-found`?`not-found`:(q(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function d1e(e={}){let t=e.resolveLoginShellPath??$Je(q(`acp-harness`)),n=e.preflight??N$,r=e.probe??(e=>u1e(e,t,n)),i=e.credentials??l1e,a=e.now??Date.now,o=e.ttlMs??6e4,s=[...new Set(Object.values(o1e))].filter(e=>e!==void 0),c=null;return()=>{let e=a();if(c!==null&&c.expiresAt>e)return c.value;let t=Promise.all(s.map(async e=>{let t=`unknown`;try{t=i(e)}catch(t){q(`acp-harness`).warn({cli:e,err:t},`harness credential probe threw; treating as unknown`)}try{return[e,{availability:await r(e),credentials:t}]}catch(n){return q(`acp-harness`).warn({cli:e,err:n},`harness availability probe rejected; availability unknown`),[e,{availability:`unknown`,credentials:t}]}})).then(e=>Object.fromEntries(e));return c={expiresAt:e+o,value:t},t}}const f1e=102400,p1e=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function J0(e,t={}){let n=t.platform??process.platform,r=t.checkDesktop??!1,i=t.home??Rs(),a=[],o=process.env.NODE_ENV===`test`;r&&n===`darwin`&&(o||a.push(H(`/Applications`,p1e,e)),(!o||t.home!==void 0)&&a.push(H(i,`Applications`,p1e,e))),a.push(fs(new URL(`../dist/assets/skills/${e}`,import.meta.url))),a.push(fs(new URL(`../assets/skills/${e}`,import.meta.url))),a.push(fs(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of a)if(G(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${a.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*m1e(e,t=e){let n=await qs(e,{withFileTypes:!0});for(let r of n){let n=H(e,r.name);r.isDirectory()?yield*m1e(n,t):r.isFile()&&(yield U(t,n))}}function h1e(e,t=rs){return t(e)||`open-knowledge`}function g1e(e,t=us){return t===`/`?e:e.split(t).join(`/`)}async function _1e(e,t,n=h1e(e)){let r=new dke.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of m1e(e))i.push(t);i.sort();for(let t of i){let i=H(e,t),a=`${n}/${g1e(t)}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=bs(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function v1e(e){return new Promise((t,n)=>{let r=ec(`sha256`),i=ys(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}async function y1e(e,t={}){let n=t.bundle??`project`,r=Ns(e).size;if(r>f1e)throw Error(`Built ${e} is ${r} bytes, exceeds ${f1e}-byte ceiling`);let i=await v1e(e),a=t.sourceDir??J0(n,{checkDesktop:!1}),o=await Ks(H(a,`SKILL.md`),`utf-8`),s=l1[n];if(!RegExp(`^name:\\s+${s}$`,`m`).test(o.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${s}'. Check packages/server/assets/skills/${n}/SKILL.md frontmatter.`);return{size:r,sha256:i}}async function b1e(e={}){let t=e.bundle??`project`,n=e.sourceDir??J0(t,{checkDesktop:e.checkDesktop??!1}),r=e.outputPath??H(process.cwd(),`openknowledge.skill`);await _1e(n,r,l1[t]);let{size:i,sha256:a}=await y1e(r,{bundle:t,sourceDir:n});return{outputPath:r,size:i,sha256:a}}var x1e=class{threads=new Map;docToThreads=new Map;async build(e){this.threads.clear(),this.docToThreads.clear();for(let t of await e.scanCoverSheets())this.upsert(t)}upsert(e){let t=this.threads.get(e.threadId);t!==void 0&&t.docName!==e.docName&&this.detach(t.docName,e.threadId),this.threads.set(e.threadId,e);let n=this.docToThreads.get(e.docName);n||(n=new Set,this.docToThreads.set(e.docName,n)),n.add(e.threadId)}remove(e){let t=this.threads.get(e);t!==void 0&&(this.threads.delete(e),this.detach(t.docName,e))}renameDoc(e,t){let n=this.docToThreads.get(e);if(!n)return;this.docToThreads.delete(e);let r=this.docToThreads.get(t)??new Set;for(let e of n){r.add(e);let n=this.threads.get(e);n&&this.threads.set(e,{...n,docName:t})}this.docToThreads.set(t,r)}listForDoc(e){let t=[];for(let n of this.docToThreads.get(e)??[]){let e=this.threads.get(n);e&&t.push(e)}return t}listAll(){return[...this.threads.values()]}threadsForDoc(e){return[...this.docToThreads.get(e)??[]]}countsForDocs(e){let t=new Map;for(let n of e)t.set(n,this.countForDoc(n));return t}countsUnderPrefix(e){let t=e===``?``:e.endsWith(`/`)?e:`${e}/`,n=new Map;for(let e of this.docToThreads.keys()){if(!e.startsWith(t))continue;let r=this.countForDoc(e);r>0&&n.set(e,r)}return n}countForDoc(e){let t=0;for(let n of this.docToThreads.get(e)??[])this.threads.get(n)?.state!==`resolved`&&t++;return t}get size(){return this.threads.size}detach(e,t){let n=this.docToThreads.get(e);n&&(n.delete(t),n.size===0&&this.docToThreads.delete(e))}};function Y0(e,t,n,r=32){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>e.length||t>=n)throw Error(`invalid selection range [${t}, ${n}) for body length ${e.length}`);let i=e.slice(t,n),a=e.slice(Math.max(0,t-r),t),o=e.slice(n,Math.min(e.length,n+r));if(w1e(e,i)>1){let s=r;for(;!T1e(e,a,i,o)&&s<e.length;)s=Math.min(s*2,e.length),a=e.slice(Math.max(0,t-s),t),o=e.slice(n,Math.min(e.length,n+s))}return{exact:i,prefix:a,suffix:o,start:t,end:n}}function S1e(e,t){return Q0(e,t).map(e=>({start:e,end:e+t.length}))}function C1e(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=kr(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function X0(e,t){let{exact:n,prefix:r,suffix:i,start:a}=t,o=a+n.length;if(o<=e.length&&e.slice(a,o)===n)return{status:`anchored`,start:a,end:o};if(r!==``&&i!==``&&!e.includes(r+n+i)&&e.includes(r+i))return{status:`orphaned`};let s=Q0(e,n);if(s.length===0)return Z0(e,t);let c=at(t,{syntaxInContext:!0}),l=t=>c===0||kr(e,t,{prefix:r,suffix:i},{syntaxIn:`haystack`,syntaxInContext:!0})>=c;if(s.length===1){let r={start:s[0],end:s[0]+n.length};return l(r)?{status:`anchored`,start:r.start,end:r.end}:Z0(e,t)}let u=C1e(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return Z0(e,t);if(u.length===1)return{status:`anchored`,start:u[0].start,end:u[0].end};let d=[],f=1/0;for(let e of u){let t=Math.abs(e.start-a);t<f?(f=t,d=[e]):t===f&&d.push(e)}return d.length===1?{status:`anchored`,start:d[0].start,end:d[0].end}:{status:`orphaned`}}function Z0(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:Q0(e,n).map(e=>e+n.length),o=r===``?[e.length]:Q0(e,r);if(a.length!==1||o.length!==1)return{status:`orphaned`};let s=a[0],c=o[0];if(c<s||c===s)return{status:`orphaned`};let l=_ie(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function w1e(e,t){if(t===``)return 0;let n=0,r=e.indexOf(t);for(;r!==-1;)n+=1,r=e.indexOf(t,r+1);return n}function Q0(e,t){let n=[];if(t===``)return n;let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1);return n}function T1e(e,t,n,r){return w1e(e,t+n+r)===1}function $0(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r)||e>=r.length)return;r=r[e];continue}if(typeof r!=`object`||Array.isArray(r))return;let t=r;if(!Object.hasOwn(t,e))return;r=t[e]}return r}function E1e(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function D1e(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var e2=class extends Error{},t2=class extends Error{},n2=class extends Error{},r2=class extends Error{},O1e=class{store;index;getDocBody;getDocFrontmatter;now;newId;indexReady=null;constructor(e){this.store=e.store,this.index=e.index,this.getDocBody=e.getDocBody,this.getDocFrontmatter=e.getDocFrontmatter,this.now=e.now??Date.now,this.newId=e.newId??tc}buildIndex(){return this.indexReady??=this.index.build(this.store),this.indexReady}async createThread(e){await this.buildIndex();let t=e.propertyKey,n,r;if(t===void 0){let t=await this.requireDocBody(e.docName),{start:i,end:a}=this.resolveRange(t,e);n={kind:`body`},r=Y0(t,i,a)}else{let i=e.propertyPath??[];n={kind:`property`,key:t,path:i};let a=e.quote?.trim();if(a===void 0||a.length===0)await this.requirePropertyTarget(e.docName,t,i),r=null;else{let n=await this.requirePropertyText(e.docName,t,i),{start:a,end:o}=this.resolveRange(n,e);r=Y0(n,a,o)}}let i=this.newId(),a=this.now(),o=await this.store.createThread({threadId:i,docName:e.docName,target:n,anchor:r,createdBy:e.author,createdAt:a,body:e.body});return this.index.upsert(o),e.queue===!0?this.mutate(i,{queued:!0}):o}async listThreads(e){return await this.buildIndex(),e===void 0?this.index.listAll():this.index.listForDoc(e)}async countThreads(e){return await this.buildIndex(),`prefix`in e?this.index.countsUnderPrefix(e.prefix):this.index.countsForDocs(e.docNames)}async readThread(e){return this.requireMeta(e)}async editComment(e,t){return this.mutate(e,{latestComment:t,updatedAt:this.now()})}async resolve(e){return this.mutate(e,{state:`resolved`})}async reopen(e){return await this.mutate(e,{state:`anchored`,queued:!0}),this.refindOnLoad(e)}async replaceAnchor(e,t){let n=await this.requireMeta(e);if(n.target.kind===`property`)throw new n2(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=Y0(r,i,a);return this.mutate(e,{anchor:o,state:`anchored`})}async queueForDispatch(e,t){await this.mutate(e,{queued:!0});let n=await this.refindOnLoad(e,t);return{meta:n,orphaned:n.state===`orphaned`}}async prepareDispatch(e){let t=await this.getDocBody((await this.requireMeta(e)).docName),n=await this.queueForDispatch(e,t),{anchor:r,docName:i,target:a}=n.meta,o=await this.latestComment(e);return a.kind===`property`?{meta:n.meta,payload:{docName:i,instruction:o,property:i2(a.key,a.path),passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:!1}}:{meta:n.meta,payload:{docName:i,instruction:o,property:null,passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:r!==null&&t!==null&&D1e(t,r.exact)}}}async completeDispatch(e){return this.mutate(e,{queued:!1,state:`resolved`})}async prepareDispatchBatch(e){let t=[];for(let n of e)try{let e=await this.prepareDispatch(n);t.push({threadId:n,ok:!0,...e})}catch(e){if(e instanceof t2){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async completeDispatchBatch(e){let t=[];for(let n of e)try{t.push({threadId:n,ok:!0,meta:await this.completeDispatch(n)})}catch(e){if(e instanceof t2){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async latestComment(e){return(await this.requireMeta(e)).latestComment.trim()}async unqueue(e){return this.mutate(e,{queued:!1})}async delete(e){await this.buildIndex(),await this.store.delete(e),this.index.remove(e)}async renameDoc(e,t){if(e===t)return;await this.buildIndex();let n=this.index.threadsForDoc(e);n.length!==0&&(this.index.renameDoc(e,t),await Promise.all(n.map(e=>this.store.update(e,{docName:t}))))}async deleteDoc(e){await this.buildIndex();let t=this.index.threadsForDoc(e);for(let e of t)await this.store.delete(e),this.index.remove(e);return t.length}async refindDoc(e){await this.buildIndex();let t=this.index.listForDoc(e).filter(e=>e.state!==`resolved`);if(t.length===0)return!1;let n=await this.getDocBody(e);if(n===null)return!1;let r=t.some(e=>e.target.kind===`property`)?await this.getDocFrontmatter(e):null,i=!1;for(let a of t){if(a.target.kind===`property`){let t=await this.refindProperty(e,a.target,a.anchor,r);if(t===null||t.state===a.state)continue;await this.mutate(a.threadId,{state:t.state}),i=!0;continue}if(a.anchor===null)continue;let t=X0(n,a.anchor);if(t.status===`orphaned`){if(a.state===`orphaned`)continue;await this.mutate(a.threadId,{state:`orphaned`}),i=!0;continue}let o=t.rewritten===!0?Y0(n,t.start,t.end):void 0,s=a.state!==`anchored`;o===void 0&&!s||(await this.mutate(a.threadId,{...o?{anchor:o}:{},state:`anchored`}),(s||o!==void 0)&&(i=!0))}return i}async refindOnLoad(e,t){let n=await this.requireMeta(e);if(n.state===`resolved`)return n;if(n.target.kind===`property`){let t=await this.refindProperty(n.docName,n.target,n.anchor);return t===null||t.anchor===void 0&&t.state===n.state?n:this.mutate(e,{...t.anchor?{anchor:t.anchor}:{},state:t.state})}let r=t===void 0?await this.getDocBody(n.docName):t;if(r===null)return n;let i=n.anchor;if(i===null)return n;let a=X0(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?Y0(r,a.start,a.end):a.start!==i.start||a.end!==i.end?{...i,start:a.start,end:a.end}:void 0;return o===void 0&&n.state===`anchored`?n:this.mutate(e,{...o?{anchor:o}:{},state:`anchored`})}async mutate(e,t){let n=await this.store.update(e,t);if(!n)throw new t2(e);return this.index.upsert(n),n}resolveRange(e,t){if(t.start!==void 0&&t.end!==void 0)return{start:t.start,end:t.end};let n=t.quote?.trim();if(n===void 0||n.length===0)throw Error(`either start/end offsets or a non-empty quote is required`);let r=S1e(e,n),i=r.length>0?r:Bre(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new r2(n);return i.length===1?i[0]:C1e(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new t2(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new e2(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new e2(e);let i=$0(r,t,n);if(i===void 0)throw new n2(i2(t,n));let a=E1e(i);if(a===null)throw new n2(i2(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new e2(e);if($0(r,t,n)===void 0)throw new n2(i2(t,n))}async refindProperty(e,t,n,r){let i=r===void 0?await this.getDocFrontmatter(e):r;if(i===null)return null;let a=$0(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=E1e(a);if(o===null)return{state:`orphaned`};let s=X0(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:Y0(o,s.start,s.end)}:s.start!==n.start||s.end!==n.end?{state:`anchored`,anchor:{...n,start:s.start,end:s.end}}:{state:`anchored`}}};function i2(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}var k1e=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=H(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=mJ(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return H(this.dir,`${e}.meta.json`)}enqueueResult(e,t){let n=(this.writeQueues.get(e)??Promise.resolve()).then(()=>t());return this.writeQueues.set(e,n.then(()=>void 0,()=>void 0)),n}async whenIdle(e){await(this.writeQueues.get(e)??Promise.resolve())}createThread(e){let t=la.parse({threadId:e.threadId,docName:e.docName,target:e.target,anchor:e.anchor,state:`anchored`,queued:!1,latestComment:e.body,createdBy:e.createdBy,createdAt:e.createdAt});return this.enqueueResult(e.threadId,async()=>(await this.ensureDir(),await this.write(t),t))}update(e,t){return this.enqueueResult(e,async()=>{await this.ensureDir();let n=await this.readMeta(e);if(!n)return null;let r=la.parse({...n,...A1e(t)});return await this.write(r),r})}write(e){return jk(this.metaPath(e.threadId),j1e(e),{fs:TJ})}async readMeta(e){let t;try{t=await Ks(this.metaPath(e),`utf8`)}catch{return null}let n=la.safeParse(M1e(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await qs(this.dir)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(`.meta.json`))continue;let e=await this.readMeta(n.slice(0,-10));e&&t.push(e)}return t}async delete(e){await this.enqueueResult(e,async()=>{await fJ(this.metaPath(e),{force:!0}),await fJ(H(this.dir,`${e}.ndjson`),{force:!0})})}};function A1e(e){let{docName:t,anchor:n,state:r,queued:i,latestComment:a,updatedAt:o}=e;return{...t!==void 0&&{docName:t},...n!==void 0&&{anchor:n},...r!==void 0&&{state:r},...i!==void 0&&{queued:i},...a!==void 0&&{latestComment:a},...o!==void 0&&{updatedAt:o}}}function j1e(e){return`${JSON.stringify(e,null,1)}\n`}function M1e(e){try{return JSON.parse(e)}catch{return}}const a2=[`claude`,`codex`,`cursor`],o2=2e3,N1e={claude:[`Claude`],codex:[`Codex`],cursor:[`Cursor`]};function P1e(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(a2.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}function F1e(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return I1e(e)}catch{}let n=e.headers.origin;if(typeof n==`string`&&n.length>0)try{return I1e(new URL(n).hostname)}catch{return!1}return!0}function I1e(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function L1e(e,t,n){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{let r=F1e(e)?await n():Object.fromEntries(a2.map(e=>[e,!0]));Q(t,200,Ke,r,{handler:`installed-agents`})}catch(e){q(`handoff`).error({err:e},`[installed-agents] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function s2(e,t=$o){return n=>e===`darwin`?R1e(n,t):e===`win32`?z1e(n,t):B1e(n,t)}function R1e(e,t){let n=N1e[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],vX({timeout:o2,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function z1e(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],vX({timeout:o2,encoding:`utf-8`}),e=>{n(!e)})})}function B1e(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],vX({timeout:o2,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const V1e=[`.ok`,`skill-install-events.jsonl`];async function c2(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{q(`skills`).warn(e,t)}),i=n();if(!i){r({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let a=H(i,...V1e),o=`${JSON.stringify(e)}\n`;try{await mJ(V(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await uJ(a,o,{flag:`a`,encoding:`utf-8`})}catch(e){r({event:`skill-install-events.append-failed`,err:e},`[skill-install-events] append failed; telemetry skipped`)}}function l2(e){let t=e??Rs(),n;try{n=Fk(`user`,t,t)}catch(e){return q(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!G(n))return{enabled:!0,home:t};try{let e=(0,wk.parse)(K(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e!=`boolean`||e,home:t}}catch(e){return q(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}function u2(){let e=new Map;return(t,n)=>{let r=(e.get(t)??Promise.resolve()).then(n,n);return e.set(t,r.then(()=>void 0,()=>void 0)),r}}const H1e=[`.ok`,`local`,`skill-placements.json`];function d2(e){return H(e,...H1e)}function f2(e,t){if(t.length===0||t.includes(`\0`)||os(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let n=W(e),r=W(n,t);if(r===n||!r.startsWith(`${n}${us}`))return null;let i;try{i=ks(n)}catch{return null}let a=r;for(;!G(a);){let e=V(a);if(e===a)return null;a=e}try{let e=ks(a);if(e!==i&&!e.startsWith(`${i}${us}`))return null}catch{return null}return r}function p2(){return{schema:1,skills:{}}}function U1e(e,t){if(!t||typeof t!=`object`)return!1;let n=t;return typeof n.path==`string`&&f2(e,n.path)!==null&&(n.mode===`copy`||n.mode===`link`)&&(n.hash===void 0||typeof n.hash==`string`)}function W1e(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>e[1]===`copy`||e[1]===`link`);return t.length>0?Object.fromEntries(t):void 0}function G1e(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1]!==``);return t.length>0?Object.fromEntries(t):void 0}function K1e(e,t){if(!t||typeof t!=`object`)return;let n=[];for(let[r,i]of Object.entries(t)){if(f2(e,r)===null||!i||typeof i!=`object`)continue;let t=i;t.expect===`own`?n.push([r,{expect:`own`}]):t.expect===`link`&&typeof t.target==`string`&&f2(e,t.target)!==null&&n.push([r,{expect:`link`,target:t.target}])}return n.length>0?Object.fromEntries(n):void 0}function q1e(e,t){let n={};if(t.skills&&typeof t.skills==`object`)for(let[r,i]of Object.entries(t.skills)){if(!Array.isArray(i))continue;let t=i.filter(t=>U1e(e,t));t.length>0&&(n[r]=t)}let r=Array.isArray(t.roots)?t.roots.filter(t=>typeof t==`string`&&f2(e,t)!==null):[],i=W1e(t.preferences),a=G1e(t.sources),o=K1e(e,t.folders);return{schema:1,skills:n,...i?{preferences:i}:{},...a?{sources:a}:{},...r.length>0?{roots:r}:{},...o?{folders:o}:{}}}function m2(e){let t=d2(e);if(!G(t))return p2();try{let n=JSON.parse(K(t,`utf-8`));return!n||typeof n!=`object`?p2():q1e(e,n)}catch(e){return q(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),p2()}}function J1e(e){let t=d2(e);if(!G(t))return{ok:!0,store:p2()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,store:p2()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch(e){return{ok:!1,reason:`it is not valid JSON`,cause:e}}if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,reason:`its contents are not a placements ledger`};let i=r.schema;return i!==void 0&&i!==1?{ok:!1,reason:typeof i==`number`?`it declares schema ${i}, which this server does not understand (it writes schema 1)`:`it declares an unsupported schema value`}:{ok:!0,store:q1e(e,r)}}const Y1e=u2();function h2(e,t){return Y1e(d2(e),async()=>{let n=J1e(e);if(!n.ok){let t=d2(e);throw q(`skill-placements`).error({path:t,reason:n.reason,err:n.cause},`refusing to rewrite skill-placements.json because it could not be read — rewriting it would replace every placement it records with this one`),Error(`Refusing to rewrite ${t}: ${n.reason}`)}let r=n.store;t(r),await X1e(e,r)})}async function X1e(e,t){let n=d2(e);await mJ(V(n),{recursive:!0}),await jk(n,`${JSON.stringify(t,null,2)}\n`,{fs:TJ})}function Z1e(e){let t=m2(e),n=new Set(t.roots??[]);for(let r of Object.values(t.skills))for(let t of r){let r=t.path.split(`/`).slice(0,-1).join(`/`);r!==``&&f2(e,r)!==null&&n.add(r)}return[...n].sort()}function Q1e(e){return m2(e).sources??{}}const $1e=new Set([400,404,410,422]),e0e=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function t0e(e){let t=e.split(`/`);return t.length===1?/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)?!e0e.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2&&t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`)}function g2(e,t){if(e.scope===void 0)return`${e.source}#${t}`;let n=e.scope;try{n=ks(n)}catch{}return`${e.source}#${t}@${n}`}function n0e(e){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function _2(e,t){let n=t.env??process.env;if(!t.enabled||n0e(n)||!t0e(e.source.trim()))return[];let r=await WXe(t.home).catch(t=>(q(`skills`).warn({err:t,source:e.source},`could not read the install-report ledger; a duplicate report is possible`),new Set)),i=e.skills.filter(t=>!r.has(g2(e,t)));if(i.length===0)return[];let a=new URLSearchParams({event:`install`,source:e.source,skills:i.join(`,`)});e.agents&&e.agents.length>0&&a.set(`agents`,e.agents.join(`,`)),e.global&&a.set(`global`,`1`),e.version&&a.set(`v`,e.version);let o=t.fetchImpl??globalThis.fetch;if(!o)return[];try{await GXe(t.home,i.map(t=>g2(e,t)))}catch(t){return q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report ledger write failed; not reporting this install`),[]}try{let n=await o(`https://add-skill.vercel.sh/t?${a.toString()}`,{signal:AbortSignal.timeout(3e3)});if(!n.ok&&$1e.has(n.status))return q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected by the collector; releasing the claim to retry later`),await KXe(t.home,i.map(t=>g2(e,t))).catch(t=>{q(`skills`).warn({err:t,status:n.status,source:e.source,skills:i},`could not release the install-report claim; this install will not be retried`)}),[];n.ok||q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected with an ambiguous status; keeping the claim so a counted install cannot be double-reported`)}catch(t){q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const v2=`.agents`;function r0e(e,t){return H(e,v2,`skills`,t)}function y2(e){return pie.filter(t=>G(H(e,t.hostDir)))}function i0e(e){let t=y2(e).map(e=>({editor:e.editorId,skillsRoot:e.skillsRoot,custom:!1})),n=new Set(t.map(e=>e.skillsRoot)),r=Z1e(e).filter(t=>!n.has(t)&&G(H(e,t))).map(e=>({editor:e,skillsRoot:e,custom:!0}));return[...t,...r]}function a0e(e){return Mn.filter(t=>{let n=y[t];return n!==null&&G(H(e,ee(n)))})}async function o0e(e,t){let n=y2(e).map(n=>H(e,n.skillsRoot,t));G(H(e,v2))&&n.push(r0e(e,t));for(let e of n)try{if((await Xs(e)).isDirectory())return!0}catch{}return!1}function s0e(e,t,n){let r=[...t.map(e=>e.skillsRoot),`${v2}/skills`];for(let t of r){let r=H(e,t,`open-knowledge`);if(G(r))try{CJ(r,{recursive:!0,force:!0}),n.info?.({event:`skill-install.legacy-removed`,path:r},"Removed pre-split `open-knowledge` user-global skill dir.")}catch(e){n.warn({event:`skill-install.legacy-remove-failed`,path:r,err:e},"Legacy `open-knowledge` skill removal failed; continuing with install.")}}}function c0e(e,t){CJ(t,{recursive:!0,force:!0}),_J(V(t),{recursive:!0}),yJ(e,t,{recursive:!0})}function l0e(e,t,n,r,i){let a=[],o=r0e(e,t),s=[...i?[o]:[],...r.map(n=>H(e,n.skillsRoot,t)).filter(e=>e!==o)];for(let e of s)try{c0e(n,e),a.push({path:e,status:`written`})}catch(t){a.push({path:e,status:`failed`,error:t instanceof Error?t.message:String(t)})}return a}async function u0e(e={}){let t=e.home??Rs(),n=e.logger??{warn:(e,t)=>q(`skills`).warn(e,t),info:(e,t)=>q(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=l1[i];if(!os(t))return n.warn({event:`skill-install.failed`,reason:`home-not-absolute`,home:t},`Skill install aborted — $HOME is not an absolute path.`),`failed`;let o=async(e,a,o)=>{await c2({ts:new Date().toISOString(),surface:r,target:`cli-hosts`,bundle:i,outcome:e,...a===void 0?{}:{version:a},...o===void 0?{}:{reason:o}},{homedir:()=>t,warn:n.warn})},s;try{s=await HXe(t,a,n)}catch(e){return n.warn({event:`skill-install.gate.decision-read-failed`,bundle:i,err:e},`Could not read the opt-out decision; skipping the install rather than risk reversing it.`),await o(`skip-current`,void 0,`decision-read-failed`),`skip-current`}if(s===!1)return n.info?.({event:`skill-install.declined`,bundle:i},`Bundle is opted out; skipping user-global skill install.`),await o(`skip-current`,void 0,`declined`),`skip-current`;let c;try{c=await x1()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,err:e},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await o(`failed`,void 0,`version-read-failed`),`failed`}let l=await y1(t,`cli-hosts`,n).catch(e=>(n.warn({event:`skill-install.gate.read-failed`,err:e},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&l!==null&&l===c){if(await o0e(t,a))return n.info?.({event:`skill-install.skip-current`,version:c},`OpenKnowledge skill already installed at current version; skipping.`),await o(`skip-current`,c),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:c},`Sidecar matches current version but skill files are missing; reinstalling.`)}let u;try{u=J0(i,{checkDesktop:!1})}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,err:e},`Skill install aborted — bundled SKILL.md asset not found.`),await o(`failed`,c,`bundled-asset-missing`),`failed`}let d=y2(t),f=G(H(t,v2));if(d.length===0&&!f)return n.info?.({event:`skill-install.no-hosts`,version:c},`No supported agent host detected; skipping user-global skill install.`),await o(`skip-current`,c,`no-hosts`),`no-hosts`;s0e(t,d,n);let p=l0e(t,a,u,d,f),m=p.filter(e=>e.status===`written`),h=p.filter(e=>e.status===`failed`);if(m.length===0)return n.warn({event:`skill-install.failed`,reason:`write-failed`,entries:h},`Skill install failed — every destination write errored.`),await o(`failed`,c,`write-failed`),`failed`;try{await b1(t,`cli-hosts`,c,r,n)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,err:e},`Skill install succeeded but sidecar write failed.`),await o(`failed`,c,`sidecar-write-failed`),`failed`}return h.length>0&&n.warn({event:`skill-install.partial`,version:c,entries:h},`Some agent hosts could not be written; the remaining copies are installed.`),n.info?.({event:`skill-install.installed`,version:c,hosts:d.map(e=>e.editorId),paths:m.map(e=>e.path)},`OpenKnowledge skill installed to ${m.length} location(s): ${m.map(e=>e.path).join(`, `)}`),await o(`installed`,c),_2({source:jr,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:l2(t).enabled}),`installed`}function d0e(e){return H(e,`Downloads`,`openknowledge.skill`)}function f0e(e,t,n){let r=vX({detached:!0,stdio:`ignore`});try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function p0e(e={}){let t=e.home??Rs(),n=W(e.out??d0e(t)),r=e.platformName??Bs(),i=e.spawnFn??es,a=e.logger,o=async(e,n,r)=>{await c2({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...n===void 0?{}:{version:n},...r===void 0?{}:{reason:r}},{homedir:()=>t,warn:a?.warn})};if(!e.force){let e=null;try{e=await x1()}catch(e){a?.warn?.({event:`skill-install.gate.version-read-failed`,err:e},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let n=null,r=null;try{[n,r]=await Promise.all([y1(t,`claude-cowork`,a),VXe(t,`claude-cowork`,a)])}catch(e){a?.warn?.({event:`skill-install.gate.read-failed`,err:e},`Could not read claude-cowork install-state; rebuilding.`)}if(n!==null&&n===e)return a?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await o(`skip-current`,e),{status:`skip-current`,skillVersion:e,...r===null?{}:{recordedAt:r}}}}try{await mJ(V(n),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let s;try{s=await b1e({outputPath:n,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let c;try{c=await x1()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await b1(t,`claude-cowork`,c,`server-build-and-open`,a)}catch(e){a?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:c,err:e},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await o(`built`,c),l;let u=f0e(s.outputPath,r,i);return u.ok?(await o(`installed`,c),_2({source:jr,skills:[l1.project],agents:[`claude-desktop`],global:!0,version:c},{home:t,enabled:l2(t).enabled}),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function m0e(e){let{checkLocalOpSecurity:t}=e;return L1({"/api/install-skill":Z(yn,async(e,t,n)=>{if(n.out!==void 0&&!I1(n.out)){X(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{let e=await p0e({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}});Q(t,200,Rn,e,{handler:`install-skill`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,n)=>t(e,n,{handler:`install-skill`})})},{mutating:[`/api/install-skill`]})}const h0e=1024,g0e=[`anthropic`,`claude`],b2=`SKILL.md`;function _0e(e){let t=O2(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=S0e(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${w0e(e.frontmatter)}---\n${e.body}`,i=[],a=[],o=g0e.filter(t=>e.name.includes(t));o.length>0&&(i.push(`Skill name contains ${o.map(e=>`"${e}"`).join(`, `)} — Anthropic's authoring guidance discourages vendor words in skill names.`),a.push(`skill-name-vendor-word`));let s=e.body.split(`
1010
- `).length;return s>500&&(i.push(`SKILL.md body is ${s} lines — keep it under 500 for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),a.push(`skill-body-too-long`)),{ok:!0,content:r,warnings:i,warningCodes:a}}function x2(e){let t=V(e),n=`${rs(e)}${Dk}`;try{for(let e of Ds(t))e.startsWith(n)&&bJ(H(t,e))}catch{}}function S2(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=_0e({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i,warningCodes:a}=n,{skillDir:o,filePath:s}=k2(e.skillsRoot,e.name);try{_J(o,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${A2(e.skillsRoot,o)}: ${t.message}`}}}let c=!G(s);x2(s);let l=kk(s);try{hJ(l,r,`utf-8`),vJ(l,s)}catch(t){try{bJ(l)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${A2(e.skillsRoot,s)}: ${t.message}`}}}return{ok:!0,path:A2(e.skillsRoot,s),created:c,warnings:i,warningCodes:a}}function C2(e){let t=H(e.skillDir,b2),n;if(e.skillMd!==void 0)n=e.skillMd;else try{n=K(t,`utf-8`)}catch(e){return{ok:!1,stage:`read`,cause:e}}let{fenced:r,body:i}=na(n),a=Li(r,{name:e.toName});if(!a.ok)return{ok:!1,stage:`patch`,error:a.error};x2(t);let o=kk(t);try{hJ(o,`${a.nextFenced}${i}`,`utf-8`),vJ(o,t)}catch(e){try{bJ(o)}catch{}return{ok:!1,stage:`write`,cause:e}}return{ok:!0}}function w2(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let n=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(n.length===0||n.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(n.length===1&&n[0]===b2)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`SKILL.md is written through the skill write path, not as a bundle file.`}};let r=H(e,...n);return r!==e&&!r.startsWith(e+us)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:r}}function v0e(e){let t=0,n=r=>{let i;try{i=Ds(r)}catch{return}for(let a of i){let i=H(r,a),o;try{o=Ns(i).isDirectory()}catch{continue}o?n(i):(r!==e||a!==b2)&&t++}};return n(e),t}function T2(e){let t=e.bytes??e.content??``,n=D2(e.skillsRoot);if(!n.ok)return{ok:!1,error:n.error};let r=O2(e.name);if(!r.ok)return{ok:!1,error:r.error};let{skillDir:i,filePath:a}=k2(e.skillsRoot,e.name);if(!G(a))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let o=w2(i,e.relPath);if(!o.ok)return{ok:!1,error:o.error};let{abs:s}=o,c=typeof t==`string`?Buffer.byteLength(t,`utf-8`):t.length,l=e.limits?.maxFileBytes??262144,u=e.limits?.maxFiles??50;if(c>l)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${c} bytes — the per-file cap is ${l}.`}};let d=!G(s);if(d&&v0e(i)>=u)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds ${u} bundle files (the cap) — delete one before adding another.`}};try{_J(H(s,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}x2(s);let f=kk(s);try{typeof t==`string`?hJ(f,t,`utf-8`):hJ(f,t),vJ(f,s)}catch(t){try{bJ(f)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:A2(e.skillsRoot,s),created:d}}function y0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=k2(e.skillsRoot,e.name),i=w2(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let a=w2(r,e.toRelPath);if(!a.ok)return{ok:!1,error:a.error};if(!G(i.abs))return{ok:!1,error:{code:`FILE_NOT_FOUND`,message:`No bundle file at ${e.relPath}.`}};if(G(a.abs))return{ok:!1,error:{code:`DEST_EXISTS`,message:`A bundle file already exists at ${e.toRelPath} — renames never overwrite.`}};try{_J(H(a.abs,`..`),{recursive:!0}),vJ(i.abs,a.abs)}catch(t){return{ok:!1,error:{code:`RENAME_FAILED`,message:`Failed to rename ${e.relPath} -> ${e.toRelPath}: ${t.message}`}}}let o=H(i.abs,`..`);if(o!==r&&j2(o))try{wJ(o)}catch{}return{ok:!0}}function b0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=k2(e.skillsRoot,e.name),i=w2(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let{abs:a}=i,o=G(a);if(o){try{Ns(a).isDirectory()?CJ(a,{recursive:!0,force:!0}):bJ(a)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=H(a,`..`);if(t!==r&&j2(t))try{wJ(t)}catch{}}return{ok:!0,path:A2(e.skillsRoot,a),existed:o}}function E2(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillsRoot:r}=t,{skillDir:i}=k2(e.skillsRoot,e.name),a=G(i);if(a)try{CJ(i,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${A2(e.skillsRoot,i)}: ${t.message}`}}}return C0e(r),{ok:!0,path:A2(e.skillsRoot,i),existed:a}}async function x0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.fromName);if(!n.ok)return{ok:!1,error:n.error};let r=O2(e.toName);if(!r.ok)return{ok:!1,error:r.error};let i=k2(e.skillsRoot,e.fromName),a=k2(e.skillsRoot,e.toName);if(i.skillDir===a.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!G(i.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${A2(e.skillsRoot,i.skillDir)}.`}};if(G(a.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${A2(e.skillsRoot,a.skillDir)}.`}};let o;try{o=await e.relocate(i.skillDir,a.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:A2(e.skillsRoot,i.skillDir),toPath:A2(e.skillsRoot,a.skillDir),committed:o}}function D2(e){return os(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function O2(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>64?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤64 characters.`}}:Qe.test(e)?{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function S0e(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?Rr(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description==`string`?e.description.length>h0e?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${h0e} characters (got ${e.description.length}).`}}:Rr(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description must be a string — it is the primary triggering surface (when to use the skill).`}}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function k2(e,t){let n=H(e,t);return{skillDir:n,filePath:H(n,b2)}}function C0e(e){if(G(e)&&j2(e))try{wJ(e)}catch{}let t=ss(H(e,`..`));if(t.endsWith(`${us}.ok`)&&G(t)&&j2(t))try{wJ(t)}catch{}}function A2(e,t){let n=t.startsWith(e+us)?t.slice(e.length+1):t;return ss(n).split(us).join(`/`)}function w0e(e){return(0,wk.stringify)({name:e.name,description:e.description,...e.metadata===void 0?{}:{metadata:e.metadata}})}function j2(e){try{return Ds(e).length===0}catch{return!1}}const T0e=new Map;function E0e(e,t){T0e.set(e,t)}function M2(e,t){let n=T0e.get(e);if(n===void 0)return null;if(!Qe.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=W(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=W(n,...e)}if(!r.startsWith(n+us))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}function D0e(e){switch(e.kind){case`invalid_value`:return`${e.kind} (${e.key}: ${e.reason})`;case`reserved_key`:return`${e.kind} ('${e.key}' is reserved)`;case`unknown_key`:return`${e.kind} ('${e.key}' is not a recognized key)`;case`duplicate_target`:return`${e.kind} ('${e.key}' appears more than once)`;case`reorder_mismatch`:return`${e.kind} (expected: ${e.expected.join(`, `)}; got: ${e.got.join(`, `)})`;case`region_too_large`:return`${e.kind} (frontmatter region too large: ${e.bytes} > ${e.limit} bytes)`;case`parse_failed`:return`${e.kind} (frontmatter region unparseable: ${e.reason})`;case`invalid_path`:return`${e.kind} (${e.path.map(String).join(`.`)||`__path__`}: ${e.reason})`;default:return`unhandled frontmatter edit error (${String(e)})`}}function O0e(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}const N2=O0e(y,qi),P2=O0e(Ki,qi);function F2(e,t){let n=I2(e,t),r={},i;try{i=ks(e)}catch{return r}for(let{editor:t,root:a}of n){let n;try{n=ks(H(e,a))}catch{continue}if(n===H(i,a))continue;let o=U(i,n);o===``||o.startsWith(`..`)||os(o)||(r[t]=o.split(us).join(`/`))}return r}function k0e(e){return e===`project`?N2:P2}function A0e(e){let t=I2(e,`global`).map(t=>H(e,t.root)),n=H(e,`.ok`,`skills`);return t.includes(n)?t:[...t,n]}function I2(e,t){let n=k0e(t),r=new Set(n.map(e=>e.root));return[...n,...Z1e(e).filter(e=>!r.has(e)).map(e=>({editor:e,root:e}))]}function L2(e){return new Set((e===`project`?N2:P2).map(e=>e.root))}function R2(e,t,n,r){return!L2(t).has(n)||G(H(e,ee(n)))?!0:n===`.agents/skills`&&mn.some(e=>e.scope===t&&G(H(r,e.dotDir)))}function j0e(e,t,n,r){let i=new Set([...I2(e,t).map(e=>e.root),Ba]),a=[];for(let t of i){let i=H(e,t,n),o;try{o=xs(i)}catch{continue}if(o.isSymbolicLink()){a.push(i);continue}oI(i)?.contentHash===r&&a.push(i)}return a}function M0e(e,t){let n=new Map((t===`project`?N2:P2).map(e=>[e.editor,e.root])),r=new Set;for(let t of Object.keys(e)){let e=n.get(t);e===void 0?t.includes(`/`)&&r.add(t):r.add(e)}return r}function z2(e,t){let n=t===`project`?N2:P2;if(G(H(e,`.agents`)))return qi;let r=[...n].filter(e=>e.editor!==`agents`).sort((e,t)=>{let n=fI.indexOf(e.editor),r=fI.indexOf(t.editor);return(n===-1?fI.length:n)-(r===-1?fI.length:r)});for(let{root:t}of r)if(G(H(e,ee(t))))return t;return null}function N0e(e){return[...new Set((e===`project`?N2:P2).map(e=>`${ee(e.root)}/`))]}function P0e(e){let t=[],n=(e,r)=>{for(let i of Ds(e,{withFileTypes:!0})){let a=H(e,i.name),o=r===``?i.name:`${r}/${i.name}`,s=Ns(a);s.isDirectory()?n(a,o):t.push(`${o}:${s.size}:${s.mtimeMs}`)}};try{n(e,``)}catch{return null}return t.sort().join(`|`)}const F0e=new Map;function I0e(e){let t=P0e(e);if(t===null)return null;let n=F0e.get(e);if(n!==void 0&&n.stamp===t)return n;let r=oI(e);if(!r)return null;let i=eI(sa(r.skillMd)??{}),a={stamp:t,contentHash:r.contentHash,description:r.description,size:Cne(r),...i===void 0?{}:{pack:i}};return F0e.set(e,a),a}function L0e(e,t){let n=[],r=Q1e(e),i=I2(e,t),a=null;try{a=ks(e)}catch{a=null}for(let{editor:o,root:s}of i){let i=H(e,s),c,l=!1;try{if(!G(i))continue;l=a!==null&&ks(i)!==H(a,s),c=Ds(i)}catch{continue}for(let e of c){let a=H(i,e);try{if(!Ns(a).isDirectory())continue;let i=I0e(a);if(!i)continue;n.push({name:e,scope:t,editor:o,contentHash:i.contentHash,dir:`${s}/${e}`,description:i.description,size:i.size,...i.pack===void 0?{}:{pack:i.pack},viaLink:l||xs(a).isSymbolicLink(),...l?{aliasRooted:!0}:{},...r[e]===o?{preferredSource:!0}:{}})}catch{}}}let{admittedDirs:o,canonicalDir:s}=nke(n),c=new Set(s.values());return mI(n).filter(e=>o.has(e.canonical.dir)).filter(e=>c.has(e.canonical.dir)||!d1(e.name)).sort((e,t)=>e.name.localeCompare(t.name)||Number(c.has(t.canonical.dir))-Number(c.has(e.canonical.dir))||e.contentHash.localeCompare(t.contentHash)).map(t=>{let r=null;try{r=ks(H(e,t.canonical.dir))}catch{r=null}let i=t=>{if(r===null)return!1;try{return ks(H(e,t))===r}catch{return!1}},a=t.copies.filter(e=>e.aliasRooted!==!0&&(e.viaLink||!i(e.dir))),o=d1(t.canonical.name)?[]:n.filter(e=>e.name===t.canonical.name&&e.contentHash!==t.contentHash).map(e=>e.editor);return{name:t.canonical.name,description:t.canonical.description,dir:t.canonical.dir,hosts:[t.canonical.editor,...a.map(e=>e.editor)],linkedHosts:[t.canonical,...a].filter(e=>e.viaLink).map(e=>e.editor),conflictHosts:o,copyDirs:a.filter(e=>!e.viaLink).map(e=>e.dir),contentHash:t.contentHash,size:t.canonical.size,...t.canonical.pack===void 0?{}:{pack:t.canonical.pack}}})}function B2(e){return L0e(e,`project`).filter(e=>!IXe(e.name))}function V2(e){return L0e(e,`global`)}const R0e=[...P2].sort((e,t)=>{let n=fI.indexOf(e.editor),r=fI.indexOf(t.editor);return(n===-1?fI.length:n)-(r===-1?fI.length:r)||e.editor.localeCompare(t.editor)});function H2(e,t){for(let{root:n}of R0e){let r=H(e,n,t);try{if(G(H(r,`SKILL.md`)))return r}catch{}}return null}function z0e(e){return new Set(I2(e,`project`).map(e=>e.root))}function U2(e){return new Set(B2(e).map(e=>e.dir))}const B0e=q(`installed-skills-marker`);function W2(e){return H(e,...un)}const V0e=u2();function H0e(e,t){return V0e(W2(e),t)}function G2(e){let t=W2(e);if(!G(t))return hi();try{return Tne(K(t,`utf-8`))??hi()}catch(e){return B0e.warn({err:e,path:t},`installed-skills marker unreadable`),hi()}}function U0e(e){let t=W2(e);if(!G(t))return{ok:!0,state:hi()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,state:hi()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r=Tne(n);return r===null?{ok:!1,reason:`its contents are not an installed-skills marker this server understands`}:{ok:!0,state:r}}function W0e(e){let t=U0e(e);if(t.ok)return t.state;let n=W2(e);throw B0e.error({path:n,reason:t.reason,err:t.cause},`refusing to rewrite the installed-skills marker because it could not be read — rewriting it would replace every install it records with this one`),Error(`Refusing to rewrite ${n}: ${t.reason}`)}async function G0e(e,t){let n=Ct.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid installed-skills marker: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=W2(e);await mJ(V(r),{recursive:!0}),await jk(r,`${JSON.stringify(n.data,null,2)}\n`,{fs:TJ})}async function K2(e,t,n){return H0e(e,async()=>{let r=W0e(e);await G0e(e,{...r,skills:{...r.skills,[t]:n}})})}async function q2(e,t){return H0e(e,async()=>{let n=W0e(e),r=n.skills[t]??null;if(r===null)return null;let{[t]:i,...a}=n.skills;return await G0e(e,{...n,skills:a}),r})}function J2(e,t){return`${e}:${t}`}function K0e(e){return H(aX(e),`skill-move-retained.json`)}function Y2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X2(e){return typeof e==`string`?e:``}const q0e=()=>({ok:!0,store:{schema:1,retained:{}}});function J0e(e){let t=K0e(e);if(!G(t))return q0e();let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?q0e():{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch{return{ok:!1,reason:`it is not valid JSON`}}if(!Y2(r)||!Y2(r.retained))return{ok:!1,reason:`its contents are not a retained-record ledger`};if(r.schema!==1)return{ok:!1,reason:typeof r.schema==`number`?`it declares schema ${r.schema}, which this server does not understand (it writes schema 1)`:`it declares a schema this server does not understand (it writes schema 1)`};let i={};for(let[e,t]of Object.entries(r.retained)){let n=Y2(t)?t:{};i[e]={retainedAt:X2(n.retainedAt),from:X2(n.from),to:X2(n.to),sourceState:Gn(n.sourceState)?n.sourceState:`unknown`,reason:X2(n.reason),retainedContentHash:X2(n.retainedContentHash)}}return{ok:!0,store:{schema:1,retained:i}}}function Z2(e,t,n){let r=J0e(e);if(!r.ok)return{state:`unreadable`,reason:r.reason,...r.cause===void 0?{}:{cause:r.cause}};let i=r.store.retained[J2(t,n)];return i===void 0?{state:`none`}:{state:`record`,record:i}}const Y0e=u2();function X0e(e,t){let n=K0e(e);return Y0e(n,async()=>{let r=J0e(e);if(!r.ok)throw q(`skill-move-retained`).error({event:`skill-move-retained.unreadable`,path:n,reason:r.reason},`refusing to rewrite the retained-destination ledger because it could not be read — rewriting it would replace every record it holds with this one`),Error(`Refusing to rewrite ${n}: ${r.reason}`);t(r.store.retained)&&(await mJ(V(n),{recursive:!0}),await jk(n,`${JSON.stringify(r.store,null,2)}\n`,{fs:TJ}))})}function Z0e(e,t,n,r){return X0e(e,e=>(e[J2(t,n)]=r,!0))}function Q0e(e,t,n){return X0e(e,e=>{let r=J2(t,n);return r in e&&(delete e[r],!0)})}function Q2(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}async function $2(e,t,n){await h2(e,e=>{e.sources={...e.sources,[t]:n}})}async function $0e(e,t,n){await h2(e,e=>{e.folders={...e.folders,[t]:n}})}function e2e(e){return m2(e).folders??{}}async function t2e(e,t){await h2(e,e=>{let n=new Set(e.roots??[]);n.has(t)||(n.add(t),e.roots=[...n].sort())})}function n2e(e,t){let n=m2(e).preferences?.[t];return n===`link`||n===`copy`?n:void 0}function e4(e){let t={};for(let[n,r]of Object.entries(m2(e).skills)){let i=r.filter(t=>{let n=f2(e,t.path);return n!==null&&G(H(n,`SKILL.md`))});i.length>0&&(t[n]=i)}return t}async function r2e(e,t,n){await h2(e,e=>{let r=(e.skills[t]??[]).filter(e=>e.path!==n);e.skills={...e.skills},r.length>0?e.skills[t]=r:delete e.skills[t]})}async function i2e(e,t){await h2(e,e=>{e.skills[t]!==void 0&&(e.skills={...e.skills},delete e.skills[t])})}async function t4(e,t,n){await h2(e,e=>{e.skills={...e.skills};let r=(e.skills[t]??[]).filter(e=>e.path!==n.path);r.push(n),e.skills[t]=r})}async function n4(e,t,n){let r=e4(e),i=n??B2(t);for(let t of i){let n=new Set((r[t.name]??[]).map(e=>e.path));for(let i of t.copyDirs){if(n.has(i)||f2(e,i)===null)continue;let a={path:i,mode:`copy`,hash:t.contentHash};await t4(e,t.name,a),r[t.name]=[...r[t.name]??[],a]}}if(Object.keys(r).length===0)return 0;let a=0;for(let n of i){let i=r[n.name];if(!i)continue;let o=f2(t,n.dir);if(o!==null)for(let t of i){if(t.mode!==`copy`||t.hash===void 0)continue;let r=f2(e,t.path);if(r===null||r===o)continue;let i=oI(r)?.contentHash;if(i!==void 0){if(i===n.contentHash){t.hash!==i&&await t4(e,n.name,{...t,hash:i});continue}i===t.hash&&(r=f2(e,t.path),r!==null&&(CJ(r,{recursive:!0,force:!0}),yJ(o,r,{recursive:!0,dereference:!0}),await t4(e,n.name,{...t,hash:n.contentHash}),a+=1))}}}return a}function a2e(e,t,n){let r;try{r=xs(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return ks(e)===ks(t)?{kind:`symlink`,resolution:`target`}:{kind:`symlink`,resolution:`elsewhere`}}catch{return{kind:`symlink`,resolution:`dangling`}}if(!r.isDirectory())return{kind:`other`};try{if(ks(e)===ks(t))return{kind:`dir`,identity:`is-target`}}catch{return{kind:`dir`,identity:`different`}}return oI(e)?.contentHash===n?{kind:`dir`,identity:`same-content`}:{kind:`dir`,identity:`different`}}function r4(e,t){let n=s4(t);return e.filter(e=>n.includes(e))}const o2e=`open-knowledge`,s2e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,c2e=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function l2e(e){let t=e.match(s2e);if(!t)return null;try{let e=(0,wk.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function i4(e,t,n){let r=[],i=[],a=H(e,`SKILL.md`),o=G(H(e,`scripts`))&&Ns(H(e,`scripts`)).isDirectory(),s=t.startsWith(o2e)&&Ur[t]===void 0;if(!n?.allowReservedName&&s&&r.push(`"${t}" uses the reserved \`${o2e}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!G(a))return r.push(`No SKILL.md found at ${e}.`),{ok:r.length===0,errors:r,warnings:i,hasScripts:o};let c;try{c=K(a,`utf-8`)}catch(e){return r.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:r,warnings:i,hasScripts:o}}c2e.some(e=>e.test(c))&&r.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let l=l2e(c);if(l===null)r.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=l.name,n=l.description;typeof e!=`string`||e.length===0?r.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&r.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof n!=`string`||n.length===0)&&i.push("This skill has no `description`. Add one so agents know when to use it."),(typeof e==`string`&&Rr(e)||typeof n==`string`&&Rr(n))&&r.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:r.length===0,errors:r,warnings:i,hasScripts:o}}function u2e(e){return Mn.filter(t=>{let n=tne[t];return n!==null&&G(W(e,n))})}function a4(e,t){if(t&&t.length>0){let e=new Set(Mn);return t.filter(t=>e.has(t))}return u2e(e)}function o4(e){return e===`global`?Ki:y}function s4(e){return e===`global`?$n:Mn}function c4(e,t,n,r=y){let i=r[t];return i===null?null:W(e,i,n)}function l4(e,t,n,r=y){return t===`agents`?W(e,qi,n):c4(e,t,n,r)}function u4(e,t){if(!G(t))return!1;try{let n=U(ks(e),ks(t));return n.startsWith(`..`)||os(n)}catch{return!0}}function d2e(e,t){if(!G(e)||!G(t))return!1;try{return ks(e)===ks(t)}catch{return!1}}function d4(e,t,n){let r=W(n),i=U(W(e),r);return i!==``&&!i.startsWith(`..`)&&!os(i)?U(t,r):r}function f4(e,t,n,r,i=`symlink`,a=y){let o=[];for(let s of r){let r=c4(n,s,t,a);if(r===null)continue;let c=V(r);if(u4(n,c))continue;if(d2e(c,V(e))){o.push(s);continue}let l=W(r)===W(e);if(!l&&G(r))try{l=ks(r)===ks(e)}catch{l=!1}if(l){o.push(s);continue}CJ(r,{recursive:!0,force:!0}),_J(c,{recursive:!0}),i===`copy`?yJ(e,r,{recursive:!0,dereference:!0}):SJ(d4(n,c,e),r,`dir`),o.push(s)}return o}function f2e(e,t){if(!d1(t))return!1;try{return!xs(e).isSymbolicLink()&&G(H(e,`SKILL.md`))}catch{return!1}}function p4(e,t,n){let r=a2e(e,t,n);switch(r.kind){case`absent`:return`absent`;case`other`:return`different`;case`symlink`:return r.resolution===`target`?`link-to-canonical`:`link`;case`dir`:return r.identity===`is-target`?`canonical-dir`:r.identity===`same-content`?`same-copy`:`different`}}function m4(e){let{canonicalAbs:t,canonicalHash:n,canonicalRootRel:r,name:i,cwd:a,targets:o}=e,s=e.roots??y,c=e.mode??`copy`,l=[],u=[],d=(e,n)=>{CJ(e,{recursive:!0,force:!0}),_J(n,{recursive:!0}),c===`link`?SJ(d4(a,n,t),e,`dir`):yJ(t,e,{recursive:!0,dereference:!0})};for(let f of o){if(f===`agents`?r===`.agents/skills`:s[f]===r){let r=l4(a,f,i,s);if(r!==null&&!u4(a,V(r))){let i=p4(r,t,n);(c===`link`&&e.convertCopies===!0&&i===`same-copy`||c===`copy`&&e.convertLinks===!0&&i===`link-to-canonical`)&&d(r,V(r))}l.push(f);continue}let o=l4(a,f,i,s);if(o===null)continue;let p=V(o);if(!u4(a,p)){try{if(ks(p)!==H(ks(a),U(a,p)))continue}catch{}switch(p4(o,t,n)){case`canonical-dir`:l.push(f);break;case`link-to-canonical`:c===`copy`&&e.convertLinks===!0&&d(o,p),l.push(f);break;case`same-copy`:c===`link`&&e.convertCopies===!0&&d(o,p),l.push(f);break;case`different`:if(f2e(o,i)){d(o,p),l.push(f);break}u.push(f);break;case`link`:case`absent`:d(o,p),l.push(f)}}}return{hosts:l,conflicted:u}}function h4(e){let{canonicalHash:t,name:n,cwd:r,newTarget:i}=e,a=e.roots??y,o;try{o=ks(e.canonicalAbs)}catch{return{ok:!1,reason:`target-unusable`}}try{if(xs(o).isSymbolicLink()||!xs(o).isDirectory())return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}let s=e.destDirAbs??l4(r,i,n,a);if(s===null)return{ok:!1,reason:`target-missing`};if(W(s)===o)return{ok:!0,newAbs:s};let c=V(s);if(u4(r,c))return{ok:!1,reason:`target-unusable`};switch(p4(s,o,t)){case`canonical-dir`:return{ok:!0,newAbs:s};case`different`:return{ok:!1,reason:`target-unusable`};case`same-copy`:try{if(xs(s).isSymbolicLink()||!G(H(s,`SKILL.md`)))return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}CJ(o,{recursive:!0,force:!0});break;case`link`:case`link-to-canonical`:CJ(s,{recursive:!0,force:!0}),_J(c,{recursive:!0}),vJ(o,s);break;case`absent`:_J(c,{recursive:!0}),vJ(o,s)}return!G(H(s,`SKILL.md`))||xs(s).isSymbolicLink()?{ok:!1,reason:`target-unusable`}:(e.leaveLinkBehind===!0&&!G(o)&&SJ(d4(r,V(o),s),o,`dir`),g4({name:n,cwd:r,roots:a,target:s,skip:[s,o],alsoClaim:[o,s]}),{ok:!0,newAbs:s})}function p2e(e){return[`agents`,...s4(e===Ki?`global`:`project`)]}function m2e(e,t,n){return p2e(n).map(r=>l4(e,r,t,n)).filter(e=>e!==null)}function g4(e){let{name:t,cwd:n,roots:r,target:i}=e,a=new Set((e.skip??[]).map(e=>W(e))),o=new Set((e.alsoClaim??[]).map(e=>W(e))),s=e.slots??m2e(n,t,r);for(let e of s){if(a.has(W(e)))continue;try{if(!xs(e).isSymbolicLink())continue}catch{continue}let t=null;try{t=ks(e)}catch{t=null}t!==null&&!o.has(t)||(CJ(e,{recursive:!0,force:!0}),SJ(d4(n,V(e),i),e,`dir`))}}function _4(e){let{canonicalHash:t,name:n,cwd:r,targets:i}=e,a=e.roots??y,o;try{o=ks(e.canonicalAbs)}catch{return[]}let s=[];for(let e of i){let i=l4(r,e,n,a);if(i!==null&&!u4(r,V(i)))switch(p4(i,o,t)){case`same-copy`:case`link`:case`link-to-canonical`:CJ(i,{recursive:!0,force:!0}),s.push(e);break;case`different`:f2e(i,n)&&(CJ(i,{recursive:!0,force:!0}),s.push(e))}}return s.length>0&&g4({name:n,cwd:r,roots:a,target:o}),s}function v4(e,t,n,r=y){let i=[];for(let a of n){let n=c4(t,a,e,r);if(n===null)continue;let o=!1;try{xs(n),o=!0}catch{o=!1}o&&(CJ(n,{recursive:!0,force:!0}),i.push(a))}return i}function h2e(e){try{return G(e)?y4(e).filter(e=>e!==`SKILL.md`):[]}catch{return[]}}function y4(e,t=``){let n=[];for(let r of Ds(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...y4(H(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function g2e(e){if(!G(e))return[];let t=[];for(let n of y4(e)){if(n===`SKILL.md`)continue;let r=null;try{let t=K(H(e,n));t.length<=262144&&!t.includes(0)&&(r=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;r=null}t.push({path:n,text:r})}return t}function _2e(e){let t=[];G(W(e,`SKILL.md`))&&t.push(`SKILL.md`);let n=W(e,`references`);if(!G(n))return t;let r=(e,n)=>{let i;try{i=Ds(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;a.isDirectory()?r(W(e,a.name),i):a.isFile()&&a.name.toLowerCase().endsWith(`.md`)&&t.push(`references/${i}`)}};return r(n,``),t}function v2e(e){let{base:t,scope:n,fromName:r,toName:i}=e;if(r===i)return[];let a=q(`skill-ref-rename`),o;try{o=n===`project`?B2(t):V2(t)}catch(e){return a.warn({err:e,scope:n},`skill scan failed; refs to the old name are left as authored`),[]}let s=[];for(let e of o){let n=W(t,e.dir);for(let t of _2e(n)){let o=W(n,t),c;try{c=K(o,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`unreadable skill markdown; skipped`);continue}let l=ete(c,r,i);if(l!==c){try{hJ(o,l,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`skill ref rewrite could not be written; skipped`);continue}s.push({dir:e.dir,rel:t,absPath:o,markdown:l})}}}return s}function b4(e){return G(e)?QF(K(e,`utf-8`))||(q(`skills-lock`).warn({lockPath:e},`skills-lock.json is unreadable; continuing with an empty lock (import provenance for this project is lost)`),ZF()):ZF()}function y2e(e){if(!G(e))return{ok:!0,lock:ZF()};let t;try{t=K(e,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,lock:ZF()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let n=QF(t);return n===null?{ok:!1,reason:`its contents are not a skills lock this server understands`}:{ok:!0,lock:n}}const b2e=u2();function x4(e,t){return b2e(e,async()=>{let n=y2e(e);if(!n.ok)throw q(`skills-lock`).error({lockPath:e,reason:n.reason,err:n.cause},`refusing to rewrite skills-lock.json because it could not be read — rewriting it would replace every import it records with this one`),Error(`Refusing to rewrite ${e}: ${n.reason}`);let r=n.lock,i=t(r)??r;await mJ(V(e),{recursive:!0}),await jk(e,`${JSON.stringify(i,null,2)}\n`,{fs:TJ})})}function S4(e,t){let n=Object.keys(e).join(`, `);return async(r,i)=>{let a=r.method===void 0?void 0:e[r.method];if(a){await a(r,i);return}X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}function x2e(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,parseFrontmatterDoc:o,resolveSkillDirForRead:s,skillRelPath:c,derivedDocumentIndex:l,contentFilter:u,bumpSkillsCatalogGen:d,settleSkillCatalog:f,invalidateSkillCatalog:m,scheduleDeferredIgnoreRebuild:h,recordDerivedDocumentBestEffort:g,getPrincipal:_,rejectReservedBuiltinSkill:v,contentDir:y,attributeOkArtifactWrite:b,scheduleOkArtifactFlush:x,signalChannel:S,checkSkillDocConflictGate:C,extractAgentIdentity:w,sessionManager:T,flushDiskAndDetectOutcome:E,respondStaleExternalWrite:D,respondPersistenceFailure:O,respondDiskDivergence:k,okArtifactKey:A,resolveSkillsRoot:ee,extractActorIdentityFromQuery:j,captureAndCloseDocuments:M,log:N,commitOkArtifactWrite:P,skillInstallBase:te,uninstallSkillFromHostDirs:ne,renameTrackedPathInGit:re,renamePathOnDisk:ie,localSkillHash:ae,shadowHeadSha:oe,artifactWriterId:se,checkLocalOpSecurity:ce,effectiveSkillRoot:le}=e;function ue(e,t){let n=e===`project`?i:r;if(!n)return`symlink`;try{return b4(H(n,...XF)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function de(e){let t=e===`project`?i:r;return t?H(t,...XF):null}function fe(e,t,n,r={}){let i=de(e);return i?x4(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function pe(e,t,n,r=n){let i=de(e),a=de(t);if(!i||!a)return!1;let o=b4(i).skills[n];if(!o)return!1;let s={...o};return t===`global`&&delete s.baselineRef,await x4(a,e=>({...e,skills:{...e.skills,[r]:s}})),await x4(i,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function me(e,t,n){let r=de(e);return r?x4(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function he(e,t){let n=W(e,t,`references`);if(!G(n))return[];let r=[],i=(e,t)=>{for(let n of Ds(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(W(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function ge(e,t,n){if(!l){q(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=K(n,`utf-8`)}catch(i){q(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=U(y,e).split(us).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),W(e,n,`SKILL.md`));for(let r of he(e,n))i(o(t,r),o(n,r),W(e,n,r));await l.recordDirectMutations(r)}async function _e(e,t){if(!l||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await l.recordDirectMutations(n)}let ve=Z(Ii,async(e,l)=>{try{let u=new URL(e.url??``,`http://localhost`),d=u.searchParams.get(`name`)??``;if(!t(d,l,`skill-get`))return;let f=n(u.searchParams.get(`scope`),l,`skill-get`);if(f===null)return;if(d1(d)){let e=f===`global`?r:i,t=e?a(e,d,f,u.searchParams.get(`host`)??void 0):null;if(t){let{frontmatter:e,body:n}=o(await Ks(t.skillMd,`utf-8`));Q(l,200,lee,{skill:{name:d,scope:f,path:t.relPath,frontmatter:{name:typeof e.name==`string`?e.name:d,description:typeof e.description==`string`?e.description:``},body:n,files:g2e(t.dir),managed:!0}},{handler:`skill-get`});return}}let p=u.searchParams.get(`host`)??void 0,m=s(f,d,p);if(m===null){X(l,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:p===void 0?`Skill "${d}" not found in ${f} scope.`:`No skill "${d}" (${f}) in ${p}.`});return}let h=W(m,`SKILL.md`),{frontmatter:g,body:_}=o(await Ks(h,`utf-8`));Q(l,200,lee,{skill:{name:d,scope:f,path:c(h,f),frontmatter:{name:typeof g.name==`string`?g.name:d,description:typeof g.description==`string`?g.description:``},body:_,files:g2e(m)}},{handler:`skill-get`})}catch(e){X(l,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function ye(e,t){!l||rX(e)||(u&&(d(),u.refreshInPlaceSkillDirs(),h()),g(e,t,`skill-put`))}let be=Z(Sre,async(e,n,i)=>{try{let e=C1(i,_);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!t(i.name,n,`skill-put`)||v(i.name,n,`skill-put`))return;let a=_0e({name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!a.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=i.scope===`project`?y:r,c=s(i.scope,i.name);if(c===null){let t=z2(o,i.scope);if(t===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let r=S2({skillsRoot:W(o,t),name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!r.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}i.scope===`project`&&(b(e,`${t}/${i.name}/SKILL`,`skill-create: ${t}/${i.name}/SKILL.md`),x(`skill-put`)),await ye(i.scope===`project`?`${t}/${i.name}/SKILL`:gr(`global`,i.name),a.content),S?.(`files`),Q(n,200,One,{path:`${t}/${i.name}/SKILL.md`,created:!0,warnings:r.warnings,warningCodes:r.warningCodes},{handler:`skill-put`});return}let l=U(o,c).split(us).join(`/`),u=`${l}/SKILL.md`,d=i.scope===`project`?`${l}/SKILL`:gr(i.scope,i.name);if(C(d,`skill-put`,n))return;let{agentId:f,agentName:p,colorSeed:m,clientName:h}=w(i),g=await T.getSession(d,f,{displayName:p,colorSeed:m,clientName:h});g.dc.document.transact(()=>{Zq(g.dc.document,a.content,`agent`)},g.origin);let ee=await E(d);if(ee?.kind===`failure`){O(n,ee.failure,`skill-put`);return}if(ee?.kind===`divergence`){k(n,`skill-put`);return}if(ee?.kind===`stale-external-write`){D(n,`skill-put`,d);return}i.scope===`project`&&(b(e,A(`skill`,``,i.name),`skill-edit: ${u}`),x(`skill-put`)),await ye(d,a.content),S?.(`files`),Q(n,200,One,{path:u,created:!1,warnings:a.warnings,warningCodes:a.warningCodes},{handler:`skill-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function xe(e,t){let n=e===`project`?y:r,i=(e===`project`?B2(y):V2(r)).find(e=>e.name===t);return i?_4({canonicalAbs:W(n,i.dir),canonicalHash:i.contentHash,name:t,cwd:n,targets:i.hosts.filter(e=>$r(e)),roots:o4(e)}):[]}let Se=Z(Ii,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams.get(`name`)??``;if(!t(a,r,`skill-delete`))return;let o=n(i.searchParams.get(`scope`),r,`skill-delete`);if(o===null)return;let s=i.searchParams.get(`host`)??void 0,{root:c,dirRel:l,realDir:u}=le(o,a,s),f=s===void 0?te(o):void 0,p=f===void 0?{state:`none`}:Z2(f,o,a),m=p.state===`record`&&p.record.sourceState!==`intact`&&p.record.retainedContentHash!==``&&u!==null?ke(u):void 0;if(s!==void 0&&u===null){X(r,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${a}" (${o}) in ${s}.`});return}let h=j(i,_);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await M(o===`project`?[...new Set([`${l}/SKILL`,gr(o,a)])]:[gr(o,a,s)],`deleted-upstream`),s===void 0&&xe(o,a);let g=E2({skillsRoot:c,name:a}),v=ee(o);if(s===void 0&&g.ok&&v!==c&&G(W(v,a,`SKILL.md`))){let e=E2({skillsRoot:v,name:a});e.ok||N.warn({name:a,scope:o,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!g.ok){let e=g.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:g.error.code,cause:Error(g.error.message)});return}g.existed&&(o===`project`&&(b(h,l,`skill-delete: ${l}`),d(),P(`skill-delete`)),S?.(`files`));let y=te(o),x=[];if(s===void 0&&y)try{await ne(y,a,o)}catch(t){N.error({requestId:lX(e),handler:`skill-delete`,name:a,scope:o,err:t},`[skill-delete] skill content removed, but install bookkeeping could not be updated`),x.push(`The skill was deleted, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(s===void 0){if(p.state===`record`&&p.record.sourceState!==`intact`){let t=p.record,n=t.retainedContentHash!==``&&m?.ok===!0&&t.retainedContentHash===m.hash,r=m!==void 0&&!m.ok&&m.kind!==`absent`,i=t.from===``?`an earlier move`:`a move of "${t.from}"`,s=t.retainedAt?` on ${t.retainedAt}`:``;(n||r)&&N.error({requestId:lX(e),handler:`skill-delete`,name:a,scope:o,from:t.from,retainedAt:t.retainedAt,sourceState:t.sourceState,verified:n,...r&&m.kind===`read-error`?{err:m.cause}:{}},n?`[skill-delete] deleted a copy this server retained when an earlier move failed to remove its source; the source was never verified unchanged, so files that only existed here may now be gone`:`[skill-delete] deleted a directory carrying an unverified retained-copy record; this server could not read that directory before removing it, so it could not confirm whether it was the copy an earlier failed move retained`),n?x.push(`A recovery copy was deleted: ${i} failed to remove its source${s}, and this server kept this copy in case it held files that failed removal had already deleted. That source was never verified unchanged. Check the other location before relying on this deletion.`):r&&x.push(`A directory this server could not read was deleted: ${i} failed to remove its source${s}, and this server has a record of keeping a copy under this name in case it held files that failed removal had already deleted. It could not read the directory before removing it, so it could not confirm whether that was the copy it kept. Check the other location before assuming nothing was lost.`)}await je(f,o,a,{requestId:lX(e),handler:`skill-delete`})}Q(r,200,ln,{existed:g.existed,path:g.path,...x.length>0?{warnings:x}:{}},{handler:`skill-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Ce=Z(jee,async(e,n,a)=>{try{let l=C1(a,_);if(l.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!t(a.fromName,n,`skill-move`)||!t(a.toName,n,`skill-move`)||v(a.toName,n,`skill-move`))return;let{root:u,dirRel:d}=le(a.scope,a.fromName),f=s(a.scope,a.toName);if(f!==null){let t=te(a.scope),r=t===void 0?{state:`none`}:Z2(t,a.scope,a.toName),i=ke(f),{verdict:o,detail:s}=Ae(le(a.scope,a.toName).dirRel,r,i);r.state===`record`&&o.kind===`plain-collision`&&await je(t,a.scope,a.toName,{requestId:lX(e),handler:`skill-move`}),X(n,409,`urn:ok:error:doc-already-exists`,`A skill named "${a.toName}" already exists.`,{handler:`skill-move`,detail:s??`Delete or rename it first; this move will not overwrite it.`,...!i.ok&&i.kind===`read-error`?{cause:i.cause}:r.state===`unreadable`&&r.cause!==void 0?{cause:r.cause}:{}});return}let p=te(a.scope),h=p?G2(p).skills[a.fromName]:void 0,g=a.scope===`project`?y:r,x=(a.scope===`project`?B2(y):V2(r)).find(e=>e.name===a.fromName),C=x?V(x.dir):null,w=C===null?[]:Object.entries(F2(g,a.scope)).filter(([,e])=>e===C).map(([e])=>e),T=[...new Set([...h?r4(h.hosts,a.scope):[],...x?r4(x.hosts,a.scope):[],...r4(w,a.scope)])];await M(a.scope===`project`?[...new Set([`${d}/SKILL`,gr(a.scope,a.fromName)])]:[gr(a.scope,a.fromName)],`renamed`),xe(a.scope,a.fromName);let E=await x0e({skillsRoot:u,fromName:a.fromName,toName:a.toName,relocate:async(e,t)=>{let n=await re(i,e,t);return n||ie(e,t),n}});if(!E.ok){if(E.error.code===`SKILL_NOT_FOUND`){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:E.error.message});return}if(E.error.code===`SKILL_EXISTS`){X(n,409,`urn:ok:error:doc-already-exists`,E.error.message,{handler:`skill-move`,detail:E.error.code});return}let e=E.error.code===`MOVE_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:E.error.code,cause:Error(E.error.message)});return}let D=null,O=W(u,a.toName,`SKILL.md`),k=``,ee=``;try{let e=o(K(O,`utf-8`));k=e.body,typeof e.frontmatter.description==`string`&&(ee=e.frontmatter.description)}catch{}let j=typeof a.body==`string`?a.body:k,ne=a.frontmatter===void 0?ee:a.frontmatter.description,ce=S2({skillsRoot:u,name:a.toName,body:j,frontmatter:{name:a.toName,description:ne}});ce.ok||(D=ce.error);let de=[];if(!D)try{de=v2e({base:a.scope===`project`?y:r,scope:a.scope,fromName:a.fromName,toName:a.toName})}catch(e){q(`skill-move`).warn({err:e,fromName:a.fromName,toName:a.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}a.scope===`project`&&!D&&(m(),ge(u,a.fromName,a.toName).then(()=>_e(de,a.toName)).catch(()=>{}));let pe=c(W(u,a.fromName),a.scope),he=c(W(u,a.toName),a.scope),ve=ae(u,a.toName),ye=[],be=(e,t)=>{N.error({err:e,fromName:a.fromName,toName:a.toName,scope:a.scope},`skill renamed, but its bookkeeping could not be updated`),ye.push(`The skill was renamed to "${a.toName}", but this server could not update its ${t} (${Me(e)}). A stale entry may remain until that file is repaired.`)};try{await fe(a.scope,a.fromName,a.toName,{localHash:ve})}catch(e){be(e,`import records`)}if(a.scope===`project`&&(b(l,A(`skill`,``,a.toName),`skill-rename: ${pe} -> ${he}`,[{from:pe,to:he}]),(async()=>{try{await P(`skill-move`);let e=await oe(se(l),he);e!==void 0&&await me(`project`,a.toName,{baselineRef:e})}catch(e){q(`skill-move`).warn({err:e,toName:a.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),p){try{await q2(p,a.fromName)}catch(e){be(e,`install records`)}v4(a.fromName,p,T,o4(a.scope));let e=W(u,a.toName);if(T.length>0){let t=f4(e,a.toName,p,T,ue(a.scope,a.toName),o4(a.scope));try{await K2(p,a.toName,{...h,scope:a.scope,hosts:t,scripts:h?.scripts??i4(e,a.toName).hasScripts,installedAt:h?.installedAt??new Date().toISOString()})}catch(e){be(e,`install records`)}}}if(S?.(`files`),D){let e=D.code===`WRITE_ERROR`;X(n,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${a.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:D.code,cause:Error(D.message)});return}Q(n,200,mte,{from:pe,to:he,committed:E.committed,...ye.length>0?{warnings:ye}:{}},{handler:`skill-move`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),we=Z(Ge,async(e,n,r)=>{let{name:i,home:a}=r;if(!t(i,n,`skill-edit-external`))return;let o;try{o=ks(a)}catch{X(n,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!Ns(o).isDirectory()||!G(W(o,`SKILL.md`))){X(n,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}E0e(i,o),Q(n,200,xt,{docName:Dre(i)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>ce(e,t,{handler:`skill-edit-external`})}),Te={retained:void 0,"plain-collision":void 0,"stray-occupant":void 0,"ledger-unreadable":`unreadable`,"occupant-unverifiable":`occupant-unverifiable`,"retained-slot-unverifiable":`occupant-unverifiable`,"occupant-unreadable":`occupant-unverifiable`},Ee=null;function De(){return Ee||=Uq().createCounter(`ok.skill_move_scope.outcome`,{description:"Count of cross-scope skill-move handler invocations by terminal outcome, one per invocation. Bounded labels: move_state ∈ SKILL_MOVE_STATE_CODES plus `success`; source_state ∈ SKILL_SOURCE_STATE_CODES plus `none`; retention_ledger ∈ SKILL_RETENTION_LEDGER_CODES plus `none`. Skill names, filesystem paths, droppedLocations, problem detail text, error messages and request IDs are never labels. Transport-level and schema-level rejections happen outside the handler and stay covered by ok.api.error."}),Ee}function Oe(e,t,n,r){De().add(1,{move_state:e,source_state:t??`none`,retention_ledger:n??`none`}),q(`skill-move-scope`)[r?.logLevel??((r?.status??200)>=500?`error`:`warn`)]({event:`skill-move-scope.outcome`,...r?.instance===void 0?{}:{instance:r.instance},...r?.requestId===void 0?{}:{requestId:r.requestId},handler:`skill-move-scope`,...r?.status===void 0?{}:{status:r.status},moveState:e,sourceState:t??null,retentionLedger:n??null,droppedLocationCount:r?.droppedLocationCount??0},r?.message??`cross-scope skill move did not complete`)}function ke(e){try{let t=oI(e);return t===null?G(e)?{ok:!1,kind:`no-manifest`,reason:`it has no readable SKILL.md`}:{ok:!1,kind:`absent`,reason:`it does not exist`}:{ok:!0,hash:t.contentHash}}catch(e){let t=e?.code;return{ok:!1,kind:`read-error`,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}}function Ae(e,t,n){let r=t.state===`record`?t.record:null,i=r!==null&&r.retainedContentHash!==``&&n.ok&&r.retainedContentHash===n.hash?r:null,a=r!==null&&r.from!==``?`a move of "${r.from}"`:`an earlier move`,o=r?.retainedAt?` on ${r.retainedAt}`:``;return i?.sourceState===`intact`?{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. That source was verified unchanged, so this copy is a redundant duplicate whose install records never transferred: remove it, then retry. This call wrote nothing.`}:i===null?t.state===`unreadable`?{verdict:{kind:`ledger-unreadable`},detail:`A directory already exists at ${e}, and this server could not read its retained-destination ledger (${t.reason}), so it cannot tell whether that directory is a copy an earlier failed move retained. Do NOT delete it before comparing it against the source. This call wrote nothing.`}:r!==null&&!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`retained-slot-unverifiable`},detail:`A directory already exists at ${e} with no readable SKILL.md, and this server has a record of retaining a copy under this name${o} when ${a} failed to remove the source. Nothing in it could be matched against that record, so verify it against the source before assuming it is that copy.`}:r!==null&&!n.ok?{verdict:{kind:`occupant-unverifiable`},detail:`A directory already exists at ${e}, and this server has a record of retaining a copy under that name${o} from ${a}, but it could not read that directory to confirm the copy is the one it retained (${n.reason}). Do NOT delete it before comparing it against the source. This call wrote nothing.`}:!n.ok&&n.kind===`read-error`?{verdict:{kind:`occupant-unreadable`},detail:`A directory exists at ${e} and this server could not read it to determine whether it is a skill (${n.reason}). Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`stray-occupant`},detail:`A directory exists at ${e} with no readable SKILL.md. Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:{verdict:{kind:`plain-collision`},detail:void 0}:{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. Do NOT delete it before reconciling it against the source: it may hold the only copy of files that failed removal already deleted. Reconcile the two locations, then remove whichever copy is redundant. This call wrote nothing.`}}async function je(e,t,n,r){if(e!==void 0)try{await Q0e(e,t,n)}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.retention-clear-failed`,scope:t,name:n,...r,err:e},`could not clear a retained-destination record — a later collision on this name may still report it as retained`)}}let Me=e=>e instanceof Error?e.message:String(e),Ne={"nothing-written":!1,"destination-removed":!0,"destination-stray":!0,"destination-retained":!0,"destination-retained-blocking":!1,"destination-unreadable":!0,"partially-applied":!0},Pe=Z(Kn,async(e,n,a)=>{let o;try{o=C1(a,_)}catch(t){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,detail:`Could not resolve who is making the request. Nothing was written.`,extensions:{moveState:`nothing-written`,droppedLocations:[]},cause:t}),Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}let c=f,l=!1,u=!1,d=[],m=(t,r,i,a)=>{let o=`urn:uuid:${tc()}`;Oe(a.moveState,a.sourceState,a.retentionLedger,{instance:o,requestId:lX(e),status:t,droppedLocationCount:d.length,...a.logLevel===void 0?{}:{logLevel:a.logLevel}}),(u||Ne[a.moveState])&&c(),X(n,t,r,i,{instance:o,handler:`skill-move-scope`,...a.detail===void 0?{}:{detail:a.detail},extensions:{moveState:a.moveState,droppedLocations:d,...a.sourceState===void 0?{}:{sourceState:a.sourceState},...a.retentionLedger===void 0?{}:{retentionLedger:a.retentionLedger}},...a.cause===void 0?{}:{cause:a.cause},...a.logLevel?{logLevel:a.logLevel}:{}})};try{if(o.kind===`invalid-summary`){m(400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{moveState:`nothing-written`});return}let{name:f,fromScope:h,toScope:g}=a,_=a.toName??f,v={moveState:`nothing-written`,droppedLocations:[]};if(!t(f,n,`skill-move-scope`,v)){Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}if(!t(_,n,`skill-move-scope`,v)){Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}if(d1(f)){m(400,`urn:ok:error:invalid-request`,`"${f}" is a built-in skill and always lives at its own scope.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(d1(_)){m(400,`urn:ok:error:invalid-request`,`"${_}" is a built-in skill name and cannot be used as a destination name.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(h===g){m(400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{moveState:`nothing-written`});return}if(g===`project`&&!i){m(400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{moveState:`nothing-written`,detail:`NO_PROJECT_ROOT`});return}let{root:x,dirRel:S,realDir:C}=le(h,f),w=W(x,f),T=(()=>{try{return ks(w)}catch{return w}})(),E=g===`project`?y:r,D=z2(E,g);if(D===null){m(400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{moveState:`nothing-written`,detail:`NO_USABLE_SKILL_HOME`});return}let O=W(E,D),k=W(O,_),A=U(E,k).split(us).join(`/`);if(C===null||!G(w)){m(404,`urn:ok:error:not-found`,`Skill not found.`,{moveState:`nothing-written`,detail:`Skill "${f}" not found in ${h} scope.`});return}if(W(C)===W(k)||G(k)&&ks(C)===ks(k)){m(409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{moveState:`nothing-written`,detail:`SAME_STORAGE`});return}if(s(g,_)!==null||G(k)){let t=te(g),n=t!==void 0&&G(k)?Z2(t,g,_):{state:`none`},r=ke(k),{verdict:i,detail:a}=Ae(A,n,r);n.state===`record`&&i.kind===`plain-collision`&&await je(t,g,_,{requestId:lX(e),handler:`skill-move-scope`,toDirRel:A});let o=Te[i.kind],s=i.kind===`retained`?{moveState:`destination-retained-blocking`,sourceState:i.record.sourceState}:{moveState:`nothing-written`,...o===void 0?{}:{retentionLedger:o}};m(409,`urn:ok:error:doc-already-exists`,`A ${g} skill named "${_}" already exists.`,{...s,detail:a??`Delete or rename it first; this move will not overwrite it.`,...!r.ok&&r.kind===`read-error`?{cause:r.cause}:n.state===`unreadable`&&n.cause!==void 0?{cause:n.cause}:{}});return}let ee=te(h),j=te(g),N=ee?G2(ee).skills[f]:void 0,re=h===`project`?y:r,ie=(h===`project`?B2(y):V2(r)).find(e=>e.name===f),ce=ie?V(ie.dir):null,de=ce===null?[]:Object.entries(F2(re,h)).filter(([,e])=>e===ce).map(([e])=>e),fe=[...new Set([...N?r4(N.hosts,h):[],...ie?r4(ie.hosts,h):[],...r4(de,h)])],he=e=>e.filter(e=>r4([e],g).length===0),ge=[...new Set([...he(N?.hosts??[]),...he(ie?.hosts??[])])].sort();if(u=!0,await M([...new Set([...h===`project`?[`${S}/SKILL`]:[],gr(h,f),gr(g,_)])],`renamed`),l=!0,_J(O,{recursive:!0}),yJ(T,k,{recursive:!0,dereference:!0}),_!==f){let e=(e,t,n,r)=>{let i=E2({skillsRoot:O,name:_});m(i.ok?e:500,i.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,i.ok?`Failed to rename the copied skill; destination copy removed.`:`Failed to rename the copied skill; destination cleanup failed.`,{moveState:i.ok?`destination-removed`:`destination-stray`,detail:i.ok?`Rename failed (${t}). The source "${h}:${f}" was not removed.`:`Rename failed (${t}); destination cleanup failed (${i.error.code}). The source "${h}:${f}" was not removed. A partial copy may remain at "${g}:${_}" (${A}). Inspect the destination before retrying.`,cause:i.ok?n:Error(i.error.message,{cause:n}),...r?{logLevel:r}:{}})};try{let t=oI(k);if(t===null){e(400,`UNREADABLE_SKILL`,Error(`UNREADABLE_SKILL`),`error`);return}let n=C2({skillDir:k,toName:_,skillMd:t.skillMd});if(!n.ok){if(n.stage===`patch`){let t=D0e(n.error);e(400,t,Error(t),`error`)}else e(500,`RENAME_FAILED`,n.cause);return}}catch(t){e(500,`RENAME_FAILED`,t);return}}if(!G(H(k,`SKILL.md`))){let e=E2({skillsRoot:O,name:_});m(500,`urn:ok:error:internal-server-error`,e.ok?`The copied skill is unreadable; destination copy removed.`:`The copied skill is unreadable; destination cleanup failed.`,{moveState:e.ok?`destination-removed`:`destination-stray`,detail:e.ok?`No readable SKILL.md at the destination copy (${A}); it was removed. The source "${h}:${f}" was not touched and is unchanged.`:`No readable SKILL.md at the destination copy (${A}); cleanup failed (${e.error.code}). The source "${h}:${f}" was not touched and is unchanged. A partial copy remains at "${g}:${_}". Inspect the destination before retrying.`,...e.ok?{}:{cause:Error(e.error.message)}});return}d=[...new Set(xe(h,f))].sort();let _e=E2({skillsRoot:x,name:f});if(_e.ok&&T!==w){let e=(()=>{try{return ks(re)}catch{return re}})(),t=U(e,T);t!==``&&!t.startsWith(`..`)&&!os(t)&&CJ(T,{recursive:!0,force:!0})}if(!_e.ok){let t,n=(()=>{if(!ie)return`unknown`;try{let e=oI(w);return e&&e.contentHash===ie.contentHash?`intact`:`lossy`}catch(e){return t=e,`unknown`}})(),r=!1,i=ke(k);if(j!==void 0){let t=i.ok?void 0:Error(`the destination copy could not be hashed (${i.reason})`,{cause:i.kind===`read-error`?i.cause:void 0});if(i.ok)try{await Z0e(j,g,_,{retainedAt:new Date().toISOString(),from:`${h}:${f}`,to:`${g}:${_}`,sourceState:n,reason:_e.error.code,retainedContentHash:i.hash}),r=!0}catch(e){t=e}r||q(`skill-move-scope`).error({event:`skill-move-scope.retention-record-failed`,requestId:lX(e),handler:`skill-move-scope`,toScope:g,toDirRel:A,sourceState:n,err:t},`could not record the retained destination copy — a retry will report an ordinary name collision instead of a retained copy`)}let a=r?``:i.ok?` This server could not record the retention, so a retry will not recognise ${A} as a copy it retained and will report an ordinary name collision instead.`:` This server could not read the destination copy at ${A} to confirm it is intact (${i.reason}), so do not rely on it for recovery until you have inspected it yourself. It was not recorded as a retained copy either, so a retry will report an ordinary name collision instead.`;m(500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); destination copy retained for recovery.`,{moveState:`destination-retained`,sourceState:n,detail:n===`intact`?`Source removal failed (${_e.error.code}) without deleting anything. The source "${h}:${f}" is unchanged at its original scope, so no files were lost. The destination copy "${g}:${_}" at ${A} is a duplicate whose install records have not transferred; remove it before retrying.${a}`:n===`lossy`?`Source removal failed (${_e.error.code}). The source "${h}:${f}" may be partially removed. The destination copy "${g}:${_}" remains at ${A}; its install records have not transferred. Inspect both locations before retrying, and recover missing source files from the retained copy.${a}`:`Source removal failed (${_e.error.code}). The source "${h}:${f}" could not be verified against a known content hash, so whether any files were lost is unknown. The destination copy "${g}:${_}" remains at ${A}; its install records have not transferred. Compare both locations before removing either.${a}`,cause:t?Error(_e.error.message,{cause:t}):Error(_e.error.message)});return}await je(j,g,_,{requestId:lX(e),handler:`skill-move-scope`,toDirRel:A});let ve=[],ye=!1;try{if(ye=await pe(h,g,f,_),ee&&await ne(ee,f,h,ie?{purge:{contentHash:ie.contentHash}}:{}),ee&&await i2e(ee,f),j&&fe.length>0){let e=f4(k,_,j,fe,ue(g,_),o4(g));await K2(j,_,{...N,scope:g,hosts:e,scripts:N?.scripts??i4(k,_).hasScripts,installedAt:N?.installedAt??new Date().toISOString()})}ye&&await me(g,_,{localHash:ae(O,_)})}catch(t){q(`skill-move-scope`).error({err:t,name:f,toName:_,fromScope:h,toScope:g,requestId:lX(e)},`skill moved across scopes, but its bookkeeping could not be updated`),ve.push(`The skill moved to ${g}, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(!G(H(k,`SKILL.md`))){m(500,`urn:ok:error:internal-server-error`,`The source was removed, but the destination skill is unreadable.`,{moveState:`destination-unreadable`,detail:`Inspect "${g}:${_}" at ${A} before retrying. Restore the skill from a backup, or check the project Timeline / shadow-repo history for an earlier version if available.`});return}if(h===`project`||g===`project`){b(o,h===`project`?S:U(y,k).split(us).join(`/`),`skill-move-scope: ${h} -> ${g} ${f}${_===f?``:` -> ${_}`}`);let t=U(y,k).split(us).join(`/`),n=!!ye&&g===`project`,r=lX(e);(async()=>{let e=await P(`skill-move-scope`);if(n){if(e!==`flushed`){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,flush:e},`the deferred shadow flush did not complete, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}try{let n=await oe(se(o),t);if(n===void 0){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,flush:e},`no shadow head was readable after the flush, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}await me(g,_,{baselineRef:n})}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.baseline-update-failed`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,err:e},`could not record the Revert baseline for the moved skill, so this move did not establish or update its baseline; any baseline an earlier write recorded is unchanged`)}}})()}c(),Oe(`success`,void 0,void 0,{requestId:lX(e),status:200,droppedLocationCount:ge.length,logLevel:`debug`,message:`cross-scope skill move completed`}),Q(n,200,p,{scope:g,path:A,droppedLocations:ge,...ve.length>0?{warnings:ve}:{}},{handler:`skill-move-scope`})}catch(e){m(500,`urn:ok:error:internal-server-error`,l?`Failed to move skill across scopes; the move may be partially applied.`:`Failed to move skill across scopes; nothing was written.`,{moveState:l?`partially-applied`:`nothing-written`,detail:l?`Inspect the source "${a.fromScope}:${a.name}" and destination "${a.toScope}:${a.toName??a.name}" before retrying. Preserve any remaining copies and recover missing files from a backup or available project Timeline / shadow-repo history.`:`The failure happened before any file was copied, so no files were copied or removed for "${a.fromScope}:${a.name}" or "${a.toScope}:${a.toName??a.name}". Retrying is safe once the underlying error clears.`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),Fe=Z(vn,async(e,n,i)=>{let a=f,o=!1,c=!1,l=!1;try{let e=C1(i,_);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!t(i.name,n,`skill-duplicate`)||!t(i.toName,n,`skill-duplicate`)||v(i.toName,n,`skill-duplicate`))return;let u=s(i.scope,i.name);if(u===null||!G(H(u,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let d=i.scope===`project`?y:r,f=z2(d,i.scope);if(f===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let p=W(d,f),m=W(p,i.toName);if(s(i.scope,i.toName)!==null||G(m)){X(n,409,`urn:ok:error:doc-already-exists`,`A ${i.scope} skill named "${i.toName}" already exists.`,{handler:`skill-duplicate`});return}let h=oI(u);if(!h){X(n,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}let g=U(d,m).split(us).join(`/`);o=!0,_J(p,{recursive:!0}),c=!0,yJ(u,m,{recursive:!0,dereference:!0}),l=!0;let x=(e,t,r,o)=>{let s=E2({skillsRoot:p,name:i.toName});a(),X(n,s.ok?e:500,s.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,s.ok?`Failed to write duplicated skill; destination copy removed.`:`Failed to write duplicated skill; destination cleanup failed.`,{handler:`skill-duplicate`,detail:s.ok?`Duplicate failed (${t}). The source "${i.scope}:${i.name}" was not touched.`:`Duplicate failed (${t}); destination cleanup failed (${s.error.code}). The source "${i.scope}:${i.name}" was not touched. A partial copy may remain at "${i.scope}:${i.toName}" (${g}). Inspect the destination before retrying.`,cause:s.ok?r:Error(s.error.message,{cause:r}),...o?{logLevel:o}:{}})},S=C2({skillDir:m,toName:i.toName,skillMd:h.skillMd});if(!S.ok){if(S.stage===`patch`){let e=D0e(S.error);x(400,e,Error(e),`error`)}else x(500,`WRITE_FAILED`,S.cause);return}if(i.scope===`project`){let t=U(y,m).split(us).join(`/`);b(e,A(`skill`,``,i.toName),`skill-duplicate: ${i.name} -> ${t}`),P(`skill-duplicate`)}a(),Q(n,200,In,{name:i.toName},{handler:`skill-duplicate`})}catch(e){o&&a(),X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,...l?{detail:`A complete copy was created at "${i.scope}:${i.toName}" and was left in place. Inspect it before retrying.`}:c?{detail:`A copy of "${i.scope}:${i.name}" was started at "${i.scope}:${i.toName}" and may be incomplete; it was left in place, and its SKILL.md may still carry the source's name. Inspect or remove it before retrying.`}:{},cause:e})}},{handler:`skill-duplicate`,method:`POST`});return L1({"/api/skill":S4({GET:ve,PUT:be,POST:Ce,DELETE:Se},{handler:`skill`}),"/api/skill/edit-external":we,"/api/skill/duplicate":Fe,"/api/skill/move-scope":Pe},{mutating:[`/api/skill`,`/api/skill/edit-external`,`/api/skill/duplicate`,`/api/skill/move-scope`]})}function S2e(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,resolveSkillDirForRead:o,resolveSkillsRoot:s,getPrincipal:c,rejectReservedBuiltinSkill:l,contentDir:u,checkSkillDocConflictGate:d,extractAgentIdentity:f,sessionManager:p,flushDiskAndDetectOutcome:m,respondStaleExternalWrite:h,respondPersistenceFailure:g,respondDiskDivergence:_,attributeOkArtifactWrite:v,okArtifactKey:y,commitOkArtifactWrite:b,signalChannel:x,extractActorIdentityFromQuery:S,captureAndCloseDocuments:C,derivedDocumentIndex:w,log:T,recordDerivedMutationsBestEffort:E}=e;function D(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function O(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function k(e,t){let n=W(e,t),r=U(u,e).split(us).join(`/`),i;try{i=Ds(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(us).join(`/`).replace(/\.md$/i,``)}`)}function A(e,t){let n=t.replace(/\.md$/i,``);return`${Ure(e).replace(/\/SKILL$/,``)}/${n}`}return L1({"/api/skill-file":S4({GET:Z(Ii,async(e,c)=>{try{let l=new URL(e.url??``,`http://localhost`),u=l.searchParams.get(`name`)??``;if(!t(u,c,`skill-file-get`))return;let d=n(l.searchParams.get(`scope`),c,`skill-file-get`);if(d===null)return;let f=l.searchParams.get(`path`)??``,p=d1(u)?d===`global`?r:i:void 0,m=l.searchParams.get(`host`)??void 0,h=p?a(p,u,d,m):null;if(f===``||f.includes(`\0`)){X(c,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let g=(h&&f===`SKILL.md`?`reference`:D(f))??`reference`,_=m,v=p?h?.dir??null:o(d,u,_);if(v===null&&_!==void 0){X(c,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${u}" (${d}) in ${_}.`});return}let y=v??W(s(d),u),b=W(y,f);if(b!==y&&!b.startsWith(`${y}${us}`)){X(c,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let x=b,S=f;if(!G(x)){let e=f.match(/^(.*)\.(?:md|mdx)$/),t=e?Qr.map(t=>`${e[1]}${t}`).find(e=>e!==f&&G(W(y,e))):void 0;if(t===void 0){X(c,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${f} not found in skill "${u}" (${d}).`});return}S=t,x=W(y,t)}let C=await Ks(x);if(C.includes(0)){X(c,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}Q(c,200,ir,{path:S.replace(/\\/g,`/`),kind:g,text:C.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(gie,async(e,n,i)=>{try{let e=C1(i,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!t(i.name,n,`skill-file-put`)||l(i.name,n,`skill-file-put`))return;let a=D(i.path);if(a===null){X(n,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(i.content,`utf-8`)>262144){X(n,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let s=o(i.scope,i.name);if(s===null||!G(H(s,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${i.name}" before adding bundle files.`});return}let S=i.scope===`project`?u:r,C=U(S,s).split(us).join(`/`),w=i.path.replace(/\\/g,`/`),T=O(i.scope,a,w),E;if(T){let e=`${C}/${w.replace(/\.mdx?$/i,``)}`;if(d(e,`skill-file-put`,n))return;if(E=!G(W(s,w)),E&&v0e(s)>=50){X(n,400,`urn:ok:error:invalid-request`,`Skill "${i.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:t,agentName:r,colorSeed:a,clientName:o}=f(i),c=await p.getSession(e,t,{displayName:r,colorSeed:a,clientName:o});c.dc.document.transact(()=>{Zq(c.dc.document,i.content,`agent`)},c.origin);let l=await m(e);if(l?.kind===`failure`){g(n,l.failure,`skill-file-put`);return}if(l?.kind===`divergence`){_(n,`skill-file-put`);return}if(l?.kind===`stale-external-write`){h(n,`skill-file-put`,e);return}}else{let e=T2({skillsRoot:V(s),name:i.name,relPath:w,content:i.content});if(!e.ok){let t=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;X(n,t,t===500?`urn:ok:error:internal-server-error`:t===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,t===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}E=e.created}i.scope===`project`&&(v(e,y(`skill`,``,i.name),`${E?`skill-file-create`:`skill-file-edit`}: ${C}/${w}`),b(`skill-file-put`)),x?.(`files`),Q(n,200,te,{path:w,created:E,kind:a,content:T},{handler:`skill-file-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:Z(Ii,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams,d=a.get(`name`)??``;if(!t(d,r,`skill-file-delete`)||l(d,r,`skill-file-delete`))return;let f=n(a.get(`scope`),r,`skill-file-delete`);if(f===null)return;let p=(a.get(`path`)??``).replace(/\\/g,`/`),m=D(p);if(m===null){X(r,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let h=S(i,c);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let g=o(f,d),_=g===null?s(f):V(g),w=W(g??H(_,d),p);if(G(w)&&O(f,m,p)){let e=p.replace(/\.md$/i,``),t=g===null?A(d,p):`${U(u,g).split(us).join(`/`)}/${e}`;await C([t],`deleted-upstream`)}else if(f===`project`&&g!==null&&G(w)&&Ns(w).isDirectory()){let e=k(g,p);e.length>0&&await C(e,`deleted-upstream`)}let T=b0e({skillsRoot:_,name:d,relPath:p});if(!T.ok){let e=T.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:T.error.code,cause:Error(T.error.message)});return}T.existed&&f===`project`&&(v(h,y(`skill`,``,d),`skill-file-delete: ${g===null?`${d}/${p}`:`${U(u,g).split(us).join(`/`)}/${p}`}`),b(`skill-file-delete`)),T.existed&&x?.(`files`),Q(r,200,$t,{path:p,existed:T.existed,kind:m},{handler:`skill-file-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),"/api/skill-file/rename":Z(Vr,async(e,n,r)=>{try{if(!t(r.name,n,`skill-file-rename`)||l(r.name,n,`skill-file-rename`))return;let e=C1(r,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let i=r.from.replace(/\\/g,`/`),a=r.to.replace(/\\/g,`/`),s=D(i),f=D(a);if(s===null||f===null){X(n,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:s===null?i:a});return}let p=o(r.scope,r.name);if(p===null){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let m=V(p),h=O(r.scope,s,i),g=O(r.scope,f,a),_=U(u,p).split(us).join(`/`),S=h?`${_}/${i.replace(/\.md$/i,``)}`:null,T=g?`${_}/${a.replace(/\.md$/i,``)}`:null;if(S!==null&&d(S,`skill-file-rename`,n))return;if(S!==null)await C([S],`deleted-upstream`);else if(r.scope===`project`){let e=W(p,i);if(G(e)&&Ns(e).isDirectory()){let e=k(p,i);e.length>0&&await C(e,`deleted-upstream`)}}let A=y0e({skillsRoot:m,name:r.name,relPath:i,toRelPath:a});if(!A.ok){let e=A.error.code===`RENAME_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,A.error.message,{handler:`skill-file-rename`,detail:A.error.code});return}if(w){let e=[];if(S!==null&&T!==null)try{e.push({kind:`rename`,oldDocumentName:S,newDocumentName:T,markdown:K(W(m,r.name,a),`utf-8`)})}catch{e.push({kind:`delete`,documentName:S})}else if(S!==null)e.push({kind:`delete`,documentName:S});else if(T!==null)try{e.push({kind:`upsert`,documentName:T,markdown:K(W(m,r.name,a),`utf-8`)})}catch{}await E(e,`skill-file-rename`)}r.scope===`project`&&(v(e,y(`skill`,``,r.name),`skill-file-rename: ${r.name}/${i} -> ${a}`),b(`skill-file-rename`)),x?.(`files`),Q(n,200,dt,{from:i,to:a,...S===null?{}:{fromDocName:S},...T===null?{}:{toDocName:T}},{handler:`skill-file-rename`})}catch(e){T.error({err:e},`[skill-file-rename] failed`),n.headersSent||X(n,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`})},{mutating:[`/api/skill-file`,`/api/skill-file/rename`]})}function C2e(e,t){return(0,pke.default)({headers:e.headers,defParamCharset:`utf8`,limits:t})}function w2e(e){return e.kind===`git`&&!P1(e.url)}function C4(e,t,n){return t.kind===`git`&&w2e(t)?(X(e,400,`urn:ok:error:url-not-allowed`,`Git URL protocol is not allowed.`,{handler:n,cause:Error(`url=${t.url}`)}),!0):!1}function T2e(e){let{projectDir:t,getPrincipal:n,skillImportService:r,bumpSkillsCatalogGen:i,contentFilter:a,scheduleDeferredIgnoreRebuild:o,signalChannel:s,parseSkillScope:c}=e;function l(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}function u(e,t){if(t.ok){Q(e,200,Ht,t.body,{handler:`skill-import`});return}X(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let d=Z(et,async(e,c,d)=>{let f=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=C1(d,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let p=d.scope,m=null,h,g,_,v,y=d.source;{let e=d.source;try{let t=await dI(e,d.skill),n=t?.source??e;y=n;let r=d.skill??t?.skill,i=t?.spec??qF(n);if(!i){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(C4(c,i,`skill-import`))return;let a=await YF(i);f=a.cleanup,g=a.ref;let o=sI(a.dir);if(o.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let s=o[0];if(r){let e=o.find(e=>e.name===r)??o.find(e=>iI(e.dir)?.name===r)??o.find(e=>e.name===Ur[r]);if(!e){X(c,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${r}" not among: ${o.map(e=>e.name).join(`, `)}.`});return}s=e}else if(o.length>1){X(c,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:o.map(e=>e.name).join(`, `)});return}m=s.dir,v=s.name,h=e,_=t?.publisher??l(n)}catch(e){if(e instanceof zF){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!m){X(c,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let b=await r.runSkillImport({acquiredDir:m,scope:p,sourceLabel:h,ref:g,publisher:_,upstreamSkill:v,actor:e,skipProjection:d.install===!1});b.ok&&(d.marketplace===!0||aa(y))&&_2({source:y,skills:[b.body.name]},l2()),i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),u(c,b)}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{f()}},{handler:`skill-import`,method:`POST`}),f=Z(Lre,async(e,c,u)=>{let d=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=C1(u,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let f=u.source,p=null,m=null,h=[],g,_,v=f;try{let e=await dI(f,u.skills[0]),t=e?.source??f;v=t;let n=e?.spec??qF(t);if(!n){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(C4(c,n,`skills-import-bulk`))return;if(_=e?.publisher??l(t),n.kind===`well-known`)p=n,m=await GF(n.origin);else{let e=await YF(n);d=e.cleanup,g=e.ref,h=sI(e.dir)}}catch(e){if(e instanceof zF){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(p===null&&h.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let y=[];for(let t of new Set(u.skills)){let n,i,a=()=>{};if(p!==null)try{let e=await YF({...p,skill:t},m?{index:m}:{});n=e.dir,a=e.cleanup,i=t}catch(e){y.push({requested:t,status:e instanceof zF?`not-found`:`failed`,warnings:[],warningCodes:[],...e instanceof zF?{}:{error:String(e)}});continue}else{let e=h.find(e=>e.name===t)??h.find(e=>oI(e.dir)?.name===t)??h.find(e=>e.name===Ur[t]);if(!e){y.push({requested:t,status:`not-found`,warnings:[],warningCodes:[]});continue}n=e.dir,i=e.name}try{let a=await r.runSkillImport({acquiredDir:n,scope:u.scope,sourceLabel:f,ref:g,publisher:_,upstreamSkill:i,actor:e,skipProjection:u.install===!1});if(!a.ok){q(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:a.detail??a.title});continue}y.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings,warningCodes:a.body.warningCodes})}catch(e){q(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:e instanceof Error?e.message:String(e)})}finally{a()}}if(u.marketplace===!0||aa(v)){let e=y.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&_2({source:v,skills:e},l2())}i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),Q(c,200,oie,{results:y,imported:y.filter(e=>e.status===`imported`).length,alreadyImported:y.filter(e=>e.status===`already-imported`).length,failed:y.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{d()}},{handler:`skills-import-bulk`,method:`POST`}),p=8388608,m=33554432;function h(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=W(e,n);return r!==e&&!r.startsWith(e+us)?null:r}function g(e){return new Promise((t,n)=>{let r;try{r=C2e(e,{files:200,fields:10,fieldSize:2048,fileSize:p})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>m){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function _(e,t){return new Promise((n,r)=>{(0,fke.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=h(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){_J(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>p){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>m){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{_J(V(n),{recursive:!0}),hJ(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function v(e,i){let a=Cs(H(Vs(),`ok-skill-upload-`)),o=()=>{try{CJ(a,{recursive:!0,force:!0})}catch{}};try{if(!t){X(i,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){X(i,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let o=new URL(e.url??``,`http://localhost`),s=c(o.searchParams.get(`scope`),i,`skill-upload`);if(!s)return;let l=e=>o.searchParams.get(e)??void 0,d=C1({agentId:l(`agentId`),agentName:l(`agentName`),colorSeed:l(`colorSeed`),clientName:l(`clientName`),summary:l(`summary`)},n);if(d.kind===`invalid-summary`){X(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let f;try{f=await g(e)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(f.length===0){X(i,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let p=f.length===1?f[0]:null,m=p&&/\.(zip|skill)$/i.test(p.relPath)?p.relPath:null;if(p&&m)try{await _(p.data,a)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of f){let t=h(a,e.relPath);if(!t){X(i,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}_J(V(t),{recursive:!0}),hJ(t,e.data)}let v=sI(a);if(v.length===0){X(i,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(v.length>1){X(i,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:v.map(e=>e.name).join(`, `)});return}let y=v[0];u(i,await r.runSkillImport({acquiredDir:y.dir,scope:s,sourceLabel:`upload:${m??y.name}`,upstreamSkill:y.name,actor:d}))}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{o()}}return L1({"/api/skill/import":d,"/api/skills/import-bulk":f,"/api/skill-upload":v},{mutating:[`/api/skill/import`,`/api/skills/import-bulk`,`/api/skill-upload`]})}function E2e(e){let{resolveSkillsRoot:t,validateSkillName:n,projectDir:r,skillInstallBase:i,contentDir:a,skillsHome:o,shippedBundleSkillMd:s,flushDiskAndDetectOutcome:c,respondStaleExternalWrite:l,respondPersistenceFailure:u,respondDiskDivergence:d,skillInstallOps:f,skillPlacementOps:p,signalChannel:m,bumpSkillsCatalogGen:h,contentFilter:g,scheduleDeferredIgnoreRebuild:_,effectiveInstallMode:v,log:y}=e;return L1({"/api/skill/install":Z(nre,async(e,b,x)=>{try{let e=t(x.scope);if(!n(x.name,b,`skill-install`))return;if(x.scope===`project`&&!r){X(b,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let S=i(x.scope),C=W(e,x.name),w=x.scope===`project`?a:o,T=(x.scope===`project`?B2(a):V2(o)).find(e=>e.name===x.name),E=d1(x.name)?s(x.name,x.scope):null,D=T?W(w,T.dir):G(C)||E===null?C:V(E);if(!G(D)){X(b,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${x.name}" not found in ${x.scope} scope — create it with write({ skill }) first.`});return}let O=x.scope===`project`?`${U(w,D).split(us).join(`/`)}/SKILL`:gr(x.scope,x.name),k=await c(O);if(k?.kind===`failure`){u(b,k.failure,`skill-install`);return}if(k?.kind===`divergence`){d(b,`skill-install`);return}if(k?.kind===`stale-external-write`){l(b,`skill-install`,O);return}let A=i4(D,x.name,{allowReservedName:d1(x.name)});if(!A.ok){X(b,400,`urn:ok:error:invalid-request`,`Skill "${x.name}" cannot be installed: ${A.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(x.fork!==void 0){if(!T){X(b,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=f.resolveFork({scope:x.scope,name:x.name,fork:x.fork,inPlaceEntry:T});if(!e.ok)switch(e.kind){case`unknown-editor`:X(b,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:X(b,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:X(b,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:X(b,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:X(b,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T.hosts.filter($r),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let ee=x.setSource??x.source,j=x.linkMode??(x.mode===void 0?void 0:x.mode===`link`),M=x.targets,N=[],P=[];if(x.add!==void 0||x.remove!==void 0){if(!T){X(b,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await f.applyAddRemove({scope:x.scope,name:x.name,inPlaceEntry:T,...x.add===void 0?{}:{add:x.add},...x.remove===void 0?{}:{remove:x.remove}});if(!e.ok){e.kind===`remove-source`?X(b,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):X(b,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}M=e.targets.filter($r),N.push(...e.rootAdds),P.push(...e.rootRemoves)}if(ee&&!T){let e=await f.promoteStoreBackedSource({scope:x.scope,name:x.name,base:S,skillDir:D,newSource:ee});if(!e.ok){X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(x.place){let e=x.scope===`project`?r:o;if(!e){X(b,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await p.place({placeBase:e,name:x.name,rawDir:x.place.dir,skillDir:D,mode:x.place.mode});if(!t.ok){t.kind===`invalid-path`?X(b,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):X(b,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in t||m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,warnings:[],warningCodes:[],placedAt:t.placedAt},{handler:`skill-install`});return}if(x.unplace){let e=x.scope===`project`?r:o;if(!e){X(b,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await p.unplace({placeBase:e,name:x.name,rawPath:x.unplace.path,skillDir:D});if(!t.ok)switch(t.kind){case`not-recorded`:X(b,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:t.path});return;case`unsafe-path`:X(b,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:X(b,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:t.path});return;case`canonical-dir`:X(b,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:t.path});return;default:throw Error(`Unhandled unplace outcome: ${String(t.kind)}`)}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(x.convert){if(!T){X(b,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:t}=x.convert,n=x.scope===`project`?r:o,i=await p.convert({ledgerBase:n??S,scope:x.scope,name:x.name,target:e,mode:t,skillDir:D,canonicalHash:T.contentHash});if(!i.ok)switch(i.kind){case`invalid-location`:X(b,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:X(b,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:X(b,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:X(b,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(i.kind)}`)}m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:[...T.hosts],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let te=x.scope===`global`?M===void 0?y2(o).map(e=>e.editorId):$n.filter(e=>M?.some(t=>t===e)):M===void 0?a4(S):Mn.filter(e=>M?.some(t=>t===e)),ne=[],re=[];if(te.length===0&&M===void 0&&(ne.push(x.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),re.push(`no-targets`)),A.hasScripts&&(ne.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),re.push(`scripts-present`)),A.warnings.length>0&&(ne.push(A.warnings[0]),re.push(`no-description`)),T){let e=T.dir.split(`/`).slice(0,-1).join(`/`),t=(M===void 0?x.scope===`global`&&G(H(o,`.agents`)):M.includes(`agents`))?[...te,`agents`]:[...te],n=x.scope===`project`?r:o,i=j===void 0?v(x.scope,x.name,T):j?`link`:`copy`;if(ee){let e=await f.promoteInPlaceSource({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,newSource:ee});if(!e.ok){e.kind===`invalid-target`?X(b,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let a=await f.fanOutInPlace({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,canonicalRootRel:e,inPlaceTargets:t,setExact:M!==void 0,installMode:i,...j===void 0?{}:{linkModeReq:j},rootAdds:N,rootRemoves:P});if(!a.ok){X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:a.reason});return}ne.push(...a.warnings),re.push(...a.warningCodes),m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:a.hosts,scripts:A.hasScripts,warnings:ne,warningCodes:re,...a.sourceMovedTo===void 0?{}:{sourceMovedTo:a.sourceMovedTo}},{handler:`skill-install`});return}let ie=r4(G2(S).skills[x.name]?.hosts??[],x.scope).filter(e=>!te.includes(e));ie.length>0&&v4(x.name,S,ie,o4(x.scope));let ae=H(S,...XF),oe=G(ae)?K(ae,`utf-8`):null,se=oe===null?null:QF(oe);oe!==null&&se===null&&y.warn({skill:x.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let ce=se?.skills[x.name]!==void 0,le=j===void 0?ce?`copy`:`symlink`:j?`symlink`:`copy`,ue=f4(D,x.name,S,te,le,o4(x.scope));ue.length===0?await q2(S,x.name):await K2(S,x.name,{hosts:ue,scope:x.scope,scripts:A.hasScripts,installedAt:new Date().toISOString(),projection:le}),m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:ue,scripts:A.hasScripts,warnings:ne,warningCodes:re},{handler:`skill-install`})}catch(e){X(b,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`})},{mutating:[`/api/skill/install`]})}const D2e=[`.ok`,`local`,`plugin-skill-baselines.json`];function O2e(e){return H(e,...D2e)}function k2e(e){try{let t=O2e(e);if(!G(t))return{};let n=JSON.parse(K(t,`utf-8`));if(typeof n!=`object`||!n)return{};let r=Object.create(null);for(let[e,t]of Object.entries(n))typeof t==`object`&&t&&typeof t.local==`string`&&typeof t.upstream==`string`&&(r[e]={local:t.local,upstream:t.upstream});return r}catch{return{}}}function A2e(e,t,n){return e===void 0||e.upstream!==n?{modified:!1,next:{local:t,upstream:n}}:{modified:t!==e.local,next:e}}function j2e(e){let t=k2e(e),n=!1;return{isModified(e,r,i,a){let o=`${e}:${r}`,{modified:s,next:c}=A2e(t[o],i,a),l=t[o];return(l===void 0||l.local!==c.local||l.upstream!==c.upstream)&&(t[o]=c,n=!0),s},flush(){if(n){n=!1;try{_J(H(e,`.ok`,`local`),{recursive:!0}),hJ(O2e(e),`${JSON.stringify(t,null,2)}\n`)}catch{}}}}}function M2e(e){let{contentDir:t,projectDir:n,skillsHome:r,contentFilter:i,catalogCache:a,resolveSkillsRoot:o,resolveSkillsList:s,skillOriginFor:c,localSkillHash:l,effectiveInstallMode:u,pluginSelfIdentity:d,synthBuiltinLockEntry:f,synthPluginLockEntry:p,pluginUpstreamHash:m,builtinSkillListEntry:h,indexedSkillContentPath:g,healUnservableSkillAdmission:_}=e,v=l1.project,y={lastKey:null};return L1({"/api/skills":Z(Ii,z1(async(e,b)=>{let x=(i?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(n?a0e(n).join(`,`):``)+``+y2(r).map(e=>e.editorId).join(`,`)+``+V2(r).map(e=>e.dir).sort().join(`,`),S=a.readList(x);if(S!==null){Q(b,200,di,S.body,{handler:`skills-list`});return}let C=o(`project`),w=s(C,`project`),T=s(o(`global`),`global`),E=n?a0e(n):[],D=y2(r).map(e=>e.editorId),O=n?R2(n,`project`,qi,r):!1,k=R2(r,`global`,qi,r),A=n?G2(n).skills:{},ee=G2(r).skills,j=n?QF(G(H(n,...XF))?K(H(n,...XF),`utf-8`):``)??null:null,M=c,N=(e,t,n)=>e.skills.map(e=>{let r=t[e.name]?.hosts??[],i=n?j?.skills[e.name]:void 0,a=i?M(i):void 0,o=i?.localHash!==void 0&&l(C,e.name)!==i.localHash,s=i?.baselineRef!==void 0;return{...e,installed:r.length>0,hosts:r,...a?{origin:a}:{},...o?{modified:!0}:{},...s?{revertable:!0}:{}}}),P=n?e4(n):{},te=(e,t,n)=>{let r=[];for(let i of t??[]){let t=W(e,i.path);if(n!==void 0&&t===W(n))continue;let a=!1;try{a=xs(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(ks(t)===ks(n))continue}catch{}r.push(i.path)}}return{drift:r}},ne=n?F2(t,`project`):{},re=M0e(ne,`project`),ie=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),ae=kw(n??t),oe=j2e(t),se=L2(`project`),ce=L2(`global`),le=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),ue=new Set,de=ZOe(t),fe=e=>{let t=$Oe(de,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},pe=n?B2(t).map(e=>{let r=!ue.has(e.name);ue.add(e.name);let i=W(t,e.dir),a=r?d(e.name,ae,i)??fe(i):null,o=r&&a===null?j?.skills[e.name]??f(t,e.name,`project`)??p(e.name,ae,i):void 0,s=o?M(o):void 0,c=o?.localHash===void 0?(()=>{if(!o||!r)return!1;let t=m(e.name,ae);return t!==null&&oe.isModified(`project`,e.name,e.contentHash,t)})():e.contentHash!==o.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:W(t,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:E,hubOffered:O,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ne).length>0?{hostAliases:ne}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...a===null?{}:{plugin:a},...(()=>{let t=le(r?P[e.name]:void 0,re).filter(e=>!ie(e.path,se));return t.length?{customPlacements:t.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let i=te(n,le(r?P[e.name]:void 0,re),W(t,e.dir));return i.drift.length>0?{driftPaths:i.drift}:{}})(),...u(`project`,e.name,e)===`link`?{linkMode:!0}:{},...s?{origin:s}:{},...c?{modified:!0}:{},...o?.baselineRef===void 0?{}:{revertable:!0},...d1(e.name)?{managed:!0}:{}}}):[],me=e4(r),he=b4(H(r,...XF)),ge=F2(r,`global`),_e=M0e(ge,`global`),ve=new Set(V2(r).map(e=>e.name));T.skills=T.skills.filter(e=>!ve.has(e.name));let ye=new Set,be=V2(r).map(e=>{let t=!ye.has(e.name);ye.add(e.name);let n=t?me[e.name]:void 0,i=H2(r,e.name),a=i!==null&&W(r,e.dir)!==W(i)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:W(r,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],...a===void 0?{}:{hostQualifier:a},size:e.size,installableEditors:D,hubOffered:k,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ge).length>0?{hostAliases:ge}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=te(r,le(n,_e),W(r,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=le(n,_e).filter(e=>!ie(e.path,ce));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...u(`global`,e.name,e)===`link`?{linkMode:!0}:{},...d1(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=W(r,e.dir),i=d(e.name,ae,n);if(i!==null)return{plugin:i};let a=he.skills[e.name]??f(r,e.name,`global`)??p(e.name,ae,n);if(!a)return{};let o=a.localHash===void 0?(()=>{let t=m(e.name,ae);return t!==null&&oe.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==a.localHash;return{origin:M(a),...o?{modified:!0}:{}}})()}}),xe=new Set(pe.map(e=>e.name)),Se=n&&!w.skills.some(e=>e.name===v)&&!xe.has(v)?h(n,v,`project`):null,Ce=new Set(be.map(e=>e.name)),we=m1.map(e=>l1[e]).filter(e=>!T.skills.some(t=>t.name===e)&&!Ce.has(e)).map(e=>h(r,e,`global`)).filter(e=>e!==null),Te=new Set(pe.map(e=>e.name)),Ee=[...N(w,A,!0).filter(e=>!Te.has(e.name)),...pe,...N(T,ee,!1),...be,...Se?[Se]:[],...we];oe.flush();let De={skills:Ee.map(e=>{let n=e.scope===`project`&&e.absolutePath?g(e.absolutePath,t):null,r=e.absolutePath?h2e(V(e.absolutePath)):[],a=r.length>0?{...e,filePaths:r}:e,o=n===null||n===e.path?a:{...a,canonicalPath:n},s=n??e.path;return e.scope===`project`&&i?.isPathIgnored(s)===!0?{...o,ignored:!0}:o}),truncated:w.truncated||T.truncated},Oe=await _(pe.map(e=>e.path),i??null,y)?{...De,skills:De.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=i?.isPathIgnored(t)===!0;if(n===(e.ignored===!0))return e;if(n)return{...e,ignored:!0};let{ignored:r,...a}=e;return a})}:De;a.writeList(x,Oe),Q(b,200,di,Oe,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0})})}const N2e=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,P2e=/[/\\\x00-\x1f\x7f]/g;function F2e(e){let t=e.replace(P2e,``);if(t=t.replace(N2e,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let n=new TextEncoder;if(n.encode(t).length>255){let e=t.lastIndexOf(`.`),r=e>=0?t.slice(e):``,i=e>=0?t.slice(0,e):t;for(;n.encode(i+r).length>255&&i.length>0;)i=i.slice(0,-1);t=(i||`upload`)+r,n.encode(t).length>255&&(t=`upload`)}return t}const I2e=q(`skill-import`),L2e={maxFileBytes:Ze,maxFiles:512};function R2e(e){if(e.files.length>512)return`Skill has ${e.files.length} dependent files; the import cap is 512.`;let t=Buffer.byteLength(e.skillMd);for(let n of e.files){let e=n.bytes?.byteLength??Buffer.byteLength(n.content??``);if(e>16777216)return`${n.relPath} is ${e} bytes; the import per-file cap is ${Ze}.`;t+=e}return t>67108864?`Skill is ${t} bytes; the import bundle cap is ${zt}.`:null}function z2e(e){function t(e,t){return oI(W(e,t))?.contentHash}return{async runSkillImport(n){let{acquiredDir:r,scope:i,sourceLabel:a,ref:o,publisher:s,upstreamSkill:c,actor:l}=n;if(!e.projectDir)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let u=aI(r);if(u)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:u};let d=oI(r);if(!d)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let f=R2e(d);if(f)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:f};let p=H(i===`project`?e.projectDir:e.skillsHome,...XF),m=b4(p),h=i===`project`?e.contentDir:e.skillsHome,g=z2(h,i);if(g===null)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Open Knowledge only writes skills into an agent folder that already exists (${N0e(i).join(`, `)}) and never creates one for you. Create the folder your agent uses, then import again.`,detail:`NO_USABLE_SKILL_HOME`};let _=W(h,g),v=tOe(m,d.contentHash);if(v&&e.resolveSkillDirForRead(i,v)!==null)return{ok:!0,body:{name:v,path:`${v}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:[],warningCodes:[]}};let y=F2e(d.name),b=t=>e.resolveSkillDirForRead(i,t)!==null||G(W(_,t,`SKILL.md`)),x=b(y),S=y;if(x){S=`${y}-imported`;let e=2;for(;b(S);)S=`${y}-imported-${e}`,e+=1}let C=e.parseFrontmatterDoc(d.skillMd),w=C.body,T=eI(C.frontmatter),E=S2({skillsRoot:_,name:S,body:w,frontmatter:{name:S,description:d.description,...T===void 0?{}:{metadata:{pack:T}}}});if(!E.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:E.error.code,cause:Error(E.error.message)};let D=[...E.warnings];for(let e of d.files){let t=T2({skillsRoot:_,name:S,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:L2e});if(!t.ok){let n=E2({skillsRoot:_,name:S});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}i===`project`&&(e.attributeOkArtifactWrite(l,`${g}/${S}/SKILL`,`skill-import: ${a} -> ${g}/${S}/SKILL.md`),await e.commitOkArtifactWrite(`skill-import`));let O=t(_,S),k=MI(a),A=i===`project`?await e.shadowHeadSha(e.artifactWriterId(l),`${g}/${S}`):void 0;if(await x4(p,e=>$F(e,S,{source:a,...k?{pluginProvider:k.provider}:{},ref:o,contentHash:d.contentHash,files:d.files.map(e=>e.relPath),...O===void 0?{}:{localHash:O},...A===void 0?{}:{baselineRef:A},publisher:s,importedAt:new Date().toISOString(),...c===void 0?{}:{skill:c}})),n.skipProjection!==!0)try{let t=a4(h);if(t.length>0){let n=W(_,S),r=o4(i),a=t.filter(e=>{let t=c4(h,e,S,r);return t!==null&&t!==n&&G(t)}),o=a.filter(e=>{let t=c4(h,e,S,r);try{return t!==null&&xs(t).isSymbolicLink()}catch{return!1}});m4({canonicalAbs:n,canonicalHash:oI(n)?.contentHash??``,canonicalRootRel:g,name:S,cwd:h,targets:t,mode:e.effectiveInstallMode(i,S,{hosts:[`<source>`,...a],linkedHosts:o}),roots:o4(i)})}}catch(e){I2e.warn({err:e,skill:S},`post-import editor fan-out failed (import kept)`)}return e.signalFiles(),{ok:!0,body:{name:S,path:`${g}/${S}/SKILL.md`,created:E.created,alreadyImported:!1,...x?{collisionRenamedFrom:d.name}:{},provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:D,warningCodes:E.warningCodes}}}}}function B2e(e,t){let{recordedSkill:n,localName:r,frontmatterNameOf:i}=t;return(n?e.find(e=>e.name===n):void 0)??e.find(e=>e.name===r)??e.find(e=>i(e.dir)===r)??e.find(e=>e.name===Ur[n??r])??(e.length===1?e[0]:void 0)}function V2e(e){let t=new Set(e.upstreamFiles),n=new Set(e.local?.files??[]),r=(e.entry.files??(e.entry.localHash!==void 0&&e.local?.contentHash===e.entry.localHash?[...n]:[])).filter(e=>!t.has(e)).filter(e=>n.has(e));return{upToDate:e.upstreamHash===e.entry.contentHash&&r.length===0,removedUpstream:r}}function H2e(e,t){let n=new Map,r=[];for(let i of new Set(e)){let e=t(i);if(!e){r.push(i);continue}let a=n.get(e.source);a?a.push(i):n.set(e.source,[i])}return{bySource:[...n].map(([e,t])=>({source:e,names:t})),unrecorded:r}}function U2e(e){return{async runSkillReimport(t){let{acquiredDir:n,name:r,scope:i,entry:a,lockPath:o,ref:s,actor:c}=t,l=i===`global`?e.skillsHome:e.contentDir,{root:u,dirRel:d,realDir:f}=e.effectiveSkillRoot(i,r),p=!d.startsWith(`${e.legacyStoreRoot}/`);if(f===null||!G(W(l,d,`SKILL.md`)))return{ok:!1,status:404,urn:`urn:ok:error:not-found`,title:`Skill is not installed.`,detail:`SKILL_ABSENT`};let m=aI(n);if(m)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:m};let h=oI(n);if(!h)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let g=R2e(h);if(g)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:g};let _=oI(W(u,r)),{upToDate:v,removedUpstream:y}=V2e({upstreamHash:h.contentHash,upstreamFiles:h.files.map(e=>e.relPath),entry:a,local:_?{contentHash:_.contentHash,files:_.files.map(e=>e.relPath)}:null});if(v)return{ok:!0,body:{name:r,updated:!1,source:a.source,warnings:[],warningCodes:[]}};let b=e.parseFrontmatterDoc(h.skillMd),x=b.body,S=eI(b.frontmatter);if(t.dryRun){let t;if(i===`project`&&e.projectDir)try{let n=IF({baseDir:e.projectDir,timeout:{block:15e3}}),i=U(e.projectDir,W(u,r)).split(us).join(`/`);t=(await n.raw(`ls-files`,...Fi([i]))).trim().length>0}catch{t=void 0}return{ok:!0,body:{name:r,updated:!0,source:a.source,localBody:e.parseFrontmatterDoc(_?.skillMd??``).body,upstreamBody:x,...t===void 0?{}:{gitTracked:t},warnings:[],warningCodes:[]}}}if(i===`project`){let t=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${d}/${e.replace(/\.mdx?$/i,``)}`);t.length>0&&await e.captureAndCloseDocuments(t,`deleted-upstream`)}let C=S2({skillsRoot:u,name:r,body:x,frontmatter:{name:r,description:h.description,...S===void 0?{}:{metadata:{pack:S}}}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of h.files){let t=T2({skillsRoot:u,name:r,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:L2e});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to write the complete refreshed skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(t.error.message)}}for(let e of y){let t=b0e({skillsRoot:u,name:r,relPath:e});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to reconcile files removed upstream.`,detail:`${e}: ${t.error.code}`,cause:Error(t.error.message)}}i===`project`&&(e.attributeOkArtifactWrite(c,e.skillArtifactKey(r),`skill-reimport: ${a.source} -> ${d}`),await e.commitOkArtifactWrite(`skill-reimport`));let T=oI(W(u,r))?.contentHash,E=i===`project`?await e.shadowHeadSha(e.artifactWriterId(c),d):void 0;return await x4(o,e=>$F(e,r,{...e.skills[r]??a,contentHash:h.contentHash,files:h.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...E===void 0?{}:{baselineRef:E},ref:s,importedAt:new Date().toISOString()})),!p&&i===`project`&&await e.projectImportedSkillCopy({skillsRoot:u,name:r,scope:`project`,hasScripts:h.files.some(e=>e.relPath.startsWith(`scripts/`)),handler:`skill-reimport`}),e.signalFiles(),{ok:!0,body:{name:r,updated:!0,source:a.source,warnings:w,warningCodes:C.warningCodes}}}}}function W2e(e,t){let n=e===`.`?``:e.replace(/^\.\//,``);return n?`${n}/${t}`:t}function G2e(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function K2e(e){let{shadow:t,contentDir:n,contentRoot:r,name:i,version:a}=e,o=e.skillDirRel??`.ok/skills/${i}`;if(!G(t.workTree)||!G(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let s=xY(t),c=[...new Set([o,`.ok/skills/${i}`])],l=[],u=W2e(r,o);try{for(let e of c){let t=W2e(r,e),n=await kJ(s,[`ls-tree`,`-r`,`--name-only`,a,...Fi([t])]);if(n.length>0){l=n,u=t;break}}}catch(e){let t=e instanceof Error?e.message:String(e);return G2e(t)?{ok:!1,code:`version-not-found`,error:`Version ${a.slice(0,8)} not found.`}:{ok:!1,code:`io-error`,error:`Failed to read version ${a.slice(0,8)}: ${t}`}}if(l.length===0)return{ok:!1,code:`skill-absent`,error:`Skill "${i}" did not exist at version ${a.slice(0,8)}.`};let d=W(n,o),f=d+us,p=[];for(let e of l){let t=e.slice(u.length).replace(/^\//,``),n=W(d,t);if(n!==d&&!n.startsWith(f))return{ok:!1,code:`path-escape`,error:`Refusing to restore path outside skill dir: ${t}`};try{p.push({rel:t,destAbs:n,content:await s.raw(`show`,`${a}:${e}`)})}catch(e){let n=e instanceof Error?e.message:String(e);return{ok:!1,code:`io-error`,error:`Failed reading ${t} at ${a.slice(0,8)}: ${n}`}}}CJ(d,{recursive:!0,force:!0});let m=[];for(let{rel:e,destAbs:t,content:n}of p)_J(V(t),{recursive:!0}),hJ(t,n,`utf-8`),m.push(e);return{ok:!0,restoredFiles:m}}function q2e(e){try{let t=K(H(e,`SKILL.md`),`utf-8`),n=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(t)?.[1];return n!==void 0&&/^[ \t]+pack:[ \t]*"?[a-z0-9-]+"?[ \t]*$/m.test(n)}catch{return!1}}function J2e(e){let{synthPluginLockEntry:t,synthBuiltinLockEntry:n,isValidSkillName:r,getPrincipal:i,validateSkillName:a,rejectReservedBuiltinSkill:o,shadowRef:s,contentDir:c,contentRoot:l,projectDir:u,skillsHome:d,projectSkillDirRel:f,attributeOkArtifactWrite:p,okArtifactKey:m,commitOkArtifactWrite:h,signalChannel:g,bumpSkillsCatalogGen:_,contentFilter:v,scheduleDeferredIgnoreRebuild:y,effectiveSkillRoot:b,skillReimportService:x,localSkillHash:S,resolveSkillsRoot:C,projectImportedSkillCopy:w}=e;function T(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];X(e,r,i,t.error,{handler:n,detail:t.code})}function E(e,t){if(t.ok){Q(e,200,Vte,t.body,{handler:`skill-reimport`});return}X(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function D(e,t,n){let r=e===`project`?c:d,i=(e===`project`?B2(c):V2(d)).find(e=>e.name===t);return i?W(r,i.dir):W(n,t)}function O(e,r,i,a){let o=a.skills[r];if(o)return o;let s=D(e,r,i);return eOe(r,oI(s)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:q2e(s)})??n(e===`global`?d:c,r,e)??t(r,kw(u??c),s)}return L1({"/api/skill/restore":Z(Uee,async(e,t,n)=>{try{let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!a(n.name,t,`skill-restore`)||o(n.name,t,`skill-restore`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=s?.current;if(!r){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let u=await K2e({shadow:r,contentDir:c,contentRoot:l??`.`,name:n.name,version:n.version,skillDirRel:f(n.name)});if(!u.ok){T(t,u,`skill-restore`);return}let d=[],b=i4(W(c,f(n.name)),n.name);b.ok||d.push(`Restored, but the skill no longer validates: ${b.errors.join(` `)}`),p(e,m(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await h(`skill-restore`),g?.(`files`),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,Ine,{name:n.name,version:n.version,restoredFiles:u.restoredFiles,warnings:d},{handler:`skill-restore`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),"/api/skill/reimport":Z(sre,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!a(n.name,t,`skill-reimport`))return;let o=n.scope===`global`?d:c,{root:s,dirRel:l,realDir:f}=b(n.scope,n.name);if(f===null||!G(W(o,l,`SKILL.md`))){X(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let p=H(n.scope===`global`?d:u,...XF),m=O(n.scope,n.name,s,b4(p));if(!m){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await x4(p,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??m,autoUpdate:n.setAutoUpdate}}})),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,Vte,{name:n.name,updated:!1,source:m.source,warnings:[],warningCodes:[]},{handler:`skill-reimport`});return}let h,g=null;try{let e=m.skill??n.name,i=Ur[e],a=await dI(m.source,e).catch(async e=>{if(i===void 0)throw e;return dI(m.source,i)}),o=a?.source??NI(m.source,m.pluginProvider),s=a?.skill??m.skill,c=a?.spec??qF(o);if(!c){X(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:m.source});return}if(C4(t,c,`skill-reimport`))return;let l=await YF(c);r=l.cleanup,h=l.ref;let u=sI(l.dir),d=B2e(u,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>oI(e)?.name});if(!d){X(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}g=d.dir}catch(e){if(e instanceof zF){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!g){X(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let S=await x.runSkillReimport({acquiredDir:g,name:n.name,scope:n.scope,entry:m,lockPath:p,ref:h,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});_(),v?.refreshInPlaceSkillDirs(),y(),E(t,S)}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),"/api/skills/reimport-bulk":Z(Zre,async(e,t,n)=>{try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let a=C1(n,i);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let o=H(n.scope===`global`?d:u,...XF),s=b4(o),c=[],{bySource:l,unrecorded:f}=H2e([...new Set(n.names)].filter(e=>r(e)?!0:(c.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`,warningCodes:[]}),!1)),e=>O(n.scope,e,b(n.scope,e).root,s));for(let e of f)c.push({requested:e,status:`not-found`,warnings:[],warningCodes:[]});for(let t of l){let r=()=>{};try{let i,l=[];try{let e=t.names[0],n=await dI(t.source,e).catch(async n=>{let r=Ur[e];if(r===void 0)throw n;return dI(t.source,r)}),a=n?.source??NI(t.source,s.skills[t.names[0]]?.pluginProvider),o=n?.spec??qF(a);if(!o||w2e(o)){for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:`INVALID_SOURCE`});continue}let u=await YF(o);r=u.cleanup,i=u.ref,l=sI(u.dir)}catch(n){q(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:lX(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)});continue}for(let r of t.names){let t=O(n.scope,r,b(n.scope,r).root,s);if(!t){c.push({requested:r,status:`not-found`,warnings:[],warningCodes:[]});continue}let u=B2e(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:r,frontmatterNameOf:e=>oI(e)?.name});if(!u){c.push({requested:r,status:`not-found`,source:t.source,warnings:[],warningCodes:[]});continue}try{let s=await x.runSkillReimport({acquiredDir:u.dir,name:r,scope:n.scope,entry:t,lockPath:o,ref:i,actor:a});if(!s.ok){q(`skills-reimport-bulk`).warn({skill:r,err:s.cause,detail:s.detail,requestId:lX(e)},`bulk update: one skill failed (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:s.detail??s.title});continue}c.push({requested:r,status:s.body.updated?`updated`:`up-to-date`,source:s.body.source,warnings:s.body.warnings,warningCodes:s.body.warningCodes})}catch(n){q(`skills-reimport-bulk`).warn({skill:r,err:n,requestId:lX(e)},`bulk update: one skill threw (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)})}}}finally{r()}}Q(t,200,fr,{results:c,updated:c.filter(e=>e.status===`updated`).length,upToDate:c.filter(e=>e.status===`up-to-date`).length,failed:c.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{_(),v?.refreshInPlaceSkillDirs(),_(),await v?.rebuildIgnorePatterns()}catch(e){q(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),"/api/skill/revert":Z(gre,async(e,t,n)=>{try{if(!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!a(n.name,t,`skill-revert`)||o(n.name,t,`skill-revert`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=H(u,...XF),d=b4(r).skills[n.name];if(!d?.baselineRef){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let _=s?.current;if(!_){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let v=await K2e({shadow:_,contentDir:c,contentRoot:l??`.`,name:n.name,version:d.baselineRef,skillDirRel:f(n.name)});if(!v.ok){T(t,v,`skill-revert`);return}p(e,m(`skill`,``,n.name),`skill-revert: ${n.name} @ ${d.baselineRef.slice(0,8)}`),await h(`skill-revert`);let y=W(c,f(n.name),`..`),b=S(y,n.name);await x4(r,e=>$F(e,n.name,{...e.skills[n.name]??d,...b===void 0?{}:{localHash:b}})),y===C(`project`)&&await w({skillsRoot:y,name:n.name,scope:`project`,hasScripts:v.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),g?.(`files`),Q(t,200,ite,{name:n.name,baselineRef:d.baselineRef,restoredFiles:v.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`})},{mutating:[`/api/skill/restore`,`/api/skill/reimport`,`/api/skills/reimport-bulk`,`/api/skill/revert`]})}function Y2e(e){let{contentDir:t,projectDir:n,contentFilter:r,validateSkillName:i,indexedSkillContentPath:a,bumpSkillsCatalogGen:o,signalChannel:s}=e;function c(e){return`!/${V(e).split(us).join(`/`)}/`}return L1({"/api/skill/track-in-git":Z(bne,z1(async(e,l,u)=>{if(!i(u.name,l,`skill-track-in-git`))return;if(u.scope!==`project`){X(l,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!n){X(l,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let d=B2(t).find(e=>e.name===u.name)?.dir??`.ok/skills/${u.name}`,f=a(W(t,d,`SKILL.md`),t)??`${d}/SKILL.md`,p=V(f),m=f,h=c(p),g=`.gitignore`,_=W(t,g);if(r&&!r.isPathIgnored(m)){Q(l,200,zi,{line:h,gitignorePath:g,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(u.apply!==!0){Q(l,200,zi,{line:h,gitignorePath:g,applied:!1},{handler:`skill-track-in-git`});return}let v=G(_)?K(_,`utf-8`):null;if((v??``).split(`
1010
+ `).length;return s>500&&(i.push(`SKILL.md body is ${s} lines — keep it under 500 for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),a.push(`skill-body-too-long`)),{ok:!0,content:r,warnings:i,warningCodes:a}}function x2(e){let t=V(e),n=`${rs(e)}${Dk}`;try{for(let e of Ds(t))e.startsWith(n)&&bJ(H(t,e))}catch{}}function S2(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=_0e({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i,warningCodes:a}=n,{skillDir:o,filePath:s}=k2(e.skillsRoot,e.name);try{_J(o,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${A2(e.skillsRoot,o)}: ${t.message}`}}}let c=!G(s);x2(s);let l=kk(s);try{hJ(l,r,`utf-8`),vJ(l,s)}catch(t){try{bJ(l)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${A2(e.skillsRoot,s)}: ${t.message}`}}}return{ok:!0,path:A2(e.skillsRoot,s),created:c,warnings:i,warningCodes:a}}function C2(e){let t=H(e.skillDir,b2),n;if(e.skillMd!==void 0)n=e.skillMd;else try{n=K(t,`utf-8`)}catch(e){return{ok:!1,stage:`read`,cause:e}}let{fenced:r,body:i}=na(n),a=Li(r,{name:e.toName});if(!a.ok)return{ok:!1,stage:`patch`,error:a.error};x2(t);let o=kk(t);try{hJ(o,`${a.nextFenced}${i}`,`utf-8`),vJ(o,t)}catch(e){try{bJ(o)}catch{}return{ok:!1,stage:`write`,cause:e}}return{ok:!0}}function w2(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let n=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(n.length===0||n.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(n.length===1&&n[0]===b2)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`SKILL.md is written through the skill write path, not as a bundle file.`}};let r=H(e,...n);return r!==e&&!r.startsWith(e+us)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:r}}function v0e(e){let t=0,n=r=>{let i;try{i=Ds(r)}catch{return}for(let a of i){let i=H(r,a),o;try{o=Ns(i).isDirectory()}catch{continue}o?n(i):(r!==e||a!==b2)&&t++}};return n(e),t}function T2(e){let t=e.bytes??e.content??``,n=D2(e.skillsRoot);if(!n.ok)return{ok:!1,error:n.error};let r=O2(e.name);if(!r.ok)return{ok:!1,error:r.error};let{skillDir:i,filePath:a}=k2(e.skillsRoot,e.name);if(!G(a))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let o=w2(i,e.relPath);if(!o.ok)return{ok:!1,error:o.error};let{abs:s}=o,c=typeof t==`string`?Buffer.byteLength(t,`utf-8`):t.length,l=e.limits?.maxFileBytes??262144,u=e.limits?.maxFiles??50;if(c>l)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${c} bytes — the per-file cap is ${l}.`}};let d=!G(s);if(d&&v0e(i)>=u)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds ${u} bundle files (the cap) — delete one before adding another.`}};try{_J(H(s,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}x2(s);let f=kk(s);try{typeof t==`string`?hJ(f,t,`utf-8`):hJ(f,t),vJ(f,s)}catch(t){try{bJ(f)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:A2(e.skillsRoot,s),created:d}}function y0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=k2(e.skillsRoot,e.name),i=w2(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let a=w2(r,e.toRelPath);if(!a.ok)return{ok:!1,error:a.error};if(!G(i.abs))return{ok:!1,error:{code:`FILE_NOT_FOUND`,message:`No bundle file at ${e.relPath}.`}};if(G(a.abs))return{ok:!1,error:{code:`DEST_EXISTS`,message:`A bundle file already exists at ${e.toRelPath} — renames never overwrite.`}};try{_J(H(a.abs,`..`),{recursive:!0}),vJ(i.abs,a.abs)}catch(t){return{ok:!1,error:{code:`RENAME_FAILED`,message:`Failed to rename ${e.relPath} -> ${e.toRelPath}: ${t.message}`}}}let o=H(i.abs,`..`);if(o!==r&&j2(o))try{wJ(o)}catch{}return{ok:!0}}function b0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=k2(e.skillsRoot,e.name),i=w2(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let{abs:a}=i,o=G(a);if(o){try{Ns(a).isDirectory()?CJ(a,{recursive:!0,force:!0}):bJ(a)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=H(a,`..`);if(t!==r&&j2(t))try{wJ(t)}catch{}}return{ok:!0,path:A2(e.skillsRoot,a),existed:o}}function E2(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillsRoot:r}=t,{skillDir:i}=k2(e.skillsRoot,e.name),a=G(i);if(a)try{CJ(i,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${A2(e.skillsRoot,i)}: ${t.message}`}}}return C0e(r),{ok:!0,path:A2(e.skillsRoot,i),existed:a}}async function x0e(e){let t=D2(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=O2(e.fromName);if(!n.ok)return{ok:!1,error:n.error};let r=O2(e.toName);if(!r.ok)return{ok:!1,error:r.error};let i=k2(e.skillsRoot,e.fromName),a=k2(e.skillsRoot,e.toName);if(i.skillDir===a.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!G(i.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${A2(e.skillsRoot,i.skillDir)}.`}};if(G(a.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${A2(e.skillsRoot,a.skillDir)}.`}};let o;try{o=await e.relocate(i.skillDir,a.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:A2(e.skillsRoot,i.skillDir),toPath:A2(e.skillsRoot,a.skillDir),committed:o}}function D2(e){return os(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function O2(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>64?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤64 characters.`}}:Qe.test(e)?{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function S0e(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?Rr(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description==`string`?e.description.length>h0e?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${h0e} characters (got ${e.description.length}).`}}:Rr(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description must be a string — it is the primary triggering surface (when to use the skill).`}}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function k2(e,t){let n=H(e,t);return{skillDir:n,filePath:H(n,b2)}}function C0e(e){if(G(e)&&j2(e))try{wJ(e)}catch{}let t=ss(H(e,`..`));if(t.endsWith(`${us}.ok`)&&G(t)&&j2(t))try{wJ(t)}catch{}}function A2(e,t){let n=t.startsWith(e+us)?t.slice(e.length+1):t;return ss(n).split(us).join(`/`)}function w0e(e){return(0,wk.stringify)({name:e.name,description:e.description,...e.metadata===void 0?{}:{metadata:e.metadata}})}function j2(e){try{return Ds(e).length===0}catch{return!1}}const T0e=new Map;function E0e(e,t){T0e.set(e,t)}function M2(e,t){let n=T0e.get(e);if(n===void 0)return null;if(!Qe.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=W(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=W(n,...e)}if(!r.startsWith(n+us))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}function D0e(e){switch(e.kind){case`invalid_value`:return`${e.kind} (${e.key}: ${e.reason})`;case`reserved_key`:return`${e.kind} ('${e.key}' is reserved)`;case`unknown_key`:return`${e.kind} ('${e.key}' is not a recognized key)`;case`duplicate_target`:return`${e.kind} ('${e.key}' appears more than once)`;case`reorder_mismatch`:return`${e.kind} (expected: ${e.expected.join(`, `)}; got: ${e.got.join(`, `)})`;case`region_too_large`:return`${e.kind} (frontmatter region too large: ${e.bytes} > ${e.limit} bytes)`;case`parse_failed`:return`${e.kind} (frontmatter region unparseable: ${e.reason})`;case`invalid_path`:return`${e.kind} (${e.path.map(String).join(`.`)||`__path__`}: ${e.reason})`;default:return`unhandled frontmatter edit error (${String(e)})`}}function O0e(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}const N2=O0e(y,qi),P2=O0e(Ki,qi);function F2(e,t){let n=I2(e,t),r={},i;try{i=ks(e)}catch{return r}for(let{editor:t,root:a}of n){let n;try{n=ks(H(e,a))}catch{continue}if(n===H(i,a))continue;let o=U(i,n);o===``||o.startsWith(`..`)||os(o)||(r[t]=o.split(us).join(`/`))}return r}function k0e(e){return e===`project`?N2:P2}function A0e(e){let t=I2(e,`global`).map(t=>H(e,t.root)),n=H(e,`.ok`,`skills`);return t.includes(n)?t:[...t,n]}function I2(e,t){let n=k0e(t),r=new Set(n.map(e=>e.root));return[...n,...Z1e(e).filter(e=>!r.has(e)).map(e=>({editor:e,root:e}))]}function L2(e){return new Set((e===`project`?N2:P2).map(e=>e.root))}function R2(e,t,n,r){return!L2(t).has(n)||G(H(e,ee(n)))?!0:n===`.agents/skills`&&mn.some(e=>e.scope===t&&G(H(r,e.dotDir)))}function j0e(e,t,n,r){let i=new Set([...I2(e,t).map(e=>e.root),Ba]),a=[];for(let t of i){let i=H(e,t,n),o;try{o=xs(i)}catch{continue}if(o.isSymbolicLink()){a.push(i);continue}oI(i)?.contentHash===r&&a.push(i)}return a}function M0e(e,t){let n=new Map((t===`project`?N2:P2).map(e=>[e.editor,e.root])),r=new Set;for(let t of Object.keys(e)){let e=n.get(t);e===void 0?t.includes(`/`)&&r.add(t):r.add(e)}return r}function z2(e,t){let n=t===`project`?N2:P2;if(G(H(e,`.agents`)))return qi;let r=[...n].filter(e=>e.editor!==`agents`).sort((e,t)=>{let n=fI.indexOf(e.editor),r=fI.indexOf(t.editor);return(n===-1?fI.length:n)-(r===-1?fI.length:r)});for(let{root:t}of r)if(G(H(e,ee(t))))return t;return null}function N0e(e){return[...new Set((e===`project`?N2:P2).map(e=>`${ee(e.root)}/`))]}function P0e(e){let t=[],n=(e,r)=>{for(let i of Ds(e,{withFileTypes:!0})){let a=H(e,i.name),o=r===``?i.name:`${r}/${i.name}`,s=Ns(a);s.isDirectory()?n(a,o):t.push(`${o}:${s.size}:${s.mtimeMs}`)}};try{n(e,``)}catch{return null}return t.sort().join(`|`)}const F0e=new Map;function I0e(e){let t=P0e(e);if(t===null)return null;let n=F0e.get(e);if(n!==void 0&&n.stamp===t)return n;let r=oI(e);if(!r)return null;let i=eI(sa(r.skillMd)??{}),a={stamp:t,contentHash:r.contentHash,description:r.description,size:Cne(r),...i===void 0?{}:{pack:i}};return F0e.set(e,a),a}function L0e(e,t){let n=[],r=Q1e(e),i=I2(e,t),a=null;try{a=ks(e)}catch{a=null}for(let{editor:o,root:s}of i){let i=H(e,s),c,l=!1;try{if(!G(i))continue;l=a!==null&&ks(i)!==H(a,s),c=Ds(i)}catch{continue}for(let e of c){let a=H(i,e);try{if(!Ns(a).isDirectory())continue;let i=I0e(a);if(!i)continue;n.push({name:e,scope:t,editor:o,contentHash:i.contentHash,dir:`${s}/${e}`,description:i.description,size:i.size,...i.pack===void 0?{}:{pack:i.pack},viaLink:l||xs(a).isSymbolicLink(),...l?{aliasRooted:!0}:{},...r[e]===o?{preferredSource:!0}:{}})}catch{}}}let{admittedDirs:o,canonicalDir:s}=nke(n),c=new Set(s.values());return mI(n).filter(e=>o.has(e.canonical.dir)).filter(e=>c.has(e.canonical.dir)||!d1(e.name)).sort((e,t)=>e.name.localeCompare(t.name)||Number(c.has(t.canonical.dir))-Number(c.has(e.canonical.dir))||e.contentHash.localeCompare(t.contentHash)).map(t=>{let r=null;try{r=ks(H(e,t.canonical.dir))}catch{r=null}let i=t=>{if(r===null)return!1;try{return ks(H(e,t))===r}catch{return!1}},a=t.copies.filter(e=>e.aliasRooted!==!0&&(e.viaLink||!i(e.dir))),o=d1(t.canonical.name)?[]:n.filter(e=>e.name===t.canonical.name&&e.contentHash!==t.contentHash).map(e=>e.editor);return{name:t.canonical.name,description:t.canonical.description,dir:t.canonical.dir,hosts:[t.canonical.editor,...a.map(e=>e.editor)],linkedHosts:[t.canonical,...a].filter(e=>e.viaLink).map(e=>e.editor),conflictHosts:o,copyDirs:a.filter(e=>!e.viaLink).map(e=>e.dir),contentHash:t.contentHash,size:t.canonical.size,...t.canonical.pack===void 0?{}:{pack:t.canonical.pack}}})}function B2(e){return L0e(e,`project`).filter(e=>!IXe(e.name))}function V2(e){return L0e(e,`global`)}const R0e=[...P2].sort((e,t)=>{let n=fI.indexOf(e.editor),r=fI.indexOf(t.editor);return(n===-1?fI.length:n)-(r===-1?fI.length:r)||e.editor.localeCompare(t.editor)});function H2(e,t){for(let{root:n}of R0e){let r=H(e,n,t);try{if(G(H(r,`SKILL.md`)))return r}catch{}}return null}function z0e(e){return new Set(I2(e,`project`).map(e=>e.root))}function U2(e){return new Set(B2(e).map(e=>e.dir))}const B0e=q(`installed-skills-marker`);function W2(e){return H(e,...un)}const V0e=u2();function H0e(e,t){return V0e(W2(e),t)}function G2(e){let t=W2(e);if(!G(t))return hi();try{return Tne(K(t,`utf-8`))??hi()}catch(e){return B0e.warn({err:e,path:t},`installed-skills marker unreadable`),hi()}}function U0e(e){let t=W2(e);if(!G(t))return{ok:!0,state:hi()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,state:hi()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r=Tne(n);return r===null?{ok:!1,reason:`its contents are not an installed-skills marker this server understands`}:{ok:!0,state:r}}function W0e(e){let t=U0e(e);if(t.ok)return t.state;let n=W2(e);throw B0e.error({path:n,reason:t.reason,err:t.cause},`refusing to rewrite the installed-skills marker because it could not be read — rewriting it would replace every install it records with this one`),Error(`Refusing to rewrite ${n}: ${t.reason}`)}async function G0e(e,t){let n=Ct.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid installed-skills marker: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=W2(e);await mJ(V(r),{recursive:!0}),await jk(r,`${JSON.stringify(n.data,null,2)}\n`,{fs:TJ})}async function K2(e,t,n){return H0e(e,async()=>{let r=W0e(e);await G0e(e,{...r,skills:{...r.skills,[t]:n}})})}async function q2(e,t){return H0e(e,async()=>{let n=W0e(e),r=n.skills[t]??null;if(r===null)return null;let{[t]:i,...a}=n.skills;return await G0e(e,{...n,skills:a}),r})}function J2(e,t){return`${e}:${t}`}function K0e(e){return H(aX(e),`skill-move-retained.json`)}function Y2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X2(e){return typeof e==`string`?e:``}const q0e=()=>({ok:!0,store:{schema:1,retained:{}}});function J0e(e){let t=K0e(e);if(!G(t))return q0e();let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?q0e():{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch{return{ok:!1,reason:`it is not valid JSON`}}if(!Y2(r)||!Y2(r.retained))return{ok:!1,reason:`its contents are not a retained-record ledger`};if(r.schema!==1)return{ok:!1,reason:typeof r.schema==`number`?`it declares schema ${r.schema}, which this server does not understand (it writes schema 1)`:`it declares a schema this server does not understand (it writes schema 1)`};let i={};for(let[e,t]of Object.entries(r.retained)){let n=Y2(t)?t:{};i[e]={retainedAt:X2(n.retainedAt),from:X2(n.from),to:X2(n.to),sourceState:Gn(n.sourceState)?n.sourceState:`unknown`,reason:X2(n.reason),retainedContentHash:X2(n.retainedContentHash)}}return{ok:!0,store:{schema:1,retained:i}}}function Z2(e,t,n){let r=J0e(e);if(!r.ok)return{state:`unreadable`,reason:r.reason,...r.cause===void 0?{}:{cause:r.cause}};let i=r.store.retained[J2(t,n)];return i===void 0?{state:`none`}:{state:`record`,record:i}}const Y0e=u2();function X0e(e,t){let n=K0e(e);return Y0e(n,async()=>{let r=J0e(e);if(!r.ok)throw q(`skill-move-retained`).error({event:`skill-move-retained.unreadable`,path:n,reason:r.reason},`refusing to rewrite the retained-destination ledger because it could not be read — rewriting it would replace every record it holds with this one`),Error(`Refusing to rewrite ${n}: ${r.reason}`);t(r.store.retained)&&(await mJ(V(n),{recursive:!0}),await jk(n,`${JSON.stringify(r.store,null,2)}\n`,{fs:TJ}))})}function Z0e(e,t,n,r){return X0e(e,e=>(e[J2(t,n)]=r,!0))}function Q0e(e,t,n){return X0e(e,e=>{let r=J2(t,n);return r in e&&(delete e[r],!0)})}function Q2(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}async function $2(e,t,n){await h2(e,e=>{e.sources={...e.sources,[t]:n}})}async function $0e(e,t,n){await h2(e,e=>{e.folders={...e.folders,[t]:n}})}function e2e(e){return m2(e).folders??{}}async function t2e(e,t){await h2(e,e=>{let n=new Set(e.roots??[]);n.has(t)||(n.add(t),e.roots=[...n].sort())})}function n2e(e,t){let n=m2(e).preferences?.[t];return n===`link`||n===`copy`?n:void 0}function e4(e){let t={};for(let[n,r]of Object.entries(m2(e).skills)){let i=r.filter(t=>{let n=f2(e,t.path);return n!==null&&G(H(n,`SKILL.md`))});i.length>0&&(t[n]=i)}return t}async function r2e(e,t,n){await h2(e,e=>{let r=(e.skills[t]??[]).filter(e=>e.path!==n);e.skills={...e.skills},r.length>0?e.skills[t]=r:delete e.skills[t]})}async function i2e(e,t){await h2(e,e=>{e.skills[t]!==void 0&&(e.skills={...e.skills},delete e.skills[t])})}async function t4(e,t,n){await h2(e,e=>{e.skills={...e.skills};let r=(e.skills[t]??[]).filter(e=>e.path!==n.path);r.push(n),e.skills[t]=r})}async function n4(e,t,n){let r=e4(e),i=n??B2(t);for(let t of i){let n=new Set((r[t.name]??[]).map(e=>e.path));for(let i of t.copyDirs){if(n.has(i)||f2(e,i)===null)continue;let a={path:i,mode:`copy`,hash:t.contentHash};await t4(e,t.name,a),r[t.name]=[...r[t.name]??[],a]}}if(Object.keys(r).length===0)return 0;let a=0;for(let n of i){let i=r[n.name];if(!i)continue;let o=f2(t,n.dir);if(o!==null)for(let t of i){if(t.mode!==`copy`||t.hash===void 0)continue;let r=f2(e,t.path);if(r===null||r===o)continue;let i=oI(r)?.contentHash;if(i!==void 0){if(i===n.contentHash){t.hash!==i&&await t4(e,n.name,{...t,hash:i});continue}i===t.hash&&(r=f2(e,t.path),r!==null&&(CJ(r,{recursive:!0,force:!0}),yJ(o,r,{recursive:!0,dereference:!0}),await t4(e,n.name,{...t,hash:n.contentHash}),a+=1))}}}return a}function a2e(e,t,n){let r;try{r=xs(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return ks(e)===ks(t)?{kind:`symlink`,resolution:`target`}:{kind:`symlink`,resolution:`elsewhere`}}catch{return{kind:`symlink`,resolution:`dangling`}}if(!r.isDirectory())return{kind:`other`};try{if(ks(e)===ks(t))return{kind:`dir`,identity:`is-target`}}catch{return{kind:`dir`,identity:`different`}}return oI(e)?.contentHash===n?{kind:`dir`,identity:`same-content`}:{kind:`dir`,identity:`different`}}function r4(e,t){let n=s4(t);return e.filter(e=>n.includes(e))}const o2e=`open-knowledge`,s2e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,c2e=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function l2e(e){let t=e.match(s2e);if(!t)return null;try{let e=(0,wk.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function i4(e,t,n){let r=[],i=[],a=H(e,`SKILL.md`),o=G(H(e,`scripts`))&&Ns(H(e,`scripts`)).isDirectory(),s=t.startsWith(o2e)&&Ur[t]===void 0;if(!n?.allowReservedName&&s&&r.push(`"${t}" uses the reserved \`${o2e}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!G(a))return r.push(`No SKILL.md found at ${e}.`),{ok:r.length===0,errors:r,warnings:i,hasScripts:o};let c;try{c=K(a,`utf-8`)}catch(e){return r.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:r,warnings:i,hasScripts:o}}c2e.some(e=>e.test(c))&&r.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let l=l2e(c);if(l===null)r.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=l.name,n=l.description;typeof e!=`string`||e.length===0?r.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&r.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof n!=`string`||n.length===0)&&i.push("This skill has no `description`. Add one so agents know when to use it."),(typeof e==`string`&&Rr(e)||typeof n==`string`&&Rr(n))&&r.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:r.length===0,errors:r,warnings:i,hasScripts:o}}function u2e(e){return Mn.filter(t=>{let n=tne[t];return n!==null&&G(W(e,n))})}function a4(e,t){if(t&&t.length>0){let e=new Set(Mn);return t.filter(t=>e.has(t))}return u2e(e)}function o4(e){return e===`global`?Ki:y}function s4(e){return e===`global`?$n:Mn}function c4(e,t,n,r=y){let i=r[t];return i===null?null:W(e,i,n)}function l4(e,t,n,r=y){return t===`agents`?W(e,qi,n):c4(e,t,n,r)}function u4(e,t){if(!G(t))return!1;try{let n=U(ks(e),ks(t));return n.startsWith(`..`)||os(n)}catch{return!0}}function d2e(e,t){if(!G(e)||!G(t))return!1;try{return ks(e)===ks(t)}catch{return!1}}function d4(e,t,n){let r=W(n),i=U(W(e),r);return i!==``&&!i.startsWith(`..`)&&!os(i)?U(t,r):r}function f4(e,t,n,r,i=`symlink`,a=y){let o=[];for(let s of r){let r=c4(n,s,t,a);if(r===null)continue;let c=V(r);if(u4(n,c))continue;if(d2e(c,V(e))){o.push(s);continue}let l=W(r)===W(e);if(!l&&G(r))try{l=ks(r)===ks(e)}catch{l=!1}if(l){o.push(s);continue}CJ(r,{recursive:!0,force:!0}),_J(c,{recursive:!0}),i===`copy`?yJ(e,r,{recursive:!0,dereference:!0}):SJ(d4(n,c,e),r,`dir`),o.push(s)}return o}function f2e(e,t){if(!d1(t))return!1;try{return!xs(e).isSymbolicLink()&&G(H(e,`SKILL.md`))}catch{return!1}}function p4(e,t,n){let r=a2e(e,t,n);switch(r.kind){case`absent`:return`absent`;case`other`:return`different`;case`symlink`:return r.resolution===`target`?`link-to-canonical`:`link`;case`dir`:return r.identity===`is-target`?`canonical-dir`:r.identity===`same-content`?`same-copy`:`different`}}function m4(e){let{canonicalAbs:t,canonicalHash:n,canonicalRootRel:r,name:i,cwd:a,targets:o}=e,s=e.roots??y,c=e.mode??`copy`,l=[],u=[],d=(e,n)=>{CJ(e,{recursive:!0,force:!0}),_J(n,{recursive:!0}),c===`link`?SJ(d4(a,n,t),e,`dir`):yJ(t,e,{recursive:!0,dereference:!0})};for(let f of o){if(f===`agents`?r===`.agents/skills`:s[f]===r){let r=l4(a,f,i,s);if(r!==null&&!u4(a,V(r))){let i=p4(r,t,n);(c===`link`&&e.convertCopies===!0&&i===`same-copy`||c===`copy`&&e.convertLinks===!0&&i===`link-to-canonical`)&&d(r,V(r))}l.push(f);continue}let o=l4(a,f,i,s);if(o===null)continue;let p=V(o);if(!u4(a,p)){try{if(ks(p)!==H(ks(a),U(a,p)))continue}catch{}switch(p4(o,t,n)){case`canonical-dir`:l.push(f);break;case`link-to-canonical`:c===`copy`&&e.convertLinks===!0&&d(o,p),l.push(f);break;case`same-copy`:c===`link`&&e.convertCopies===!0&&d(o,p),l.push(f);break;case`different`:if(f2e(o,i)){d(o,p),l.push(f);break}u.push(f);break;case`link`:case`absent`:d(o,p),l.push(f)}}}return{hosts:l,conflicted:u}}function h4(e){let{canonicalHash:t,name:n,cwd:r,newTarget:i}=e,a=e.roots??y,o;try{o=ks(e.canonicalAbs)}catch{return{ok:!1,reason:`target-unusable`}}try{if(xs(o).isSymbolicLink()||!xs(o).isDirectory())return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}let s=e.destDirAbs??l4(r,i,n,a);if(s===null)return{ok:!1,reason:`target-missing`};if(W(s)===o)return{ok:!0,newAbs:s};let c=V(s);if(u4(r,c))return{ok:!1,reason:`target-unusable`};switch(p4(s,o,t)){case`canonical-dir`:return{ok:!0,newAbs:s};case`different`:return{ok:!1,reason:`target-unusable`};case`same-copy`:try{if(xs(s).isSymbolicLink()||!G(H(s,`SKILL.md`)))return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}CJ(o,{recursive:!0,force:!0});break;case`link`:case`link-to-canonical`:CJ(s,{recursive:!0,force:!0}),_J(c,{recursive:!0}),vJ(o,s);break;case`absent`:_J(c,{recursive:!0}),vJ(o,s)}return!G(H(s,`SKILL.md`))||xs(s).isSymbolicLink()?{ok:!1,reason:`target-unusable`}:(e.leaveLinkBehind===!0&&!G(o)&&SJ(d4(r,V(o),s),o,`dir`),g4({name:n,cwd:r,roots:a,target:s,skip:[s,o],alsoClaim:[o,s]}),{ok:!0,newAbs:s})}function p2e(e){return[`agents`,...s4(e===Ki?`global`:`project`)]}function m2e(e,t,n){return p2e(n).map(r=>l4(e,r,t,n)).filter(e=>e!==null)}function g4(e){let{name:t,cwd:n,roots:r,target:i}=e,a=new Set((e.skip??[]).map(e=>W(e))),o=new Set((e.alsoClaim??[]).map(e=>W(e))),s=e.slots??m2e(n,t,r);for(let e of s){if(a.has(W(e)))continue;try{if(!xs(e).isSymbolicLink())continue}catch{continue}let t=null;try{t=ks(e)}catch{t=null}t!==null&&!o.has(t)||(CJ(e,{recursive:!0,force:!0}),SJ(d4(n,V(e),i),e,`dir`))}}function _4(e){let{canonicalHash:t,name:n,cwd:r,targets:i}=e,a=e.roots??y,o;try{o=ks(e.canonicalAbs)}catch{return[]}let s=[];for(let e of i){let i=l4(r,e,n,a);if(i!==null&&!u4(r,V(i)))switch(p4(i,o,t)){case`same-copy`:case`link`:case`link-to-canonical`:CJ(i,{recursive:!0,force:!0}),s.push(e);break;case`different`:f2e(i,n)&&(CJ(i,{recursive:!0,force:!0}),s.push(e))}}return s.length>0&&g4({name:n,cwd:r,roots:a,target:o}),s}function v4(e,t,n,r=y){let i=[];for(let a of n){let n=c4(t,a,e,r);if(n===null)continue;let o=!1;try{xs(n),o=!0}catch{o=!1}o&&(CJ(n,{recursive:!0,force:!0}),i.push(a))}return i}function h2e(e){try{return G(e)?y4(e).filter(e=>e!==`SKILL.md`):[]}catch{return[]}}function y4(e,t=``){let n=[];for(let r of Ds(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...y4(H(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function g2e(e){if(!G(e))return[];let t=[];for(let n of y4(e)){if(n===`SKILL.md`)continue;let r=null;try{let t=K(H(e,n));t.length<=262144&&!t.includes(0)&&(r=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;r=null}t.push({path:n,text:r})}return t}function _2e(e){let t=[];G(W(e,`SKILL.md`))&&t.push(`SKILL.md`);let n=W(e,`references`);if(!G(n))return t;let r=(e,n)=>{let i;try{i=Ds(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;a.isDirectory()?r(W(e,a.name),i):a.isFile()&&a.name.toLowerCase().endsWith(`.md`)&&t.push(`references/${i}`)}};return r(n,``),t}function v2e(e){let{base:t,scope:n,fromName:r,toName:i}=e;if(r===i)return[];let a=q(`skill-ref-rename`),o;try{o=n===`project`?B2(t):V2(t)}catch(e){return a.warn({err:e,scope:n},`skill scan failed; refs to the old name are left as authored`),[]}let s=[];for(let e of o){let n=W(t,e.dir);for(let t of _2e(n)){let o=W(n,t),c;try{c=K(o,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`unreadable skill markdown; skipped`);continue}let l=ete(c,r,i);if(l!==c){try{hJ(o,l,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`skill ref rewrite could not be written; skipped`);continue}s.push({dir:e.dir,rel:t,absPath:o,markdown:l})}}}return s}function b4(e){return G(e)?QF(K(e,`utf-8`))||(q(`skills-lock`).warn({lockPath:e},`skills-lock.json is unreadable; continuing with an empty lock (import provenance for this project is lost)`),ZF()):ZF()}function y2e(e){if(!G(e))return{ok:!0,lock:ZF()};let t;try{t=K(e,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,lock:ZF()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let n=QF(t);return n===null?{ok:!1,reason:`its contents are not a skills lock this server understands`}:{ok:!0,lock:n}}const b2e=u2();function x4(e,t){return b2e(e,async()=>{let n=y2e(e);if(!n.ok)throw q(`skills-lock`).error({lockPath:e,reason:n.reason,err:n.cause},`refusing to rewrite skills-lock.json because it could not be read — rewriting it would replace every import it records with this one`),Error(`Refusing to rewrite ${e}: ${n.reason}`);let r=n.lock,i=t(r)??r;await mJ(V(e),{recursive:!0}),await jk(e,`${JSON.stringify(i,null,2)}\n`,{fs:TJ})})}function S4(e,t){let n=Object.keys(e).join(`, `);return async(r,i)=>{let a=r.method===void 0?void 0:e[r.method];if(a){await a(r,i);return}X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}function x2e(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,parseFrontmatterDoc:o,resolveSkillDirForRead:s,skillRelPath:c,derivedDocumentIndex:l,contentFilter:u,bumpSkillsCatalogGen:d,settleSkillCatalog:f,invalidateSkillCatalog:m,scheduleDeferredIgnoreRebuild:h,recordDerivedDocumentBestEffort:g,getPrincipal:_,rejectReservedBuiltinSkill:v,contentDir:y,attributeOkArtifactWrite:b,scheduleOkArtifactFlush:x,signalChannel:S,checkSkillDocConflictGate:C,extractAgentIdentity:w,sessionManager:T,flushDiskAndDetectOutcome:E,respondStaleExternalWrite:D,respondPersistenceFailure:O,respondDiskDivergence:k,okArtifactKey:A,resolveSkillsRoot:ee,extractActorIdentityFromQuery:j,captureAndCloseDocuments:M,log:N,commitOkArtifactWrite:P,skillInstallBase:te,uninstallSkillFromHostDirs:ne,renameTrackedPathInGit:re,renamePathOnDisk:ie,localSkillHash:ae,shadowHeadSha:oe,artifactWriterId:se,checkLocalOpSecurity:ce,effectiveSkillRoot:le}=e;function ue(e,t){let n=e===`project`?i:r;if(!n)return`symlink`;try{return b4(H(n,...XF)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function de(e){let t=e===`project`?i:r;return t?H(t,...XF):null}function fe(e,t,n,r={}){let i=de(e);return i?x4(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function pe(e,t,n,r=n){let i=de(e),a=de(t);if(!i||!a)return!1;let o=b4(i).skills[n];if(!o)return!1;let s={...o};return t===`global`&&delete s.baselineRef,await x4(a,e=>({...e,skills:{...e.skills,[r]:s}})),await x4(i,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function me(e,t,n){let r=de(e);return r?x4(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function he(e,t){let n=W(e,t,`references`);if(!G(n))return[];let r=[],i=(e,t)=>{for(let n of Ds(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(W(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function ge(e,t,n){if(!l){q(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=K(n,`utf-8`)}catch(i){q(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=U(y,e).split(us).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),W(e,n,`SKILL.md`));for(let r of he(e,n))i(o(t,r),o(n,r),W(e,n,r));await l.recordDirectMutations(r)}async function _e(e,t){if(!l||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await l.recordDirectMutations(n)}let ve=Z(Ii,async(e,l)=>{try{let u=new URL(e.url??``,`http://localhost`),d=u.searchParams.get(`name`)??``;if(!t(d,l,`skill-get`))return;let f=n(u.searchParams.get(`scope`),l,`skill-get`);if(f===null)return;if(d1(d)){let e=f===`global`?r:i,t=e?a(e,d,f,u.searchParams.get(`host`)??void 0):null;if(t){let{frontmatter:e,body:n}=o(await Ks(t.skillMd,`utf-8`));Q(l,200,lee,{skill:{name:d,scope:f,path:t.relPath,frontmatter:{name:typeof e.name==`string`?e.name:d,description:typeof e.description==`string`?e.description:``},body:n,files:g2e(t.dir),managed:!0}},{handler:`skill-get`});return}}let p=u.searchParams.get(`host`)??void 0,m=s(f,d,p);if(m===null){X(l,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:p===void 0?`Skill "${d}" not found in ${f} scope.`:`No skill "${d}" (${f}) in ${p}.`});return}let h=W(m,`SKILL.md`),{frontmatter:g,body:_}=o(await Ks(h,`utf-8`));Q(l,200,lee,{skill:{name:d,scope:f,path:c(h,f),frontmatter:{name:typeof g.name==`string`?g.name:d,description:typeof g.description==`string`?g.description:``},body:_,files:g2e(m)}},{handler:`skill-get`})}catch(e){X(l,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function ye(e,t){!l||rX(e)||(u&&(d(),u.refreshInPlaceSkillDirs(),h()),g(e,t,`skill-put`))}let be=Z(Sre,async(e,n,i)=>{try{let e=C1(i,_);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!t(i.name,n,`skill-put`)||v(i.name,n,`skill-put`))return;let a=_0e({name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!a.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=i.scope===`project`?y:r,c=s(i.scope,i.name);if(c===null){let t=z2(o,i.scope);if(t===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let r=S2({skillsRoot:W(o,t),name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!r.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}i.scope===`project`&&(b(e,`${t}/${i.name}/SKILL`,`skill-create: ${t}/${i.name}/SKILL.md`),x(`skill-put`)),await ye(i.scope===`project`?`${t}/${i.name}/SKILL`:gr(`global`,i.name),a.content),S?.(`files`),Q(n,200,One,{path:`${t}/${i.name}/SKILL.md`,created:!0,warnings:r.warnings,warningCodes:r.warningCodes},{handler:`skill-put`});return}let l=U(o,c).split(us).join(`/`),u=`${l}/SKILL.md`,d=i.scope===`project`?`${l}/SKILL`:gr(i.scope,i.name);if(C(d,`skill-put`,n))return;let{agentId:f,agentName:p,colorSeed:m,clientName:h}=w(i),g=await T.getSession(d,f,{displayName:p,colorSeed:m,clientName:h});g.dc.document.transact(()=>{Zq(g.dc.document,a.content,`agent`)},g.origin);let ee=await E(d);if(ee?.kind===`failure`){O(n,ee.failure,`skill-put`);return}if(ee?.kind===`divergence`){k(n,`skill-put`);return}if(ee?.kind===`stale-external-write`){D(n,`skill-put`,d);return}i.scope===`project`&&(b(e,A(`skill`,``,i.name),`skill-edit: ${u}`),x(`skill-put`)),await ye(d,a.content),S?.(`files`),Q(n,200,One,{path:u,created:!1,warnings:a.warnings,warningCodes:a.warningCodes},{handler:`skill-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function xe(e,t){let n=e===`project`?y:r,i=(e===`project`?B2(y):V2(r)).find(e=>e.name===t);return i?_4({canonicalAbs:W(n,i.dir),canonicalHash:i.contentHash,name:t,cwd:n,targets:i.hosts.filter(e=>$r(e)),roots:o4(e)}):[]}let Se=Z(Ii,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams.get(`name`)??``;if(!t(a,r,`skill-delete`))return;let o=n(i.searchParams.get(`scope`),r,`skill-delete`);if(o===null)return;let s=i.searchParams.get(`host`)??void 0,{root:c,dirRel:l,realDir:u}=le(o,a,s),f=s===void 0?te(o):void 0,p=f===void 0?{state:`none`}:Z2(f,o,a),m=p.state===`record`&&p.record.sourceState!==`intact`&&p.record.retainedContentHash!==``&&u!==null?ke(u):void 0;if(s!==void 0&&u===null){X(r,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${a}" (${o}) in ${s}.`});return}let h=j(i,_);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await M(o===`project`?[...new Set([`${l}/SKILL`,gr(o,a)])]:[gr(o,a,s)],`deleted-upstream`),s===void 0&&xe(o,a);let g=E2({skillsRoot:c,name:a}),v=ee(o);if(s===void 0&&g.ok&&v!==c&&G(W(v,a,`SKILL.md`))){let e=E2({skillsRoot:v,name:a});e.ok||N.warn({name:a,scope:o,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!g.ok){let e=g.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:g.error.code,cause:Error(g.error.message)});return}g.existed&&(o===`project`&&(b(h,l,`skill-delete: ${l}`),d(),P(`skill-delete`)),S?.(`files`));let y=te(o),x=[];if(s===void 0&&y)try{await ne(y,a,o)}catch(t){N.error({requestId:lX(e),handler:`skill-delete`,name:a,scope:o,err:t},`[skill-delete] skill content removed, but install bookkeeping could not be updated`),x.push(`The skill was deleted, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(s===void 0){if(p.state===`record`&&p.record.sourceState!==`intact`){let t=p.record,n=t.retainedContentHash!==``&&m?.ok===!0&&t.retainedContentHash===m.hash,r=m!==void 0&&!m.ok&&m.kind!==`absent`,i=t.from===``?`an earlier move`:`a move of "${t.from}"`,s=t.retainedAt?` on ${t.retainedAt}`:``;(n||r)&&N.error({requestId:lX(e),handler:`skill-delete`,name:a,scope:o,from:t.from,retainedAt:t.retainedAt,sourceState:t.sourceState,verified:n,...r&&m.kind===`read-error`?{err:m.cause}:{}},n?`[skill-delete] deleted a copy this server retained when an earlier move failed to remove its source; the source was never verified unchanged, so files that only existed here may now be gone`:`[skill-delete] deleted a directory carrying an unverified retained-copy record; this server could not read that directory before removing it, so it could not confirm whether it was the copy an earlier failed move retained`),n?x.push(`A recovery copy was deleted: ${i} failed to remove its source${s}, and this server kept this copy in case it held files that failed removal had already deleted. That source was never verified unchanged. Check the other location before relying on this deletion.`):r&&x.push(`A directory this server could not read was deleted: ${i} failed to remove its source${s}, and this server has a record of keeping a copy under this name in case it held files that failed removal had already deleted. It could not read the directory before removing it, so it could not confirm whether that was the copy it kept. Check the other location before assuming nothing was lost.`)}await je(f,o,a,{requestId:lX(e),handler:`skill-delete`})}Q(r,200,ln,{existed:g.existed,path:g.path,...x.length>0?{warnings:x}:{}},{handler:`skill-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Ce=Z(jee,async(e,n,a)=>{try{let l=C1(a,_);if(l.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!t(a.fromName,n,`skill-move`)||!t(a.toName,n,`skill-move`)||v(a.toName,n,`skill-move`))return;let{root:u,dirRel:d}=le(a.scope,a.fromName),f=s(a.scope,a.toName);if(f!==null){let t=te(a.scope),r=t===void 0?{state:`none`}:Z2(t,a.scope,a.toName),i=ke(f),{verdict:o,detail:s}=Ae(le(a.scope,a.toName).dirRel,r,i);r.state===`record`&&o.kind===`plain-collision`&&await je(t,a.scope,a.toName,{requestId:lX(e),handler:`skill-move`}),X(n,409,`urn:ok:error:doc-already-exists`,`A skill named "${a.toName}" already exists.`,{handler:`skill-move`,detail:s??`Delete or rename it first; this move will not overwrite it.`,...!i.ok&&i.kind===`read-error`?{cause:i.cause}:r.state===`unreadable`&&r.cause!==void 0?{cause:r.cause}:{}});return}let p=te(a.scope),h=p?G2(p).skills[a.fromName]:void 0,g=a.scope===`project`?y:r,x=(a.scope===`project`?B2(y):V2(r)).find(e=>e.name===a.fromName),C=x?V(x.dir):null,w=C===null?[]:Object.entries(F2(g,a.scope)).filter(([,e])=>e===C).map(([e])=>e),T=[...new Set([...h?r4(h.hosts,a.scope):[],...x?r4(x.hosts,a.scope):[],...r4(w,a.scope)])];await M(a.scope===`project`?[...new Set([`${d}/SKILL`,gr(a.scope,a.fromName)])]:[gr(a.scope,a.fromName)],`renamed`),xe(a.scope,a.fromName);let E=await x0e({skillsRoot:u,fromName:a.fromName,toName:a.toName,relocate:async(e,t)=>{let n=await re(i,e,t);return n||ie(e,t),n}});if(!E.ok){if(E.error.code===`SKILL_NOT_FOUND`){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:E.error.message});return}if(E.error.code===`SKILL_EXISTS`){X(n,409,`urn:ok:error:doc-already-exists`,E.error.message,{handler:`skill-move`,detail:E.error.code});return}let e=E.error.code===`MOVE_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:E.error.code,cause:Error(E.error.message)});return}let D=null,O=W(u,a.toName,`SKILL.md`),k=``,ee=``;try{let e=o(K(O,`utf-8`));k=e.body,typeof e.frontmatter.description==`string`&&(ee=e.frontmatter.description)}catch{}let j=typeof a.body==`string`?a.body:k,ne=a.frontmatter===void 0?ee:a.frontmatter.description,ce=S2({skillsRoot:u,name:a.toName,body:j,frontmatter:{name:a.toName,description:ne}});ce.ok||(D=ce.error);let de=[];if(!D)try{de=v2e({base:a.scope===`project`?y:r,scope:a.scope,fromName:a.fromName,toName:a.toName})}catch(e){q(`skill-move`).warn({err:e,fromName:a.fromName,toName:a.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}a.scope===`project`&&!D&&(m(),ge(u,a.fromName,a.toName).then(()=>_e(de,a.toName)).catch(()=>{}));let pe=c(W(u,a.fromName),a.scope),he=c(W(u,a.toName),a.scope),ve=ae(u,a.toName),ye=[],be=(e,t)=>{N.error({err:e,fromName:a.fromName,toName:a.toName,scope:a.scope},`skill renamed, but its bookkeeping could not be updated`),ye.push(`The skill was renamed to "${a.toName}", but this server could not update its ${t} (${Me(e)}). A stale entry may remain until that file is repaired.`)};try{await fe(a.scope,a.fromName,a.toName,{localHash:ve})}catch(e){be(e,`import records`)}if(a.scope===`project`&&(b(l,A(`skill`,``,a.toName),`skill-rename: ${pe} -> ${he}`,[{from:pe,to:he}]),(async()=>{try{await P(`skill-move`);let e=await oe(se(l),he);e!==void 0&&await me(`project`,a.toName,{baselineRef:e})}catch(e){q(`skill-move`).warn({err:e,toName:a.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),p){try{await q2(p,a.fromName)}catch(e){be(e,`install records`)}v4(a.fromName,p,T,o4(a.scope));let e=W(u,a.toName);if(T.length>0){let t=f4(e,a.toName,p,T,ue(a.scope,a.toName),o4(a.scope));try{await K2(p,a.toName,{...h,scope:a.scope,hosts:t,scripts:h?.scripts??i4(e,a.toName).hasScripts,installedAt:h?.installedAt??new Date().toISOString()})}catch(e){be(e,`install records`)}}}if(S?.(`files`),D){let e=D.code===`WRITE_ERROR`;X(n,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${a.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:D.code,cause:Error(D.message)});return}Q(n,200,mte,{from:pe,to:he,committed:E.committed,...ye.length>0?{warnings:ye}:{}},{handler:`skill-move`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),we=Z(Ge,async(e,n,r)=>{let{name:i,home:a}=r;if(!t(i,n,`skill-edit-external`))return;let o;try{o=ks(a)}catch{X(n,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!Ns(o).isDirectory()||!G(W(o,`SKILL.md`))){X(n,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}E0e(i,o),Q(n,200,xt,{docName:Dre(i)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>ce(e,t,{handler:`skill-edit-external`})}),Te={retained:void 0,"plain-collision":void 0,"stray-occupant":void 0,"ledger-unreadable":`unreadable`,"occupant-unverifiable":`occupant-unverifiable`,"retained-slot-unverifiable":`occupant-unverifiable`,"occupant-unreadable":`occupant-unverifiable`},Ee=null;function De(){return Ee||=Uq().createCounter(`ok.skill_move_scope.outcome`,{description:"Count of cross-scope skill-move handler invocations by terminal outcome, one per invocation. Bounded labels: move_state ∈ SKILL_MOVE_STATE_CODES plus `success`; source_state ∈ SKILL_SOURCE_STATE_CODES plus `none`; retention_ledger ∈ SKILL_RETENTION_LEDGER_CODES plus `none`. Skill names, filesystem paths, droppedLocations, problem detail text, error messages and request IDs are never labels. Transport-level and schema-level rejections happen outside the handler and stay covered by ok.api.error."}),Ee}function Oe(e,t,n,r){De().add(1,{move_state:e,source_state:t??`none`,retention_ledger:n??`none`}),q(`skill-move-scope`)[r?.logLevel??((r?.status??200)>=500?`error`:`warn`)]({event:`skill-move-scope.outcome`,...r?.instance===void 0?{}:{instance:r.instance},...r?.requestId===void 0?{}:{requestId:r.requestId},handler:`skill-move-scope`,...r?.status===void 0?{}:{status:r.status},moveState:e,sourceState:t??null,retentionLedger:n??null,droppedLocationCount:r?.droppedLocationCount??0},r?.message??`cross-scope skill move did not complete`)}function ke(e){try{let t=oI(e);return t===null?G(e)?{ok:!1,kind:`no-manifest`,reason:`it has no readable SKILL.md`}:{ok:!1,kind:`absent`,reason:`it does not exist`}:{ok:!0,hash:t.contentHash}}catch(e){let t=e?.code;return{ok:!1,kind:`read-error`,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}}function Ae(e,t,n){let r=t.state===`record`?t.record:null,i=r!==null&&r.retainedContentHash!==``&&n.ok&&r.retainedContentHash===n.hash?r:null,a=r!==null&&r.from!==``?`a move of "${r.from}"`:`an earlier move`,o=r?.retainedAt?` on ${r.retainedAt}`:``;return i?.sourceState===`intact`?{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. That source was verified unchanged, so this copy is a redundant duplicate whose install records never transferred: remove it, then retry. This call wrote nothing.`}:i===null?t.state===`unreadable`?{verdict:{kind:`ledger-unreadable`},detail:`A directory already exists at ${e}, and this server could not read its retained-destination ledger (${t.reason}), so it cannot tell whether that directory is a copy an earlier failed move retained. Do NOT delete it before comparing it against the source. This call wrote nothing.`}:r!==null&&!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`retained-slot-unverifiable`},detail:`A directory already exists at ${e} with no readable SKILL.md, and this server has a record of retaining a copy under this name${o} when ${a} failed to remove the source. Nothing in it could be matched against that record, so verify it against the source before assuming it is that copy.`}:r!==null&&!n.ok?{verdict:{kind:`occupant-unverifiable`},detail:`A directory already exists at ${e}, and this server has a record of retaining a copy under that name${o} from ${a}, but it could not read that directory to confirm the copy is the one it retained (${n.reason}). Do NOT delete it before comparing it against the source. This call wrote nothing.`}:!n.ok&&n.kind===`read-error`?{verdict:{kind:`occupant-unreadable`},detail:`A directory exists at ${e} and this server could not read it to determine whether it is a skill (${n.reason}). Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`stray-occupant`},detail:`A directory exists at ${e} with no readable SKILL.md. Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:{verdict:{kind:`plain-collision`},detail:void 0}:{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. Do NOT delete it before reconciling it against the source: it may hold the only copy of files that failed removal already deleted. Reconcile the two locations, then remove whichever copy is redundant. This call wrote nothing.`}}async function je(e,t,n,r){if(e!==void 0)try{await Q0e(e,t,n)}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.retention-clear-failed`,scope:t,name:n,...r,err:e},`could not clear a retained-destination record — a later collision on this name may still report it as retained`)}}let Me=e=>e instanceof Error?e.message:String(e),Ne={"nothing-written":!1,"destination-removed":!0,"destination-stray":!0,"destination-retained":!0,"destination-retained-blocking":!1,"destination-unreadable":!0,"partially-applied":!0},Pe=Z(Kn,async(e,n,a)=>{let o;try{o=C1(a,_)}catch(t){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,detail:`Could not resolve who is making the request. Nothing was written.`,extensions:{moveState:`nothing-written`,droppedLocations:[]},cause:t}),Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}let c=f,l=!1,u=!1,d=[],m=(t,r,i,a)=>{let o=`urn:uuid:${tc()}`;Oe(a.moveState,a.sourceState,a.retentionLedger,{instance:o,requestId:lX(e),status:t,droppedLocationCount:d.length,...a.logLevel===void 0?{}:{logLevel:a.logLevel}}),(u||Ne[a.moveState])&&c(),X(n,t,r,i,{instance:o,handler:`skill-move-scope`,...a.detail===void 0?{}:{detail:a.detail},extensions:{moveState:a.moveState,droppedLocations:d,...a.sourceState===void 0?{}:{sourceState:a.sourceState},...a.retentionLedger===void 0?{}:{retentionLedger:a.retentionLedger}},...a.cause===void 0?{}:{cause:a.cause},...a.logLevel?{logLevel:a.logLevel}:{}})};try{if(o.kind===`invalid-summary`){m(400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{moveState:`nothing-written`});return}let{name:f,fromScope:h,toScope:g}=a,_=a.toName??f,v={moveState:`nothing-written`,droppedLocations:[]};if(!t(f,n,`skill-move-scope`,v)){Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}if(!t(_,n,`skill-move-scope`,v)){Oe(`nothing-written`,void 0,void 0,{requestId:lX(e),status:400});return}if(d1(f)){m(400,`urn:ok:error:invalid-request`,`"${f}" is a built-in skill and always lives at its own scope.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(d1(_)){m(400,`urn:ok:error:invalid-request`,`"${_}" is a built-in skill name and cannot be used as a destination name.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(h===g){m(400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{moveState:`nothing-written`});return}if(g===`project`&&!i){m(400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{moveState:`nothing-written`,detail:`NO_PROJECT_ROOT`});return}let{root:x,dirRel:S,realDir:C}=le(h,f),w=W(x,f),T=(()=>{try{return ks(w)}catch{return w}})(),E=g===`project`?y:r,D=z2(E,g);if(D===null){m(400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{moveState:`nothing-written`,detail:`NO_USABLE_SKILL_HOME`});return}let O=W(E,D),k=W(O,_),A=U(E,k).split(us).join(`/`);if(C===null||!G(w)){m(404,`urn:ok:error:not-found`,`Skill not found.`,{moveState:`nothing-written`,detail:`Skill "${f}" not found in ${h} scope.`});return}if(W(C)===W(k)||G(k)&&ks(C)===ks(k)){m(409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{moveState:`nothing-written`,detail:`SAME_STORAGE`});return}if(s(g,_)!==null||G(k)){let t=te(g),n=t!==void 0&&G(k)?Z2(t,g,_):{state:`none`},r=ke(k),{verdict:i,detail:a}=Ae(A,n,r);n.state===`record`&&i.kind===`plain-collision`&&await je(t,g,_,{requestId:lX(e),handler:`skill-move-scope`,toDirRel:A});let o=Te[i.kind],s=i.kind===`retained`?{moveState:`destination-retained-blocking`,sourceState:i.record.sourceState}:{moveState:`nothing-written`,...o===void 0?{}:{retentionLedger:o}};m(409,`urn:ok:error:doc-already-exists`,`A ${g} skill named "${_}" already exists.`,{...s,detail:a??`Delete or rename it first; this move will not overwrite it.`,...!r.ok&&r.kind===`read-error`?{cause:r.cause}:n.state===`unreadable`&&n.cause!==void 0?{cause:n.cause}:{}});return}let ee=te(h),j=te(g),N=ee?G2(ee).skills[f]:void 0,re=h===`project`?y:r,ie=(h===`project`?B2(y):V2(r)).find(e=>e.name===f),ce=ie?V(ie.dir):null,de=ce===null?[]:Object.entries(F2(re,h)).filter(([,e])=>e===ce).map(([e])=>e),fe=[...new Set([...N?r4(N.hosts,h):[],...ie?r4(ie.hosts,h):[],...r4(de,h)])],he=e=>e.filter(e=>r4([e],g).length===0),ge=[...new Set([...he(N?.hosts??[]),...he(ie?.hosts??[])])].sort();if(u=!0,await M([...new Set([...h===`project`?[`${S}/SKILL`]:[],gr(h,f),gr(g,_)])],`renamed`),l=!0,_J(O,{recursive:!0}),yJ(T,k,{recursive:!0,dereference:!0}),_!==f){let e=(e,t,n,r)=>{let i=E2({skillsRoot:O,name:_});m(i.ok?e:500,i.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,i.ok?`Failed to rename the copied skill; destination copy removed.`:`Failed to rename the copied skill; destination cleanup failed.`,{moveState:i.ok?`destination-removed`:`destination-stray`,detail:i.ok?`Rename failed (${t}). The source "${h}:${f}" was not removed.`:`Rename failed (${t}); destination cleanup failed (${i.error.code}). The source "${h}:${f}" was not removed. A partial copy may remain at "${g}:${_}" (${A}). Inspect the destination before retrying.`,cause:i.ok?n:Error(i.error.message,{cause:n}),...r?{logLevel:r}:{}})};try{let t=oI(k);if(t===null){e(400,`UNREADABLE_SKILL`,Error(`UNREADABLE_SKILL`),`error`);return}let n=C2({skillDir:k,toName:_,skillMd:t.skillMd});if(!n.ok){if(n.stage===`patch`){let t=D0e(n.error);e(400,t,Error(t),`error`)}else e(500,`RENAME_FAILED`,n.cause);return}}catch(t){e(500,`RENAME_FAILED`,t);return}}if(!G(H(k,`SKILL.md`))){let e=E2({skillsRoot:O,name:_});m(500,`urn:ok:error:internal-server-error`,e.ok?`The copied skill is unreadable; destination copy removed.`:`The copied skill is unreadable; destination cleanup failed.`,{moveState:e.ok?`destination-removed`:`destination-stray`,detail:e.ok?`No readable SKILL.md at the destination copy (${A}); it was removed. The source "${h}:${f}" was not touched and is unchanged.`:`No readable SKILL.md at the destination copy (${A}); cleanup failed (${e.error.code}). The source "${h}:${f}" was not touched and is unchanged. A partial copy remains at "${g}:${_}". Inspect the destination before retrying.`,...e.ok?{}:{cause:Error(e.error.message)}});return}d=[...new Set(xe(h,f))].sort();let _e=E2({skillsRoot:x,name:f});if(_e.ok&&T!==w){let e=(()=>{try{return ks(re)}catch{return re}})(),t=U(e,T);t!==``&&!t.startsWith(`..`)&&!os(t)&&CJ(T,{recursive:!0,force:!0})}if(!_e.ok){let t,n=(()=>{if(!ie)return`unknown`;try{let e=oI(w);return e&&e.contentHash===ie.contentHash?`intact`:`lossy`}catch(e){return t=e,`unknown`}})(),r=!1,i=ke(k);if(j!==void 0){let t=i.ok?void 0:Error(`the destination copy could not be hashed (${i.reason})`,{cause:i.kind===`read-error`?i.cause:void 0});if(i.ok)try{await Z0e(j,g,_,{retainedAt:new Date().toISOString(),from:`${h}:${f}`,to:`${g}:${_}`,sourceState:n,reason:_e.error.code,retainedContentHash:i.hash}),r=!0}catch(e){t=e}r||q(`skill-move-scope`).error({event:`skill-move-scope.retention-record-failed`,requestId:lX(e),handler:`skill-move-scope`,toScope:g,toDirRel:A,sourceState:n,err:t},`could not record the retained destination copy — a retry will report an ordinary name collision instead of a retained copy`)}let a=r?``:i.ok?` This server could not record the retention, so a retry will not recognise ${A} as a copy it retained and will report an ordinary name collision instead.`:` This server could not read the destination copy at ${A} to confirm it is intact (${i.reason}), so do not rely on it for recovery until you have inspected it yourself. It was not recorded as a retained copy either, so a retry will report an ordinary name collision instead.`;m(500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); destination copy retained for recovery.`,{moveState:`destination-retained`,sourceState:n,detail:n===`intact`?`Source removal failed (${_e.error.code}) without deleting anything. The source "${h}:${f}" is unchanged at its original scope, so no files were lost. The destination copy "${g}:${_}" at ${A} is a duplicate whose install records have not transferred; remove it before retrying.${a}`:n===`lossy`?`Source removal failed (${_e.error.code}). The source "${h}:${f}" may be partially removed. The destination copy "${g}:${_}" remains at ${A}; its install records have not transferred. Inspect both locations before retrying, and recover missing source files from the retained copy.${a}`:`Source removal failed (${_e.error.code}). The source "${h}:${f}" could not be verified against a known content hash, so whether any files were lost is unknown. The destination copy "${g}:${_}" remains at ${A}; its install records have not transferred. Compare both locations before removing either.${a}`,cause:t?Error(_e.error.message,{cause:t}):Error(_e.error.message)});return}await je(j,g,_,{requestId:lX(e),handler:`skill-move-scope`,toDirRel:A});let ve=[],ye=!1;try{if(ye=await pe(h,g,f,_),ee&&await ne(ee,f,h,ie?{purge:{contentHash:ie.contentHash}}:{}),ee&&await i2e(ee,f),j&&fe.length>0){let e=f4(k,_,j,fe,ue(g,_),o4(g));await K2(j,_,{...N,scope:g,hosts:e,scripts:N?.scripts??i4(k,_).hasScripts,installedAt:N?.installedAt??new Date().toISOString()})}ye&&await me(g,_,{localHash:ae(O,_)})}catch(t){q(`skill-move-scope`).error({err:t,name:f,toName:_,fromScope:h,toScope:g,requestId:lX(e)},`skill moved across scopes, but its bookkeeping could not be updated`),ve.push(`The skill moved to ${g}, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(!G(H(k,`SKILL.md`))){m(500,`urn:ok:error:internal-server-error`,`The source was removed, but the destination skill is unreadable.`,{moveState:`destination-unreadable`,detail:`Inspect "${g}:${_}" at ${A} before retrying. Restore the skill from a backup, or check the project Timeline / shadow-repo history for an earlier version if available.`});return}if(h===`project`||g===`project`){b(o,h===`project`?S:U(y,k).split(us).join(`/`),`skill-move-scope: ${h} -> ${g} ${f}${_===f?``:` -> ${_}`}`);let t=U(y,k).split(us).join(`/`),n=!!ye&&g===`project`,r=lX(e);(async()=>{let e=await P(`skill-move-scope`);if(n){if(e!==`flushed`){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,flush:e},`the deferred shadow flush did not complete, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}try{let n=await oe(se(o),t);if(n===void 0){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,flush:e},`no shadow head was readable after the flush, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}await me(g,_,{baselineRef:n})}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.baseline-update-failed`,requestId:r,handler:`skill-move-scope`,toScope:g,toName:_,err:e},`could not record the Revert baseline for the moved skill, so this move did not establish or update its baseline; any baseline an earlier write recorded is unchanged`)}}})()}c(),Oe(`success`,void 0,void 0,{requestId:lX(e),status:200,droppedLocationCount:ge.length,logLevel:`debug`,message:`cross-scope skill move completed`}),Q(n,200,p,{scope:g,path:A,droppedLocations:ge,...ve.length>0?{warnings:ve}:{}},{handler:`skill-move-scope`})}catch(e){m(500,`urn:ok:error:internal-server-error`,l?`Failed to move skill across scopes; the move may be partially applied.`:`Failed to move skill across scopes; nothing was written.`,{moveState:l?`partially-applied`:`nothing-written`,detail:l?`Inspect the source "${a.fromScope}:${a.name}" and destination "${a.toScope}:${a.toName??a.name}" before retrying. Preserve any remaining copies and recover missing files from a backup or available project Timeline / shadow-repo history.`:`The failure happened before any file was copied, so no files were copied or removed for "${a.fromScope}:${a.name}" or "${a.toScope}:${a.toName??a.name}". Retrying is safe once the underlying error clears.`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),Fe=Z(vn,async(e,n,i)=>{let a=f,o=!1,c=!1,l=!1;try{let e=C1(i,_);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!t(i.name,n,`skill-duplicate`)||!t(i.toName,n,`skill-duplicate`)||v(i.toName,n,`skill-duplicate`))return;let u=s(i.scope,i.name);if(u===null||!G(H(u,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let d=i.scope===`project`?y:r,f=z2(d,i.scope);if(f===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let p=W(d,f),m=W(p,i.toName);if(s(i.scope,i.toName)!==null||G(m)){X(n,409,`urn:ok:error:doc-already-exists`,`A ${i.scope} skill named "${i.toName}" already exists.`,{handler:`skill-duplicate`});return}let h=oI(u);if(!h){X(n,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}let g=U(d,m).split(us).join(`/`);o=!0,_J(p,{recursive:!0}),c=!0,yJ(u,m,{recursive:!0,dereference:!0}),l=!0;let x=(e,t,r,o)=>{let s=E2({skillsRoot:p,name:i.toName});a(),X(n,s.ok?e:500,s.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,s.ok?`Failed to write duplicated skill; destination copy removed.`:`Failed to write duplicated skill; destination cleanup failed.`,{handler:`skill-duplicate`,detail:s.ok?`Duplicate failed (${t}). The source "${i.scope}:${i.name}" was not touched.`:`Duplicate failed (${t}); destination cleanup failed (${s.error.code}). The source "${i.scope}:${i.name}" was not touched. A partial copy may remain at "${i.scope}:${i.toName}" (${g}). Inspect the destination before retrying.`,cause:s.ok?r:Error(s.error.message,{cause:r}),...o?{logLevel:o}:{}})},S=C2({skillDir:m,toName:i.toName,skillMd:h.skillMd});if(!S.ok){if(S.stage===`patch`){let e=D0e(S.error);x(400,e,Error(e),`error`)}else x(500,`WRITE_FAILED`,S.cause);return}if(i.scope===`project`){let t=U(y,m).split(us).join(`/`);b(e,A(`skill`,``,i.toName),`skill-duplicate: ${i.name} -> ${t}`),P(`skill-duplicate`)}a(),Q(n,200,In,{name:i.toName},{handler:`skill-duplicate`})}catch(e){o&&a(),X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,...l?{detail:`A complete copy was created at "${i.scope}:${i.toName}" and was left in place. Inspect it before retrying.`}:c?{detail:`A copy of "${i.scope}:${i.name}" was started at "${i.scope}:${i.toName}" and may be incomplete; it was left in place, and its SKILL.md may still carry the source's name. Inspect or remove it before retrying.`}:{},cause:e})}},{handler:`skill-duplicate`,method:`POST`});return L1({"/api/skill":S4({GET:ve,PUT:be,POST:Ce,DELETE:Se},{handler:`skill`}),"/api/skill/edit-external":we,"/api/skill/duplicate":Fe,"/api/skill/move-scope":Pe},{mutating:[`/api/skill`,`/api/skill/edit-external`,`/api/skill/duplicate`,`/api/skill/move-scope`]})}function S2e(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,resolveSkillDirForRead:o,resolveSkillsRoot:s,getPrincipal:c,rejectReservedBuiltinSkill:l,contentDir:u,checkSkillDocConflictGate:d,extractAgentIdentity:f,sessionManager:p,flushDiskAndDetectOutcome:m,respondStaleExternalWrite:h,respondPersistenceFailure:g,respondDiskDivergence:_,attributeOkArtifactWrite:v,okArtifactKey:y,commitOkArtifactWrite:b,signalChannel:x,extractActorIdentityFromQuery:S,captureAndCloseDocuments:C,derivedDocumentIndex:w,log:T,recordDerivedMutationsBestEffort:E}=e;function D(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function O(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function k(e,t){let n=W(e,t),r=U(u,e).split(us).join(`/`),i;try{i=Ds(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(us).join(`/`).replace(/\.md$/i,``)}`)}function A(e,t){let n=t.replace(/\.md$/i,``);return`${Ure(e).replace(/\/SKILL$/,``)}/${n}`}return L1({"/api/skill-file":S4({GET:Z(Ii,async(e,c)=>{try{let l=new URL(e.url??``,`http://localhost`),u=l.searchParams.get(`name`)??``;if(!t(u,c,`skill-file-get`))return;let d=n(l.searchParams.get(`scope`),c,`skill-file-get`);if(d===null)return;let f=l.searchParams.get(`path`)??``,p=d1(u)?d===`global`?r:i:void 0,m=l.searchParams.get(`host`)??void 0,h=p?a(p,u,d,m):null;if(f===``||f.includes(`\0`)){X(c,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let g=(h&&f===`SKILL.md`?`reference`:D(f))??`reference`,_=m,v=p?h?.dir??null:o(d,u,_);if(v===null&&_!==void 0){X(c,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${u}" (${d}) in ${_}.`});return}let y=v??W(s(d),u),b=W(y,f);if(b!==y&&!b.startsWith(`${y}${us}`)){X(c,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let x=b,S=f;if(!G(x)){let e=f.match(/^(.*)\.(?:md|mdx)$/),t=e?Qr.map(t=>`${e[1]}${t}`).find(e=>e!==f&&G(W(y,e))):void 0;if(t===void 0){X(c,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${f} not found in skill "${u}" (${d}).`});return}S=t,x=W(y,t)}let C=await Ks(x);if(C.includes(0)){X(c,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}Q(c,200,ir,{path:S.replace(/\\/g,`/`),kind:g,text:C.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(gie,async(e,n,i)=>{try{let e=C1(i,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!t(i.name,n,`skill-file-put`)||l(i.name,n,`skill-file-put`))return;let a=D(i.path);if(a===null){X(n,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(i.content,`utf-8`)>262144){X(n,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let s=o(i.scope,i.name);if(s===null||!G(H(s,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${i.name}" before adding bundle files.`});return}let S=i.scope===`project`?u:r,C=U(S,s).split(us).join(`/`),w=i.path.replace(/\\/g,`/`),T=O(i.scope,a,w),E;if(T){let e=`${C}/${w.replace(/\.mdx?$/i,``)}`;if(d(e,`skill-file-put`,n))return;if(E=!G(W(s,w)),E&&v0e(s)>=50){X(n,400,`urn:ok:error:invalid-request`,`Skill "${i.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:t,agentName:r,colorSeed:a,clientName:o}=f(i),c=await p.getSession(e,t,{displayName:r,colorSeed:a,clientName:o});c.dc.document.transact(()=>{Zq(c.dc.document,i.content,`agent`)},c.origin);let l=await m(e);if(l?.kind===`failure`){g(n,l.failure,`skill-file-put`);return}if(l?.kind===`divergence`){_(n,`skill-file-put`);return}if(l?.kind===`stale-external-write`){h(n,`skill-file-put`,e);return}}else{let e=T2({skillsRoot:V(s),name:i.name,relPath:w,content:i.content});if(!e.ok){let t=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;X(n,t,t===500?`urn:ok:error:internal-server-error`:t===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,t===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}E=e.created}i.scope===`project`&&(v(e,y(`skill`,``,i.name),`${E?`skill-file-create`:`skill-file-edit`}: ${C}/${w}`),b(`skill-file-put`)),x?.(`files`),Q(n,200,te,{path:w,created:E,kind:a,content:T},{handler:`skill-file-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:Z(Ii,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams,d=a.get(`name`)??``;if(!t(d,r,`skill-file-delete`)||l(d,r,`skill-file-delete`))return;let f=n(a.get(`scope`),r,`skill-file-delete`);if(f===null)return;let p=(a.get(`path`)??``).replace(/\\/g,`/`),m=D(p);if(m===null){X(r,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let h=S(i,c);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let g=o(f,d),_=g===null?s(f):V(g),w=W(g??H(_,d),p);if(G(w)&&O(f,m,p)){let e=p.replace(/\.md$/i,``),t=g===null?A(d,p):`${U(u,g).split(us).join(`/`)}/${e}`;await C([t],`deleted-upstream`)}else if(f===`project`&&g!==null&&G(w)&&Ns(w).isDirectory()){let e=k(g,p);e.length>0&&await C(e,`deleted-upstream`)}let T=b0e({skillsRoot:_,name:d,relPath:p});if(!T.ok){let e=T.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:T.error.code,cause:Error(T.error.message)});return}T.existed&&f===`project`&&(v(h,y(`skill`,``,d),`skill-file-delete: ${g===null?`${d}/${p}`:`${U(u,g).split(us).join(`/`)}/${p}`}`),b(`skill-file-delete`)),T.existed&&x?.(`files`),Q(r,200,$t,{path:p,existed:T.existed,kind:m},{handler:`skill-file-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),"/api/skill-file/rename":Z(Vr,async(e,n,r)=>{try{if(!t(r.name,n,`skill-file-rename`)||l(r.name,n,`skill-file-rename`))return;let e=C1(r,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let i=r.from.replace(/\\/g,`/`),a=r.to.replace(/\\/g,`/`),s=D(i),f=D(a);if(s===null||f===null){X(n,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:s===null?i:a});return}let p=o(r.scope,r.name);if(p===null){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let m=V(p),h=O(r.scope,s,i),g=O(r.scope,f,a),_=U(u,p).split(us).join(`/`),S=h?`${_}/${i.replace(/\.md$/i,``)}`:null,T=g?`${_}/${a.replace(/\.md$/i,``)}`:null;if(S!==null&&d(S,`skill-file-rename`,n))return;if(S!==null)await C([S],`deleted-upstream`);else if(r.scope===`project`){let e=W(p,i);if(G(e)&&Ns(e).isDirectory()){let e=k(p,i);e.length>0&&await C(e,`deleted-upstream`)}}let A=y0e({skillsRoot:m,name:r.name,relPath:i,toRelPath:a});if(!A.ok){let e=A.error.code===`RENAME_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,A.error.message,{handler:`skill-file-rename`,detail:A.error.code});return}if(w){let e=[];if(S!==null&&T!==null)try{e.push({kind:`rename`,oldDocumentName:S,newDocumentName:T,markdown:K(W(m,r.name,a),`utf-8`)})}catch{e.push({kind:`delete`,documentName:S})}else if(S!==null)e.push({kind:`delete`,documentName:S});else if(T!==null)try{e.push({kind:`upsert`,documentName:T,markdown:K(W(m,r.name,a),`utf-8`)})}catch{}await E(e,`skill-file-rename`)}r.scope===`project`&&(v(e,y(`skill`,``,r.name),`skill-file-rename: ${r.name}/${i} -> ${a}`),b(`skill-file-rename`)),x?.(`files`),Q(n,200,dt,{from:i,to:a,...S===null?{}:{fromDocName:S},...T===null?{}:{toDocName:T}},{handler:`skill-file-rename`})}catch(e){T.error({err:e},`[skill-file-rename] failed`),n.headersSent||X(n,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`})},{mutating:[`/api/skill-file`,`/api/skill-file/rename`]})}function C2e(e,t){return(0,pke.default)({headers:e.headers,defParamCharset:`utf8`,limits:t})}function w2e(e){return e.kind===`git`&&!P1(e.url)}function C4(e,t,n){return t.kind===`git`&&w2e(t)?(X(e,400,`urn:ok:error:url-not-allowed`,`Git URL protocol is not allowed.`,{handler:n,cause:Error(`url=${t.url}`)}),!0):!1}function T2e(e){let{projectDir:t,getPrincipal:n,skillImportService:r,bumpSkillsCatalogGen:i,contentFilter:a,scheduleDeferredIgnoreRebuild:o,signalChannel:s,parseSkillScope:c}=e;function l(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}function u(e,t){if(t.ok){Q(e,200,Ht,t.body,{handler:`skill-import`});return}X(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let d=Z(et,async(e,c,d)=>{let f=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=C1(d,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let p=d.scope,m=null,h,g,_,v,y=d.source;{let e=d.source;try{let t=await dI(e,d.skill),n=t?.source??e;y=n;let r=d.skill??t?.skill,i=t?.spec??qF(n);if(!i){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(C4(c,i,`skill-import`))return;let a=await YF(i);f=a.cleanup,g=a.ref;let o=sI(a.dir);if(o.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let s=o[0];if(r){let e=o.find(e=>e.name===r)??o.find(e=>iI(e.dir)?.name===r)??o.find(e=>e.name===Ur[r]);if(!e){X(c,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${r}" not among: ${o.map(e=>e.name).join(`, `)}.`});return}s=e}else if(o.length>1){X(c,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:o.map(e=>e.name).join(`, `)});return}m=s.dir,v=s.name,h=e,_=t?.publisher??l(n)}catch(e){if(e instanceof zF){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!m){X(c,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let b=await r.runSkillImport({acquiredDir:m,scope:p,sourceLabel:h,ref:g,publisher:_,upstreamSkill:v,actor:e,skipProjection:d.install===!1});b.ok&&(d.marketplace===!0||aa(y))&&_2({source:y,skills:[b.body.name]},l2()),i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),u(c,b)}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{f()}},{handler:`skill-import`,method:`POST`}),f=Z(Lre,async(e,c,u)=>{let d=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=C1(u,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let f=u.source,p=null,m=null,h=[],g,_,v=f;try{let e=await dI(f,u.skills[0]),t=e?.source??f;v=t;let n=e?.spec??qF(t);if(!n){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(C4(c,n,`skills-import-bulk`))return;if(_=e?.publisher??l(t),n.kind===`well-known`)p=n,m=await GF(n.origin);else{let e=await YF(n);d=e.cleanup,g=e.ref,h=sI(e.dir)}}catch(e){if(e instanceof zF){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(p===null&&h.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let y=[];for(let t of new Set(u.skills)){let n,i,a=()=>{};if(p!==null)try{let e=await YF({...p,skill:t},m?{index:m}:{});n=e.dir,a=e.cleanup,i=t}catch(e){y.push({requested:t,status:e instanceof zF?`not-found`:`failed`,warnings:[],warningCodes:[],...e instanceof zF?{}:{error:String(e)}});continue}else{let e=h.find(e=>e.name===t)??h.find(e=>oI(e.dir)?.name===t)??h.find(e=>e.name===Ur[t]);if(!e){y.push({requested:t,status:`not-found`,warnings:[],warningCodes:[]});continue}n=e.dir,i=e.name}try{let a=await r.runSkillImport({acquiredDir:n,scope:u.scope,sourceLabel:f,ref:g,publisher:_,upstreamSkill:i,actor:e,skipProjection:u.install===!1});if(!a.ok){q(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:a.detail??a.title});continue}y.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings,warningCodes:a.body.warningCodes})}catch(e){q(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:e instanceof Error?e.message:String(e)})}finally{a()}}if(u.marketplace===!0||aa(v)){let e=y.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&_2({source:v,skills:e},l2())}i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),Q(c,200,oie,{results:y,imported:y.filter(e=>e.status===`imported`).length,alreadyImported:y.filter(e=>e.status===`already-imported`).length,failed:y.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{d()}},{handler:`skills-import-bulk`,method:`POST`}),p=8388608,m=33554432;function h(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=W(e,n);return r!==e&&!r.startsWith(e+us)?null:r}function g(e){return new Promise((t,n)=>{let r;try{r=C2e(e,{files:200,fields:10,fieldSize:2048,fileSize:p})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>m){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function _(e,t){return new Promise((n,r)=>{(0,fke.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=h(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){_J(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>p){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>m){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{_J(V(n),{recursive:!0}),hJ(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function v(e,i){let a=Cs(H(Vs(),`ok-skill-upload-`)),o=()=>{try{CJ(a,{recursive:!0,force:!0})}catch{}};try{if(!t){X(i,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){X(i,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let o=new URL(e.url??``,`http://localhost`),s=c(o.searchParams.get(`scope`),i,`skill-upload`);if(!s)return;let l=e=>o.searchParams.get(e)??void 0,d=C1({agentId:l(`agentId`),agentName:l(`agentName`),colorSeed:l(`colorSeed`),clientName:l(`clientName`),summary:l(`summary`)},n);if(d.kind===`invalid-summary`){X(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let f;try{f=await g(e)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(f.length===0){X(i,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let p=f.length===1?f[0]:null,m=p&&/\.(zip|skill)$/i.test(p.relPath)?p.relPath:null;if(p&&m)try{await _(p.data,a)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of f){let t=h(a,e.relPath);if(!t){X(i,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}_J(V(t),{recursive:!0}),hJ(t,e.data)}let v=sI(a);if(v.length===0){X(i,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(v.length>1){X(i,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:v.map(e=>e.name).join(`, `)});return}let y=v[0];u(i,await r.runSkillImport({acquiredDir:y.dir,scope:s,sourceLabel:`upload:${m??y.name}`,upstreamSkill:y.name,actor:d}))}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{o()}}return L1({"/api/skill/import":d,"/api/skills/import-bulk":f,"/api/skill-upload":v},{mutating:[`/api/skill/import`,`/api/skills/import-bulk`,`/api/skill-upload`]})}function E2e(e){let{resolveSkillsRoot:t,validateSkillName:n,projectDir:r,skillInstallBase:i,contentDir:a,skillsHome:o,shippedBundleSkillMd:s,flushDiskAndDetectOutcome:c,respondStaleExternalWrite:l,respondPersistenceFailure:u,respondDiskDivergence:d,skillInstallOps:f,skillPlacementOps:p,signalChannel:m,bumpSkillsCatalogGen:h,contentFilter:g,scheduleDeferredIgnoreRebuild:_,effectiveInstallMode:v,log:y}=e;return L1({"/api/skill/install":Z(nre,async(e,b,x)=>{try{let e=t(x.scope);if(!n(x.name,b,`skill-install`))return;if(x.scope===`project`&&!r){X(b,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let S=i(x.scope),C=W(e,x.name),w=x.scope===`project`?a:o,T=(x.scope===`project`?B2(a):V2(o)).find(e=>e.name===x.name),E=d1(x.name)?s(x.name,x.scope):null,D=T?W(w,T.dir):G(C)||E===null?C:V(E);if(!G(D)){X(b,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${x.name}" not found in ${x.scope} scope — create it with write({ skill }) first.`});return}let O=x.scope===`project`?`${U(w,D).split(us).join(`/`)}/SKILL`:gr(x.scope,x.name),k=await c(O);if(k?.kind===`failure`){u(b,k.failure,`skill-install`);return}if(k?.kind===`divergence`){d(b,`skill-install`);return}if(k?.kind===`stale-external-write`){l(b,`skill-install`,O);return}let A=i4(D,x.name,{allowReservedName:d1(x.name)});if(!A.ok){X(b,400,`urn:ok:error:invalid-request`,`Skill "${x.name}" cannot be installed: ${A.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(x.fork!==void 0){if(!T){X(b,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=f.resolveFork({scope:x.scope,name:x.name,fork:x.fork,inPlaceEntry:T});if(!e.ok)switch(e.kind){case`unknown-editor`:X(b,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:X(b,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:X(b,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:X(b,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:X(b,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T.hosts.filter($r),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let ee=x.setSource??x.source,j=x.linkMode??(x.mode===void 0?void 0:x.mode===`link`),M=x.targets,N=[],P=[];if(x.add!==void 0||x.remove!==void 0){if(!T){X(b,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await f.applyAddRemove({scope:x.scope,name:x.name,inPlaceEntry:T,...x.add===void 0?{}:{add:x.add},...x.remove===void 0?{}:{remove:x.remove}});if(!e.ok){e.kind===`remove-source`?X(b,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):X(b,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}M=e.targets.filter($r),N.push(...e.rootAdds),P.push(...e.rootRemoves)}if(ee&&!T){let e=await f.promoteStoreBackedSource({scope:x.scope,name:x.name,base:S,skillDir:D,newSource:ee});if(!e.ok){X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(x.place){let e=x.scope===`project`?r:o;if(!e){X(b,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await p.place({placeBase:e,name:x.name,rawDir:x.place.dir,skillDir:D,mode:x.place.mode});if(!t.ok){t.kind===`invalid-path`?X(b,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):X(b,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in t||m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,warnings:[],warningCodes:[],placedAt:t.placedAt},{handler:`skill-install`});return}if(x.unplace){let e=x.scope===`project`?r:o;if(!e){X(b,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await p.unplace({placeBase:e,name:x.name,rawPath:x.unplace.path,skillDir:D});if(!t.ok)switch(t.kind){case`not-recorded`:X(b,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:t.path});return;case`unsafe-path`:X(b,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:X(b,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:t.path});return;case`canonical-dir`:X(b,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:t.path});return;default:throw Error(`Unhandled unplace outcome: ${String(t.kind)}`)}m?.(`files`),h(),g?.refreshInPlaceSkillDirs(),_(),Q(b,200,Jr,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(x.convert){if(!T){X(b,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:t}=x.convert,n=x.scope===`project`?r:o,i=await p.convert({ledgerBase:n??S,scope:x.scope,name:x.name,target:e,mode:t,skillDir:D,canonicalHash:T.contentHash});if(!i.ok)switch(i.kind){case`invalid-location`:X(b,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:X(b,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:X(b,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:X(b,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(i.kind)}`)}m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:[...T.hosts],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let te=x.scope===`global`?M===void 0?y2(o).map(e=>e.editorId):$n.filter(e=>M?.some(t=>t===e)):M===void 0?a4(S):Mn.filter(e=>M?.some(t=>t===e)),ne=[],re=[];if(te.length===0&&M===void 0&&(ne.push(x.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),re.push(`no-targets`)),A.hasScripts&&(ne.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),re.push(`scripts-present`)),A.warnings.length>0&&(ne.push(A.warnings[0]),re.push(`no-description`)),T){let e=T.dir.split(`/`).slice(0,-1).join(`/`),t=(M===void 0?x.scope===`global`&&G(H(o,`.agents`)):M.includes(`agents`))?[...te,`agents`]:[...te],n=x.scope===`project`?r:o,i=j===void 0?v(x.scope,x.name,T):j?`link`:`copy`;if(ee){let e=await f.promoteInPlaceSource({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,newSource:ee});if(!e.ok){e.kind===`invalid-target`?X(b,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let a=await f.fanOutInPlace({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,canonicalRootRel:e,inPlaceTargets:t,setExact:M!==void 0,installMode:i,...j===void 0?{}:{linkModeReq:j},rootAdds:N,rootRemoves:P});if(!a.ok){X(b,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:a.reason});return}ne.push(...a.warnings),re.push(...a.warningCodes),m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:a.hosts,scripts:A.hasScripts,warnings:ne,warningCodes:re,...a.sourceMovedTo===void 0?{}:{sourceMovedTo:a.sourceMovedTo}},{handler:`skill-install`});return}let ie=r4(G2(S).skills[x.name]?.hosts??[],x.scope).filter(e=>!te.includes(e));ie.length>0&&v4(x.name,S,ie,o4(x.scope));let ae=H(S,...XF),oe=G(ae)?K(ae,`utf-8`):null,se=oe===null?null:QF(oe);oe!==null&&se===null&&y.warn({skill:x.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let ce=se?.skills[x.name]!==void 0,le=j===void 0?ce?`copy`:`symlink`:j?`symlink`:`copy`,ue=f4(D,x.name,S,te,le,o4(x.scope));ue.length===0?await q2(S,x.name):await K2(S,x.name,{hosts:ue,scope:x.scope,scripts:A.hasScripts,installedAt:new Date().toISOString(),projection:le}),m?.(`files`),Q(b,200,Jr,{name:x.name,hosts:ue,scripts:A.hasScripts,warnings:ne,warningCodes:re},{handler:`skill-install`})}catch(e){X(b,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`})},{mutating:[`/api/skill/install`]})}const D2e=[`.ok`,`local`,`plugin-skill-baselines.json`];function O2e(e){return H(e,...D2e)}function k2e(e){try{let t=O2e(e);if(!G(t))return{};let n=JSON.parse(K(t,`utf-8`));if(typeof n!=`object`||!n)return{};let r=Object.create(null);for(let[e,t]of Object.entries(n))typeof t==`object`&&t&&typeof t.local==`string`&&typeof t.upstream==`string`&&(r[e]={local:t.local,upstream:t.upstream});return r}catch{return{}}}function A2e(e,t,n){return e===void 0||e.upstream!==n?{modified:!1,next:{local:t,upstream:n}}:{modified:t!==e.local,next:e}}function j2e(e){let t=k2e(e),n=!1;return{isModified(e,r,i,a){let o=`${e}:${r}`,{modified:s,next:c}=A2e(t[o],i,a),l=t[o];return(l===void 0||l.local!==c.local||l.upstream!==c.upstream)&&(t[o]=c,n=!0),s},flush(){if(n){n=!1;try{_J(H(e,`.ok`,`local`),{recursive:!0}),hJ(O2e(e),`${JSON.stringify(t,null,2)}\n`)}catch{}}}}}function M2e(e){let{contentDir:t,projectDir:n,skillsHome:r,contentFilter:i,catalogCache:a,resolveSkillsRoot:o,resolveSkillsList:s,skillOriginFor:c,localSkillHash:l,effectiveInstallMode:u,pluginSelfIdentity:d,synthBuiltinLockEntry:f,synthPluginLockEntry:p,pluginUpstreamHash:m,builtinSkillListEntry:h,indexedSkillContentPath:g,healUnservableSkillAdmission:_}=e,v=l1.project,y={lastKey:null};return L1({"/api/skills":Z(Ii,z1(async(e,b)=>{let x=(i?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(n?a0e(n).join(`,`):``)+``+y2(r).map(e=>e.editorId).join(`,`)+``+V2(r).map(e=>e.dir).sort().join(`,`),S=a.readList(x);if(S!==null){Q(b,200,di,S.body,{handler:`skills-list`});return}let C=o(`project`),w=s(C,`project`),T=s(o(`global`),`global`),E=n?a0e(n):[],D=y2(r).map(e=>e.editorId),O=n?R2(n,`project`,qi,r):!1,k=R2(r,`global`,qi,r),A=n?G2(n).skills:{},ee=G2(r).skills,j=n?QF(G(H(n,...XF))?K(H(n,...XF),`utf-8`):``)??null:null,M=c,N=(e,t,n)=>e.skills.map(e=>{let r=t[e.name]?.hosts??[],i=n?j?.skills[e.name]:void 0,a=i?M(i):void 0,o=i?.localHash!==void 0&&l(C,e.name)!==i.localHash,s=i?.baselineRef!==void 0;return{...e,installed:r.length>0,hosts:r,...a?{origin:a}:{},...o?{modified:!0}:{},...s?{revertable:!0}:{}}}),P=n?e4(n):{},te=(e,t,n)=>{let r=[];for(let i of t??[]){let t=W(e,i.path);if(n!==void 0&&t===W(n))continue;let a=!1;try{a=xs(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(ks(t)===ks(n))continue}catch{}r.push(i.path)}}return{drift:r}},ne=n?F2(t,`project`):{},re=M0e(ne,`project`),ie=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),ae=kw(n??t),oe=j2e(t),se=L2(`project`),ce=L2(`global`),le=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),ue=new Set,de=ZOe(t),fe=e=>{let t=$Oe(de,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},pe=n?B2(t).map(e=>{let r=!ue.has(e.name);ue.add(e.name);let i=W(t,e.dir),a=r?d(e.name,ae,i)??fe(i):null,o=r&&a===null?j?.skills[e.name]??f(t,e.name,`project`)??p(e.name,ae,i):void 0,s=o?M(o):void 0,c=o?.localHash===void 0?(()=>{if(!o||!r)return!1;let t=m(e.name,ae);return t!==null&&oe.isModified(`project`,e.name,e.contentHash,t)})():e.contentHash!==o.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:W(t,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:E,hubOffered:O,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ne).length>0?{hostAliases:ne}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...a===null?{}:{plugin:a},...(()=>{let t=le(r?P[e.name]:void 0,re).filter(e=>!ie(e.path,se));return t.length?{customPlacements:t.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let i=te(n,le(r?P[e.name]:void 0,re),W(t,e.dir));return i.drift.length>0?{driftPaths:i.drift}:{}})(),...u(`project`,e.name,e)===`link`?{linkMode:!0}:{},...s?{origin:s}:{},...c?{modified:!0}:{},...o?.baselineRef===void 0?{}:{revertable:!0},...d1(e.name)?{managed:!0}:{}}}):[],me=e4(r),he=b4(H(r,...XF)),ge=F2(r,`global`),_e=M0e(ge,`global`),ve=new Set(V2(r).map(e=>e.name));T.skills=T.skills.filter(e=>!ve.has(e.name));let ye=new Set,be=V2(r).map(e=>{let t=!ye.has(e.name);ye.add(e.name);let n=t?me[e.name]:void 0,i=H2(r,e.name),a=i!==null&&W(r,e.dir)!==W(i)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:W(r,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],...a===void 0?{}:{hostQualifier:a},size:e.size,installableEditors:D,hubOffered:k,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ge).length>0?{hostAliases:ge}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=te(r,le(n,_e),W(r,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=le(n,_e).filter(e=>!ie(e.path,ce));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...u(`global`,e.name,e)===`link`?{linkMode:!0}:{},...d1(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=W(r,e.dir),i=d(e.name,ae,n);if(i!==null)return{plugin:i};let a=he.skills[e.name]??f(r,e.name,`global`)??p(e.name,ae,n);if(!a)return{};let o=a.localHash===void 0?(()=>{let t=m(e.name,ae);return t!==null&&oe.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==a.localHash;return{origin:M(a),...o?{modified:!0}:{}}})()}}),xe=new Set(pe.map(e=>e.name)),Se=n&&!w.skills.some(e=>e.name===v)&&!xe.has(v)?h(n,v,`project`):null,Ce=new Set(be.map(e=>e.name)),we=m1.map(e=>l1[e]).filter(e=>!T.skills.some(t=>t.name===e)&&!Ce.has(e)).map(e=>h(r,e,`global`)).filter(e=>e!==null),Te=new Set(pe.map(e=>e.name)),Ee=[...N(w,A,!0).filter(e=>!Te.has(e.name)),...pe,...N(T,ee,!1),...be,...Se?[Se]:[],...we];oe.flush();let De={skills:Ee.map(e=>{let n=e.scope===`project`&&e.absolutePath?g(e.absolutePath,t):null,r=e.absolutePath?h2e(V(e.absolutePath)):[],a=r.length>0?{...e,filePaths:r}:e,o=n===null||n===e.path?a:{...a,canonicalPath:n},s=n??e.path;return e.scope===`project`&&!os(s)&&i?.isPathIgnored(s)===!0?{...o,ignored:!0}:o}),truncated:w.truncated||T.truncated},Oe=await _(pe.map(e=>e.path),i??null,y)?{...De,skills:De.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=!os(t)&&i?.isPathIgnored(t)===!0;if(n===(e.ignored===!0))return e;if(n)return{...e,ignored:!0};let{ignored:r,...a}=e;return a})}:De;a.writeList(x,Oe),Q(b,200,di,Oe,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0})})}const N2e=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,P2e=/[/\\\x00-\x1f\x7f]/g;function F2e(e){let t=e.replace(P2e,``);if(t=t.replace(N2e,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let n=new TextEncoder;if(n.encode(t).length>255){let e=t.lastIndexOf(`.`),r=e>=0?t.slice(e):``,i=e>=0?t.slice(0,e):t;for(;n.encode(i+r).length>255&&i.length>0;)i=i.slice(0,-1);t=(i||`upload`)+r,n.encode(t).length>255&&(t=`upload`)}return t}const I2e=q(`skill-import`),L2e={maxFileBytes:Ze,maxFiles:512};function R2e(e){if(e.files.length>512)return`Skill has ${e.files.length} dependent files; the import cap is 512.`;let t=Buffer.byteLength(e.skillMd);for(let n of e.files){let e=n.bytes?.byteLength??Buffer.byteLength(n.content??``);if(e>16777216)return`${n.relPath} is ${e} bytes; the import per-file cap is ${Ze}.`;t+=e}return t>67108864?`Skill is ${t} bytes; the import bundle cap is ${zt}.`:null}function z2e(e){function t(e,t){return oI(W(e,t))?.contentHash}return{async runSkillImport(n){let{acquiredDir:r,scope:i,sourceLabel:a,ref:o,publisher:s,upstreamSkill:c,actor:l}=n;if(!e.projectDir)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let u=aI(r);if(u)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:u};let d=oI(r);if(!d)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let f=R2e(d);if(f)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:f};let p=H(i===`project`?e.projectDir:e.skillsHome,...XF),m=b4(p),h=i===`project`?e.contentDir:e.skillsHome,g=z2(h,i);if(g===null)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Open Knowledge only writes skills into an agent folder that already exists (${N0e(i).join(`, `)}) and never creates one for you. Create the folder your agent uses, then import again.`,detail:`NO_USABLE_SKILL_HOME`};let _=W(h,g),v=tOe(m,d.contentHash);if(v&&e.resolveSkillDirForRead(i,v)!==null)return{ok:!0,body:{name:v,path:`${v}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:[],warningCodes:[]}};let y=F2e(d.name),b=t=>e.resolveSkillDirForRead(i,t)!==null||G(W(_,t,`SKILL.md`)),x=b(y),S=y;if(x){S=`${y}-imported`;let e=2;for(;b(S);)S=`${y}-imported-${e}`,e+=1}let C=e.parseFrontmatterDoc(d.skillMd),w=C.body,T=eI(C.frontmatter),E=S2({skillsRoot:_,name:S,body:w,frontmatter:{name:S,description:d.description,...T===void 0?{}:{metadata:{pack:T}}}});if(!E.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:E.error.code,cause:Error(E.error.message)};let D=[...E.warnings];for(let e of d.files){let t=T2({skillsRoot:_,name:S,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:L2e});if(!t.ok){let n=E2({skillsRoot:_,name:S});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}i===`project`&&(e.attributeOkArtifactWrite(l,`${g}/${S}/SKILL`,`skill-import: ${a} -> ${g}/${S}/SKILL.md`),await e.commitOkArtifactWrite(`skill-import`));let O=t(_,S),k=MI(a),A=i===`project`?await e.shadowHeadSha(e.artifactWriterId(l),`${g}/${S}`):void 0;if(await x4(p,e=>$F(e,S,{source:a,...k?{pluginProvider:k.provider}:{},ref:o,contentHash:d.contentHash,files:d.files.map(e=>e.relPath),...O===void 0?{}:{localHash:O},...A===void 0?{}:{baselineRef:A},publisher:s,importedAt:new Date().toISOString(),...c===void 0?{}:{skill:c}})),n.skipProjection!==!0)try{let t=a4(h);if(t.length>0){let n=W(_,S),r=o4(i),a=t.filter(e=>{let t=c4(h,e,S,r);return t!==null&&t!==n&&G(t)}),o=a.filter(e=>{let t=c4(h,e,S,r);try{return t!==null&&xs(t).isSymbolicLink()}catch{return!1}});m4({canonicalAbs:n,canonicalHash:oI(n)?.contentHash??``,canonicalRootRel:g,name:S,cwd:h,targets:t,mode:e.effectiveInstallMode(i,S,{hosts:[`<source>`,...a],linkedHosts:o}),roots:o4(i)})}}catch(e){I2e.warn({err:e,skill:S},`post-import editor fan-out failed (import kept)`)}return e.signalFiles(),{ok:!0,body:{name:S,path:`${g}/${S}/SKILL.md`,created:E.created,alreadyImported:!1,...x?{collisionRenamedFrom:d.name}:{},provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:D,warningCodes:E.warningCodes}}}}}function B2e(e,t){let{recordedSkill:n,localName:r,frontmatterNameOf:i}=t;return(n?e.find(e=>e.name===n):void 0)??e.find(e=>e.name===r)??e.find(e=>i(e.dir)===r)??e.find(e=>e.name===Ur[n??r])??(e.length===1?e[0]:void 0)}function V2e(e){let t=new Set(e.upstreamFiles),n=new Set(e.local?.files??[]),r=(e.entry.files??(e.entry.localHash!==void 0&&e.local?.contentHash===e.entry.localHash?[...n]:[])).filter(e=>!t.has(e)).filter(e=>n.has(e));return{upToDate:e.upstreamHash===e.entry.contentHash&&r.length===0,removedUpstream:r}}function H2e(e,t){let n=new Map,r=[];for(let i of new Set(e)){let e=t(i);if(!e){r.push(i);continue}let a=n.get(e.source);a?a.push(i):n.set(e.source,[i])}return{bySource:[...n].map(([e,t])=>({source:e,names:t})),unrecorded:r}}function U2e(e){return{async runSkillReimport(t){let{acquiredDir:n,name:r,scope:i,entry:a,lockPath:o,ref:s,actor:c}=t,l=i===`global`?e.skillsHome:e.contentDir,{root:u,dirRel:d,realDir:f}=e.effectiveSkillRoot(i,r),p=!d.startsWith(`${e.legacyStoreRoot}/`);if(f===null||!G(W(l,d,`SKILL.md`)))return{ok:!1,status:404,urn:`urn:ok:error:not-found`,title:`Skill is not installed.`,detail:`SKILL_ABSENT`};let m=aI(n);if(m)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:m};let h=oI(n);if(!h)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let g=R2e(h);if(g)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:g};let _=oI(W(u,r)),{upToDate:v,removedUpstream:y}=V2e({upstreamHash:h.contentHash,upstreamFiles:h.files.map(e=>e.relPath),entry:a,local:_?{contentHash:_.contentHash,files:_.files.map(e=>e.relPath)}:null});if(v)return{ok:!0,body:{name:r,updated:!1,source:a.source,warnings:[],warningCodes:[]}};let b=e.parseFrontmatterDoc(h.skillMd),x=b.body,S=eI(b.frontmatter);if(t.dryRun){let t;if(i===`project`&&e.projectDir)try{let n=IF({baseDir:e.projectDir,timeout:{block:15e3}}),i=U(e.projectDir,W(u,r)).split(us).join(`/`);t=(await n.raw(`ls-files`,...Fi([i]))).trim().length>0}catch{t=void 0}return{ok:!0,body:{name:r,updated:!0,source:a.source,localBody:e.parseFrontmatterDoc(_?.skillMd??``).body,upstreamBody:x,...t===void 0?{}:{gitTracked:t},warnings:[],warningCodes:[]}}}if(i===`project`){let t=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${d}/${e.replace(/\.mdx?$/i,``)}`);t.length>0&&await e.captureAndCloseDocuments(t,`deleted-upstream`)}let C=S2({skillsRoot:u,name:r,body:x,frontmatter:{name:r,description:h.description,...S===void 0?{}:{metadata:{pack:S}}}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of h.files){let t=T2({skillsRoot:u,name:r,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:L2e});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to write the complete refreshed skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(t.error.message)}}for(let e of y){let t=b0e({skillsRoot:u,name:r,relPath:e});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to reconcile files removed upstream.`,detail:`${e}: ${t.error.code}`,cause:Error(t.error.message)}}i===`project`&&(e.attributeOkArtifactWrite(c,e.skillArtifactKey(r),`skill-reimport: ${a.source} -> ${d}`),await e.commitOkArtifactWrite(`skill-reimport`));let T=oI(W(u,r))?.contentHash,E=i===`project`?await e.shadowHeadSha(e.artifactWriterId(c),d):void 0;return await x4(o,e=>$F(e,r,{...e.skills[r]??a,contentHash:h.contentHash,files:h.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...E===void 0?{}:{baselineRef:E},ref:s,importedAt:new Date().toISOString()})),!p&&i===`project`&&await e.projectImportedSkillCopy({skillsRoot:u,name:r,scope:`project`,hasScripts:h.files.some(e=>e.relPath.startsWith(`scripts/`)),handler:`skill-reimport`}),e.signalFiles(),{ok:!0,body:{name:r,updated:!0,source:a.source,warnings:w,warningCodes:C.warningCodes}}}}}function W2e(e,t){let n=e===`.`?``:e.replace(/^\.\//,``);return n?`${n}/${t}`:t}function G2e(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function K2e(e){let{shadow:t,contentDir:n,contentRoot:r,name:i,version:a}=e,o=e.skillDirRel??`.ok/skills/${i}`;if(!G(t.workTree)||!G(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let s=xY(t),c=[...new Set([o,`.ok/skills/${i}`])],l=[],u=W2e(r,o);try{for(let e of c){let t=W2e(r,e),n=await kJ(s,[`ls-tree`,`-r`,`--name-only`,a,...Fi([t])]);if(n.length>0){l=n,u=t;break}}}catch(e){let t=e instanceof Error?e.message:String(e);return G2e(t)?{ok:!1,code:`version-not-found`,error:`Version ${a.slice(0,8)} not found.`}:{ok:!1,code:`io-error`,error:`Failed to read version ${a.slice(0,8)}: ${t}`}}if(l.length===0)return{ok:!1,code:`skill-absent`,error:`Skill "${i}" did not exist at version ${a.slice(0,8)}.`};let d=W(n,o),f=d+us,p=[];for(let e of l){let t=e.slice(u.length).replace(/^\//,``),n=W(d,t);if(n!==d&&!n.startsWith(f))return{ok:!1,code:`path-escape`,error:`Refusing to restore path outside skill dir: ${t}`};try{p.push({rel:t,destAbs:n,content:await s.raw(`show`,`${a}:${e}`)})}catch(e){let n=e instanceof Error?e.message:String(e);return{ok:!1,code:`io-error`,error:`Failed reading ${t} at ${a.slice(0,8)}: ${n}`}}}CJ(d,{recursive:!0,force:!0});let m=[];for(let{rel:e,destAbs:t,content:n}of p)_J(V(t),{recursive:!0}),hJ(t,n,`utf-8`),m.push(e);return{ok:!0,restoredFiles:m}}function q2e(e){try{let t=K(H(e,`SKILL.md`),`utf-8`),n=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(t)?.[1];return n!==void 0&&/^[ \t]+pack:[ \t]*"?[a-z0-9-]+"?[ \t]*$/m.test(n)}catch{return!1}}function J2e(e){let{synthPluginLockEntry:t,synthBuiltinLockEntry:n,isValidSkillName:r,getPrincipal:i,validateSkillName:a,rejectReservedBuiltinSkill:o,shadowRef:s,contentDir:c,contentRoot:l,projectDir:u,skillsHome:d,projectSkillDirRel:f,attributeOkArtifactWrite:p,okArtifactKey:m,commitOkArtifactWrite:h,signalChannel:g,bumpSkillsCatalogGen:_,contentFilter:v,scheduleDeferredIgnoreRebuild:y,effectiveSkillRoot:b,skillReimportService:x,localSkillHash:S,resolveSkillsRoot:C,projectImportedSkillCopy:w}=e;function T(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];X(e,r,i,t.error,{handler:n,detail:t.code})}function E(e,t){if(t.ok){Q(e,200,Vte,t.body,{handler:`skill-reimport`});return}X(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function D(e,t,n){let r=e===`project`?c:d,i=(e===`project`?B2(c):V2(d)).find(e=>e.name===t);return i?W(r,i.dir):W(n,t)}function O(e,r,i,a){let o=a.skills[r];if(o)return o;let s=D(e,r,i);return eOe(r,oI(s)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:q2e(s)})??n(e===`global`?d:c,r,e)??t(r,kw(u??c),s)}return L1({"/api/skill/restore":Z(Uee,async(e,t,n)=>{try{let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!a(n.name,t,`skill-restore`)||o(n.name,t,`skill-restore`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=s?.current;if(!r){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let u=await K2e({shadow:r,contentDir:c,contentRoot:l??`.`,name:n.name,version:n.version,skillDirRel:f(n.name)});if(!u.ok){T(t,u,`skill-restore`);return}let d=[],b=i4(W(c,f(n.name)),n.name);b.ok||d.push(`Restored, but the skill no longer validates: ${b.errors.join(` `)}`),p(e,m(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await h(`skill-restore`),g?.(`files`),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,Ine,{name:n.name,version:n.version,restoredFiles:u.restoredFiles,warnings:d},{handler:`skill-restore`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),"/api/skill/reimport":Z(sre,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!a(n.name,t,`skill-reimport`))return;let o=n.scope===`global`?d:c,{root:s,dirRel:l,realDir:f}=b(n.scope,n.name);if(f===null||!G(W(o,l,`SKILL.md`))){X(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let p=H(n.scope===`global`?d:u,...XF),m=O(n.scope,n.name,s,b4(p));if(!m){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await x4(p,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??m,autoUpdate:n.setAutoUpdate}}})),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,Vte,{name:n.name,updated:!1,source:m.source,warnings:[],warningCodes:[]},{handler:`skill-reimport`});return}let h,g=null;try{let e=m.skill??n.name,i=Ur[e],a=await dI(m.source,e).catch(async e=>{if(i===void 0)throw e;return dI(m.source,i)}),o=a?.source??NI(m.source,m.pluginProvider),s=a?.skill??m.skill,c=a?.spec??qF(o);if(!c){X(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:m.source});return}if(C4(t,c,`skill-reimport`))return;let l=await YF(c);r=l.cleanup,h=l.ref;let u=sI(l.dir),d=B2e(u,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>oI(e)?.name});if(!d){X(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}g=d.dir}catch(e){if(e instanceof zF){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!g){X(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let S=await x.runSkillReimport({acquiredDir:g,name:n.name,scope:n.scope,entry:m,lockPath:p,ref:h,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});_(),v?.refreshInPlaceSkillDirs(),y(),E(t,S)}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),"/api/skills/reimport-bulk":Z(Zre,async(e,t,n)=>{try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let a=C1(n,i);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let o=H(n.scope===`global`?d:u,...XF),s=b4(o),c=[],{bySource:l,unrecorded:f}=H2e([...new Set(n.names)].filter(e=>r(e)?!0:(c.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`,warningCodes:[]}),!1)),e=>O(n.scope,e,b(n.scope,e).root,s));for(let e of f)c.push({requested:e,status:`not-found`,warnings:[],warningCodes:[]});for(let t of l){let r=()=>{};try{let i,l=[];try{let e=t.names[0],n=await dI(t.source,e).catch(async n=>{let r=Ur[e];if(r===void 0)throw n;return dI(t.source,r)}),a=n?.source??NI(t.source,s.skills[t.names[0]]?.pluginProvider),o=n?.spec??qF(a);if(!o||w2e(o)){for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:`INVALID_SOURCE`});continue}let u=await YF(o);r=u.cleanup,i=u.ref,l=sI(u.dir)}catch(n){q(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:lX(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)});continue}for(let r of t.names){let t=O(n.scope,r,b(n.scope,r).root,s);if(!t){c.push({requested:r,status:`not-found`,warnings:[],warningCodes:[]});continue}let u=B2e(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:r,frontmatterNameOf:e=>oI(e)?.name});if(!u){c.push({requested:r,status:`not-found`,source:t.source,warnings:[],warningCodes:[]});continue}try{let s=await x.runSkillReimport({acquiredDir:u.dir,name:r,scope:n.scope,entry:t,lockPath:o,ref:i,actor:a});if(!s.ok){q(`skills-reimport-bulk`).warn({skill:r,err:s.cause,detail:s.detail,requestId:lX(e)},`bulk update: one skill failed (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:s.detail??s.title});continue}c.push({requested:r,status:s.body.updated?`updated`:`up-to-date`,source:s.body.source,warnings:s.body.warnings,warningCodes:s.body.warningCodes})}catch(n){q(`skills-reimport-bulk`).warn({skill:r,err:n,requestId:lX(e)},`bulk update: one skill threw (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)})}}}finally{r()}}Q(t,200,fr,{results:c,updated:c.filter(e=>e.status===`updated`).length,upToDate:c.filter(e=>e.status===`up-to-date`).length,failed:c.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{_(),v?.refreshInPlaceSkillDirs(),_(),await v?.rebuildIgnorePatterns()}catch(e){q(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),"/api/skill/revert":Z(gre,async(e,t,n)=>{try{if(!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=C1(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!a(n.name,t,`skill-revert`)||o(n.name,t,`skill-revert`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=H(u,...XF),d=b4(r).skills[n.name];if(!d?.baselineRef){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let _=s?.current;if(!_){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let v=await K2e({shadow:_,contentDir:c,contentRoot:l??`.`,name:n.name,version:d.baselineRef,skillDirRel:f(n.name)});if(!v.ok){T(t,v,`skill-revert`);return}p(e,m(`skill`,``,n.name),`skill-revert: ${n.name} @ ${d.baselineRef.slice(0,8)}`),await h(`skill-revert`);let y=W(c,f(n.name),`..`),b=S(y,n.name);await x4(r,e=>$F(e,n.name,{...e.skills[n.name]??d,...b===void 0?{}:{localHash:b}})),y===C(`project`)&&await w({skillsRoot:y,name:n.name,scope:`project`,hasScripts:v.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),g?.(`files`),Q(t,200,ite,{name:n.name,baselineRef:d.baselineRef,restoredFiles:v.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`})},{mutating:[`/api/skill/restore`,`/api/skill/reimport`,`/api/skills/reimport-bulk`,`/api/skill/revert`]})}function Y2e(e){let{contentDir:t,projectDir:n,contentFilter:r,validateSkillName:i,indexedSkillContentPath:a,bumpSkillsCatalogGen:o,signalChannel:s}=e;function c(e){return`!/${V(e).split(us).join(`/`)}/`}return L1({"/api/skill/track-in-git":Z(bne,z1(async(e,l,u)=>{if(!i(u.name,l,`skill-track-in-git`))return;if(u.scope!==`project`){X(l,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!n){X(l,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let d=B2(t).find(e=>e.name===u.name)?.dir??`.ok/skills/${u.name}`,f=a(W(t,d,`SKILL.md`),t)??`${d}/SKILL.md`,p=V(f),m=f,h=c(p),g=`.gitignore`,_=W(t,g);if(r&&!r.isPathIgnored(m)){Q(l,200,zi,{line:h,gitignorePath:g,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(u.apply!==!0){Q(l,200,zi,{line:h,gitignorePath:g,applied:!1},{handler:`skill-track-in-git`});return}let v=G(_)?K(_,`utf-8`):null;if((v??``).split(`
1011
1011
  `).some(e=>e.trim()===h)){X(l,409,`urn:ok:error:invalid-request`,`"${h}" is already in ${g}, but ${m} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}let y=`${v===null||v.endsWith(`
1012
1012
  `)||v===``?v??``:`${v}\n`}${h}\n`;if(Fs(_,y,`utf-8`),o(),await r?.rebuildIgnorePatterns(),r?.isPathIgnored(m)){v===null?js(_,{force:!0}):Fs(_,v,`utf-8`),o(),await r.rebuildIgnorePatterns(),X(l,409,`urn:ok:error:invalid-request`,`Adding "${h}" did not make ${m} trackable — another .gitignore rule excludes a parent directory. ${g} was left unchanged.`,{handler:`skill-track-in-git`});return}s?.(`files`),Q(l,200,zi,{line:h,gitignorePath:g,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`})},{mutating:[`/api/skill/track-in-git`]})}const X2e=[`INDEX`,`README`,`REPORT`,`SPEC`];function Z2e(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=$2e(t),o=e4e(e);for(;;){for(let e of X2e)if(i(Q2e(t,a,n4e(o,e))),n.length>=3)return n;let e=o===``?null:t4e(o);if(e&&(i(Q2e(t,a,n4e(o,e))),n.length>=3))return n;if(o===``)break;o=e4e(o)}return n}function Q2e(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function $2e(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function e4e(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function t4e(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function n4e(e,t){return e===``?t:`${e}/${t}`}var w4=class{entries=new Map;maxEntries;maxBytes;byteCount=0;hits=0;misses=0;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.maxBytes=e.maxBytes??67108864}static fingerprintConfig(e){return ec(`sha1`).update(JSON.stringify(e)).digest(`base64`)}static key(e){return[e.contentDir,e.docRelPath,e.mtimeMs,e.size,e.configFingerprint].join(`\0`)}get(e){let t=this.entries.get(e);return t===void 0?(this.misses+=1,null):(this.hits+=1,this.entries.delete(e),this.entries.set(e,t),JSON.parse(t.json))}set(e,t){let n=this.entries.get(e);n!==void 0&&(this.byteCount-=n.bytes,this.entries.delete(e));let r=JSON.stringify(t),i=Buffer.byteLength(r,`utf8`);this.entries.set(e,{json:r,bytes:i}),this.byteCount+=i,this.evictToBounds()}evictToBounds(){for(;(this.entries.size>this.maxEntries||this.byteCount>this.maxBytes)&&this.entries.size>1;){let e=this.entries.keys().next();if(e.done===!0)return;let t=this.entries.get(e.value);this.entries.delete(e.value),t!==void 0&&(this.byteCount-=t.bytes)}}stats(){return{hits:this.hits,misses:this.misses,entries:this.entries.size,bytes:this.byteCount}}clear(){this.entries.clear(),this.byteCount=0,this.hits=0,this.misses=0}};function T4(e,t){let n=U(t,e);return n===``||!n.startsWith(`..`)&&!os(n)}function E4(e,t){let n=kk(e);try{hJ(n,t,`utf-8`),vJ(n,e)}catch(e){try{bJ(n)}catch{}throw e}}function r4e(e){let t=H(e,`.ok`,`schemas`),n;try{n=Ds(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.toLowerCase().endsWith(`.json`)).map(e=>e.name).sort((e,t)=>e.localeCompare(t))}catch(e){let n=e.code;return n!==`ENOENT`&&n!==`ENOTDIR`&&q(`frontmatter-schemas`).warn({err:e,code:n,dir:t},`could not enumerate .ok/schemas; the schema picker will show an empty list`),{schemas:[],truncated:!1}}let r=n.length>500;return{schemas:n.slice(0,500).map(e=>`.ok/schemas/${e}`),truncated:r}}function D4(e){return e instanceof Error?e.message:String(e)}function i4e(e,t){let n=[];for(let r of e)if(r.enabled!==!1)for(let e of eie(r.appliesTo,t))n.push(`unmatched appliesTo glob ${JSON.stringify(e)} — matches no docs in this project (frontmatter mapping for ${r.file})`);return n}function a4e(e,t){let n=W(e,t);if(!T4(n,W(e)))return{problem:`frontmatter schema ${t}: resolves outside the project`};let r;try{r=ks(n)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${D4(e)})`}}let i;try{i=ks(e)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${D4(e)})`}}if(!T4(r,i))return{problem:`frontmatter schema ${t}: resolves outside the project`};let a;try{a=K(r,`utf-8`)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${D4(e)})`}}let o;try{o=JSON.parse(a)}catch(e){return{problem:`frontmatter schema ${t}: malformed JSON (${D4(e)})`}}if(typeof o!=`object`||!o||Array.isArray(o))return{problem:`frontmatter schema ${t}: not a JSON object`};let s=o;if(!f(s)){let e=JSON.stringify(bn[fre]);return{problem:`frontmatter schema ${t}: unsupported dialect ${JSON.stringify(s.$schema)} (supported: ${Wn.join(`, `)}; e.g. ${e})`}}let c=xe(s);return c===null?{schema:s,key:r}:{problem:`frontmatter schema ${t}: does not compile (${c})`}}function o4e(e,t){let n=[],r=new Map,i=new Set,a=[];for(let o of t){let t=o.enabled===!1,s=qt(o.appliesTo);for(let{pattern:e,detail:r}of s.invalidPatterns)t||n.push(`invalid appliesTo glob ${JSON.stringify(e)} — ${r} (frontmatter mapping for ${o.file})`);for(let{pattern:e,reason:r}of s.suspiciousPatterns){if(t)continue;let i=r===`trailing-slash`?`a trailing slash can never match (doc paths have no trailing slash)`:r===`leading-slash`?`a leading slash can never match (doc paths are relative)`:`doc paths are extension-less; drop the file extension`;n.push(`suspicious appliesTo glob ${JSON.stringify(e)} — ${i} (frontmatter mapping for ${o.file})`)}let c=r.get(o.file);c===void 0&&(c=a4e(e,o.file),r.set(o.file,c)),`problem`in c&&!t&&!i.has(o.file)&&(i.add(o.file),n.push(c.problem)),a.push(`problem`in c?{...o,key:o.file}:{...o,key:c.key,schema:c.schema})}return{entries:a,problems:n}}const s4e=[`.markdownlint.jsonc`,`.markdownlint.json`,`.markdownlint.yaml`,`.markdownlint.yml`,`.markdownlint.cjs`,`.markdownlint.mjs`,`.markdownlintrc`];function O4(e){for(let t of s4e){let n=H(e,t);if(G(n))return{name:t,path:n}}return null}function c4e(e){let t=O4(e);return t?d4e(t.path,t.name,e):null}function l4e(e,t){let n=W(t),r=W(e);for(T4(r,n)||(r=n);;){let e=O4(r);if(e)return d4e(e.path,U(n,e.path)||e.name,n);if(r===n)return null;let t=V(r);if(t===r)return null;r=t}}function u4e(e){let t=O4(e);if(!t||/\.(cjs|mjs|js)$/.test(t.path))return null;let n=K(t.path,`utf-8`),r=f4e(n,t.name);if(`error`in r)return null;let{value:i}=r;return!i||typeof i!=`object`||Array.isArray(i)?null:{rules:i,name:t.name,path:t.path,raw:n}}function d4e(e,t,n){let r=[],i=new Set,a=(e,t)=>{if(!T4(W(e),W(n)))return r.push(`refusing extends target outside the project: ${U(n,e)||e}`),null;let o;try{o=ks(e)}catch(t){return r.push(`cannot read ${U(n,e)||e}: ${k4(t)}`),null}if(!T4(o,ks(n)))return r.push(`refusing extends target outside the project: ${U(n,e)||e}`),null;if(i.has(o))return r.push(`extends cycle at ${U(n,e)||e}`),null;if(i.add(o),t>10)return r.push(`extends chain deeper than 10 levels`),null;if(/\.(cjs|mjs|js)$/.test(e))return r.push(`executable markdownlint config detected but not executed: ${U(n,e)||e} — use a JSON/JSONC/YAML config`),null;let s;try{s=K(o,`utf-8`)}catch(t){return r.push(`cannot read ${U(n,e)||e}: ${k4(t)}`),null}let c=f4e(s,e);if(`error`in c)return r.push(`malformed markdownlint config: ${U(n,e)||e} (${c.error})`),null;if(!c.value||typeof c.value!=`object`||Array.isArray(c.value))return r.push(`malformed markdownlint config: ${U(n,e)||e} (not an object)`),null;let{extends:l,$schema:u,...d}=c.value;if(l==null)return d;if(typeof l!=`string`||l===``)return r.push(`invalid extends value in ${U(n,e)||e}`),d;if(!l.startsWith(`.`)&&!os(l))return r.push(`package extends is not supported (${JSON.stringify(l)} in ${U(n,e)||e}) — use a relative file path`),d;let f=W(V(e),l),p=a(f,t+1);return p?{...p,...d}:d};return{rules:a(e,0),file:t,problems:r}}function k4(e){return(e instanceof Error?e.message:String(e)).split(`
1013
1013
  `,1)[0]??``}function f4e(e,t){try{if(t.endsWith(`.yaml`)||t.endsWith(`.yml`))return{value:(0,wk.parse)(e)};let n=[],r=nL(e.replace(/^\uFEFF/,``),n,{allowTrailingComma:!0}),i=n[0];return i?{error:`${Dke(i.error)} at offset ${i.offset}`}:{value:r}}catch(e){return{error:k4(e)}}}function A4(e,t,n){let r=l4e(t?H(e,V(t)):e,e);if(r&&n)for(let e of r.problems)n(`[${r.file}] ${e}`);return r}function j4(e,t){let n=t?.rules??e.plugins.markdownlint.rules;return{...e,plugins:{...e.plugins,markdownlint:{...e.plugins.markdownlint,rules:n}}}}function M4(e,t,n){let r=t.plugins.frontmatter;if(!r.enabled||r.schemas.length===0||r.schemas.every(e=>e.key!==void 0))return t;let{entries:i,problems:a}=o4e(e,r.schemas);if(n)for(let e of a)n(e);return{...t,plugins:{...t.plugins,frontmatter:{...r,schemas:i}}}}function N4(e,t,n={}){let r=j4(t,A4(e,n.docName,n.onProblem));return M4(n.projectDir??e,r,n.onProblem)}var P4=class extends Error{constructor(e=`the lint configuration or branch changed during the audit walk`){super(e),this.name=`AuditSupersededError`}};async function p4e(e){let{projectDir:t,contentDir:n,baseConfig:r,docRelPath:i,onConfigProblem:a,liveSourceFor:o,cache:c}=e,l=o?.(i)??null,u=N4(n,r,{docName:i,projectDir:t,onProblem:a}),d=s(u,{mode:`lint`}),f=[],p=e=>{f.push(e)};if(l!==null)return{file:i,diagnostics:await ra(l,u,i,p),ran:d,failures:f};let m=g4e(H(n,i),n),h=null;if(c!==void 0){try{let e=Ns(m);h=w4.key({contentDir:n,docRelPath:i,mtimeMs:e.mtimeMs,size:e.size,configFingerprint:w4.fingerprintConfig(u)})}catch{h=null}if(h!==null){let e=c.get(h);if(e!==null)return{file:i,diagnostics:e,ran:d,failures:f}}}let g=K(m,`utf-8`),_=await ra(g,u,i,p);return h!==null&&f.length===0&&c?.set(h,_),{file:i,diagnostics:_,ran:d,failures:f}}async function m4e(e){let{projectDir:t,contentDir:n,baseConfig:r,docRelPath:i,source:a,onConfigProblem:o}=e,c=N4(n,r,{docName:i,projectDir:t,onProblem:o}),l=s(c,{mode:`lint`}),u=[],d=e=>{u.push(e)};return{cfg:c,before:await ra(a,c,i,d),fixed:mr(a,c,i,d),ran:l,failures:u}}function F4(e){let{projectDir:t,contentDir:n,scopeDir:r,onWarning:i}=e,a=RX({projectDir:t,contentDir:n}),o=[];function s(e){let t;try{t=Ds(e,{withFileTypes:!0})}catch(t){i?.(`could not read ${U(n,e)||`.`}: ${y4e(t)}`);return}for(let r of t){if(r.name.startsWith(`.`))continue;let t=H(e,r.name),i=U(n,t);if(r.isDirectory()){if(a.isDirExcluded(i))continue;s(t)}else if(r.isFile()){if(!v4e(r.name)||a.isExcluded(i))continue;o.push(i)}}}return s(r??n),o}async function h4e(e){let{projectDir:t,contentDir:n,baseConfig:r,targetPath:i,auditGeneration:a}=e,o=[],c=[],l=a?.(),u=[],d=_4e(i,n),f=U(n,d.path);if(f.startsWith(`..`)||os(f))return o.push(`refusing audit scope outside the content directory: ${i??``}`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o,ran:[]};if(f.split(`/`).some(e=>e.startsWith(`.`)))return o.push(`refusing audit scope under a hidden path segment: ${i??``}`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o,ran:[]};try{if(!lZ(ks(d.path),ks(n)))return o.push(`symlink-escape: audit scope resolves outside the content directory`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o,ran:[]}}catch{}d.kind===`file`?u.push(U(n,d.path)):u.push(...F4({projectDir:t,contentDir:n,scopeDir:d.path,onWarning:e=>o.push(e)})),u.sort();let p=[],m=[],h=0,g=0,_=new Set,v=e=>{_.has(e)||(_.add(e),o.push(e))},y=M4(t,r,v);c=s(y,{mode:`lint`});let b=y.plugins.frontmatter;if((i===void 0||i===``)&&b.enabled)for(let e of i4e(b.schemas,u))v(e);let x=performance.now();for(let r of u){if(performance.now()-x>=8){if(await mae(),a!==void 0&&a()!==l)throw new P4;x=performance.now()}let i;try{i=await p4e({projectDir:t,contentDir:n,baseConfig:y,docRelPath:r,onConfigProblem:v,liveSourceFor:e.liveSourceFor,cache:e.cache})}catch(e){o.push(`could not lint ${r}: ${y4e(e)}`);continue}m.push(...i.failures);for(let e of i.diagnostics)e.severity===`error`?h++:g++;i.diagnostics.length>0&&p.push({file:i.file,diagnostics:i.diagnostics})}if(a!==void 0&&a()!==l)throw new P4;return o.push(...Kr(m)),{files:p,fileCount:u.length,errorCount:h,warningCount:g,warnings:o,ran:c}}function g4e(e,t){let n=ks(t),r;try{r=ks(e)}catch(e){throw e.code===`ELOOP`?new fZ(`symlink cycle in path`):e}if(!lZ(r,n))throw new fZ(`path resolves outside content directory`);return r}function _4e(e,t){if(e===void 0||e===``)return{kind:`dir`,path:t};let n=os(e)?e:W(t,e);try{if(Ns(n).isFile())return{kind:`file`,path:n}}catch{}return{kind:`dir`,path:n}}function v4e(e){let t=e.toLowerCase();return Qr.some(e=>t.endsWith(e))}function y4e(e){return e instanceof Error?e.message:String(e)}function b4e(e){return[e.lintConfigEpoch,e.projectConfigEpoch,e.activeBranch,e.localTargetGeneration].join(` `)}const x4e={start:{line:0,character:0},end:{line:0,character:0}};function S4e(e){let t=s(e.baseConfig,{mode:`lint`}).filter(e=>e===`okf`);return{id:`okf-project`,sourceFamilies:t,failureSourceFamily:`okf`,async run(n){if(t.length===0)return{files:[],fileCount:0,warnings:[]};let r=[],i=_4e(n.targetPath,e.contentDir),a=i.kind===`file`?U(e.contentDir,i.path):void 0,o=i.kind===`file`?V(i.path):i.path,s=F4({projectDir:e.projectDir,contentDir:e.contentDir,scopeDir:o,onWarning:e=>r.push(e)}),c=new Map;for(let t of ne(s,e.baseConfig.plugins.okf?.rules)){if(a!==void 0&&t.file!==a)continue;let e=c.get(t.file)??[];e.push({range:x4e,severity:`warning`,source:`okf`,code:t.code,message:t.message}),c.set(t.file,e)}return{files:[...c.entries()].map(([e,t])=>({file:e,diagnostics:t})),fileCount:a===void 0?s.length:1,warnings:r}}}}function C4e(e){return{files:e.files.map(e=>({file:e.file,...oee(e.diagnostics)})),fileCount:e.fileCount,errorCount:e.errorCount,warningCount:e.warningCount,warnings:e.warnings,...e.brokenLinkSuppression===void 0?{}:{brokenLinkSuppression:e.brokenLinkSuppression}}}function w4e(e,t){return e.kind===`validator`?`validator "${e.id}" failed: ${t}`:`source family "${e.sourceFamily}" validation failed: ${t}`}function T4e(e,t){return`source family "${e}" validation degraded: ${t}`}function E4e(e){return[k4e(e),A4e(e),S4e(e)]}async function D4e(e,t={}){let n=await Promise.all(e.map(async e=>{let n=e.sourceFamilies;try{let r=await e.run(t);return{...r,ran:r.ran??n}}catch(t){if(t instanceof P4)throw t;q(`validation-audit`).error({err:t,validatorId:e.id},`[audit] validator threw; degrading to a plane warning`);let r=t instanceof Error?t.message:String(t);return{files:[],fileCount:0,warnings:[w4e(e.failureSourceFamily===void 0?{kind:`validator`,id:e.id}:{kind:`source-family`,sourceFamily:e.failureSourceFamily},r)],ran:n}}})),r=new Map,i=[],a=new Set,o=0,s=0;for(let e of n){i.push(...e.warnings);for(let t of e.ran??[])a.add(t);o+=e.suppressedBrokenLinkCount??0,s=Math.max(s,e.fileCount);for(let t of e.files){let e=r.get(t.file);e?e.push(...t.diagnostics):r.set(t.file,[...t.diagnostics])}}let c=[...r.entries()].map(([e,t])=>({file:e,diagnostics:t.sort(O4e)})).sort((e,t)=>e.file.localeCompare(t.file)),l=0,u=0;for(let e of c)for(let t of e.diagnostics)t.severity===`error`?l++:u++;let d=aQe(o);return{files:c,fileCount:s,errorCount:l,warningCount:u,warnings:i,ran:[...a],...d===void 0?{}:{brokenLinkSuppression:d}}}function O4e(e,t){return e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character||e.source.localeCompare(t.source)||e.code.localeCompare(t.code)}function k4e(e){return{id:`lint`,sourceFamilies:s(e.baseConfig,{mode:`lint`}),async run(t){let n=await h4e({projectDir:e.projectDir,contentDir:e.contentDir,baseConfig:e.baseConfig,targetPath:t.targetPath,liveSourceFor:e.liveSourceFor,cache:e.cache,auditGeneration:e.auditGeneration});return{files:n.files,fileCount:n.fileCount,warnings:n.warnings,ran:n.ran}}}}function A4e(e){let t=e.linkPolicy.links,n=e.linkPolicy.suppressLogLinkAdvisories;return{id:`links`,sourceFamilies:s(e.baseConfig,{mode:`audit`,linksValidation:t}).filter(e=>e===`links`),failureSourceFamily:`links`,async run(r){if(t===`off`)return{files:[],fileCount:0,warnings:[]};let i=t===`error`?`error`:`warning`;if(!e.derivedDocumentIndex)return{files:[],fileCount:0,warnings:[w4e({kind:`source-family`,sourceFamily:`links`},`backlink index is not configured`)]};let a=e.auditGeneration?.(),o=()=>{if(e.auditGeneration!==void 0&&e.auditGeneration()!==a)throw new P4},s=[...await e.admittedDocNames()],c=N4e(s,r.targetPath);if(c!==void 0&&c.length===0)return o(),{files:[],fileCount:0,warnings:[]};let l=await e.derivedDocumentIndex.getDeadLinks(s,c),u=e=>uQe(e,n),d=new Map,f=(e,t)=>{let n=d.get(e)??[];n.push(t),d.set(e,n)},p=[],m=new Set,h=new Set,g=[],_=0;try{let t=await e.derivedDocumentIndex.getLocalTargetAssessmentsForSources(c);for(let{source:n,assessments:r}of t){if(uUe(n))continue;let t=u(n),a=e.docFilePathFor(n)??`${n}.md`;for(let e of r){let r=M4e(e,i);r&&(t?_++:p.push({file:a,diagnostic:r}),e.targetKind===`document`&&e.resolvedTarget!==null&&m.add(`${n}\0${e.resolvedTarget}`))}for(let e of r)e.status===`exact`&&e.resolvedTarget!==null&&h.add(`${n}\0${e.resolvedTarget}`)}}catch(e){if(e instanceof P4)throw e;q(`validation-audit`).warn({err:e},`[audit] local-target projection unavailable; preserving graph link findings`);let t=e instanceof Error?e.message:String(e);g.push(T4e(`links`,`local-target projection unavailable: ${t}`))}for(let{target:t,sources:n}of l)for(let r of n){if(uUe(r.source))continue;let n=`${r.source}\0${t}`;if(r.sourceForm!==`wiki`&&(m.has(n)||h.has(n)))continue;if(u(r.source)){_++;continue}let a=e.docFilePathFor(r.source)??`${r.source}.md`,o=r.line??0,s=r.column??0;f(a,{range:{start:{line:o,character:s},end:{line:o,character:s}},severity:i,source:`links`,code:`dead-link`,message:`Link target "${t}" does not resolve to an existing document.`,linkTarget:t})}for(let{file:e,diagnostic:t}of p)f(e,t);return o(),{files:[...d.entries()].map(([e,t])=>({file:e,diagnostics:t})),fileCount:0,warnings:g,..._>0?{suppressedBrokenLinkCount:_}:{}}}}}function j4e(e,t){let n=e.occurrence.role===`image`;return e.reason===`unresolvable`?n?`Image target "${t}" could not be resolved to a project-local file.`:`Link target "${t}" could not be resolved to a project-local target.`:e.targetKind===`file`?n?`Image target "${t}" does not resolve to an existing file.`:`Link target "${t}" does not resolve to an existing file.`:`Link target "${t}" does not resolve to an existing document.`}function M4e(e,t){if(e.reason===null)return null;let{occurrence:n,targetKind:r}=e,i=Z$e(e,e.reason);if(i===null)return null;let a=e.resolvedTarget??n.href,o=n.line,s=n.column,c={range:{start:{line:o,character:s},end:{line:o,character:s}},severity:t,source:`links`,code:`dead-link`,message:j4e(e,a),localTarget:i};return r===`document`&&e.status===`missing`&&e.resolvedTarget!==null&&(c.linkTarget=e.resolvedTarget),c}function N4e(e,t){if(t===void 0||t===``)return;let n=t.toLowerCase();if(Qr.some(e=>n.endsWith(e))){let n=t.slice(0,t.lastIndexOf(`.`));return e.filter(e=>e===n)}let r=`${t.replace(/\/+$/,``)}/`;return e.filter(e=>e.startsWith(r))}function P4e({homeDirOverride:e,log:t}){let n=0,r=null,i=null;function a(){n+=1}function o(e){let t=`${e?.projectDir??``}|${e&&`home`in e?e.home:``}`,r=Date.now();if(i!==null&&i.gen===n&&i.key===t&&r-i.at<5e3)return i.value;let a=II(e);return i={at:r,gen:n,key:t,value:a},a}function s(e){return r!==null&&r.fp!==e&&a(),r!==null&&r.gen===n&&r.fp===e&&Date.now()-r.at<5e3?{body:r.body}:null}function c(e,t){r={at:Date.now(),gen:n,fp:e,body:t}}let l=null;function u(n){let r=Date.now();if(l&&l.identity===n&&r-l.at<3e4)return l.byName;let i=new Map;try{i=jte(o(e===void 0?{}:{home:e}).skills,e=>oI(e)?.contentHash)}catch(e){t.warn({err:e},`plugin upstream index failed; origins will be omitted`)}return l={at:r,identity:n,byName:i},i}return{bumpSkillsCatalogGen:a,enumerateInstalledSkillsCached:o,readList:s,writeList:c,pluginSkillsByName:u}}function I4(e){return e.split(`/`).some(e=>{let t=e.toLowerCase();return t===`.ok`||t===`.git`})}function F4e(e,t){let{contentDir:n,contentFilter:r,docNameForPath:i}=t,a=[];try{if(!Ns(e).isDirectory())return a}catch(e){let t=dZ(e);if(t===`ENOENT`||t===`ENOTDIR`)return a;throw e}function o(e){for(let t of Ds(e,{withFileTypes:!0})){let s=W(e,t.name),c=U(n,s).split(us).join(`/`);if(I4(c))continue;if(t.isDirectory()){if(r?.isDirExcluded(c))continue;o(s);continue}if(!t.isFile()||!zY(c)||r?.isExcluded(c))continue;let l=i(c);WY(VY(c),as(c)),a.push(l)}}return o(e),a.sort((e,t)=>e.localeCompare(t)),a}function I4e(e){return e.filter(e=>X$e(e.occurrence))}function L4e(e,t){let n=[],r=[];if(e.resolvedTarget!==null&&(e.targetKind===`document`?n.push(e.resolvedTarget):e.targetKind===`file`&&r.push(e.resolvedTarget)),e.occurrence.role===`link`){let i=v(e.occurrence.href,t);if(i?.kind===`doc`){n.push(i.docName);let a=Ji(e.occurrence.href,t,{literal:!1});a===i.docName&&r.push(a)}}return e.fallbackTarget!==null&&n.push(e.fallbackTarget),{docs:n,files:r}}function L4(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function R4(e,t,n){let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))}function R4e(e){let t=[],n=ea(e);return n&&t.push(`slug:${n}`),!e.includes(`/`)&&n&&t.push(`basename:${n}`),t.push(`folder:${e}`),t}function z4(e){let t=[],n=ea(e);n&&t.push(`slug:${n}`);let r=e.slice(e.lastIndexOf(`/`)+1),i=ea(r);i&&t.push(`basename:${i}`);let a=e.indexOf(`/`);for(;a!==-1;)t.push(`folder:${e.slice(0,a)}`),a=e.indexOf(`/`,a+1);return t}function z4e(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];if(!r)return!1;let i=e.occurrence.reference,a=r.occurrence.reference;return e.targetKind===r.targetKind&&e.resolvedTarget===r.resolvedTarget&&e.status===r.status&&e.reason===r.reason&&e.resolutionMethod===r.resolutionMethod&&e.fallbackTarget===r.fallbackTarget&&e.occurrence.role===r.occurrence.role&&e.occurrence.sourceForm===r.occurrence.sourceForm&&e.occurrence.href===r.occurrence.href&&e.occurrence.range.start===r.occurrence.range.start&&e.occurrence.range.end===r.occurrence.range.end&&e.occurrence.line===r.occurrence.line&&e.occurrence.column===r.occurrence.column&&i?.label===a?.label&&i?.kind===a?.kind&&i?.definition.href===a?.definition.href&&i?.definition.repairRange.start===a?.definition.repairRange.start&&i?.definition.repairRange.end===a?.definition.repairRange.end})}var B4e=class e{contentDir;canonicalContentDir;contentFilter;readDocument;readDirectory;sourceAssessments=new Map;sourceDocDeps=new Map;sourceFileDeps=new Map;reverseByDoc=new Map;reverseByFile=new Map;reverseByTolerant=new Map;sourceTolerantDeps=new Map;documents=new Set;tolerantDocumentResolver=()=>null;files=new Set;generationValue=0;freshnessEpoch=0;readyValue=!1;closed=!1;folderPaths=new Set;injectedFolderPaths=new Set;inventory={hasDocument:e=>this.documents.has(e),hasFile:e=>this.files.has(e),resolveTolerantDocument:e=>this.tolerantDocumentResolver(e),hasFolder:e=>this.folderPaths.has(e)||this.injectedFolderPaths.has(e)};constructor(e){this.contentDir=e.contentDir;try{this.canonicalContentDir=ks(e.contentDir)}catch{this.canonicalContentDir=e.contentDir}this.contentFilter=e.contentFilter,this.readDocument=e.readDocument??(e=>Ks(e,`utf-8`)),this.readDirectory=e.readDirectory??(e=>qs(e,{withFileTypes:!0}))}get generation(){return this.generationValue}isReady(){return this.readyValue}markUnavailable(){this.readyValue&&this.freshnessEpoch++,this.readyValue=!1}get freshnessToken(){return`${this.generationValue}:${this.freshnessEpoch}`}getAssessments(e){return this.sourceAssessments.get(e)??[]}getAssessmentsForSources(e){let t=e&&e.length>0?new Set(e):null,n=[];for(let[e,r]of this.sourceAssessments)t&&!t.has(e)||n.push({source:e,assessments:r});return n}getDocumentDependents(e){let t=new Set(this.reverseByDoc.get(e)??[]);for(let n of z4(e))for(let e of this.reverseByTolerant.get(n)??[])t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}getFileDependents(e){return[...this.reverseByFile.get(e)??[]].sort((e,t)=>e.localeCompare(t))}getStats(){let e=0;for(let t of this.sourceAssessments.values())e+=t.length;return{sources:this.sourceAssessments.size,occurrences:e,documentTargets:this.reverseByDoc.size,fileTargets:this.reverseByFile.size}}close(){this.closed=!0}setSource(e,t){return!rX(e)&&C0(`local-target`,`source`,()=>{let n=this.sourceAssessments.get(e)??[],r=!this.documents.has(e);this.documents.add(e),r&&this.refreshTolerantDocumentIndexes();let i=I4e(U0(E0(t),e,this.inventory)),a=!z4e(n,i);a&&this.applySourceAssessments(e,i);let o=r?this.reassessDocumentDependents(e):0,s=a||o>0;return s&&this.generationValue++,{changed:s,occurrences:i.length,affectedSources:o+ +!!a}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affectedSources})).changed}removeSource(e){return!rX(e)&&C0(`local-target`,`document-target`,()=>{let t=this.sourceAssessments.get(e)?.length??0,n=t>0,r=this.documents.delete(e);r&&this.refreshTolerantDocumentIndexes(),this.applySourceAssessments(e,[]);let i=r?this.reassessDocumentDependents(e):0,a=n||i>0;return a&&this.generationValue++,{changed:a,occurrences:t,affectedSources:i+ +!!n}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affectedSources})).changed}renameSource(e,t,n){let r=this.removeSource(e),i=this.setSource(t,n);return r||i}setFileTarget(e,t){return this.files.has(e)===t?0:C0(`local-target`,`file-target`,()=>{t?this.files.add(e):this.files.delete(e);let n=this.countFileOccurrences(e),r=this.reassessFileDependents(e);return r>0&&this.generationValue++,{affected:r,occurrences:n}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affected})).affected}reconcileDocumentTargets(e){let t=new Set(e),n=new Set;for(let e of this.documents)t.has(e)||n.add(e);for(let e of t)this.documents.has(e)||n.add(e);if(n.size===0)return 0;let r=new Set;for(let e of n){for(let t of this.reverseByDoc.get(e)??[])r.add(t);for(let t of z4(e))for(let e of this.reverseByTolerant.get(t)??[])r.add(e)}this.documents=t,this.refreshTolerantDocumentIndexes();let i=0;for(let e of r)this.reassessSource(e)&&i++;return i>0&&this.generationValue++,i}reconcileFolderTargets(e){let t=new Set(e),n=new Set;for(let e of this.injectedFolderPaths)t.has(e)||n.add(e);for(let e of t)this.injectedFolderPaths.has(e)||n.add(e);if(n.size===0)return 0;let r=new Set;for(let e of n)for(let t of this.reverseByTolerant.get(`folder:${e}`)??[])r.add(t);this.injectedFolderPaths=t;let i=0;for(let e of r)this.reassessSource(e)&&i++;return i>0&&this.generationValue++,i}reconcileFileTargets(e){let t=new Set(e),n=new Set;for(let e of this.files)t.has(e)||n.add(e);for(let e of t)this.files.has(e)||n.add(e);return n.size===0?0:C0(`local-target`,`file-target`,()=>{let e=new Set,r=0;for(let t of n){r+=this.countFileOccurrences(t);for(let n of this.reverseByFile.get(t)??[])e.add(n)}this.files=t;let i=0;for(let t of e)this.reassessSource(t)&&i++;return i>0&&this.generationValue++,{affected:i,occurrences:r}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affected})).affected}async reconcileDependentFileTargetsFromDisk(e){let t=[...this.reverseByFile.keys()],n=await Promise.all(t.map(e=>this.isAdmittedFileOnDisk(e))),r=0;for(let[i,a]of t.entries()){let t=n[i]??!1,o=this.setFileTarget(a,t);o>0&&e?.(a,t),r+=o}return r}async isAdmittedFileOnDisk(e){if(this.contentFilter?.isPathIgnored(e))return!1;try{let t=await Js(H(this.contentDir,e)),n=U(this.canonicalContentDir,t);return n===``||n===`..`||n.startsWith(`..${process.platform===`win32`?`\\`:`/`}`)||os(n)?!1:(await Xs(t)).isFile()}catch{return!1}}countFileOccurrences(e){let t=0;for(let n of this.reverseByFile.get(e)??[])for(let r of this.sourceAssessments.get(n)??[])L4e(r,n).files.includes(e)&&t++;return t}rebuildFromDisk(e){return S0(`local-target`,`full`,()=>this.rebuildOnce(e),e=>({"index.sources":e.sources,"index.occurrences":e.occurrences,"index.affected_sources":e.sources}))}async rebuildOnce(t){let n=this.sourceAssessments.size>0;this.freshnessEpoch++,this.readyValue=!1;let r=new e({contentDir:this.contentDir,contentFilter:this.contentFilter,readDocument:this.readDocument,readDirectory:this.readDirectory}),i=await r.populateFromDisk(t);return this.sourceAssessments=r.sourceAssessments,this.sourceDocDeps=r.sourceDocDeps,this.sourceFileDeps=r.sourceFileDeps,this.reverseByDoc=r.reverseByDoc,this.reverseByFile=r.reverseByFile,this.reverseByTolerant=r.reverseByTolerant,this.sourceTolerantDeps=r.sourceTolerantDeps,this.documents=r.documents,this.tolerantDocumentResolver=r.tolerantDocumentResolver,this.folderPaths=r.folderPaths,this.injectedFolderPaths=r.injectedFolderPaths,this.files=r.files,this.readyValue=!0,(n||this.sourceAssessments.size>0)&&this.generationValue++,i}async populateFromDisk(e){for(let t of e.documentTargets)this.documents.add(t);for(let t of e.fileTargets)this.files.add(t);for(let t of e.folderTargets??[])this.injectedFolderPaths.add(t);if(this.refreshTolerantDocumentIndexes(),!G(this.contentDir))return this.readyValue=!0,{sources:0,occurrences:0};let t=await this.listDocsWithPaths();for(let{docName:e}of t)this.documents.add(e);this.refreshTolerantDocumentIndexes();let n=0;for(let e=0;e<t.length&&!this.closed;e+=50){let r=t.slice(e,e+50),i=await Promise.all(r.map(async({docName:e,filePath:t})=>({docName:e,markdown:await this.readDocument(t)})));for(let e of i){if(rX(e.docName))continue;let t=I4e(U0(E0(e.markdown),e.docName,this.inventory));this.applySourceAssessments(e.docName,t),n+=t.length}}return this.readyValue=!0,{sources:this.sourceAssessments.size,occurrences:n}}applySourceAssessments(e,t){let n=new Set,r=new Set,i=new Set;for(let a of t){let{docs:t,files:o}=L4e(a,e);for(let e of t)n.add(e);for(let e of o)r.add(e);if(a.targetKind===`document`&&a.resolvedTarget!==null&&(a.status!==`exact`||!this.documents.has(a.resolvedTarget)))for(let e of R4e(a.resolvedTarget))i.add(e)}let a=this.sourceDocDeps.get(e);if(a)for(let t of a)n.has(t)||R4(this.reverseByDoc,t,e);for(let t of n)a?.has(t)||L4(this.reverseByDoc,t,e);let o=this.sourceFileDeps.get(e);if(o)for(let t of o)r.has(t)||R4(this.reverseByFile,t,e);for(let t of r)o?.has(t)||L4(this.reverseByFile,t,e);let s=this.sourceTolerantDeps.get(e);if(s)for(let t of s)i.has(t)||R4(this.reverseByTolerant,t,e);for(let t of i)s?.has(t)||L4(this.reverseByTolerant,t,e);if(t.length===0){this.sourceAssessments.delete(e),this.sourceDocDeps.delete(e),this.sourceFileDeps.delete(e),this.sourceTolerantDeps.delete(e);return}this.sourceAssessments.set(e,t),this.sourceDocDeps.set(e,n),this.sourceFileDeps.set(e,r),this.sourceTolerantDeps.set(e,i)}reassessSource(e){let t=this.sourceAssessments.get(e);if(!t)return!1;let n=U0(t.map(e=>e.occurrence),e,this.inventory);return!z4e(t,n)&&(this.applySourceAssessments(e,n),!0)}reassessDocumentDependents(e){let t=new Set(this.reverseByDoc.get(e)??[]);for(let n of z4(e))for(let e of this.reverseByTolerant.get(n)??[])t.add(e);let n=0;for(let e of t)this.reassessSource(e)&&(n+=1);return n}reassessFileDependents(e){let t=[...this.reverseByFile.get(e)??[]],n=0;for(let e of t)this.reassessSource(e)&&(n+=1);return n}refreshTolerantDocumentIndexes(){this.tolerantDocumentResolver=G$e(this.documents);let e=new Set;for(let t of this.documents){let n=t.indexOf(`/`);for(;n!==-1;)e.add(t.slice(0,n)),n=t.indexOf(`/`,n+1)}this.folderPaths=e}async listDocsWithPaths(){let e=[];await 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)&&(t.add(e),!0))}async walkContentDir(e,t){let n=await this.readDirectory(e);for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=bX(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!zY(r.name))continue;let i=bX(U(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:VY(i),filePath:n})}}};const B4=q(`tag-index`),V4e=Et();function H4e(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.version!==1)return!1;let{docs:n,files:r}=t;if(typeof n!=`object`||!n||Array.isArray(n)||typeof r!=`object`||!r||Array.isArray(r))return!1;for(let e of Object.values(n))if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e.length>0))return!1;for(let e of Object.values(r)){if(typeof e!=`object`||!e)return!1;let{mtimeMs:t,size:n}=e;if(typeof t!=`number`||typeof n!=`number`)return!1}return!0}function V4(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function U4e(e){return e.replace(/`[^`]*`/g,``)}function W4e(e){let t=e.replaceAll(`\r