@inkeep/open-knowledge 0.88.2-beta.0 → 0.88.3-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-iKekN_P_.mjs +1 -0
  3. package/dist/{dist-Cnm7_eq4.mjs → dist-CqRTItlw.mjs} +2 -2
  4. package/dist/{dist-aK1pesSJ.mjs → dist-DZ47D2ZS.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-D3X4bUI7.mjs +1 -0
  7. package/dist/{init-ywNRYDbH.mjs → init-DcojktK8.mjs} +2 -2
  8. package/dist/{launch-json-removal-BaIeZszo.mjs → launch-json-removal-CZJIrfQI.mjs} +1 -1
  9. package/dist/loader-6aogCPbH.mjs +1 -0
  10. package/dist/{loader-BG4_DZyV.mjs → loader-BiwGF8bz.mjs} +1 -1
  11. package/dist/{open-browser-zEHFkT8w.mjs → open-browser-Bc67k1xM.mjs} +1 -1
  12. package/dist/{preview-B7jPTtX8.mjs → preview-B6_6Xw8I.mjs} +1 -1
  13. package/dist/preview-C8jLntfA.mjs +1 -0
  14. package/dist/public/assets/{AccountSection-BF0qrLqu.js → AccountSection-BN4Cw37c.js} +1 -1
  15. package/dist/public/assets/{ActivityModeContent-DyNI8TIL.js → ActivityModeContent-DOQAQjfZ.js} +1 -1
  16. package/dist/public/assets/{AddPropertiesButton-D0D-Tszd.js → AddPropertiesButton-Bl5CfmF_.js} +1 -1
  17. package/dist/public/assets/{AgentDiffPane-CstJFz4V.js → AgentDiffPane-CtSQuPtF.js} +1 -1
  18. package/dist/public/assets/{AttachmentsSection-Bdaynhmy.js → AttachmentsSection-C8Kht0A-.js} +1 -1
  19. package/dist/public/assets/{CodeMirrorPropInput-Dgf3j21J.js → CodeMirrorPropInput-BzqkkbNX.js} +1 -1
  20. package/dist/public/assets/{ContentRulesSection-ByeMs3u9.js → ContentRulesSection-cZPJ290U.js} +1 -1
  21. package/dist/public/assets/{DocumentContext-BSipuPTv.js → DocumentContext-DY2SpfLc.js} +1 -1
  22. package/dist/public/assets/{EditorModeToggle-B4yTd3te.js → EditorModeToggle-DDWiImgF.js} +1 -1
  23. package/dist/public/assets/{ExcalidrawDocEditor-BMOGdD_4.js → ExcalidrawDocEditor-CQfnUtWJ.js} +1 -1
  24. package/dist/public/assets/FeedbackForm-DqvCDmlT.js +1 -0
  25. package/dist/public/assets/{ImportSkillDialog-CimMkiT7.js → ImportSkillDialog-BRbHATtN.js} +1 -1
  26. package/dist/public/assets/{LinkPreviewsSection-B7NqEM6D.js → LinkPreviewsSection-CaVr6XOD.js} +1 -1
  27. package/dist/public/assets/{LintConfigEditor-B17TqMWW.js → LintConfigEditor-DaWYe45j.js} +1 -1
  28. package/dist/public/assets/{LintingSection-BCM4i9OA.js → LintingSection-D8iY3BeV.js} +1 -1
  29. package/dist/public/assets/ManagedArtifactProperties-BtDc4gv6.js +1 -0
  30. package/dist/public/assets/{ManagedArtifactProperties-D0ts-0ck.js → ManagedArtifactProperties-Ds7bk2Cg.js} +1 -1
  31. package/dist/public/assets/{MermaidDocEditor-C-ps4TIU.js → MermaidDocEditor-D5p_P15E.js} +1 -1
  32. package/dist/public/assets/{NetworkAccessSection-BJ0XN7w8.js → NetworkAccessSection-CdPfWL-6.js} +1 -1
  33. package/dist/public/assets/{PropertyDisplayRow-BZjmC1Sv.js → PropertyDisplayRow-CGtf6FxV.js} +1 -1
  34. package/dist/public/assets/{PublishToGitHubDialog-BjHeEqYe.js → PublishToGitHubDialog-C966LBq0.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-BaLgHrYT.js → SchemaConfigEditor-DV-OqSmg.js} +1 -1
  36. package/dist/public/assets/{SearchSection-DW3r2tKK.js → SearchSection-B6rHqfp_.js} +1 -1
  37. package/dist/public/assets/{SessionsHost-D52puC6E.js → SessionsHost-C80PQ9Ji.js} +2 -2
  38. package/dist/public/assets/{SettingsDialogBody-DEfOKOku.js → SettingsDialogBody-DpdBlukg.js} +2 -2
  39. package/dist/public/assets/{ShareReceiveMissDialog-Cqjn-593.js → ShareReceiveMissDialog-bsQuI8F-.js} +1 -1
  40. package/dist/public/assets/{SkillToolbarControls-CfrgNQVZ.js → SkillToolbarControls-C7VMQV0g.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-Baka-Rpr.js → SourceEditor-3mT49S9c.js} +1 -1
  42. package/dist/public/assets/{SyncSection-tP31S34_.js → SyncSection--UJ18oO3.js} +1 -1
  43. package/dist/public/assets/{SyncStatusBadge-fncpT3rs.js → SyncStatusBadge-a4kNafeZ.js} +1 -1
  44. package/dist/public/assets/{TerminalSection-DZWenTGJ.js → TerminalSection-RYIum5Rn.js} +1 -1
  45. package/dist/public/assets/{TerminalWindowApp-Bq_Il7xv.js → TerminalWindowApp-HOVOYe31.js} +1 -1
  46. package/dist/public/assets/{TextDocEditor-DHWPb7Be.js → TextDocEditor-Bnv8NUnt.js} +1 -1
  47. package/dist/public/assets/{ThreadView-CZauqnMW.js → ThreadView-B65BxjmT.js} +1 -1
  48. package/dist/public/assets/{TimelineDiffPane-hNc5buDc.js → TimelineDiffPane-DFsTESmd.js} +1 -1
  49. package/dist/public/assets/{client-version-vRocvopx.js → client-version-BDuwu8nN.js} +1 -1
  50. package/dist/public/assets/{comment-chips-BVPvbqYP.js → comment-chips-CmVjOzx9.js} +1 -1
  51. package/dist/public/assets/{config-provider-B0KSeJLI.js → config-provider-B9LKWNeQ.js} +1 -1
  52. package/dist/public/assets/{doc-undo-manager-Co7uweSe.js → doc-undo-manager-g1jPjDAZ.js} +1 -1
  53. package/dist/public/assets/{index-CpkFK70Z.js → index-DZ5ANdd4.js} +7 -7
  54. package/dist/public/assets/{lint-plugins-DQt1oy6N.js → lint-plugins-Dztmq1iU.js} +1 -1
  55. package/dist/public/assets/{pending-receive-nav-store-BXSi9rkO.js → pending-receive-nav-store-BG9-tW7s.js} +1 -1
  56. package/dist/public/assets/{preferred-session-events-4DGxmBvP.js → preferred-session-events-CiOjVspY.js} +1 -1
  57. package/dist/public/assets/{progress-DBlXhHru.js → progress-HDmUIvkS.js} +1 -1
  58. package/dist/public/assets/{selection-context-CDfJvo6K.js → selection-context-CXsG3XPe.js} +1 -1
  59. package/dist/public/assets/{src-BKxqAAAL.js → src-Dx3dqWI2.js} +1 -1
  60. package/dist/public/assets/{telemetry-impl-DairwqJS.js → telemetry-impl-Yh79UJVk.js} +1 -1
  61. package/dist/public/assets/{telemetry-startup-D7xEoNsW.js → telemetry-startup-DCztiQrG.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-CFivfF8d.js → typing-burst-detector-Cua3oA5j.js} +1 -1
  63. package/dist/public/assets/{use-activity-panel-DjEwkwyR.js → use-activity-panel-WNt6B2Wq.js} +1 -1
  64. package/dist/public/assets/{use-open-skill-C9vUANOX.js → use-open-skill-g8pBIBzf.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-CTZAEdSN.js → use-terminal-enabled-D1gCuuSr.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-zJZtfSLF.js → use-timeline-entry-diff-BjRr2sCn.js} +1 -1
  67. package/dist/public/index.html +19 -19
  68. package/dist/{registry-probes-D1whnrBk.mjs → registry-probes-BB52WJE5.mjs} +1 -1
  69. package/dist/{removal-file-path-C0pLsMD9.mjs → removal-file-path-CGfVL-G_.mjs} +1 -1
  70. package/dist/{repair-launch-json-CA5E2V32.mjs → repair-launch-json-C6Z8Lt66.mjs} +1 -1
  71. package/dist/{repair-mcp-configs-xB9Utyx4.mjs → repair-mcp-configs-Ho22omwW.mjs} +1 -1
  72. package/dist/src-BC52Vdpm.mjs +1 -0
  73. package/dist/{src-BfWFmqOR.mjs → src-DbQpB5ed.mjs} +1 -1
  74. package/dist/start-B4pN-Gox.mjs +1 -0
  75. package/dist/{start-21X4tGJP.mjs → start-DW9nXQC_.mjs} +3 -3
  76. package/package.json +4 -4
  77. package/dist/constants--jgM2tyo.mjs +0 -1
  78. package/dist/init-DEA9CDC9.mjs +0 -1
  79. package/dist/loader-CGbDCKLc.mjs +0 -1
  80. package/dist/preview-gmKJw4Ve.mjs +0 -1
  81. package/dist/public/assets/FeedbackForm-MJVtDJTs.js +0 -1
  82. package/dist/public/assets/ManagedArtifactProperties-Bzt3Nh5J.js +0 -1
  83. package/dist/src-CIt3lSM3.mjs +0 -1
  84. package/dist/start-DIPGWG8p.mjs +0 -1
@@ -1126,7 +1126,7 @@ ${B5e(e).join(`
1126
1126
  `).replaceAll(`\r`,`
1127
1127
  `).split(`
1128
1128
  `))n(i)||cmt(lmt(i,r).replace(/`[^`]*`/g,``),t);return[...t.values()]}function dmt(e){let t=nmt(e.href);if(!t||tmt(t))return null;let n=So(t,e.fromDocName,{literal:e.literal});if(!n)return null;let r=Ws(n).slice(1).toLowerCase();if(!va.has(r))return null;let i=W(e.contentDir,n),a,o;try{if(a=Ks(hc(i)),!KG(a,e.contentDir))return null;o=yc(a)}catch(t){let n=smt(t);return n!==`ENOENT`&&n!==`ENOTDIR`&&$pt.warn({href:e.href,err:t},`unexpected error resolving asset`),null}return o.isFile()?{absolutePath:a,relativePath:fmt(e.contentDir,a),stat:o}:null}function fmt(e,t){let n=Ks(hc(e));return Ks(t).slice(n.length+ +!n.endsWith(Ys)).split(Ys).join(`/`)}function pmt(e){let t;try{t=Ks(hc(e.contentDir))}catch(e){return $pt.warn({err:e},`could not resolve content directory`),[]}let n=new Map;for(let[r,i]of e.fileIndex){let a=e.readMarkdown(i.canonicalPath);if(a!==null)for(let i of umt(a)){let a=dmt({contentDir:t,fromDocName:r,href:i.href,literal:i.literal});if(!a||e.isExcluded?.(a.relativePath))continue;let o=omt(a.absolutePath),s=n.get(a.relativePath);if(s){s.referencedBy.includes(r)||s.referencedBy.push(r);continue}n.set(a.relativePath,{kind:`asset`,path:a.relativePath,assetExt:Ws(a.relativePath).toLowerCase(),mediaKind:o,size:a.stat.size,modified:a.stat.mtime.toISOString(),referencedBy:[r]})}}return[...n.values()].sort((e,t)=>e.path.localeCompare(t.path))}function mmt(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}function hmt(e){let{hocuspocus:t,conflicts:n,contentDir:r,isSafeDocName:i,resolveAlias:a,resolveContentEntryPath:o,resolveDocPath:s,extractHeadings:c,getFileIndex:l,getFileIndexGeneration:u,log:d,ready:f,contentFilter:p,safeSubdir:m,getShowAllMaxEntries:h,streamShowAllEntries:g,walkContentDirForShowAll:_,synthesizeShowAllAssetExt:v,getAllFilesIndex:y,getFolderIndex:b,getFolderAliasIndex:S,onReferencedAssetsCacheInvalidator:C}=e,w=new Map,T=null;function E(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1129
- `)}function D(){T=null}C?.(D);function O(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let k=Z(x,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=YH(a(s));if(_U(c)||vU(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,so,{docName:c,content:u.getText(`source`).toString(),lifecycle:O(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,so,{docName:c,content:t,lifecycle:O(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),A=Z(x,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&mmt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=eq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=w.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;w.set(e,c),a.finally(()=>{w.get(e)===c&&w.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),w.get(e)===a&&w.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,ue,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let c=l(),x=[...y()],C=b?.()??new Map,D=S?.()??new Map,O=[];for(let[e,t]of C)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=E(c),t=u?.();(!T||T.signature!==e||T.generation!==t||T.assets.some(e=>p?.isPathIgnored(e.path)))&&(T={signature:e,generation:t,assets:pmt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=T?.assets??[]}catch(e){T=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let A=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(A.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of x){if(t.kind===`markdown`){let n=qH(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of lX(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of lX(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=C.get(n),a=t?uX(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of C)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:uX(r,t.canonicalPath,e)})});for(let[e,t]of x){let{resolved:i,members:a}=lX(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:qH(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,ue,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),j=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,zne,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),M={"/api/document":k,"/api/documents":A,"/api/pages":Z(x,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=qH(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=JY(i,t),o=uet(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Jte,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":j};return{paths:Object.keys(M),table:{resolve(e){let t=M[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:D}}const gmt=[`date`,`user`],_mt=/\{\{([^{}\n]+?)\}\}/g;function vmt(e){let t=[];for(let n of e.matchAll(_mt)){let e=(n[1]??``).trim();bmt(e)||t.push({token:e,offset:n.index??0})}return t}function ymt(e,t){return e.replace(_mt,(e,n)=>{let r=n.trim();return bmt(r)?t[r]:e})}function bmt(e){return gmt.includes(e)}function L4(e,t,n={}){let r=Cmt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;z4(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)z4(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&z4(e,``,`inherited`,a,o,s),o}async function xmt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=R4){a=!0,q(`templates`).warn({projectDir:e,cap:R4,queueDepth:o.length},`project scan hit the ${R4}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}z4(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Mc(s,{withFileTypes:!0})}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Smt.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Fc(n)).isDirectory()}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(n)){B4.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?Js.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const R4=2e3,Smt=new Set([`node_modules`,`dist`,`build`]);function z4(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(MK(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),B4.has(o)||(B4.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=cc(s)}catch(e){let n=cG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),B4.has(s)||(B4.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=mc(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=yc(c)}catch{continue}if(!l.isFile())continue;try{jK(c,s),jK(c,e)}catch(e){if(e instanceof EK){B4.has(c)||(B4.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(cG(e)!==`ENOENT`&&!B4.has(c)){B4.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=wmt(c),d={name:o,path:t?Js.join(t,`.ok`,`templates`,a):Js.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Cmt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const B4=new Set;function wmt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(cG(t)!==`ENOENT`&&!B4.has(e)){B4.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=ct(t);typeof n.title!=`string`&&!B4.has(e)&&(B4.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var V4=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const H4=q(`file-ops`);function Tmt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)_U(r)||vU(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;XU(V(n),{recursive:!0});try{JU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),hX(n,dG(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(XU(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=yc(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(WG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?eW(s):(iW(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&yc(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=yc(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(WG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=Ws(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(_U(n)||vU(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{XU(s,{recursive:!0}),JU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{aW(s)}catch(e){let t=cG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&H4.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{KH(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),hX(r,dG(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{iW(r,{force:!0})}catch(e){H4.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw ZH(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{QU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=Ws(n.fullPath);KH(UH(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),hX(n.fullPath,dG(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){H4.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&ZH(UH(t.docName))}e.removeFolderIndexEntries(l);try{iW(u,{recursive:!0,force:!0})}catch(e){H4.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var U4=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function W4(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return pne(e)}}function G4(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function K4(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return pne(e)}}const q4=q(`upload-streaming`);var Emt=class extends Sae{hash=Rc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Dmt(e){return W(qJ(e),`tmp`)}function Omt(e){let t=Dmt(e);return XU(t,{recursive:!0}),W(t,`upload-${zc()}`)}function kmt(e,t,n){let r=Ws(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{nW(e,r);try{eW(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{eW(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new U4(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new U4(`urn:ok:error:storage-readonly`,t):new U4(`urn:ok:error:storage-error`,t)}}try{eW(e)}catch{}throw new U4(`urn:ok:error:collision-exhaustion`)}function Amt(e,{ageMs:t=864e5}={}){let n=Dmt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=mc(n)}catch(e){return q4.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(yc(t).mtimeMs>=a)continue;eW(t),r.deleted++}catch(e){q4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&q4.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function jmt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function Mmt(e){let t=cG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function Nmt(e,t){return new Promise((n,r)=>{let i;try{i=Qct(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new U4(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{bc(e)}catch{}})}if(d?.destroy(),u)try{bc(u)}catch{}r(t instanceof U4?t:new U4(e,t))}},h=G4;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Omt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Emt;d=oc(g),Wc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function Pmt(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:x,_performDocumentToFileRename:S,_performManagedRenameForDocs:C,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof DK}return H2(FK(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(BH(t)){let e=UH(t);for(let t of ae){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${Ys}`)||G(r)&&KH(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${Ys}`)&&G(r)&&KH(e,Ws(t));return}for(let e of ae){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${Ys}`))&&G(r)){KH(t,e);return}}}function O(e){if(Ws(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=mc(a,{withFileTypes:!0})}catch(t){let n=cG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>HH(e,va));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(mre,async(e,n,a)=>{try{let e=FQ(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!BH(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=UH(s);if(_U(d)||vU(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=FK(u,c,r);if(H2(s)||H2(p)||rn(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!wt.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${sn}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=L4(c,t),i=Gi(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=tn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=ymt(l,{date:Goe(),user:u}),_=i.scope}let v=UH(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:c$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Lne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),A=Z(_te,async(e,t,n)=>{try{if(FQ(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(H2(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Ate,{path:e},{handler:`create-folder`})}catch(e){if(PK(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),j=Z(xe,async(e,n,r)=>{try{let e=FQ(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?UH(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(H2(c)||E(c)||a===`file`&&(_U(u)||vU(u))||a===`folder`&&jmt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:$J(n,new QJ({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)c$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,Un,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof V4){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=Mmt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),M=Z(Oie,async(e,n,o)=>{try{let e=FQ(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(_U(u)||_U(d)||vU(u)||vU(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(H2(u)||H2(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&BH(u)&&BH(d)?`file`:l;if(f===`asset`){let t;try{t=BH(u)&&!BH(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let w=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of w){let t=s.findByDocName(e);if(t!==void 0){$J(n,new QJ({file:t.file}),`rename-path`,t);return}}if(a){let e=BH(u)?Ws(u):qH(u);if(f===`file`?a.isExcluded(BH(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await C(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof J9e){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let A,j=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);j.length>0&&(A=y(e,`Renamed ${u} → ${d}`,j.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:ove(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...A?{summary:A}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),N=Z(Lte,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&BH(o)?`file`:e;if(c===`file`&&D(t,o),H2(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):$J(n,new QJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Mee,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),P=Z(bte,async(e,n,r)=>FU(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":zU(r.path),"ok.cleanup.path.role":BU(r.path)}},async()=>{try{if(FQ(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&BH(a)?`file`:e,s=UH(a);o===`file`&&D(t,a);let c=o===`folder`&&jmt(a);if(o===`file`&&(_U(s)||vU(s))||c||H2(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Vre,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function ee(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await Nmt(e,n??t)}catch(e){if(e instanceof U4){X(i,W4(e.reason),e.reason,K4(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{bc(s)}catch{}},h=i$(w,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(H2(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,Cne,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:ZK(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:W4(x.reason),err:x.cause},`[upload] write failed`),X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return XQ({"/api/create-page":k,"/api/create-folder":A,"/api/duplicate-path":j,"/api/rename-path":M,"/api/delete-path":N,"/api/trash/cleanup":P,"/api/upload":ee},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Fmt(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||Gs(e)}function J4(e,t){if(typeof e!=`string`||!Gs(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:Fmt(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function Y4(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const X4=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Imt=`Canonical ids: ${Yn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,Z4=R().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Lmt="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",Rmt=R().length(40).regex(/^[0-9a-f]+$/i).describe(Lmt),Q4=R().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),$4=R().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),zmt=R().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),e3=L({value:R(),truncatedFrom:Ia().optional(),hint:R().optional()}).describe(`Normalized change-note summary, when one was recorded.`),t3=To(z(R(),B())),Bmt=z(R(),B()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Vmt=To(_re).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),Hmt=Aa.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function Umt(e,t){for(let n of ae){let r=J4(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Wmt={summary:e3.optional(),warnings:To(Qa).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:Vmt,brokenLinkSuppression:Hmt,templateHint:To(L({name:R(),description:R().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function Gmt(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function n3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function r3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${n3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Kmt=R().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function i3(e){return{text:Kmt,...e}}function a3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function o3(){return`Error: Hocuspocus server is not running. Start it with \`${$e()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function qmt(e,t){return typeof e==`function`?await e(t):e}async function Jmt(e,t){return typeof e==`function`?await e(t):e}async function s3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await Jmt(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function c3(e,t,n,r){let i=await l3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(o3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function l3(e,t,n,r){let i=await s3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await qmt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function u3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function d3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=la(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function f3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function p3(e,t){return t?{url:e,local:t}:e}function m3(e){return e instanceof Error&&e.name===`TimeoutError`}function h3(e,t){let n=e instanceof Error?e.message:String(e);if(!m3(e))return`${gie} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Jee} ${n}.${r}`}async function Ymt(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:h3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=f3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function g3(e,t){if(typeof e!=`string`){let n=await Ymt(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(m3(e))return{ok:!1,httpStatus:n.status,error:h3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...f3(n,r),httpStatus:n.status}}async function _3(e,t,n){let r=await g3(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function v3(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await Ymt(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e)}}let o;try{o=await a.json()}catch(e){if(m3(e))return{ok:!1,error:h3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return f3(a,o)}function y3(e,t,n){return v3(`POST`,e,t,n)}function b3(e,t,n){return v3(`PUT`,e,t,n)}function x3(e,t){return v3(`DELETE`,e,t)}function Xmt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function S3(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[Vne]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function Zmt(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const C3=Zmt(`the server`);function Qmt(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const w3=Qmt(`the server`),T3="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",$mt="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",eht=/^(?:source(?: family)?|validator) "/;function tht(e){let t=[],n=[];for(let r of e)(eht.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function E3(e,t,n=0){let r=t.filter(e=>!Mn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function nht(e,t,n,r){if(t===0&&n.some(Mn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function D3(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function O3(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function rht(e,t){let n=cht(e,t,`frontmatter.yml`);if(MK(V(n)).kind===`symlink`)return A3(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=MK(n);if(r.kind===`symlink`)return A3(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return A3(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{jK(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return A3(PK(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=sht(n);return i==null?{}:iht(i)}function iht(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const aht=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],k3=new Set;function A3(e,t,n){let r=`${e}:${t}`;k3.has(r)||(k3.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function oht(e){for(let t of aht)k3.delete(`${t}:${e}`)}function sht(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,rl.parse)(t)}catch(t){return A3(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(oht(e),n)}function cht(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function lht(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function uht(e){try{return yc(W(e,`.git`)).isDirectory()}catch{return!1}}function dht(e){return tM({baseDir:W(e),timeout:{block:5e3}})}async function fht(e,t,n=5){if(!uht(e))return{commits:[],source:`git-absent`};let r=dht(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Ut([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
1129
+ `)}function D(){T=null}C?.(D);function O(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let k=Z(x,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=YH(a(s));if(_U(c)||vU(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,so,{docName:c,content:u.getText(`source`).toString(),lifecycle:O(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,so,{docName:c,content:t,lifecycle:O(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),A=Z(x,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&mmt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=eq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=w.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;w.set(e,c),a.finally(()=>{w.get(e)===c&&w.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),w.get(e)===a&&w.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,ue,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let c=l(),x=[...y()],C=b?.()??new Map,D=S?.()??new Map,O=[];for(let[e,t]of C)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=E(c),t=u?.();(!T||T.signature!==e||T.generation!==t||T.assets.some(e=>p?.isPathIgnored(e.path)))&&(T={signature:e,generation:t,assets:pmt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=T?.assets??[]}catch(e){T=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let A=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(A.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of x){if(t.kind===`markdown`){let n=qH(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of lX(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of lX(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=C.get(n),a=t?uX(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of C)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:uX(r,t.canonicalPath,e)})});for(let[e,t]of x){let{resolved:i,members:a}=lX(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:qH(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,ue,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),j=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,zne,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),M={"/api/document":k,"/api/documents":A,"/api/pages":Z(x,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=qH(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=JY(i,t),o=uet(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Jte,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":j};return{paths:Object.keys(M),table:{resolve(e){let t=M[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:D}}const gmt=[`date`,`user`],_mt=/\{\{([^{}\n]+?)\}\}/g;function vmt(e){let t=[];for(let n of e.matchAll(_mt)){let e=(n[1]??``).trim();bmt(e)||t.push({token:e,offset:n.index??0})}return t}function ymt(e,t){return e.replace(_mt,(e,n)=>{let r=n.trim();return bmt(r)?t[r]:e})}function bmt(e){return gmt.includes(e)}function L4(e,t,n={}){let r=Cmt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;z4(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)z4(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&z4(e,``,`inherited`,a,o,s),o}async function xmt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=R4){a=!0,q(`templates`).warn({projectDir:e,cap:R4,queueDepth:o.length},`project scan hit the ${R4}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}z4(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Mc(s,{withFileTypes:!0})}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Smt.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Fc(n)).isDirectory()}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(n)){B4.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?Js.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const R4=2e3,Smt=new Set([`node_modules`,`dist`,`build`]);function z4(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(MK(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),B4.has(o)||(B4.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=cc(s)}catch(e){let n=cG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),B4.has(s)||(B4.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=mc(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=yc(c)}catch{continue}if(!l.isFile())continue;try{jK(c,s),jK(c,e)}catch(e){if(e instanceof EK){B4.has(c)||(B4.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(cG(e)!==`ENOENT`&&!B4.has(c)){B4.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=wmt(c),d={name:o,path:t?Js.join(t,`.ok`,`templates`,a):Js.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Cmt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const B4=new Set;function wmt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(cG(t)!==`ENOENT`&&!B4.has(e)){B4.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=ct(t);typeof n.title!=`string`&&!B4.has(e)&&(B4.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var V4=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const H4=q(`file-ops`);function Tmt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)_U(r)||vU(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;XU(V(n),{recursive:!0});try{JU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),hX(n,dG(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(XU(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=yc(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(WG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?eW(s):(iW(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&yc(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=yc(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(WG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=Ws(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(_U(n)||vU(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{XU(s,{recursive:!0}),JU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{aW(s)}catch(e){let t=cG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&H4.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{KH(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),hX(r,dG(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{iW(r,{force:!0})}catch(e){H4.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw ZH(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{QU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=Ws(n.fullPath);KH(UH(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),hX(n.fullPath,dG(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){H4.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&ZH(UH(t.docName))}e.removeFolderIndexEntries(l);try{iW(u,{recursive:!0,force:!0})}catch(e){H4.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var U4=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function W4(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return pne(e)}}function G4(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function K4(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return pne(e)}}const q4=q(`upload-streaming`);var Emt=class extends Sae{hash=Rc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Dmt(e){return W(qJ(e),`tmp`)}function Omt(e){let t=Dmt(e);return XU(t,{recursive:!0}),W(t,`upload-${zc()}`)}function kmt(e,t,n){let r=Ws(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{nW(e,r);try{eW(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{eW(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new U4(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new U4(`urn:ok:error:storage-readonly`,t):new U4(`urn:ok:error:storage-error`,t)}}try{eW(e)}catch{}throw new U4(`urn:ok:error:collision-exhaustion`)}function Amt(e,{ageMs:t=864e5}={}){let n=Dmt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=mc(n)}catch(e){return q4.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(yc(t).mtimeMs>=a)continue;eW(t),r.deleted++}catch(e){q4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&q4.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function jmt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function Mmt(e){let t=cG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function Nmt(e,t){return new Promise((n,r)=>{let i;try{i=Qct(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new U4(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{bc(e)}catch{}})}if(d?.destroy(),u)try{bc(u)}catch{}r(t instanceof U4?t:new U4(e,t))}},h=G4;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Omt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Emt;d=oc(g),Wc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function Pmt(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:x,_performDocumentToFileRename:S,_performManagedRenameForDocs:C,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof DK}return H2(FK(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(BH(t)){let e=UH(t);for(let t of ae){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${Ys}`)||G(r)&&KH(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${Ys}`)&&G(r)&&KH(e,Ws(t));return}for(let e of ae){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${Ys}`))&&G(r)){KH(t,e);return}}}function O(e){if(Ws(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=mc(a,{withFileTypes:!0})}catch(t){let n=cG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>HH(e,va));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(mre,async(e,n,a)=>{try{let e=FQ(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!BH(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=UH(s);if(_U(d)||vU(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=FK(u,c,r);if(H2(s)||H2(p)||rn(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!wt.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${sn}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=L4(c,t),i=Gi(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=tn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=ymt(l,{date:Goe(),user:u}),_=i.scope}let v=UH(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:c$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Lne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),A=Z(_te,async(e,t,n)=>{try{if(FQ(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(H2(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Ate,{path:e},{handler:`create-folder`})}catch(e){if(PK(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),j=Z(xe,async(e,n,r)=>{try{let e=FQ(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?UH(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(H2(c)||E(c)||a===`file`&&(_U(u)||vU(u))||a===`folder`&&jmt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:$J(n,new QJ({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)c$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,Un,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof V4){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=Mmt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),M=Z(Oie,async(e,n,o)=>{try{let e=FQ(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(_U(u)||_U(d)||vU(u)||vU(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(H2(u)||H2(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&BH(u)&&BH(d)?`file`:l;if(f===`asset`){let t;try{t=BH(u)&&!BH(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let w=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of w){let t=s.findByDocName(e);if(t!==void 0){$J(n,new QJ({file:t.file}),`rename-path`,t);return}}if(a){let e=BH(u)?Ws(u):qH(u);if(f===`file`?a.isExcluded(BH(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await C(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof J9e){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let A,j=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);j.length>0&&(A=y(e,`Renamed ${u} → ${d}`,j.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:ove(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...A?{summary:A}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),N=Z(Lte,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&BH(o)?`file`:e;if(c===`file`&&D(t,o),H2(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):$J(n,new QJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Mee,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),P=Z(bte,async(e,n,r)=>FU(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":zU(r.path),"ok.cleanup.path.role":BU(r.path)}},async()=>{try{if(FQ(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&BH(a)?`file`:e,s=UH(a);o===`file`&&D(t,a);let c=o===`folder`&&jmt(a);if(o===`file`&&(_U(s)||vU(s))||c||H2(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Vre,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function ee(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await Nmt(e,n??t)}catch(e){if(e instanceof U4){X(i,W4(e.reason),e.reason,K4(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{bc(s)}catch{}},h=i$(w,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(H2(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,Cne,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:ZK(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:W4(x.reason),err:x.cause},`[upload] write failed`),X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return XQ({"/api/create-page":k,"/api/create-folder":A,"/api/duplicate-path":j,"/api/rename-path":M,"/api/delete-path":N,"/api/trash/cleanup":P,"/api/upload":ee},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Fmt(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||Gs(e)}function J4(e,t){if(typeof e!=`string`||!Gs(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:Fmt(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i.split(Ys).join(`/`)}}function Y4(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const X4=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Imt=`Canonical ids: ${Yn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,Z4=R().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Lmt="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",Rmt=R().length(40).regex(/^[0-9a-f]+$/i).describe(Lmt),Q4=R().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),$4=R().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),zmt=R().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),e3=L({value:R(),truncatedFrom:Ia().optional(),hint:R().optional()}).describe(`Normalized change-note summary, when one was recorded.`),t3=To(z(R(),B())),Bmt=z(R(),B()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Vmt=To(_re).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),Hmt=Aa.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function Umt(e,t){for(let n of ae){let r=J4(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Wmt={summary:e3.optional(),warnings:To(Qa).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:Vmt,brokenLinkSuppression:Hmt,templateHint:To(L({name:R(),description:R().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function Gmt(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function n3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function r3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${n3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Kmt=R().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function i3(e){return{text:Kmt,...e}}function a3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function o3(){return`Error: Hocuspocus server is not running. Start it with \`${$e()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function qmt(e,t){return typeof e==`function`?await e(t):e}async function Jmt(e,t){return typeof e==`function`?await e(t):e}async function s3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await Jmt(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function c3(e,t,n,r){let i=await l3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(o3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function l3(e,t,n,r){let i=await s3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await qmt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function u3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function d3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=la(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function f3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function p3(e,t){return t?{url:e,local:t}:e}function m3(e){return e instanceof Error&&e.name===`TimeoutError`}function h3(e,t){let n=e instanceof Error?e.message:String(e);if(!m3(e))return`${gie} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Jee} ${n}.${r}`}async function Ymt(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:h3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=f3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function g3(e,t){if(typeof e!=`string`){let n=await Ymt(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(m3(e))return{ok:!1,httpStatus:n.status,error:h3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...f3(n,r),httpStatus:n.status}}async function _3(e,t,n){let r=await g3(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function v3(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await Ymt(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e)}}let o;try{o=await a.json()}catch(e){if(m3(e))return{ok:!1,error:h3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return f3(a,o)}function y3(e,t,n){return v3(`POST`,e,t,n)}function b3(e,t,n){return v3(`PUT`,e,t,n)}function x3(e,t){return v3(`DELETE`,e,t)}function Xmt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function S3(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[Vne]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function Zmt(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const C3=Zmt(`the server`);function Qmt(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const w3=Qmt(`the server`),T3="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",$mt="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",eht=/^(?:source(?: family)?|validator) "/;function tht(e){let t=[],n=[];for(let r of e)(eht.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function E3(e,t,n=0){let r=t.filter(e=>!Mn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function nht(e,t,n,r){if(t===0&&n.some(Mn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function D3(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function O3(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function rht(e,t){let n=cht(e,t,`frontmatter.yml`);if(MK(V(n)).kind===`symlink`)return A3(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=MK(n);if(r.kind===`symlink`)return A3(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return A3(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{jK(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return A3(PK(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=sht(n);return i==null?{}:iht(i)}function iht(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const aht=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],k3=new Set;function A3(e,t,n){let r=`${e}:${t}`;k3.has(r)||(k3.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function oht(e){for(let t of aht)k3.delete(`${t}:${e}`)}function sht(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,rl.parse)(t)}catch(t){return A3(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(oht(e),n)}function cht(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function lht(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function uht(e){try{return yc(W(e,`.git`)).isDirectory()}catch{return!1}}function dht(e){return tM({baseDir:W(e),timeout:{block:5e3}})}async function fht(e,t,n=5){if(!uht(e))return{commits:[],source:`git-absent`};let r=dht(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Ut([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
1130
1130
  `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const pht=5e3;async function mht(e){try{let t=(await tM({baseDir:e,timeout:{block:pht}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function hht(e,t){return tM({baseDir:t,timeout:{block:pht}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function ght(e,t){let n=X_e(t);return e.startsWith(n)?e.slice(n.length):e}async function _ht(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Ut([n]))}catch{return[]}let o=ght(t,r),s=Qx(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:Zx(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function vht(e,t,n,r,i){let a;try{a=await N8e(e,t)}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,err:e},`[shadow-log] chain anchors unresolved; per-path history degraded to empty`),[]}if(a.length===0)return[];let o=``;try{o=await e.raw(`log`,...a,`-${Math.max(r*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Ut([n]))}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,anchorCount:a.length,err:e},`[shadow-log] ancestry walk failed; per-path history degraded to empty`),[]}let s=[];for(let e of o.split(``)){if(s.length>=r)break;let n=e.trimStart();if(!n)continue;let[a=``,o=``,c=``,l=``,u=``]=n.split(`\0`),d=a.trim();if(d.length!==40||i.has(d)||l.startsWith(`checkpoint:`)||l.startsWith(`park:`)||l.startsWith(`import:`)||l.startsWith(`upstream:`))continue;let f=eve(u),p=f?.writer_id??``,m=Qx(p);i.add(d),s.push({hash:d,date:o,writerName:f?.display_name??c,message:l,contributors:Zx(u),writerId:p,isAgent:m.isAgent,writerClassification:m.classification,branch:t})}return s}async function yht(e,t,n=5){let r=Y_e(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await mht(e);if(!i)return{commits:[],source:`shadow-repo`};let a=hht(r,W(e)),o=``;try{o=await a.raw(`for-each-ref`,X_e(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
1131
1131
  `).map(e=>e.trim()).filter(Boolean),c=(s.length===0?[]:await Promise.all(s.map(e=>_ht(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n);if(c.length<n){let e=new Set(c.map(e=>e.hash)),r=await vht(a,i,t,n-c.length,e);r.length>0&&(c=[...c,...r].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n))}return{commits:c,source:`shadow-repo`}}const bht=1e3,xht=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Sht=/\.(md|mdx)$/i;function Cht(e,t){if(e===null||t===null)return null;let n=e,r=t;return n===0&&r===0?`orphan`:n>=5?`hub`:n>0&&r>0?`connector`:`leaf`}function wht(e,t){let n=e.frontmatterSchemas;if(!n||n.length===0)return[];let r=e.contentDir??e.projectDir,i=U(r,W(e.projectDir,t));if(i.startsWith(`..`))return[];let a=[];for(let e of n)e.enabled!==!1&&qr(e.appliesTo).matches(i)&&(a.includes(e.file)||a.push(e.file));return a}function Tht(e,t){return wht(e,t===``?`⁂`:`${t}/⁂`)}function j3(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const Eht=new Set;async function Dht(e){try{let t=await jc(e,`utf-8`);return{frontmatter:D(t)??{},firstHeading:cet(ka(t).body)}}catch(t){if(t?.code!==`ENOENT`&&!Eht.has(e)){Eht.add(e);let n=t instanceof Error?t.message:String(t);q(`enrichment`).warn({path:e,reason:n},`failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${n}`)}return null}}async function Oht(e,t){if(!e)return null;let n=await g3(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function kht(e,t){if(!e)return null;let n=await g3(e,`/api/comments?doc=${encodeURIComponent(t)}`);return n.ok?Aht(n.threads):null}function Aht(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=e.state;if(r!==`anchored`&&r!==`orphaned`||typeof e.threadId!=`string`||e.threadId===``)continue;let i=(typeof e.anchor==`object`&&e.anchor!==null?e.anchor:{}).exact;t.push({threadId:e.threadId,body:typeof e.latestComment==`string`?e.latestComment:``,quote:typeof i==`string`?i:``,state:r,queued:e.queued===!0})}return t}async function jht(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await g3(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function Mht(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));return Pht(await Promise.all(r.map(async t=>{let n=await g3(e,`/api/comment-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})))}async function Nht(e,t){if(!e)return null;let n=await g3(e,`/api/comment-counts?prefix=${encodeURIComponent(t)}`);return n.ok?Pht([n.counts??{}]):null}function Pht(e){let t=new Map,n=!1;for(let r of e)if(r){n=!0;for(let[e,n]of Object.entries(r))typeof n==`number`&&Number.isFinite(n)&&t.set(e,n)}return n?t:null}async function Fht(e,t){if(!e)return null;let n=await g3(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function Iht(e,t){let n=e?.title;if(typeof n!=`string`)return t;let r=n.trim();return r===``?t:r}function Lht(e,t){let n=e??{};return{title:Iht(n,t),description:typeof n.description==`string`?n.description:void 0,tags:Array.isArray(n.tags)?n.tags.filter(e=>typeof e==`string`):[],frontmatter:n}}async function Rht(e,t,n={}){let r=J4(t.projectDir,e);if(!r.ok)throw Error(`enrichPath: ${r.reason}`);let i=r.rel,a=r.abs,o=t.historyDepth??5,s=n.includeRichFields===!0,c=Dht(a),l=wht(t,i),u=l.length>0?{schemas_applicable:l}:{};if(!s){let e=await c,t=Lht(e?.frontmatter??null,e?.firstHeading);return{path:i,title:t.title,description:t.description,tags:t.tags,frontmatter:t.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null,...u}}let[d,f,p,m,h,g]=await Promise.all([c,Oht(t.serverUrl,j3(i)).catch(()=>null),Fht(t.serverUrl,j3(i)).catch(()=>null),yht(t.projectDir,i,o).catch(()=>({commits:[],source:`shadow-repo`})),fht(t.projectDir,i,o).catch(()=>({commits:[],source:`git`})),kht(t.serverUrl,j3(i)).catch(()=>null)]),_=Lht(d?.frontmatter??null,d?.firstHeading);return{path:i,title:_.title,description:_.description,tags:_.tags,frontmatter:_.frontmatter,backlinkCount:f?.length??null,backlinks:f,forwardLinkCount:p?.length??null,forwardLinks:p,history:m.commits,historySource:m.source,projectHistory:h.commits,projectHistorySource:h.source,graphRole:Cht(f?.length??null,p?.length??null),commentCount:g?.length??null,comments:g,...u}}async function zht(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=bht){n.truncated=!0;break}let a;try{a=await Mc(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=bht){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(xht.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Sht.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Fc(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:U(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function Bht(e,t,n={}){let r=J4(t.projectDir,e);if(!r.ok)throw Error(`enrichDirectory: ${r.reason}`);let i=r.rel,a=r.abs,o=await zht(a,t.projectDir),s;if(o.mostRecent){let e=await Dht(o.mostRecent.absPath);s={path:o.mostRecent.relPath,title:Iht(e?.frontmatter,e?.firstHeading)??Hs(o.mostRecent.relPath),updatedAt:new Date(o.mostRecent.mtimeMs).toISOString()}}let c={path:i,type:`directory`,directMdCount:o.directMdCount,recursiveMdCount:o.recursiveMdCount,childDirCount:o.childDirCount,mostRecentMd:s,truncated:o.truncated},l=rht(t.projectDir,i);l.title!==void 0&&(c.title=l.title),l.description!==void 0&&(c.description=l.description),(l.tags?.length??0)>0&&(c.tags=l.tags);let u=L4(t.projectDir,i,{onRefused:n.onTemplateRefused});u.length>0&&(c.templates_available=u);let d=Tht(t,i);d.length>0&&(c.schemas_applicable=d);let f=await Nht(t.serverUrl,i).catch(()=>null);if(f&&f.size>0){let e=0;for(let t of f.values())e+=t;c.commentCount=e,c.commentedDocs=[...f].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,Vht).map(([e,t])=>({docName:e,count:t}))}return c}const Vht=5;async function Hht(e,t,n){let r=await Bht(e,n);if(t<=1)return r;let i=r.path,a=W(n.projectDir,i),o;try{o=await Mc(a,{withFileTypes:!0})}catch{return r}let s=[];for(let e of o){if(!e.isDirectory()||Uht.has(e.name)||e.name.startsWith(`.`))continue;let r=await Hht(i?`${i}/${e.name}`:e.name,t-1,n);s.push(r)}return s.length>0&&(r.subfolders=s),r}const Uht=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function M3(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(r!==void 0){if(Wht(r)){delete n[e];continue}n[e]=r}return n}function Wht(e){return iie(e)}function Ght(e){if(!Gs(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=W(e.anchorDir),n=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(n.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let r=n===``?t:W(t,n);if(r!==t&&!r.startsWith(t+Ys))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${r}`}};let i=H(r,`.ok`),a=H(i,`frontmatter.yml`);if(MK(a).kind===`symlink`)return{ok:!1,error:{code:`SYMLINK_REFUSED`,message:`Refusing to operate on "${n===``?``:`${n}/`}.ok/frontmatter.yml": it is a symlink. Replace the symlink with a real file or directory and retry.`}};try{let n=Kht(a),r=Object.keys(e.patch).length===0?{}:M3(n,e.patch);if(Object.keys(r).length===0)return G(a)?(bc(a),qht(i),{ok:!0,path:N3(t,a),action:`deleted`}):{ok:!0,path:N3(t,a),action:`noop`};lc(i,{recursive:!0});let o=(0,rl.stringify)(r),s=lS(a);return xc(s,o,`utf-8`),gc(s,a),{ok:!0,path:N3(t,a),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${n||`.`}": ${e.message}`}}}}function Kht(e){if(!G(e))return{};let t=K(e,`utf-8`),n=(0,rl.parse)(t);return typeof n!=`object`||!n||Array.isArray(n)?{}:{...n}}function qht(e){if(!G(e))return;let t;try{t=mc(e)}catch{return}if(t.length===0)try{vc(e)}catch{}}function N3(e,t){return t.startsWith(e+Ys)?t.slice(e.length+1).split(Ys).join(`/`):t}const Jht=wt;function P3(e){if(!Jht.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${sn} (got: ${JSON.stringify(e.name)}).`}};let t=$ht(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let n=egt(e.body);if(!n.ok)return{ok:!1,error:n.error};let r=tgt(e.body);if(!r.ok)return{ok:!1,error:r.error};let i={};e.frontmatter.title!==void 0&&(i.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(i.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(i.tags=e.frontmatter.tags);let a=ge(i,e.body),o=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&o.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:a,warnings:o}}function Yht(e){let t=F3(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let n=P3({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i}=n,{templatesDir:a,filePath:o}=I3(e.projectDir,t.folderRel,e.name);try{lc(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${L3(e.projectDir,a)}: ${t.message}`}}}let s=!G(o),c=lS(o);try{xc(c,r,`utf-8`),gc(c,o)}catch(t){try{bc(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${L3(e.projectDir,o)}: ${t.message}`}}}return{ok:!0,path:L3(e.projectDir,o),created:s,warnings:i}}function Xht(e){let t=F3(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:n,okDir:r,filePath:i}=I3(e.projectDir,t.folderRel,e.name),a=G(i);if(a)try{bc(i)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${L3(e.projectDir,i)}: ${t.message}`}}}return{ok:!0,path:L3(e.projectDir,i),existed:a,cleanedEmpty:Zht(n,r)}}function Zht(e,t){let n=!1,r=!1;if(G(e)&&ngt(e))try{vc(e),n=!0}catch{}if(G(t)&&ngt(t))try{vc(t),r=!0}catch{}return{templatesDir:n,okDir:r}}async function Qht(e){let t=F3(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let n=F3(e.projectDir,e.toFolder,e.toName);if(!n.ok)return{ok:!1,error:n.error};let r=I3(e.projectDir,t.folderRel,e.fromName),i=I3(e.projectDir,n.folderRel,e.toName);if(r.filePath===i.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!G(r.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${L3(e.projectDir,r.filePath)}.`}};if(G(i.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${L3(e.projectDir,i.filePath)}.`}};try{lc(i.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${L3(e.projectDir,i.templatesDir)}: ${t.message}`}}}let a;try{a=await e.relocate(r.filePath,i.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let o=Zht(r.templatesDir,r.okDir);return{ok:!0,fromPath:L3(e.projectDir,r.filePath),toPath:L3(e.projectDir,i.filePath),committed:a,cleanedEmpty:o}}function F3(e,t,n){if(!Gs(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!Jht.test(n))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${sn} (got: ${JSON.stringify(n)}).`}};let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(r.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let i=r?W(e,r):e,a=W(e);return!i.startsWith(a+Ys)&&i!==a?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${i}`}}:{ok:!0,folderRel:r}}function $ht(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function egt(e){let t=vmt(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function I3(e,t,n){let r=t?H(e,t,`.ok`):H(e,`.ok`),i=H(r,`templates`);return{okDir:r,templatesDir:i,filePath:H(i,`${n}.md`)}}function L3(e,t){let n=t.startsWith(e+Ys)?t.slice(e.length+1):t;return Ks(n).split(Ys).join(`/`)}function tgt(e){let{frontmatter:t}=ka(e);if(t===``)return{ok:!0};let n=ha(t);return RegExp(`^template:`,`m`).test(n)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${mie}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function ngt(e){try{return mc(e).length===0}catch{return!1}}const rgt={BAD_CONTENT_DIR:{status:400,urn:`urn:ok:error:invalid-request`},PATH_ESCAPE:{status:400,urn:`urn:ok:error:path-escape`},SYMLINK_REFUSED:{status:400,urn:`urn:ok:error:symlink-refused`},WRITE_ERROR:{status:500,urn:`urn:ok:error:internal-server-error`}};function igt(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,hocuspocus:a,sessionManager:o,getPrincipal:s,signalChannel:c,conflicts:l,recentlyRemovedDocs:u,isSafeDocName:d,resolveAlias:f,resolveContentEntryPath:p,validateFolderRel:m,extractAgentIdentity:h,extractActorIdentityFromQuery:g,okArtifactKey:_,attributeOkArtifactWrite:v,scheduleOkArtifactFlush:y,flushDiskAndDetectOutcome:b,markAgentWriteStore:S,respondPersistenceFailure:C,respondStaleExternalWrite:w,registerWrittenDocInFileIndex:T,captureAndCloseDocuments:E,captureNamespaceMove:D,renameTrackedPathInGit:O,renamePathOnDisk:k,splitContentPath:A,mutateFileIndex:j}=e;function N(e,t,n=`template`){return!e||!wt.test(e)?(X(t,400,`urn:ok:error:invalid-request`,`Invalid name: must use ${sn}, without the \`.md\` extension.`,{handler:n}),!1):!0}function P(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:W(e,i);if(a!==e&&!a.startsWith(`${e}${Ys}`))continue;let o=W(a,`.ok`),s=MK(o);if(s.kind===`symlink`)return{kind:`refused`,folder:i};if(s.kind===`unverifiable`&&s.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:s.code};let c=W(o,`templates`),l=MK(c);if(l.kind===`symlink`)return{kind:`refused`,folder:i};if(l.kind===`unverifiable`&&l.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:l.code};let u=W(c,`${n}.md`);if(G(u))return{kind:`found`,abs:u,folder:i,scope:t===r.length?`local`:`inherited`}}return{kind:`absent`}}function ee(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function te(e,t){return Qe(e,t)}let F=new Set;function ne(e,t){let n=W(e,`${t}.md`);return F.has(n)||G(n)}let re=D0({GET:Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=m(n.searchParams.get(`path`)??``,t,`path`,`folder-config-get`,`ok`);if(!r)return;let a=W(r.resolvedContentDir,r.folderRel,`.ok`),o=W(a,`frontmatter.yml`),s=[],c=[],l=(e,t)=>{s.push(t),c.push(e)},u=await Bht(r.folderRel,{projectDir:r.resolvedContentDir},{onTemplateRefused:e=>{let t=`${e.folder||`.`}/${e.component}`,n=W(r.resolvedContentDir,e.folder,e.component);switch(e.kind){case`symlink`:l(`templates-symlink-refused`,`${t} is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.`),i.warn({path:n,folder:r.folderRel||`.`},`[folder-config:get] ${t} is a symlink — templates_available skips it.`);break;case`unverifiable`:l(`templates-unverifiable`,`${t} could not be inspected (${e.code??`unknown errno`}) — its templates are not enumerated. The errno may come from ${e.folder||`.`}/.ok itself; check its permissions.`),i.warn({path:n,folder:r.folderRel||`.`,code:e.code},`[folder-config:get] cannot lstat ${t} (${e.code??`unknown errno`}) — templates_available skips it.`);break;default:throw Error(`Unhandled template refusal kind in handleFolderConfigGet: ${String(e.kind)}`)}}}),d=null,f=MK(o);if(f.kind===`symlink`)l(`symlink-refused`,`${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`),i.warn({path:o,folder:r.folderRel||`.`},`[folder-config:get] ${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it.`);else if(f.kind===`unverifiable`)l(`unverifiable`,`${r.folderRel||`.`}/.ok/frontmatter.yml could not be inspected (${f.code??`unknown errno`}) — folder properties skipped.`),i.warn({path:o,code:f.code},`[folder-config:get] cannot lstat ${o} (${f.code??`unknown errno`}) — frontmatter_local skipped.`);else if(G(o))try{let e=await jc(o,`utf-8`),t=(0,rl.parse)(e);d=t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e instanceof Error?e.message:String(e);l(`malformed-yaml`,`${r.folderRel||`.`}/.ok/frontmatter.yml has malformed YAML.`),i.warn({path:o,reason:t},`[folder-config:get] malformed YAML in ${o}: ${t}`),d=null}Q(t,200,une,{folder:u,frontmatter_local:d,...c.length>0?{warnings:s,warningCodes:c}:{}},{handler:`folder-config-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(bn,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=FQ(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let i=m(n.path,t,`path`,`folder-config-put`,`ok`);if(!i)return;let a=[];if(n.frontmatter!==void 0){let r=Ght({anchorDir:i.resolvedContentDir,folderRel:i.folderRel,patch:n.frontmatter});if(!r.ok){let{status:e,urn:n}=rgt[r.error.code];X(t,e,n,e===500?`Failed to write folder config.`:r.error.message,{handler:`folder-config-put`,detail:r.error.code,cause:Error(r.error.message)});return}a.push({path:r.path,action:r.action}),r.action!==`noop`&&(v(e,_(`folder-frontmatter`,i.folderRel),`folder-frontmatter-${r.action===`deleted`?`delete`:`edit`}: ${r.path}`),y(`folder-config-put`))}Q(t,200,jn,{applied:a},{handler:`folder-config-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function ie(e,t,n){let r=l.findByDocName(e);return r!==void 0&&($J(n,new QJ({file:r.file}),t,r),!0)}let ae=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!N(r,t,`template-get`))return;let i=m(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`,`ok-and-templates`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=P(o,a,r);if(s.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${s.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:s.folder||`.`});return}if(s.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${s.folder||`.`}/.ok" (${s.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-get`,detail:s.code??`unknown-errno`});return}if(s.kind===`absent`){X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s;if(MK(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" at "${l||`.`}/.ok/templates/${r}.md" is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}try{jK(c,o)}catch(e){if(PK(e)){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" resolves through a symlink outside the content directory — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}throw e}let d=await jc(c,`utf-8`),f=ct(d),p=f.identity,h=f.starterContent,g=U(o,c).split(/[\\/]/).filter(Boolean).join(`/`);Q(t,200,pi,{template:{name:r,folder:l,scope:u,path:g,frontmatter:p,body:h}},{handler:`template-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),oe=Z(qt,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=FQ(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=n.name;if(!N(i,t,`template-put`))return;let a=m(n.folder,t,`folder`,`template-put`,`ok-and-templates`);if(!a)return;let c=W(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`);if(MK(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`${a.folderRel||`.`}/.ok/templates/${i}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-put`,detail:a.folderRel||`.`});return}if(ie(te(a.folderRel,i),`template-put`,t))return;let l=P3({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:ee(n.frontmatter)});if(!l.ok){X(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:l.error.code,cause:Error(l.error.message)});return}let u=!G(c),d=U(a.resolvedContentDir,c).split(/[\\/]/).filter(Boolean).join(`/`),f=te(a.folderRel,i),{agentId:p,agentName:g,colorSeed:x,clientName:E}=h(n),D=await o.getSession(f,p,{displayName:g,colorSeed:x,clientName:E});D.dc.document.transact(()=>{Rq(D.dc.document,l.content,`agent`)},D.origin),S(f);let O=await b(f);if(O?.kind===`failure`&&!IG(O.failure)){C(t,O.failure,`template-put`);return}if(O?.kind===`stale-external-write`){w(t,`template-put`,f);return}T(f,l.content),v(e,_(`template`,a.folderRel,i),`${u?`template-create`:`template-edit`}: ${d}`),y(`template-put`),Q(t,200,Sre,{...LG(void 0,O),path:d,created:u,warnings:l.warnings},{handler:`template-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),se=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!N(r,t,`template-delete`))return;let i=m(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`,`ok-and-templates`);if(!i)return;let a=g(n,s);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ie(te(i.folderRel,r),`template-delete`,t))return;await E([te(i.folderRel,r)],`deleted-upstream`);let o=Xht({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(v(a,_(`template`,i.folderRel,r),`template-delete: ${o.path}`),y(`template-delete`),u?.setDeleted(te(i.folderRel,r))),Q(t,200,M,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});return XQ({"/api/folder-config":re,"/api/template":D0({GET:ae,PUT:oe,POST:Z(tee,async(e,t,r)=>{try{let e=FQ(r,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!N(r.fromName,t,`template-move`)||!N(r.toName,t,`template-move`))return;let a=m(r.fromFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!a)return;let o=m(r.toFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!o||ie(te(a.folderRel,r.fromName),`template-move`,t))return;await E([te(a.folderRel,r.fromName)],`renamed`);let l=D?.(te(o.folderRel,r.toName)),d=await Qht({projectDir:a.resolvedContentDir,fromFolder:a.folderRel,fromName:r.fromName,toFolder:o.folderRel,toName:r.toName,relocate:async(e,t)=>{let r=await O(n,e,t);return r||k(e,t),r}});if(!d.ok){if(d.error.code===`TEMPLATE_NOT_FOUND`){let e=P(a.resolvedContentDir,a.folderRel,r.fromName);if(e.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${e.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-move`,detail:e.folder||`.`});return}if(e.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${e.folder||`.`}/.ok" (${e.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-move`,detail:e.code??`unknown-errno`});return}if(e.kind===`found`&&e.scope===`inherited`){X(t,400,`urn:ok:error:invalid-request`,`Template "${r.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${a.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:d.error.message});return}if(d.error.code===`TEMPLATE_EXISTS`){X(t,409,`urn:ok:error:doc-already-exists`,d.error.message,{handler:`template-move`,detail:d.error.code});return}let e=d.error.code===`WRITE_ERROR`||d.error.code===`MOVE_FAILED`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:d.error.code,cause:Error(d.error.message)});return}l?.(),u?.setDeleted(te(a.folderRel,r.fromName));let f=W(o.resolvedContentDir,d.toPath),p=MK(f).kind===`symlink`;if(v(e,_(`template`,o.folderRel,r.toName),`template-rename: ${d.fromPath} -> ${d.toPath}`,[{from:d.fromPath,to:d.toPath}]),y(`template-move`),c?.(`files`),p){if(i.warn({path:f,folder:o.folderRel||`.`},`[template-move] moved template "${d.toPath}" is a symlink — skipping content read-back and index registration.`),r.body!==void 0||r.frontmatter!==void 0){X(t,400,`urn:ok:error:symlink-refused`,`Template moved to "${d.toPath}", but it is a symlink — refusing to read or rewrite through it. Replace it with a regular file and retry the edit.`,{handler:`template-move`,detail:o.folderRel||`.`});return}Q(t,200,et,{from:d.fromPath,to:d.toPath,committed:d.committed},{handler:`template-move`});return}let h=null;if(r.body!==void 0||r.frontmatter!==void 0){let e;if(typeof r.body==`string`)e=r.body;else try{e=tn(K(f,`utf-8`))}catch{e=null}if(e===null)h={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=Yht({projectDir:o.resolvedContentDir,folder:o.folderRel,name:r.toName,body:e,frontmatter:ee(r.frontmatter)});t.ok||(h=t.error)}}try{T(te(o.folderRel,r.toName),K(f,`utf-8`))}catch{}if(h){let e=h.code===`WRITE_ERROR`||h.code===`READ_FAILED`;X(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${d.toPath}", but updating its content failed.`,{handler:`template-move`,detail:h.code,cause:Error(h.message)});return}Q(t,200,et,{from:d.fromPath,to:d.toPath,committed:d.committed},{handler:`template-move`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:se},{handler:`template`}),"/api/template/import":Z(pt,async(e,n,i)=>{let g;try{if(r){X(n,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=FQ(i,s);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let x=i.sourcePath;if(!d(x)){X(n,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let D=f(x);if(_U(D)||vU(D)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`template-import`});return}let O=p(t,`file`,D);if(!G(O)){X(n,404,`urn:ok:error:doc-not-found`,`Source document not found: ${D}.`,{handler:`template-import`});return}let k=a.documents.get(D);if(i.deleteSource){let e=l.findByDocName(D);if(e!==void 0){$J(n,new QJ({file:e.file}),`template-import`,e);return}}let M=``;if(k)M=k.getText(`source`).toString();else{let e=await a.openDirectConnection(D);try{let t=e.document;if(!t){X(n,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}M=t.getText(`source`).toString()}finally{await e.disconnect()}}let P=i.name;if(!P){let{basename:e}=A(x),t=e.replace(/\.(md|mdx)$/i,``);P=Lee(t).replace(/[^\p{L}\p{M}\p{N}_-]|\p{DI}/gu,`-`).toLowerCase(),P=P.replace(/^[-_]+|[-_]+$/g,``),P||=`imported-template`}if(!N(P,n,`template-import`))return;let ee=m(i.targetFolder,n,`folder`,`template-import`,`ok-and-templates`);if(!ee)return;let re=W(ee.resolvedContentDir,ee.folderRel,`.ok`,`templates`);if(!i.name){let e=P;for(let t=2;ne(re,P);t++)P=`${e}-${t}`}let ae=W(re,`${P}.md`);if(MK(ae).kind===`symlink`){X(n,400,`urn:ok:error:symlink-refused`,`${ee.folderRel||`.`}/.ok/templates/${P}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-import`,detail:ee.folderRel||`.`});return}if(ie(te(ee.folderRel,P),`template-import`,n))return;if(ne(re,P)){X(n,409,`urn:ok:error:doc-already-exists`,`Template "${P}" already exists in "${ee.folderRel||`(root)`}". Choose another name, or edit the existing template instead.`,{handler:`template-import`,detail:`TEMPLATE_EXISTS`});return}F.add(ae),g=ae;let{frontmatter:oe,body:se}=ka(M),ce=ha(oe),le={};try{ce.trim()&&(le=(0,rl.parse)(ce))}catch{}let ue=i.title||le?.title||JY(M,P),de=le?.description||``,fe=Array.isArray(le?.tags)?le.tags:[],pe={...le};delete pe.template,delete pe.title;let me=``;Object.keys(pe).length>0&&(me=`${(0,rl.stringify)(pe).trim()}\n`),me=me?`---\n${me}---\n${se}`:se;let he=P3({name:P,body:me,frontmatter:{title:ue,description:de,tags:fe}});if(!he.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:he.error.code,cause:Error(he.error.message)});return}let ge=!G(ae),_e=U(ee.resolvedContentDir,ae).split(/[\\/]/).filter(Boolean).join(`/`),ve=te(ee.folderRel,P),{agentId:ye,agentName:be,colorSeed:xe,clientName:Se}=h(i),Ce=await o.getSession(ve,ye,{displayName:be,colorSeed:xe,clientName:Se});Ce.dc.document.transact(()=>{Rq(Ce.dc.document,he.content,`agent`)},Ce.origin),S(ve);let we=await b(ve);if(we?.kind===`failure`&&!IG(we.failure)){C(n,we.failure,`template-import`);return}if(we?.kind===`stale-external-write`){w(n,`template-import`,ve);return}T(ve,he.content),v(e,_(`template`,ee.folderRel,P),`template-import: ${_e}`),i.deleteSource&&(await E([D],`deleted-upstream`),u&&u.setDeleted(D),eW(O),j?.({kind:`delete`,path:O,docName:D})),y(`template-import`),c?.(`files`),Q(n,200,ti,{...LG(void 0,we),path:_e,created:ge,warnings:he.warnings},{handler:`template-import`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}finally{g!==void 0&&F.delete(g)}},{handler:`template-import`,method:`POST`})},{mutating:[`/api/folder-config`,`/api/template`,`/api/template/import`]})}function R3(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function agt(e,t){let{git:n}=gK(e,{credentialConfig:[]}),[r,i]=await Promise.allSettled([z8e(n,Gq),Jq(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function ogt(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function sgt(e,t,n,r){let{git:i}=gK(e,{credentialConfig:[]});await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``||i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=agt(e,t).catch(e=>(cgt(e)||q(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${R3(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const z3=`git-branch-info`;function cgt(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const B3=q(`git-checkout`),lgt=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function ugt(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(lgt);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=hc(n)}catch{r=n}return{held:!0,path:r}}const V3=`git-checkout`,dgt=fte;async function fgt(e,t,n){if(n.fastForward&&await pgt(e,t,n.credentialConfig)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r,env:i}=gK(e,{credentialConfig:n.credentialConfig}),a=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!a)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:dgt(e)?`branch-not-found`:`fetch-failed`}}let o;try{o=await SK(r,a?`refs/heads/${t}`:`refs/remotes/origin/${t}`)}catch(e){return B3.warn({branch:t,err:e},`action=checkout-failed branch=${t}`),{ok:!1,reason:`checkout-failed`}}let s=await agt(e,o);if(s.conflicts)return{ok:!1,reason:`dirty-conflict`,files:s.files};try{await wK(r,o,`checkout`,i)}catch(e){return e instanceof CK?(B3.warn({event:`unsafe-incoming-symlinks`,branch:t,target:o,links:e.unsafe.slice(0,50),refusedCount:e.unsafe.length},`action=checkout-refused branch=${t}`),{ok:!1,reason:`unsafe-symlinks`,refusedSymlinkPaths:e.displayPaths()}):(B3.warn({branch:t,target:o,err:e},`action=symlink-check-failed branch=${t}`),{ok:!1,reason:`symlink-check-failed`})}let c=()=>r.raw([`symbolic-ref`,`--quiet`,`HEAD`]).then(e=>e.trim()).catch(()=>``),l=`refs/heads/${t}`,u=await c(),d=!1;try{return a||(await r.raw([`branch`,`--no-track`,t,o]),d=!0,await r.raw([`branch`,`--set-upstream-to=refs/remotes/origin/${t}`,t])),await r.raw([`checkout`,t]),{ok:!0}}catch(e){if(u!==l&&await c()===l)return B3.warn({branch:t,target:o,err:e},`action=checkout-hook-failed branch=${t} error=${R3(e)}`),{ok:!0};d&&await r.raw([`branch`,`-D`,t]).catch(e=>{B3.warn({branch:t,target:o,err:e},`action=checkout-cleanup-failed branch=${t}`)});let n=ugt(e);return n.held?(B3.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(B3.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${R3(e)}`),{ok:!1,reason:`checkout-failed`})}}async function pgt(e,t,n){let{git:r}=gK(e,{timeoutMs:15e3,credentialConfig:n}),i=e=>r.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await r.raw([`fetch`,`origin`,t])}catch(e){return B3.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${R3(e)}`),`unavailable`}let a=await i(`refs/remotes/origin/${t}`);if(!a)return`unavailable`;let o=await i(`refs/heads/${t}`);if(!o||o===a)return`up-to-date`;let s=await r.raw([`merge-base`,o,a]).then(e=>e.trim()).catch(()=>``);if(s===o){try{await r.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return B3.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${R3(e)}`),`unavailable`}return await i(`refs/heads/${t}`)===a?`advanced`:`unavailable`}return s===a?`up-to-date`:`diverged`}const H3=q(`git-worktree-status`);function U3(e){return Ge.includes(e)?e:`M`}function mgt(e,t){let n=[],r=[],i=[];for(let a of e){let e=t(a.path);if(a.x===`?`||a.y===`?`){i.push({path:a.path,code:`?`,syncScoped:e});continue}a.x!==`!`&&a.y!==`!`&&(a.x!==` `&&a.x!==``&&n.push({path:a.path,code:U3(a.x),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}),a.y!==` `&&a.y!==``&&r.push({path:a.path,code:U3(a.y),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}))}let a=n.length>100||r.length>100||i.length>100,o=e=>[...e.filter(e=>e.syncScoped),...e.filter(e=>!e.syncScoped)].slice(0,100);return{staged:o(n),notStaged:o(r),untracked:o(i),truncated:a}}const hgt=[`unknown revision or path not in the working tree`,`no upstream configured for branch`,`does not point to a branch`,`no such branch`];function ggt(e){let t=e instanceof Error?e.message:String(e??``);return hgt.some(e=>t.includes(e))}async function _gt(e,t){let n;try{n=await Yq(e,[`diff`,`--name-status`,`HEAD...@{upstream}`])}catch(e){return!t?.aborted&&!ggt(e)&&H3.warn({event:`worktree-incoming-read-failed`,err:e},`[sync] incoming-change read failed — panel shows nothing incoming`),[]}return n.map(e=>({path:e.to,code:U3(e.status.charAt(0)),syncScoped:!0,...e.status.charAt(0)===`R`||e.status.charAt(0)===`C`?{origPath:e.from}:{}}))}async function vgt(e,t,n,r={}){let i={readable:!0,branch:null,detached:!1,upstream:null,staged:[],notStaged:[],untracked:[],incoming:[],truncated:!1},{git:a}=gK(e,{credentialConfig:[],timeoutMs:r.timeoutMs??1e4,...r.abortSignal===void 0?{}:{abortSignal:r.abortSignal}}),o=Date.now(),[s,c,l,u]=await Promise.allSettled([B8e(a,Gq),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`HEAD`]),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`@{upstream}`]),_gt(a,r.abortSignal)]),d=c.status===`fulfilled`?c.value.trim():``,f=d===`HEAD`,p=f||d===``?null:d,m=r.abortSignal?.aborted===!0,h=s.status===`rejected`,g=(e,t,n)=>{e.status===`rejected`&&(m||h||ggt(e.reason)||H3.warn({event:t,err:e.reason,elapsedMs:Date.now()-o,branch:p},`[sync] ${n}`))};if(g(c,`worktree-branch-read-failed`,`branch read failed — panel shows no branch`),g(l,`worktree-upstream-read-failed`,`upstream read failed — panel shows no upstream`),s.status===`rejected`)return m||H3.error({event:`worktree-read-failed`,err:s.reason,elapsedMs:Date.now()-o,branch:p},`[sync] worktree status read failed — panel listing marked unreadable`),{...i,readable:!1};let _=l.status===`fulfilled`&&l.value.trim()||null,v=u.status===`fulfilled`?u.value:[],y=mgt(s.value,t),b=e=>n?e.map(e=>{let t=n(e.path);return t===void 0?e:{...e,open:t}}):e;return{readable:!0,branch:p,detached:f,upstream:_,staged:b(y.staged),notStaged:b(y.notStaged),untracked:b(y.untracked),truncated:y.truncated||v.length>100,incoming:b(v.slice(0,100))}}function ygt(e){let{projectDir:t,contentDir:n,contentFilter:r,getFileIndex:i,checkLocalOpSecurity:a,getSyncEngine:o,getPrincipal:s,resolveCredentialConfig:c}=e;function l(e){let a=H(t??n,e),o=lG(U(n,a));if(!o||o.startsWith(`..`))return;let s=UH(o);if(i().has(s))return{kind:`doc`,docName:s};if(r&&!r.isExcluded(o,{bypassFilters:!0,showOk:!0})&&G(a))return{kind:`asset`,path:o}}async function u(e,r){if(!a(e,r,{handler:`git-worktree-status`}))return;if(e.method!==`GET`){X(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`git-worktree-status`,extraHeaders:{Allow:`GET`}});return}let i=new AbortController;r.on(`close`,()=>{r.writableEnded||i.abort()});try{let e=o?.(),a=await vgt(t??n,e?t=>e.isSyncScopedPath(t):()=>!1,l,{abortSignal:i.signal});if(r.writableEnded||r.destroyed)return;Q(r,200,Mie,a,{handler:`git-worktree-status`})}catch(e){if(r.writableEnded||r.destroyed)return;X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`git-worktree-status`,cause:e})}}return XQ({"/api/git/branch-info":Z(x,async(e,n)=>{try{if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:z3});return}let r=sG(e),i=r.get(`branch`),a=r.get(`path`),o=r.get(`kind`)===`folder`?`folder`:`doc`;if(!dre(i)){X(n,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:z3});return}if(!ogt(a,o)){X(n,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:z3});return}let s=await sgt(t,i,a,o);Q(n,200,Cn,s,{handler:z3})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:z3,cause:e})}},{handler:z3,method:`GET`,skipBodyParse:!0}),"/api/git/worktree-status":u,"/api/git/checkout":Z(ir,async(e,n,r)=>{if(FQ(r,s).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:V3});return}if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:V3});return}try{let e=await c(),i=await hK(()=>fgt(t,r.branch,{fastForward:r.fastForward===!0,credentialConfig:e}));Q(n,200,Je,i,{handler:V3})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:V3,cause:e})}},{handler:V3,method:`POST`})},{mutating:[`/api/git/checkout`]})}function bgt(){let e=new Map;return{run(t,n){let r=e.get(t);if(r)return{promise:r,coalesced:!0};let i=n();e.set(t,i);let a=()=>{e.get(t)===i&&e.delete(t)};return i.then(a,a),{promise:i,coalesced:!1}},get size(){return e.size}}}function W3(e,t,n){return t!==null&&uG(e,t)?lG(U(t,e)):uG(e,n)?`~/${lG(U(n,e))}`:lG(e)}const xgt=q(`edit-backups`),Sgt=/^(?!.*__)[A-Za-z0-9.-](?:[A-Za-z0-9._-]*[A-Za-z0-9.-])?$/;function Cgt(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`__`),n=[_n,Dn,sne].find(t=>e.startsWith(t));if((n===void 0?e:e.slice(n.length)).split(`/`).every(e=>Sgt.test(e)))return t;let r=e.normalize(`NFC`),i=Rc(`sha256`).update(r).digest(`hex`).slice(0,12);return`${r.replace(/[^A-Za-z0-9._-]+/g,`__`).replace(/^\.+/,`_`).slice(0,100)}-${i}`}function wgt(e,t,n){let r=W(sS(e),`edit-backups`,`discarded`),i=Cgt(n);return t===null?W(r,i):W(r,`projects`,Vi(t),i)}async function Tgt(e,t,n,r,i){try{let a=wgt(e,t,n);await qU(a,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,`-`),s=W(a,`${o}${Ws(i)}`);await uS(s,r,{fs:oW});let c=mc(a).sort();for(let e of c.slice(0,Math.max(0,c.length-5)))try{eW(W(a,e))}catch{}pQe();let l={abs:s,display:W3(s,null,e)};return xgt.info({documentName:n,backup:l.display},`a displaced version was kept in the backup folder`),l}catch(e){return mQe(),xgt.warn({documentName:n,err:e},`a displaced version could not be kept in the backup folder`),null}}function G3(e){return{kind:`held`,cause:e}}function K3(e,t){return{kind:`held`,cause:`not-utf8`,path:e,observation:t}}function Egt(e){switch(e.cause){case`no-history-or-backup`:case`keeps-changing`:case`not-utf8`:case`unreadable`:return e.cause;case`edits-changing`:return null;default:return Dgt(e)}}function Dgt(e){throw Error(`unhandled save hold: ${JSON.stringify(e)}`)}const Ogt=[50,200,800],q3=new Set([`ENOENT`,`ENOTDIR`]),kgt=new Set([`EBUSY`,`EAGAIN`,`EINTR`,`EMFILE`,`ENFILE`]),Agt=new Set([`EPERM`,`EACCES`]);var jgt=class extends Error{code=`EAGAIN`;constructor(){super(`the file changed while it was being read for the pre-write compare`),this.name=`FileChangedDuringReadError`}},J3=class extends Error{constructor(e){super(`the file for ${e} changed between the pre-write compare and the rename`),this.name=`StoreRestatRefusedError`}},Y3=class extends Error{code;constructor(e,t){super(`the file for ${e} could not be re-read before the rename`,{cause:t}),this.name=`StoreRestatFailedError`,this.code=cG(t)}};function Mgt(e){throw Error(`unhandled disk compare outcome: ${e.kind}`)}function Ngt(e,t=process.platform){if(e instanceof jgt)return!0;let n=cG(e);return n===void 0?!1:kgt.has(n)?!0:t===`win32`&&Agt.has(n)}function X3(e){return{size:e.size,mtimeNs:e.mtimeNs,dev:e.dev,ino:e.ino}}function Pgt(e,t){return e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.dev===t.dev&&e.ino===t.ino}function Fgt(e,t=$U,n=process.platform){let r;try{r=t(e.path)}catch(e){let t=cG(e);return t!==void 0&&q3.has(t)?{kind:`absent`}:{kind:`unreadable`,error:e,transient:Ngt(e,n)}}let i=X3(r.before);if(!Pgt(i,X3(r.after))||BigInt(r.bytes.byteLength)!==r.before.size)return{kind:`unreadable`,error:new jgt,transient:!0};let a=r.bytes.toString(`utf8`),o=dG(a),s=e.receiptHash??e.baseHash;return o===e.candidateHash?{kind:`match`,observation:i,alreadyCandidate:!0}:o===s?{kind:`match`,observation:i,alreadyCandidate:!1}:e.baseHash!==void 0&&o===e.baseHash?{kind:`drift`,observation:i}:{kind:`changed`,text:a,lossless:Buffer.from(a,`utf8`).equals(r.bytes),observation:i}}function Z3(e,t=$U){let n;try{n=t(e)}catch(e){let t=cG(e);return t!==void 0&&q3.has(t)?{kind:`absent`}:{kind:`failed`,error:e}}let r=n.bytes.toString(`utf8`);return{kind:`read`,text:r,lossless:Buffer.from(r,`utf8`).equals(n.bytes),observation:X3(n.before)}}function Q3(e,t){let n;try{n=yc(e,{bigint:!0})}catch(e){let t=cG(e);if(t===void 0||!q3.has(t))return{kind:`failed`,error:e};n=void 0}return t===null?n===void 0?{kind:`same`}:{kind:`moved`}:n!==void 0&&Pgt(t,X3(n))?{kind:`same`}:{kind:`moved`}}function $3(e){try{let t=yc(e,{bigint:!0,throwIfNoEntry:!1});return t?X3(t):void 0}catch{return}}function Igt(e){return e.receiptHash===void 0?`outside`:e.eventHash===e.receiptHash?`own-write`:e.isRecentOwnWrite&&e.readDiskHash()===e.receiptHash?`superseded`:`outside`}function Lgt(e){switch(e){case`own-write`:return`echo`;case`superseded`:return`superseded`;case`outside`:return null;default:return Rgt(e)}}function Rgt(e){throw Error(`unhandled receipt intake decision: ${String(e)}`)}const e6=q(`managed-artifact-persistence`);function zgt(e){if(typeof e==`object`)return!1;switch(e){case`persisted`:case`merged`:case`both-kept`:case`kept-live`:case`stash-fallback`:return!0;case`no-op`:case`write-failed`:case`applied`:case`unchanged`:case`outside-taken-in`:case`dropped-legacy-name`:case`dropped-unresolvable`:case`dropped-container-gone`:case`dropped-intake-landed`:return!1;default:return Bgt(e)}}function Bgt(e){throw Error(`unhandled skill store outcome: ${String(e)}`)}function t6(e){return e.homedirOverride??wc()}function Vgt(e){let t=k(e);return t===null||t.kind!==`skill`||t.scope!==`project`?null:{docKey:`${y}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}}function n6(e){if(!k(e))return{managed:!1};let t=Vgt(e);return t?{managed:!0,versioned:!0,docKey:t.docKey,filePath:`${t.docKey}/SKILL.md`}:{managed:!0,versioned:!1}}function Hgt(e){let t=t6(e);return Wst(t).filter(e=>G(W(t,br(U(t,e).split(Ys).join(`/`)))))}function Ugt(e){return G(`${e}.md`)?`${e}.md`:G(`${e}.mdx`)?`${e}.mdx`:`${e}.md`}function Wgt(e,t,n,r=null){if(!Ce.test(t)||t.length>64)throw Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(t)}`);if(r!==null&&(!Ce.test(r)||r.length>64))throw Error(`managedSkillBundleDir: invalid host qualifier: ${JSON.stringify(r)}`);let i=e===`global`?t6(n):n.projectDir;if(e!==`global`)return W(i,`.ok`,`skills`,t);if(r!==null){let e=F1(i,`global`).find(e=>e.editor===r);return e===void 0?null:W(i,e.root,t)}let a=K1(i,t),o=W(i,`.ok`,`skills`,t);if(a!==null)return a;if(G(W(o,`SKILL.md`)))return o;let s=R1(i,`global`);return s===null?null:W(i,s,t)}function Ggt(e,t){let n=yr(e);if(n!==null){let e=A1(n.name,null);return e===null?null:V(e)}let r=k(e);return r===null||r.kind!==`skill`?null:Wgt(r.scope,r.name,t,r.host)}function r6(e,t){let n=yr(e);if(n!==null){let t=A1(n.name,n.rel);if(t===null)throw Error(`managedArtifactAbsPath: external skill not registered: ${e}`);return n.rel===null?t:Ugt(t)}let r=k(e);if(r===null||r.kind!==`skill`)throw Error(`managedArtifactAbsPath: not a managed skill doc name: ${e}`);let i=Wgt(r.scope,r.name,t,r.host);if(i===null)throw Error(`managedArtifactAbsPath: no usable skill home for ${e}`);let a;if(r.rel===null)a=W(i,`SKILL.md`);else{let t=r.rel.split(`/`).filter(e=>e!==``&&e!==`.`);if(t.length===0||t.some(e=>e===`..`))throw Error(`managedArtifactAbsPath: invalid skill file path for ${e}`);a=Ugt(W(i,...t))}if(!a.startsWith(i+Ys))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return a}function Kgt(e,t){let n=W(e),r=t6(t),i=F1(r,`global`);for(let e of Wst(r)){let t=W(e);if(!n.startsWith(t+Ys))continue;let a=n.slice(t.length+1).split(Ys),o=a[0];if(o&&Ce.test(o)&&o.length<=64&&a.length>=2){let e=W(t,o),n=K1(r,o),s=``;if(n!==null&&W(n)!==e){let e=i.find(e=>W(r,e.root)===t)?.editor;e!==void 0&&(s=`@${e}`)}let c=a.slice(1);if(c.length===1&&c[0]===`SKILL.md`)return`${_n}global/${o}${s}`;let l=c[c.length-1]??``;if(/\.mdx?$/i.test(l)&&!c.includes(`..`)){let e=c.join(`/`).replace(/\.mdx?$/i,``);return`${_n}global/${o}${s}/${e}`}}return null}return null}function qgt(e,t,n){let r=k(t);if(r?.kind===`skill`&&r.scope===`project`||t.startsWith(`__template__/`))return;let i=yr(t);if(i&&A1(i.name,i.rel)===null||e.getXmlFragment(`default`).length>0)return;let a=r6(t,n);if(!G(a))return;let o;try{o=K(a,`utf-8`)}catch(e){e6.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}e.transact(()=>{d$(e,o,void 0,t),e.getMap(`lifecycle`).set(el,crypto.randomUUID())},u$),n.setReconciledBase(t,o),n.lkgCache.set(t,o)}async function Jgt(e,t,n){if(t.rel===null)try{if(!G(e))return;let r=W(sS(t6(n)),`edit-backups`,t.name),i=W(r,`SKILL.md.bak`);if(G(i))return;await qU(r,{recursive:!0}),await uS(i,K(e,`utf-8`),{fs:oW})}catch(e){e6.warn({name:t.name,err:e},`external-skill backup failed`)}}function i6(e,t,n,r,i){let a=i.beforeReconcileDivergence?.(e,t,n,r);e.transact(()=>{d$(e,r,void 0,t,void 0,a)},u$)}function a6(e,t,n){n.setReconciledBase(e,t),n.lkgCache.set(e,t)}var Ygt=class extends Error{constructor(e){super(`the version of ${e} here changed while the merge was being written`),this.name=`LiveMovedOnError`}};async function o6(e,t,n,r,i){try{return await uS(e,n,{fs:oW,beforeRename:()=>{let n=Q3(e,r);if(n.kind===`failed`)throw new Y3(t,n.error);if(n.kind===`moved`)throw new J3(t);if(i!==void 0&&!i())throw new Ygt(t)}}),`written`}catch(e){if(e instanceof J3)return sU(),`moved`;if(e instanceof Ygt)return`moved`;if(e instanceof Y3)return`unreadable`;throw e}}async function Xgt(e,t,n,r,i,a){let o=a===`store`?`skill-store`:`skill-intake`,s=e=>(lU(a,e),e),c=e=>(lU(a,`held`),e);if(!n.lossless)return e6.info({documentName:t},`the file changed outside to bytes that are not valid UTF-8; nothing was applied or written so they stay on disk`),c(K3(r,n.observation));let l=e.getText(`source`).toString(),u=i.getReconciledBase(t)??i.lkgCache.get(t)??``;if(l===u)return i6(e,t,l,n.text,i),a6(t,n.text,i),s(`applied`);let d=cY({docName:t,base:u,ours:l,theirs:n.text});switch(d.kind){case`noop`:return s(`unchanged`);case`clean`:return i6(e,t,l,d.newContent,i),a6(t,d.newContent,i),s(`applied`);case`merged`:case`both-kept`:{let a=await o6(r,t,d.newContent,n.observation,()=>e.getText(`source`).toString()===l&&(i6(e,t,l,d.newContent,i),!0));return a===`moved`?`retry`:a===`unreadable`?c(G3(`unreadable`)):(a6(t,d.newContent,i),d.kind===`merged`?s(`merged`):(i.history?.bothKept(t,{ours:l,theirs:n.text},d.kept),v$(t,d.kept,o),s(`both-kept`)))}case`refused`:{_$(t,d,o);let a=i.history!==null&&await i.history.keptLive(t,{side:`theirs`,bytes:n.text},d.reason),l=a?null:await Tgt(t6(i),null,t,n.text,`SKILL.md`);if(!a&&l===null)return e6.warn({documentName:t,reason:d.reason},`the outside version could not be merged or kept in history or the backup folder; nothing was written so it stays on disk`),c(G3(`no-history-or-backup`));l!==null&&i.history?.noticeBackup(t,`theirs`,d.reason,l);let u=Z3(r);if(u.kind!==`read`||u.text!==n.text)return`retry`;let f=await o6(r,t,e.getText(`source`).toString(),u.observation);return f===`moved`?`retry`:f===`unreadable`?c(G3(`unreadable`)):(a6(t,e.getText(`source`).toString(),i),a?(y$(t,d.reason,o),s(`kept-live`)):(e6.warn({documentName:t,reason:d.reason,backup:l?.display},`the outside version could not be merged or saved to history; it was kept in the backup folder and the version here stays`),s(`stash-fallback`)))}default:throw Error(`unhandled reconcile outcome: ${String(d)}`)}}async function Zgt(e,t,n,r){let i=k(t);if(i?.kind===`skill`&&i.scope===`project`||t.startsWith(`__template__/`))return`dropped-legacy-name`;let a=yr(t);if(a&&A1(a.name,a.rel)===null)return`dropped-unresolvable`;let o=e.getText(`source`).toString()===r.lkgCache.get(t);if(n===u$)return o?`outside-taken-in`:`dropped-intake-landed`;if(o)return`no-op`;let s=Ggt(t,r);if(s===null)return`dropped-unresolvable`;if(!G(s))return e6.warn({documentName:t,containerDir:s},`store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it`),`dropped-container-gone`;let c=r6(t,r);try{return await qU(W(c,`..`),{recursive:!0}),a&&await Jgt(c,a,r),await fS(`${c}.lock`,async()=>{for(let n=0;n<3;n++){let n=e.getText(`source`).toString(),i=r.lkgCache.get(t);if(n===i)return`no-op`;let a=Z3(c);if(a.kind===`failed`)return lU(`store`,`held`),e6.warn({documentName:t,err:a.error},`store: the file could not be read for the compare before the write; nothing was written`),G3(`unreadable`);let o=r.getReconciledBase(t)??i;if(a.kind===`read`&&a.text!==i&&a.text!==o&&a.text!==n){sQe();let n=await Xgt(e,t,a,c,r,`store`);if(n===`retry`)continue;return n}let s=await o6(c,t,n,a.kind===`read`?a.observation:null);if(s!==`moved`)return s===`unreadable`?(lU(`store`,`held`),G3(`unreadable`)):(a6(t,n,r),`persisted`)}return lU(`store`,`held`),e6.warn({documentName:t,rounds:3},`store: the file kept changing outside while it was being saved; nothing more was written`),G3(`keeps-changing`)})}catch(e){return e instanceof dS?(e6.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(e6.warn({documentName:t,err:e},`store: write failed`),`write-failed`)}}async function Qgt(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);if(i!==void 0&&i===n)return`no-op`;if(e.getText(`source`).toString()===n)return a6(t,n,r),`no-op`;let a=r6(t,r);try{return await fS(`${a}.lock`,async()=>{let i=Z3(a);if(i.kind!==`read`||i.text!==n)return`no-op`;let o=await Xgt(e,t,i,a,r,`intake`);return o===`retry`?`no-op`:typeof o==`object`?`held`:o})}catch(e){if(!(e instanceof dS))throw e;return lU(`intake`,`held`),e6.warn({documentName:t,err:e},`intake: the file lock timed out, so the outside change was not taken in; the next save compares it`),`held`}}function $gt(e){return e<=0?`0`:e===1?`1`:e<=5?`2-5`:e<=20?`6-20`:e<=50?`21-50`:`50+`}function e_t(e){return e<=0?`0`:e<=50?`1-50`:e<=200?`51-200`:e<=500?`201-500`:`500+`}let t_t=null,n_t=null;function r_t(){return t_t||=PU().createHistogram(`ok.timeline.query_duration_ms`,{description:`Wall-clock duration of one history query. Bounded labels: width_bucket (ref fan-out), commits_bucket (commits gathered), capped (depth bound hit), error (the walk threw — e.g. the PRD-6972 git timeout). The error label is what separates a timeout storm from a burst of legitimately-empty docs, both of which otherwise record width/commits 0.`,unit:`ms`}),t_t}function i_t(){return n_t||=PU().createCounter(`ok.timeline.coalesced_total`,{description:`History requests served by an in-flight single-flight walk instead of a fresh git walk. Bounded label: mode ∈ {doc, folder}. A high value is the poll-storm / fan-out signal.`}),n_t}function a_t(e){r_t().record(Math.max(0,e.durationMs),{width_bucket:$gt(e.width),commits_bucket:e_t(e.commits),capped:e.capped,error:e.error??!1})}function o_t(e){i_t().add(1,{mode:e})}const s6=q(`timeline`);function s_t(e,t){return Math.min(500,3*(Math.max(0,e)+Math.max(1,t)))}const c6=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,l6={entries:[],total:0,hasMore:!1},c_t=/^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;function l_t(e){return c_t.test(e)}function u_t(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function u6(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=u_t(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:Zx(s),checkpoint:c===`checkpoint`?Ee(s):null,rawBody:s}}).filter(e=>e!==null&&e.sha.length===40):[]}function d6(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let d_t=null;function f_t(){return d_t||=PU().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),d_t}let p_t=null;function m_t(){return p_t||=PU().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),p_t}function f6(e,t){return t.length===0||t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function h_t(e,t,n){return e.length===0||t.length===0?e:e.filter(e=>{let r=Xx(e.rawBody);if(r.length===0)return!0;let i=new Set;for(let e of r){for(let t of e.docs)i.add(t);if(e.previous_paths)for(let t of e.previous_paths)i.add(t.from),i.add(t.to)}if(i.size===0)return!0;for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!(o!==null&&!o.has(e.sha))&&i.has(a.path))return!0}return!1})}async function g_t(e,t,n,r,i,a,o){if(t.length===0||n.length===0)return t;let s=await Promise.all(n.map(async t=>{if(t.renameCommit===null)return null;let n=await I$(e,t.renameCommit,r,o,t.anchors);return n.length===0?new Set:R$(e,n,r,a)})),c=[];for(let e=0;e<t.length;e++){let r=t[e];for(let t=0;t<n.length;t++){let a=n[t],o=s[t];if(!(o!==null&&!o.has(r.sha)))for(let t of i(a.path))c.push({entryIdx:e,sha:r.sha,path:t})}}if(c.length===0)return[];let l=await Jat(e,c.map(e=>({sha:e.sha,path:e.path}))),u=new Set;for(let e=0;e<c.length;e++)l[e]&&u.add(c[e].entryIdx);return t.filter((e,t)=>u.has(t))}async function __t(e,t,n,r,i){if(t.length<2||n.length===0)return t;let a=new Set(n.map(e=>e.renameCommit).filter(e=>e!==null)),o=e=>e.type===`checkpoint`||a.has(e.sha),s=[];for(let e=0;e<t.length;e++)if(!o(t[e]))for(let a=0;a<n.length;a++){let o=r[a];o!==null&&!o.has(t[e].sha)||s.push({entryIdx:e,sha:t[e].sha,path:i(n[a].path)})}if(s.length===0)return t;let c=await Yat(e,s.map(e=>({sha:e.sha,path:e.path}))),l=t.map(()=>null);for(let e=0;e<s.length;e++){let t=s[e].entryIdx;l[t]===null&&c[e]!==null&&(l[t]=c[e])}let u=new Set,d=null,f=-1;for(let e=t.length-1;e>=0;e--){if(o(t[e]))continue;let n=l[e];if(n!==null){if(d!==null&&n===d){t[e].type!==`upstream`&&t[f].type===`upstream`?(u.add(f),f=e):u.add(e);continue}d=n,f=e}}return u.size===0?t:t.filter((e,t)=>!u.has(t))}async function v_t(e,t,n=`.`,r){if(!G(e.workTree)||!G(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return l6;let i=t.branch??`main`,a=Math.max(1,t.limit??50),o=Math.max(0,t.offset??0),s=s_t(o,a),c=performance.now(),l=!1,u=(e,t,n=!1)=>a_t({durationMs:performance.now()-c,width:e,commits:t,capped:l,error:n}),d=d6(t.type),f=d6(t.author),p=d6(t.excludeAuthor),m=t.includeAutoCheckpoints??!1,h=n===`.`?``:n.replace(/^\.\//,``),g=e=>h?`${h}/${e}${qH(e)}`:`${e}${qH(e)}`,_=e=>{let t=g(e),n=UXe(t,e);return n?[t,n]:[t]},v=t.docName?n6(t.docName):{managed:!1},y=v.managed&&v.versioned?v.filePath:void 0,b=v.managed&&v.versioned?v.docKey:t.docName,x=t.docName?y?h?`${h}/${y}`:y:g(t.docName):void 0;try{let n=r?.renameLogIndex??N$(e.gitDir),{chain:c,skipped:h}=await FU(`rename.expandPredecessors`,void 0,async()=>t.docName?Vat(b,i,n):{chain:[],skipped:0}),v=c.length>1;t.docName&&f_t().record(c.length),h>0&&m_t().add(h);let y=Hat(),S=F$(),C=OJ(e);if(d.length===1&&d[0]===`checkpoint`){let t=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${i}/`)).trim().split(`
1132
1132
  `).filter(e=>e.length===40),n=[];if(i!==`main`)try{n=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
@@ -2086,7 +2086,7 @@ tags: [lore, history]
2086
2086
  }
2087
2087
  }
2088
2088
  }`,variables:{owner:e.owner,name:e.repo,number:e.number}})},n,r);if(a.status!==200)return l8(a)?(i(a),u8):`fallback`;let o=bxt(a.body);if((o||a.headers.get(`x-ratelimit-remaining`)===`0`)&&i(a),o)return`fallback`;let s=d8(d8(a.body)?.data);if(s===null)return`fallback`;let c=d8(s.repository);if(c===null||c.issueOrPullRequest===null)return Cxt;let l=Oxt(e,c.issueOrPullRequest);return l===null?`fallback`:{ok:!0,preview:l}}async function jxt(e,t,n,r,i){let a={headers:Ext(t,`application/vnd.github+json`)},o=wxt(e),s=e=>e.status===404||e.status===410?Cxt:(l8(e)&&i(e),u8),c=async()=>{let t=await m8(`${o}/pulls/${e.number}`,a,n,r);if(t.status!==200)return s(t);let i=kxt(e,null,t.body);return i===null?u8:{ok:!0,preview:i}};if(e.kind===`pull`)return c();let l=await m8(`${o}/issues/${e.number}`,a,n,r);if(l.status!==200)return s(l);if(d8(d8(l.body)?.pull_request)!==null)return c();let u=kxt(e,l.body,null);return u===null?u8:{ok:!0,preview:u}}async function Mxt(e){let{target:t,token:n,rateLimits:r}=e,i=e.fetchFn??fetch,a=e.timeoutMs??5e3,o=e.now??Date.now,s=`graphql ${t.host}`,c=`rest ${n===null?`anonymous`:`signed-in`} ${t.host}`,l=e=>r?.holding(e,o())===!0,u=(e,i)=>{if(r===void 0)return;let a=vxt(i)?n===null?[c]:[s,c]:[e===`graphql`?s:c],l=0;for(let e of a)l=Math.max(l,r.hold(e,i.headers,o()));let u=a.length>1?`graphql+rest`:e;hxt.info({host:t.host,signedIn:n!==null,api:u,until:new Date(l).toISOString()},xxt[u])};try{if(n!==null&&!l(s)){let e=await Axt(t,n,i,a,e=>u(`graphql`,e));if(e!==`fallback`)return e}return l(c)?u8:await jxt(t,n,i,a,e=>u(`rest`,e))}catch(e){let n=e instanceof Error&&e.name===`AbortError`?`timeout`:e instanceof SyntaxError?`bad-response`:`network`;return hxt.warn({reason:n,host:t.host,repo:`${t.owner}/${t.repo}`,number:t.number,...n===`timeout`?{}:{err:e}},`[github-reference] GitHub request failed; the reference stays a plain link`),u8}}function Nxt(e){if(!e.ok)return e.reason===`not-found`?3e5:6e4;let t=e.preview.lifecycle;return t===`open`||t===`draft`?6e4:18e5}var Pxt=class{entries=new Map;inflight=new Map;now;constructor(e=Date.now){this.now=e}load(e,t){let n=this.entries.get(e);if(n!==void 0&&n.expiresAt>this.now())return this.entries.delete(e),this.entries.set(e,n),Promise.resolve(n.outcome);let r=this.inflight.get(e);if(r!==void 0)return r;let i=t().then(t=>(this.store(e,t),t)).finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,i),i}store(e,t){for(this.entries.delete(e),this.entries.set(e,{outcome:t,expiresAt:this.now()+Nxt(t)});this.entries.size>256;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}}};const Fxt=/^\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})\/(pull|issues)\/(\d{1,10})(?:\/[^?#]*)?$/;function Ixt(e,t){let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`https:`||n.username!==``||n.password!==``||n.port!==``)return null;let r=Bi(n.hostname);if(!pa(r,t))return null;let i=Fxt.exec(n.pathname);if(i===null)return null;let[,a,o,s,c]=i;if(a===void 0||o===void 0||o===`.`||o===`..`)return null;let l=Number(c);return!Number.isSafeInteger(l)||l<1?null:{host:r,owner:a,repo:o,number:l,kind:s===`pull`?`pull`:`issues`}}function Lxt(e){return`${e.host}/${e.owner}/${e.repo}#${e.number}`.toLowerCase()}function Rxt(e,t={}){let n=t.ttlMs??6e4,r=t.fallbackTtlMs??5e3,i=t.now??Date.now,a=new Map,o=new Map;function s(e,t){return e.token==null?null:{token:e.token,host:t,...e.resolvedLogin?{login:e.resolvedLogin}:{}}}return{get(t,c){if(!e)return null;let l=`${t}\0${c??``}`,u=i(),d=a.get(l);if(d&&d.expiresAt>u)return s(d,t);let f=e(t,{login:c}),p=f.available&&f.token?f.token:null,m=f.available?f.resolvedLogin:void 0,h=!c||p!=null&&b6(m,c),g;if(h)o.delete(l),g=n;else{let e=o.get(l)??0;o.set(l,e+1),g=Math.min(r*2**e,n)}let _={token:p,resolvedLogin:m,expiresAt:u+g};return a.set(l,_),s(_,t)},invalidate(){a.clear(),o.clear()}}}const zxt=q(`github-reference`);function Bxt(e){return IQ(e.socket?.remoteAddress)&&!RQ(e)}function Vxt(e,t){let n=Rxt(e);return async e=>{let r=n.get(e);if(r!==null)return r.token;if(!t)return null;try{let n=await t.get(e);return n?.token?n.token:null}catch(t){return zxt.warn({err:t,host:e},`[github-reference] token store lookup failed; reading anonymously`),null}}}const Hxt={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function Uxt(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function Wxt(e){return e.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if(t.startsWith(`#`)){let n=t[1]===`x`||t[1]===`X`;return Uxt(Number.parseInt(t.slice(n?2:1),n?16:10))??e}return Hxt[t.toLowerCase()]??e})}function Gxt(e){return e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8288&&e<=8292||e>=8294&&e<=8297||e===65279}function Kxt(e){return e<=31||e>=127&&e<=159}function qxt(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;Gxt(e)||(t+=Kxt(e)?` `:n)}return t}function Jxt(e,t){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``).trimEnd()}…`}function g8(e,t){return Jxt(qxt(Wxt(e)).replace(/\s+/g,` `).trim(),t)}function Yxt(e){return e.trim().toLowerCase().split(/\s+/)}function Xxt(e){return e.replace(/[A-Z]+/g,e=>e.toLowerCase())}function _8(e){return e===32||e===9||e===10||e===12||e===13}const Zxt=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function Qxt(e,t){let n=t;for(;n<e.length;){let t=e.charCodeAt(n);if(!(t>=97&&t<=122||t>=48&&t<=57||t===45))break;n++}return{name:e.slice(t,n),end:n}}function v8(e,t,n,r){let i=t.length,a=n;for(;a<i;){let n=t.charCodeAt(a);if(_8(n)||n===47){a++;continue}if(n===62)return a+1;let o=a;for(;a<i&&(n=t.charCodeAt(a),!(_8(n)||n===61||n===62||n===47));)a++;let s=t.slice(o,a);for(;a<i&&_8(t.charCodeAt(a));)a++;let c=``;if(a<i&&t.charCodeAt(a)===61){for(a++;a<i&&_8(t.charCodeAt(a));)a++;if(a<i){let r=t.charCodeAt(a);if(r===34||r===39){a++;let n=t.indexOf(r===34?`"`:`'`,a);c=e.slice(a,n===-1?i:n),a=n===-1?i:n+1}else{let r=a;for(;a<i&&(n=t.charCodeAt(a),!(_8(n)||n===62));)a++;c=e.slice(r,a)}}}r&&s&&!r.has(s)&&r.set(s,c)}return i}function $xt(e,t,n){let r=`</${t}`,i=n;for(;i<e.length;){let t=e.indexOf(r,i);if(t===-1)return null;let n=t+r.length,a=n<e.length?e.charCodeAt(n):-1;if(a===62||a===47||a===-1||_8(a)){let r=e.indexOf(`>`,n);return{textEnd:t,end:r===-1?e.length:r+1}}i=t+1}return null}function eSt(e){let t=``,n=new Map,r,i=-1;try{let a=Xxt(e),o=a.length,s=0;for(;s<o;){let c=a.indexOf(`<`,s);if(c===-1)break;let l=c+1<o?a.charCodeAt(c+1):-1;if(l===33){if(a.startsWith(`<!--`,c)){let e=a.indexOf(`-->`,c+2);if(e===-1)break;s=e+3}else{let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1}continue}if(l===63){let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1;continue}if(l===47){let{name:e,end:t}=Qxt(a,c+2);if(e===`head`){if(t<o){let e=a.indexOf(`>`,t);e!==-1&&(i=e+1)}break}let n=a.indexOf(`>`,t);if(n===-1)break;s=n+1;continue}if(!(l>=97&&l<=122)){s=c+1;continue}let{name:u,end:d}=Qxt(a,c+1);if(u===`body`){if(d<o){let e=a.charCodeAt(d);(e===62||e===47||_8(e))&&(i=d+1)}break}if(u===`title`){let n=v8(e,a,d,null),r=$xt(a,`title`,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.textEnd),s=r.end;continue}if(Zxt.has(u)){let t=$xt(a,u,v8(e,a,d,null));if(t===null)break;s=t.end;continue}if(u===`meta`){let t=new Map;s=v8(e,a,d,t);let r=t.get(`content`);if(r){let e=t.get(`property`),i=t.get(`name`);e?n.set(e.toLowerCase(),r):i&&n.set(i.toLowerCase(),r)}continue}if(u===`link`){let t=new Map;if(s=v8(e,a,d,t),r===void 0){let e=t.get(`href`),n=t.get(`rel`);e&&n&&Yxt(n).includes(`icon`)&&(r=e)}continue}s=v8(e,a,d,null)}}catch{}return{rawTitle:t,metaContent:n,faviconHref:r,headEndOffset:i}}function tSt(e){let{rawTitle:t,metaContent:n,faviconHref:r}=eSt(e),i=g8(n.get(`og:title`)??t,200),a=g8(n.get(`og:description`)??n.get(`description`)??``,500),o=g8(n.get(`og:site_name`)??``,100),s={};return i&&(s.title=i),a&&(s.description=a),o&&(s.siteName=o),r&&(s.faviconHref=r),s}function nSt(e){return eSt(e).headEndOffset}function rSt(e){let t;try{t=new URL(e).hostname}catch{return e}return t.startsWith(`www.`)&&t.slice(4).includes(`.`)&&(t=t.slice(4)),t}function iSt(e){let t=e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;try{if(EF.default.IPv4.isValid(t))return EF.default.IPv4.parse(t);if(EF.default.IPv6.isValid(t))return EF.default.IPv6.parse(t)}catch{return null}return null}function aSt(e){let t=iSt(e);return t!==null&&t.range()===`unicast`}function oSt(e){let t=iSt(e);return t===null?{kind:`hostname`}:{kind:`ip-literal`,allowed:t.range()===`unicast`,canonical:t.toString(),family:t.kind()===`ipv6`?6:4}}const sSt=q(`link-preview.guarded-fetch`),cSt=async e=>(await Vae(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function lSt(e,t){let n=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${n}${e.pathname}${e.search}`}async function uSt(e,t,n){let r;try{r=new URL(e)}catch{return{ok:!1,reason:`fetch-error`}}if(r.protocol!==`http:`&&r.protocol!==`https:`)return{ok:!1,reason:`bad-scheme`};let i=oSt(r.hostname);if(i.kind===`ip-literal`){if(!i.allowed)return{ok:!1,reason:`private-ip`};let e=i.family===6?`[${i.canonical}]`:i.canonical;return{ok:!0,target:{requestUrl:lSt(r,e),pinnedAddress:void 0,serverName:void 0,logicalUrl:r.toString()}}}let a;try{a=await t(r.hostname)}catch{return{ok:!1,reason:`dns-failure`}}if(a.length===0)return{ok:!1,reason:`dns-failure`};for(let e of a)if(!n(e.address))return{ok:!1,reason:`private-ip`};let o=a[0];return{ok:!0,target:{requestUrl:lSt(r,r.hostname),pinnedAddress:{address:o.address,family:o.family===6||o.address.includes(`:`)?6:4},serverName:r.hostname,logicalUrl:r.toString()}}}function dSt(e){return(t,n,r)=>{n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}function fSt(e){return e===301||e===302||e===303||e===307||e===308}function pSt(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function y8(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function b8(e){try{e.destroy()}catch{}}function mSt(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=e.requestUrl.startsWith(`https:`),o={method:`GET`,agent:!1,signal:t,headers:{"User-Agent":`OpenKnowledge-LinkPreview/1.x`,Accept:`text/html`,"Accept-Encoding":`identity`}};e.pinnedAddress&&(o.lookup=dSt(e.pinnedAddress)),a&&e.serverName&&(o.servername=e.serverName);try{let n=(a?Hae:zae)(e.requestUrl,o,e=>{e.on(`error`,()=>{}),i({ok:!0,response:e})});n.on(`error`,e=>i({ok:!1,reason:y8(e,t)})),n.end()}catch(e){i({ok:!1,reason:y8(e,t)})}})}function hSt(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?Wae():e===`deflate`?Gae():e===`br`?Uae():null}function gSt(){let e=``;return t=>{let n=e.length;e+=Buffer.from(t).toString(`latin1`);let r=nSt(e);return r===-1?-1:r-n}}function _St(e,t,n,r){let i=hSt((e.headers[`content-encoding`]??``).trim().toLowerCase());if(i===null)return b8(e),Promise.resolve({ok:!1,reason:`fetch-error`});let a=i===`identity`?e:e.pipe(i);return new Promise(i=>{let o=[],s=r?gSt():null,c=0,l=!1,u=()=>{n.removeEventListener(`abort`,f),b8(e),a!==e&&a.destroy()},d=e=>{l||(l=!0,u(),i(e))},f=()=>d({ok:!1,reason:`timeout`});n.addEventListener(`abort`,f,{once:!0}),a!==e&&e.on(`error`,e=>d({ok:!1,reason:y8(e,n)})),a.on(`data`,e=>{if(s){let n=s(e);if(n!==-1){if(c+n>t){d({ok:!1,reason:`oversized`});return}o.push(e.subarray(0,n)),d({ok:!0,body:new Uint8Array(Buffer.concat(o))});return}}if(c+=e.byteLength,c>t){d({ok:!1,reason:`oversized`});return}o.push(e)}),a.on(`end`,()=>d({ok:!0,body:new Uint8Array(Buffer.concat(o))})),a.on(`error`,e=>d({ok:!1,reason:y8(e,n)}))})}function x8(e){return sSt.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function vSt(e,t={}){let n=t.allowContentType??(e=>e===`text/html`),r=t.maxBytes??524288,i=t.timeoutMs??5e3,a=t.maxRedirects??3,o=t.resolve??cSt,s=t.isAddressAllowed??aSt,c=AbortSignal.timeout(i),l=e,u=0;for(;;){let e=await uSt(l,o,s);if(!e.ok)return x8(e.reason);let{target:t}=e,i=await mSt(t,c);if(!i.ok)return x8(i.reason);let d=i.response;if(fSt(d.statusCode??0)){let e=d.headers.location;if(b8(d),e===void 0)return x8(`fetch-error`);if(u>=a)return x8(`redirect-limit`);u+=1;try{l=new URL(e,t.logicalUrl).toString()}catch{return x8(`fetch-error`)}continue}let f=pSt(d.headers[`content-type`]);if(!n(f))return b8(d),x8(`non-html`);let p=await _St(d,r,c,f===`text/html`);return p.ok?{ok:!0,body:p.body,contentType:f,finalUrl:t.logicalUrl}:x8(p.reason)}}function ySt(e){let t=e;return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?`image/png`:t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?`image/jpeg`:t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97?`image/gif`:t.length>=2&&t[0]===66&&t[1]===77?`image/bmp`:t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?`image/webp`:t.length>=4&&t[0]===0&&t[1]===0&&t[2]===1&&t[3]===0?`image/x-icon`:null}function bSt(e){return e.startsWith(`image/`)}function xSt(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function SSt(e,t){let n=await t(e,{allowContentType:bSt,maxBytes:102400,timeoutMs:2500});if(!n.ok)return;let r=ySt(n.body);if(r)return`data:${r};base64,${Buffer.from(n.body).toString(`base64`)}`}async function CSt(e){let t=tSt(e.html),n=xSt(t.faviconHref,e.finalUrl),r=n?await SSt(n,e.fetch??vSt):void 0;return{domain:rSt(e.requestUrl),...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.siteName===void 0?{}:{siteName:t.siteName},...r===void 0?{}:{faviconDataUri:r}}}const S8=q(`link-preview.cache`);function wSt(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function C8(e){return Rc(`sha256`).update(e,`utf-8`).digest(`hex`)}var TSt=class{cacheDir;metaDir;manifestPath;maxEntries;successTtlMs;negativeTtlMs;now;entries=new Map;payloads=new Map;persistedKeys=new Set;inFlight=new Map;dirty=!1;persisting=!1;persistPending=!1;constructor(e){this.cacheDir=e.cacheDir,this.metaDir=e.cacheDir?H(e.cacheDir,`meta`):null,this.manifestPath=e.cacheDir?H(e.cacheDir,`manifest.json`):null,this.maxEntries=e.maxEntries??256,this.successTtlMs=e.successTtlMs??6048e5,this.negativeTtlMs=e.negativeTtlMs??36e5,this.now=e.now??Date.now}async init(){if(!this.cacheDir||!this.manifestPath||!this.metaDir)return;let e=null;try{G(this.manifestPath)&&(e=JSON.parse(await jc(this.manifestPath,`utf-8`)))}catch(e){S8.warn({err:e},`[link-preview] unreadable cache manifest — starting empty`);return}if(!e||e.schemaVersion!==1||!e.entries)return;let t=this.now();for(let[n,r]of Object.entries(e.entries))if(!(!r||r.status!==`ok`&&r.status!==`negative`)&&!(typeof r.expiresAt!=`number`||t>=r.expiresAt)){if(r.status===`ok`){let e=await this.readBlob(n);if(!e)continue;this.payloads.set(n,e),this.persistedKeys.add(n)}this.entries.set(n,r)}}async load(e,t){let n=wSt(e);if(n===null)return t();let r=this.getFresh(n);if(r)return r;let i=this.inFlight.get(n);if(i)return i;let a=(async()=>{let e=await t();return this.record(n,e),e})().finally(()=>{this.inFlight.delete(n)});return this.inFlight.set(n,a),a}getFresh(e){let t=this.entries.get(e);if(!t)return;if(this.now()>=t.expiresAt){this.drop(e),this.dirty=!0;return}if(this.entries.delete(e),this.entries.set(e,t),t.status===`negative`)return{ok:!1,reason:t.reason??`error`};let n=this.payloads.get(e);if(!n){this.drop(e),this.dirty=!0;return}return{ok:!0,metadata:n}}record(e,t){let n=this.now();this.persistedKeys.delete(e),this.entries.delete(e),this.payloads.delete(e),t.ok?(this.entries.set(e,{status:`ok`,fetchedAt:n,expiresAt:n+this.successTtlMs}),this.payloads.set(e,t.metadata)):this.entries.set(e,{status:`negative`,fetchedAt:n,expiresAt:n+this.negativeTtlMs,reason:t.reason}),this.dirty=!0,this.evict()}evict(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.drop(e),this.dirty=!0}}drop(e){this.entries.delete(e),this.payloads.delete(e),this.persistedKeys.delete(e)}async persist(){if(this.cacheDir){if(this.persisting){this.persistPending=!0;return}this.persisting=!0;try{do this.persistPending=!1,await this.writeToDisk();while(this.persistPending&&this.dirty)}finally{this.persisting=!1}}}async writeToDisk(){if(!(!this.cacheDir||!this.manifestPath||!this.metaDir)&&this.dirty)try{await qU(this.metaDir,{recursive:!0});let e=new Set;for(let[t,n]of this.entries){if(n.status!==`ok`||(e.add(C8(t)),this.persistedKeys.has(t)))continue;let r=this.payloads.get(t);r&&(await UU(H(this.metaDir,`${C8(t)}.json`),JSON.stringify(r)),this.persistedKeys.add(t))}let t={schemaVersion:1,entries:Object.fromEntries(this.entries)},n=`${this.manifestPath}.tmp`;await UU(n,JSON.stringify(t)),await KU(n,this.manifestPath);for(let t of mc(this.metaDir)){if(!t.endsWith(`.json`))continue;let n=t.slice(0,-5);e.has(n)||eW(H(this.metaDir,t))}this.dirty=!1}catch(e){S8.warn({err:e},`[link-preview] failed to persist cache`)}}clearMemory(){this.entries.clear(),this.payloads.clear(),this.persistedKeys.clear(),this.inFlight.clear(),this.dirty=!1}async wipe(){if(this.clearMemory(),this.cacheDir)try{iW(this.cacheDir,{recursive:!0,force:!0})}catch(e){S8.warn({err:e},`[link-preview] failed to wipe cache`)}}get size(){return this.entries.size}async readBlob(e){if(!this.metaDir)return null;let t=H(this.metaDir,`${C8(e)}.json`);try{if(!G(t))return null;let e=nt.safeParse(JSON.parse(await jc(t,`utf-8`)));return e.success?e.data:null}catch(e){return S8.warn({err:e},`[link-preview] unreadable cache blob — treating as miss`),null}}};function ESt(e){if(!e||e===`null`)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)}function DSt(e){return ESt(e.origin)?Xit(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}let OSt=null,kSt=null,ASt=null,jSt=null,MSt=null,NSt=null;function PSt(){return OSt||=PU().createCounter(`ok.saved_themes.save_total`,{description:`Successful saved-theme file saves. Attribute-free to keep cardinality bounded.`}),OSt}function FSt(){return kSt||=PU().createCounter(`ok.saved_themes.delete_total`,{description:`Successful saved-theme file deletions. Attribute-free to keep cardinality bounded.`}),kSt}function ISt(){return MSt||=PU().createCounter(`ok.saved_themes.parse_failure_total`,{description:`Saved-theme scheme parse failures. Attribute-free to keep cardinality bounded.`}),MSt}function LSt(){return ASt||=PU().createCounter(`ok.saved_themes.scan_total`,{description:`Saved-theme store scans. Attribute-free to keep cardinality bounded.`}),ASt}function RSt(){return jSt||=PU().createCounter(`ok.saved_themes.parse_total`,{description:`Saved-theme scheme parse attempts. Attribute-free to keep cardinality bounded.`}),jSt}function zSt(){return NSt||=PU().createHistogram(`ok.saved_themes.usable_count`,{description:`Usable saved themes returned by a completed bounded scan. Attribute-free to keep cardinality bounded.`}),NSt}function BSt(){PSt().add(1)}function VSt(){FSt().add(1)}function HSt(){LSt().add(1)}function USt(){RSt().add(1)}function WSt(){ISt().add(1)}function GSt(e){zSt().record(e)}const w8=q(`saved-themes`),T8=[`.yaml`,`.yml`];function E8(e){return W(sS(e??wc()),nne)}function KSt(e={}){HSt();let t=e.root??E8(e.homedirOverride),n=e.cap??500,r=[],i=!1;try{let n=fc(t);try{let t=e.observationCap??2e3;for(;r.length<t;){let e=n.readSync();if(e===null)break;r.push(e)}i=n.readSync()!==null}finally{try{n.closeSync()}catch{}}}catch(e){return cG(e)===`ENOENT`?GSt(0):w8.warn({root:t,reason:e instanceof Error?e.message:String(e)},`failed to read saved-theme store at ${t} — treating as empty`),{entries:[],truncated:!1}}let a=r.filter(qSt).map(e=>e.name).sort(),o=new Map;for(let e of a){let t=JSt(e),n=o.get(t)??[];n.push(e),o.set(t,n)}let s=[...o.entries()].sort(([e],[t])=>e.localeCompare(t)),c=i||s.length>n;c&&w8.warn({root:t,cap:n,found:s.length,observationTruncated:i},`saved-theme store at ${t} exceeded a scan bound; the returned list is incomplete.`);let l=[];for(let[e,r]of s.slice(0,n)){let n=r[0];if(!n)continue;if(r.length>1){let t=Jt(e);l.push({ok:!1,filename:n,...t.ok?{id:t.id}:{},code:`duplicate-identity`,conflictingFilenames:r});continue}let i=YSt(t,n);i&&l.push(i)}return GSt(l.filter(e=>e.ok).length),{entries:l,truncated:c}}function qSt(e){if(e.name.startsWith(`.`))return!1;let t=e.name.toLowerCase();return T8.some(e=>t.endsWith(e))}function JSt(e){let t=e.toLowerCase(),n=T8.find(e=>t.endsWith(e));return n?e.slice(0,-n.length):qs(e).name}function YSt(e,t){let n=Jt(qs(t).name);if(!n.ok)return{ok:!1,filename:t,code:n.code};if(!T8.some(e=>t.endsWith(e)))return{ok:!1,filename:t,id:n.id,code:`unsupported-extension-case`};let r=H(e,t);try{let e=cc(r);if(e.isSymbolicLink())return{ok:!1,filename:t,id:n.id,code:`symlink`};if(!e.isFile())return{ok:!1,filename:t,id:n.id,code:`not-regular-file`}}catch(r){return cG(r)===`ENOENT`?null:(w8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to inspect saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`})}let i;try{i=dc(r,ic.O_RDONLY|ic.O_NOFOLLOW)}catch(r){let i=cG(r);return i===`ENOENT`?null:i===`ELOOP`?{ok:!1,filename:t,id:n.id,code:`symlink`}:(w8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to open saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`})}let a;try{let e=sc(i);if(!e.isFile())return{ok:!1,filename:t,id:n.id,code:`not-regular-file`};if(e.size>65536)return{ok:!1,filename:t,id:n.id,code:`file-too-large`};let r=Buffer.alloc(65537),o=0;for(;o<r.length;){let e=pc(i,r,o,r.length-o,null);if(e===0)break;o+=e}if(o>65536)return{ok:!1,filename:t,id:n.id,code:`file-too-large`};a=r.subarray(0,o).toString(`utf-8`)}catch(r){return w8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to read saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`}}finally{try{rc(i)}catch{}}USt();let o=uee(a);return o.ok?{ok:!0,id:n.id,filename:t,scheme:o.scheme}:(WSt(),{ok:!1,filename:t,id:n.id,code:o.error.kind})}async function D8(e,t,n,r){let i=W(sS(t));await qU(i,{recursive:!0});let a=Rc(`sha256`).update(W(e)).digest(`hex`).slice(0,24);try{return await fS(H(i,`saved-themes-${a}.lock`),n,{timeoutMs:r})}catch(e){if(e instanceof dS)return{ok:!1,code:`lock-timeout`};throw e}}function XSt(e){try{return cc(e).isFile()?`regular`:`unsafe`}catch(e){if(e.code===`ENOENT`)return`missing`;throw e}}function O8(e,t){let n=[],r;try{r=fc(e)}catch(e){if(e.code===`ENOENT`)return{complete:!0,filenames:n};throw e}try{for(let e=0;e<2e3;e+=1){let e=r.readSync();if(e===null)return{complete:!0,filenames:n.sort()};let i=e.name.toLowerCase(),a=T8.find(e=>i.endsWith(e));a&&e.name.slice(0,-a.length)===t&&n.push(e.name)}return{complete:r.readSync()===null,filenames:n.sort()}}finally{try{r.closeSync()}catch{}}}async function ZSt(e){let t=e.stem===void 0?Cre(e.name):(()=>{let t=Jt(e.stem);return t.ok?{...t,stem:e.stem}:t})();if(!t.ok)return{ok:!1,code:t.code};let n=e.homedirOverride??wc(),r=e.root??E8(n);return D8(r,n,async()=>{let n=O8(r,t.stem);if(!n.complete||n.filenames.length>0)return{ok:!1,code:`name-taken`};let i=`${t.stem}${e.extension??`.yaml`}`;return XSt(H(r,i))===`missing`?(await qU(r,{recursive:!0}),await uS(H(r,i),Mi(e.scheme),{fs:oW,sweepStaleTmps:!1}),BSt(),{ok:!0,id:t.id,filename:i}):{ok:!1,code:`name-taken`}},e.lockTimeoutMs)}async function QSt(e){let t=It(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??wc(),r=e.root??E8(n);return D8(r,n,async()=>{let n=O8(r,t.stem);if(!n.complete)return{ok:!1,code:`ambiguous-id`};let{filenames:i}=n;if(i.length===0)return{ok:!1,code:`not-found`};if(i.length>1)return{ok:!1,code:`ambiguous-id`};let a=i[0];return a?!T8.some(e=>a.endsWith(e))||XSt(H(r,a))!==`regular`?{ok:!1,code:`unsafe-target`}:(await uS(H(r,a),Mi(e.scheme),{fs:oW,sweepStaleTmps:!1}),{ok:!0,id:e.id,filename:a}):{ok:!1,code:`not-found`}},e.lockTimeoutMs)}async function $St(e){let t=It(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??wc(),r=e.root??E8(n);return D8(r,n,async()=>{let e=O8(r,t.stem);if(!e.complete)return{ok:!1,code:`ambiguous-id`};let{filenames:n}=e;if(n.length===0)return{ok:!0,existed:!1};if(n.length>1)return{ok:!1,code:`ambiguous-id`};let i=n[0];if(!i)return{ok:!0,existed:!1};let a=YSt(r,i);return a===null?{ok:!0,existed:!1}:a.ok?(eW(H(r,i)),VSt(),{ok:!0,existed:!0,filename:i,scheme:a.scheme}):{ok:!1,code:`unusable-theme`}},e.lockTimeoutMs)}const eCt=new Set([`.DS_Store`,`.localized`,`Thumbs.db`,`.gitignore`,`.gitkeep`,`.gitattributes`]);function tCt(e){let t=[],n=[],r=[];for(let i of mc(e,{withFileTypes:!0})){if(eCt.has(i.name))continue;if(i.name.startsWith(`.`)){r.push(i.name);continue}let a=H(e,i.name);if(G(H(a,`SKILL.md`))){t.push(i.name);continue}if(i.isSymbolicLink()&&!G(a)){r.push(i.name);continue}i.isDirectory()&&nCt(a)||n.push(i.name)}return{bundles:t,strays:n,ignored:r}}function nCt(e){try{return mc(e).length===0}catch{return!1}}function rCt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=H(t,n),o=H(t,r),s=[r,n].filter(e=>!G(H(t,e))&&!i(e));if(s.length>0)return{kind:`not-permitted`,roots:s};let c;try{c=cc(a)}catch{return{kind:`absent`}}if(c.isSymbolicLink()||!c.isDirectory())return{kind:`not-linkable`};try{if(hc(a)===hc(o))return{kind:`not-linkable`}}catch{}let{bundles:l,strays:u,ignored:d}=tCt(a);if(u.length>0)return{kind:`stray-entries`,strays:u};let f=[],p=[],m=[],h=[],g=[],_=[];for(let e of l){let t=H(a,e),n=H(o,e);if(cc(t).isSymbolicLink()){let r=hc(t),i=null,a=!1;try{a=cc(n).isSymbolicLink(),i=hc(n)}catch{}i===r?m.push(e):i===null?(a&&h.push(e),_.push({name:e,target:r})):f.push(e);continue}let r=!1;try{r=cc(n).isSymbolicLink()}catch{}if(r){h.push(e),G(n)&&g.push(e),p.push(e);continue}if(!G(n)){p.push(e);continue}let i=XM(t)?.contentHash,s=XM(n)?.contentHash;i!==void 0&&i===s?m.push(e):f.push(e)}return f.length>0?{kind:`conflicts`,conflicts:f}:{kind:`plan`,plan:{toMove:p,toDrop:m,destLinks:h,liveDestLinks:g,linkedBundlesToMove:_,removes:d}}}function iCt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=H(t,n),o=H(t,r),s=rCt({base:t,folderRel:n,targetRootRel:r,mayCreate:i});if(s.kind===`not-permitted`)return{ok:!1,reason:`not-permitted`,roots:s.roots};if(s.kind===`absent`)return XU(V(a),{recursive:!0}),XU(o,{recursive:!0}),rW(U(V(a),o),a,`dir`),{ok:!0,moved:[],dropped:[],linked:[n]};if(s.kind===`not-linkable`)return{ok:!1,reason:`not-linkable`};if(s.kind===`stray-entries`)return{ok:!1,reason:`stray-entries`,strays:s.strays};if(s.kind===`conflicts`)return{ok:!1,reason:`conflicts`,conflicts:s.conflicts};let{toMove:c,toDrop:l,destLinks:u,linkedBundlesToMove:d}=s.plan,f=[];try{XU(o,{recursive:!0});let e=hc(o);for(let e of u)iW(H(o,e),{force:!0});for(let{name:t,target:n}of d){let r=H(o,t);rW(U(e,n),r,`dir`),iW(H(a,t),{force:!0}),f.push(t)}for(let e of c)ZU(H(a,e),H(o,e)),f.push(e);for(let e of l)iW(H(a,e),{recursive:!0,force:!0});iW(a,{recursive:!0,force:!0}),rW(U(V(a),o),a,`dir`)}catch(e){return{ok:!1,reason:`partial-move`,moved:f,error:e instanceof Error?e.message:String(e)}}return{ok:!0,moved:[...d.map(({name:e})=>e),...c],dropped:l,linked:[n]}}function aCt(e){let{base:t,folderRel:n}=e,r=new Set(e.exclude??[]),i=H(t,n),a;try{a=cc(i)}catch{return{ok:!1,reason:`not-linked`}}if(!a.isSymbolicLink())return{ok:!1,reason:`not-linked`};let o;try{o=hc(i)}catch{return iW(i,{force:!0}),XU(i,{recursive:!0}),{ok:!0,moved:[],dropped:[],linked:[]}}let{bundles:s}=tCt(o);iW(i,{force:!0}),XU(i,{recursive:!0});let c=hc(i),l=[];for(let e of s)r.has(e)||(rW(U(c,H(o,e)),H(i,e),`dir`),l.push(e));return{ok:!0,moved:[],dropped:[],linked:l}}const oCt=L({enabled:A(),active:A(),git:L({state:Ct([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:Ct([`open-knowledge`,`existing`]).optional()}),applied:A().optional(),reason:Ct([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),sCt=L({enabled:A()}).strict();function cCt(e){return(t,n)=>{let r=DSt({origin:t.headers.origin,contentType:t.headers[`content-type`]});return r.ok?!0:(r.reason===`origin`?X(n,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:e}):t$(n,e),!1)}}function lCt(e){let{contentDir:t,projectDir:n,skillsHome:r,homeDirOverride:i,savedThemeLockTimeoutMs:a,ephemeral:o,log:s,signalChannel:c,searchService:l,linkPreviewFetch:u,getLinkPreviewsEnabled:d,declaredGitHubHosts:f,resolveGitHubToken:p,githubReferenceFetch:m,getGeneratedIndexSettingsStatus:h,setGeneratedIndexEnabled:g}=e,_=Z(x,async(e,t)=>{try{let{entries:e,truncated:n}=KSt({homedirOverride:i});Q(t,200,dn,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list saved themes.`,{handler:`saved-themes-list`,cause:e})}},{handler:`saved-themes-list`,method:`GET`,skipBodyParse:!0}),v=Z(Nn,async(e,t,n)=>{try{let e=await ZSt({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-save`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`name-taken`){X(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}X(t,400,`urn:ok:error:theme-name-invalid`,`That name cannot be used as a theme id.`,{handler:`saved-theme-save`,detail:e.code});return}Q(t,201,rr,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),y=Z(x,async(e,t)=>{try{let n=sG(e).get(`id`)??``;if(n===``){X(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await $St({id:n,homedirOverride:i,lockTimeoutMs:a});if(!r.ok){if(r.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}X(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}Q(t,200,Sn,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to delete theme.`,{handler:`saved-theme-delete`,cause:e})}},{handler:`saved-theme-delete`,method:`DELETE`,skipBodyParse:!0}),b=D0({POST:v,PUT:Z(qe,async(e,t,n)=>{try{let e=await QSt({id:n.id,scheme:n.scheme,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-update`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`not-found`){X(t,404,`urn:ok:error:not-found`,`Saved theme not found.`,{handler:`saved-theme-update`});return}if(e.code===`ambiguous-id`||e.code===`unsafe-target`){X(t,409,`urn:ok:error:invalid-request`,e.code===`ambiguous-id`?`Multiple saved theme files claim that id.`:`The saved theme id conflicts with a file that cannot be safely updated.`,{handler:`saved-theme-update`,detail:e.code});return}X(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}Q(t,200,Ot,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to update theme.`,{handler:`saved-theme-update`,cause:e})}},{handler:`saved-theme-update`,method:`PUT`}),DELETE:y},{handler:`saved-theme`}),S=D0({GET:Z(x,async(e,i)=>{try{let e=l0(n??``),a=(e,t)=>{let n=Ect(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Q(i,200,jr,{targets:e,configured:!1,folders:[...n?wF(t,F1(t,`project`)).filter(e=>L1(t,`project`,e.root,r)).map(e=>({...TF(e),scope:`project`,...a(t,e)})):[],...wF(r,F1(r,`global`)).filter(e=>L1(r,`global`,e.root,r)).map(e=>({...TF(e),scope:`global`,...a(r,e)}))]},{handler:`skill-targets-get`})}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(ce,async(e,i,a)=>{try{{let e=a.folderAction,o=e.scope===`project`?t:r;if(e.scope===`project`&&!n){X(i,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let t=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),r=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(t===``||t.startsWith(`/`)||t.startsWith(`~`)||/^[A-Za-z]:/.test(t)||t.includes(`\0`)||r.length===0||r.some(e=>e===`..`)){X(i,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await Dct(o,r.join(`/`)),c?.(`files`),Q(i,200,ao,{targets:l0(n??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let s=new Set(F1(o,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),l=e.action===`link`?e.target??``:e.root;if(!s.has(e.root)||e.action===`link`&&(!s.has(l)||e.root===l)){X(i,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${l}`});return}let u=e=>{X(i,400,`urn:ok:error:invalid-request`,`That link would create a folder OpenKnowledge may not create on this machine: ${e.join(`, `)}.`,{handler:`skill-targets-put`,detail:e.join(`, `)})},d=t=>L1(o,e.scope,t,r)&&!(t===`.agents/skills`&&!G(H(o,t)));if(e.action===`link`&&e.preview){let t=rCt({base:o,folderRel:e.root,targetRootRel:l,mayCreate:d});if(t.kind===`not-permitted`){u(t.roots);return}let r=t.kind===`plan`?t.plan:null;Q(i,200,ao,{targets:l0(n??``),reprojected:[],bundleHosts:[],removedFrom:[],preview:{moves:r?[...r.linkedBundlesToMove.map(({name:e})=>e),...r.toMove]:[],drops:r?.toDrop??[],removes:r?.removes??[],replaces:r?.liveDestLinks??[],conflicts:t.kind===`conflicts`?t.conflicts:[],strays:t.kind===`stray-entries`?t.strays:[]}},{handler:`skill-targets-put`});return}let f=e.action===`link`?iCt({base:o,folderRel:e.root,targetRootRel:l,mayCreate:d}):aCt({base:o,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!f.ok&&f.reason===`not-permitted`){u(f.roots);return}if(!f.ok){X(i,409,`urn:ok:error:invalid-request`,f.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${f.conflicts.join(`, `)}. Resolve them first.`:f.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${f.strays.join(`, `)}.`:f.reason===`partial-move`?`The merge stopped partway (${f.moved.length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${f.error??``})`:f.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:f.reason});return}await Tct(o,e.root,e.action===`link`?{expect:`link`,target:l}:{expect:`own`}),c?.(`files`),Q(i,200,ao,{targets:l0(n??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:f.moved,dropped:f.dropped,linked:f.linked}},{handler:`skill-targets-put`});return}}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`});function C(e){return e===`navigation`||e===`relevance`?e:void 0}function w(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function T(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function E(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function D(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let O=D0({GET:Z(x,QQ(async(e,t)=>{let n=sG(e),r=n.get(`limit`),i=n.get(`query`)??``,a=w(n.get(`intent`)),o=C(n.get(`ranking`)),s=T(n.get(`scope`)??n.get(`scopes`)),c=E(n.get(`semantic`)),u=D(n.get(`source`)),d=r===null?void 0:Number(r);if(i.length>200){X(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}let f=await l.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:d,semanticParam:c,source:u});Q(t,200,te,f,{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:Z(Tr,QQ(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=w(n.intent),a=C(n.ranking),o=T(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=E(n.semantic),u=D(n.source);if(r.length>200){X(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}let d=await l.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:u});Q(t,200,te,d,{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),k=`link-preview`,A=new TSt({cacheDir:o?null:W(n??t,`.ok`,`local`,`link-previews`)}),j=null,M=()=>(j??=A.init(),j),N=u??vSt;async function P(e){let t=await N(e);return t.ok?{ok:!0,metadata:await CSt({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:N})}:{ok:!1,reason:t.reason}}let ee=()=>{try{return d?.()===!0}catch{return!1}},F=Z(Yt,async(e,t,n)=>{try{if(!ee()){s.debug({outcome:`disabled`},`[link-preview] request outcome`),Q(t,200,wre,{ok:!1,reason:`disabled`},{handler:k});return}await M();let e=!1,r=await A.load(n.url,()=>(e=!0,P(n.url)));A.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};s.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Q(t,200,wre,i,{handler:k})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:k,cause:e})}},{handler:k,method:`POST`,preBodyGate:cCt(k)}),ne=`github-reference`,re=new Pxt,ie=new Sxt;return XQ({"/api/search":O,"/api/link-preview":F,"/api/github-reference":Z(ln,async(e,t,n)=>{try{let r=ee()?Ixt(n.url,f):null;if(r===null){let e=ee()?`unsupported`:`disabled`;s.debug({outcome:e},`[github-reference] request outcome`),Q(t,200,Cr,{ok:!1,reason:e},{handler:ne});return}let i=Bxt(e),a=`${i?`signed-in`:`anonymous`} ${Lxt(r)}`,o=await re.load(a,async()=>Mxt({target:r,token:i?await p?.(r.host)??null:null,fetchFn:m,rateLimits:ie}));s.debug({outcome:o.ok?`ok`:o.reason},`[github-reference] request outcome`),Q(t,200,Cr,o,{handler:ne})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:ne,cause:e})}},{handler:ne,method:`POST`,preBodyGate:cCt(ne)}),"/api/skill-targets":S,"/api/saved-themes":_,"/api/saved-theme":b,"/api/generated-index/settings":D0({GET:Z(x,async(e,t)=>{if(!h){X(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}Q(t,200,oCt,h(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:Z(sCt,async(e,t,n)=>{if(!g){X(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}let r=await g(n.enabled);Q(t,200,oCt,r,{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`})},{mutating:[`/api/skill-targets`,`/api/saved-theme`,`/api/generated-index/settings`]})}const k8=q(`managed-rename`);function uCt(e){return qJ(e)}function A8(e){return W(uCt(e),`managed-rename.json`)}function dCt(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function fCt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function pCt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function mCt(e){return typeof e==`string`&&e.length>0}function hCt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function gCt(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,n=e.pathSnapshots,r=e.cleanupPaths,i=Array.isArray(n)&&n.length>0,a=Array.isArray(r)&&r.length>0;if(!Array.isArray(t)||!t.every(hCt)||t.length===0&&!i&&!a)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(fCt))throw Error(`Managed rename journal v2 has invalid snapshots`);if(n!==void 0&&(!Array.isArray(n)||!n.every(pCt)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(r!==void 0&&(!Array.isArray(r)||!r.every(mCt)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let n of t)if(!e.snapshots.some(e=>e.docName===n.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${n.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...i?{pathSnapshots:n}:{},...a?{cleanupPaths:r}:{}}}function _Ct(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(fCt))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function vCt(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return gCt(t);if(t.version===1)return _Ct(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function yCt(e){let t=A8(e);if(!G(t))return null;try{let e=K(t,`utf-8`);return vCt(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function bCt(e,t){let n=A8(e);XU(V(n),{recursive:!0});let r=`${n}.tmp`;JU(r,JSON.stringify(t,null,2),`utf-8`),ZU(r,n)}function xCt(e){iW(A8(e),{force:!0})}async function SCt(e,t,n){bCt(e,t);let r=await n();return xCt(e),r}function CCt(e){return[e.destinationDocName]}function wCt(e){return e.affectedDocs.map(e=>e.to)}function TCt(e,t){let n=W(e),r=W(n,t);if(t.includes(`\0`)||r===n||!r.startsWith(`${n}${Ys}`))throw Error(`Invalid recovery path: ${t}`);return r}function ECt(e,t){let n=W(t),r=`${n}${Ys}`,i=V(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=mc(i)}catch(e){k8.warn({path:i,err:e},`pruneEmptyAncestors: cannot read ${i}`);return}if(e.length>0)return;try{aW(i)}catch(e){k8.warn({path:i,err:e},`pruneEmptyAncestors: cannot rmdir ${i}`);return}i=V(i)}}function DCt(e,t=e){let n=yCt(t);if(!n)return{recovered:!1,journal:null,restoredDocNames:[]};let r=new Set,i=new Set,a=[];for(let t of n.snapshots)try{let n=GG(t.docName,e);XU(V(n),{recursive:!0}),JU(n,t.content,`utf-8`),r.add(t.docName)}catch(e){a.push({docName:t.docName,cause:e}),k8.warn({docName:t.docName,err:e},`Failed to restore ${t.docName}`)}if(a.length>0){let e=a.map(e=>e.docName).join(`, `);k8.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let t=a.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(n.version===2){let t=[];for(let r of n.pathSnapshots??[])try{let t=TCt(e,r.path);XU(V(t),{recursive:!0}),JU(t,r.content,`utf-8`),i.add(r.path)}catch(e){t.push({path:r.path,cause:e}),k8.warn({path:r.path,err:e},`Failed to restore path ${r.path}`)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);k8.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let n=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(n,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let o=n.version===2?wCt(n):CCt(n),s=[];for(let t of o){if(r.has(t))continue;let n=GG(t,e);try{iW(n,{force:!0}),ECt(n,e)}catch(e){G(n)&&k8.warn({destination:t},`Both source and destination files exist after partial recovery for ${t}`),k8.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination ${t}`),s.push({destination:t,cause:e})}}if(n.version===2)for(let t of n.cleanupPaths??[]){if(i.has(t))continue;let n=null;try{n=TCt(e,t),iW(n,{force:!0}),ECt(n,e)}catch(e){n&&G(n)&&k8.warn({destination:t},`Both source and destination paths exist after partial recovery for ${t}`),k8.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination path ${t}`),s.push({destination:t,cause:e})}}if(s.length>0){let e=s.map(e=>e.destination).join(`, `),t=s.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return xCt(t),{recovered:!0,journal:n,restoredDocNames:[...r].sort((e,t)=>e.localeCompare(t))}}const j8=q(`reconcile`),M8={ours:`Version here`,theirs:`Outside version`};function OCt(e,t){return e===`config`?t===`ours`?`outside-settings-applied`:`outside-settings-invalid`:`no-merge-engine`}const kCt={"external-change-both-kept":{created:XXe,failed:ZXe},"external-change-kept-live":{created:XXe,failed:ZXe},"external-change-no-engine":{created:hQe,failed:gQe}};function ACt(e){let t=e.writeCheckpoint??VJ,n=(n,r)=>t(n,e.contentRoot,r).then(e=>(kCt[r.kind].created(),j8.info({docName:r.docName,kind:r.kind,side:r.metadata.side,sha:e},`[reconcile] history entry saved (${r.kind}, ${r.metadata.side}): ${r.docName}`),e),e=>(kCt[r.kind].failed(),j8.error({err:e,docName:r.docName,kind:r.kind,side:r.metadata.side},`[reconcile] history entry write failed (${r.kind}, ${r.metadata.side}): ${r.docName}`),null)),r=(e,t)=>{QXe(),j8.info({docName:e,kind:t},`[reconcile] history entry not saved for ${e} (${t}): the shadow repo is unavailable`)},i=async(t,i,a)=>{let o=e.getShadow();return o?n(o,{kind:`external-change-no-engine`,docName:t,contents:i.bytes,label:`${M8[i.side]} moved to history (no merge for ${a}) @ ${new Date().toISOString()}`,branch:e.getBranch()??`main`,metadata:{side:i.side,fileType:a}}):(r(t,`external-change-no-engine`),null)},a=(t,n,r,i)=>{e.notices?.record(t,e.getBranch()??`main`,{kind:`moved-to-backup`,side:n,reason:r,backup:i.display})};return{bothKept(t,i,a){let o=tY(a),s=e.getBranch()??`main`,c=e.notices?.record(t,s,{kind:`both-kept`,kept:o})??null,l=e.getShadow();if(!l){r(t,`external-change-both-kept`);return}let u=new Date().toISOString();for(let r of[`ours`,`theirs`]){let a={kind:`external-change-both-kept`,docName:t,contents:i[r],label:`${M8[r]} before both versions were kept @ ${u}`,branch:s,metadata:{side:r,keptBlocks:o.duplicated}};queueMicrotask(()=>{n(l,a).then(n=>{n!==null&&c!==null&&e.notices?.attachEntry(t,c,n)})})}},async keptLive(t,i,a){let o=e.getShadow();if(!o)return r(t,`external-change-kept-live`),!1;let s=e.getBranch()??`main`,c=await n(o,{kind:`external-change-kept-live`,docName:t,contents:i.bytes,label:`${M8[i.side]} moved to history (${a}) @ ${new Date().toISOString()}`,branch:s,metadata:{side:i.side,reason:a}});return c!==null&&(e.notices?.record(t,s,{kind:`moved-to-history`,side:i.side,reason:a,entry:c}),!0)},saveNoEngine:i,noticeNoEngine:(t,n,r,i)=>{let o=OCt(r,n);if(i.where===`backup`){a(t,n,o,i.backup);return}e.notices?.record(t,e.getBranch()??`main`,{kind:`moved-to-history`,side:n,reason:o,entry:i.entry})},noticeBackup:a,noticeHeld(t,n){e.notices?.record(t,e.getBranch()??`main`,{kind:`save-held`,cause:n})},clearHeld(t){e.notices?.withdrawHeld(t,e.getBranch()??`main`)}}}async function jCt(e,t,n,r,i,a,o){let s=e===null?null:await e.saveNoEngine(r,i,a);if(s!==null)return{where:`history`,entry:s};let c=await Tgt(t,n,r,i.bytes,o);return c===null?null:{where:`backup`,backup:c}}function N8(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function P8(e){for(let{from:t,to:n,toFile:r}of e.moves)t!==n&&e.notices?.rename(t,n,e.branch,r);let t=e.shadow;if(!t)return 0;let n=e.moves.filter(({from:e,to:t})=>UH(e)!==UH(t));if(n.length===0)return 0;let r=zc(),i=new Date().toISOString(),a=N$(t.gitDir);for(let{from:o,to:s}of n)Lat(t.gitDir,{v:1,from:o,to:s,at:i,commitSha:``,branch:e.branch,groupId:r,kind:e.kind,actor:{writerId:e.writer.writerId,displayName:e.writer.displayName},...e.anchors&&e.anchors.length>0?{anchors:[...e.anchors]}:{}},a,t),c$(s,e.writer.writerId,e.writer.displayName,e.writer.colorSeed,ove(o,s),e.writer.actor,void 0,[{from:o,to:s}]);return n.length}function MCt(e,t){let n=lre.has(e);return{disposition:t.has(e)||n?`inline`:`attachment`,csp:e===`svg`?`sandbox; default-src 'none'; style-src 'unsafe-inline'`:n?Kee:null,sandboxedHtml:n}}Object.assign(bI,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`});function NCt(e){return bI[Ws(e).slice(1).toLowerCase()]??null}function PCt(e){return NCt(e)!==null&&ia.has(Ws(e).slice(1).toLowerCase())}const FCt=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function ICt(e,t,n){let r=t.trim();return r===``||r===`./`?W(n,V(e)):r===`/`?n:r.startsWith(`./`)?W(n,V(e),r.slice(2)):W(n,r)}function LCt(e,t){let n=dc(e,`r`);try{let e=Buffer.alloc(t),r=pc(n,e,0,t,0);return e.subarray(0,r)}finally{rc(n)}}const F8=1e3;async function RCt(e){let t=Rc(`sha256`);return await Wc(ac(e),t),t.digest(`hex`)}async function zCt(e,t,n){let r;try{r=await Mc(e)}catch{return null}let i=q(`upload`),a=0;for(let o of r){let r=Ws(o).slice(1).toLowerCase();if(!ia.has(r))continue;let s=W(e,o),c;try{c=await Fc(s)}catch{continue}if(!c.isFile()||c.size!==n)continue;if(a++,a>F8)return i.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:F8,expectedSize:n},`[upload-dedup] candidate scan exceeded ${F8} same-size siblings — degrading to no-dedup for this upload`),null;let l;try{l=await RCt(s)}catch(e){let t=cG(e);t!==`ENOENT`&&i.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:o},`[upload-dedup] skipped candidate — read failed`);continue}if(l===t)return o}return null}function BCt(e){function t(t){let n=hc(e.contentDir),r=W(n,t),i;try{i=hc(r),e.assertContentPath?.(i)}catch(e){return{ok:!1,reason:`not-found`,cause:e}}if(!KG(i,n))return{ok:!1,reason:`invalid-path`};let a;try{a=yc(i)}catch(e){return{ok:!1,reason:`not-found`,cause:e}}if(!a.isFile())return{ok:!1,reason:`not-found`};let o=fmt(n,i);return o===t.split(`\\`).join(`/`)?{ok:!0,canonicalPath:i,relativePath:o,size:a.size}:{ok:!1,reason:`invalid-path`}}function n(n){let r=t(n);if(r.ok||r.reason!==`not-found`)return r;let i=n.split(`\\`).join(`/`),a=e.resolveTrackedFile?.(i);if(a===void 0||a===i||e.isPathIgnored?.(a))return r;let o=t(a);return o.ok?o:r}async function r(t){let{tempPath:n,sha:r,byteLength:i,filename:a,parentDocName:o,placement:s}=t,c=()=>{if(G(n))try{bc(n)}catch{}},l=W(e.contentDir),u;try{u=s===`parent-dir`?`./`:e.getAttachmentFolderPath?.()??`./`}catch(e){return c(),{ok:!1,kind:`config-error`,cause:e}}if(!mt(u))return c(),{ok:!1,kind:`invalid-attachment-folder`};let d=ICt(o,ni(u),l);if(!KG(d,l))return c(),{ok:!1,kind:`path-escape`};try{jK(d,l),e.assertContentPath?.(d)}catch(e){return c(),PK(e)?{ok:!1,kind:`path-escape`}:{ok:!1,kind:`dest-validation-error`,cause:e,destDir:d}}if(H2(FK(d,l,q(`upload`))))return c(),{ok:!1,kind:`reserved-destination`,destDir:d};try{XU(d,{recursive:!0})}catch(e){if(!IK(e))return c(),{ok:!1,kind:`mkdir-failed`,reason:G4(e),cause:e}}try{let t=hc(d);e.assertContentPath?.(t);let n;try{n=hc(l)}catch{n=l}if(!KG(t,n))return c(),{ok:!1,kind:`path-escape`};if(H2(lG(U(n,t))))return c(),{ok:!1,kind:`reserved-destination`,destDir:d}}catch(e){if(cG(e)!==`ENOENT`)return c(),{ok:!1,kind:`path-escape`,cause:e}}let f=LCt(n,4100),p=await ORe(f),m=p?.mime,h=p?.ext;if(!m){let e=f.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(m=`image/svg+xml`,h=`svg`)}{let t=await zCt(d,r,i);if(t){try{e.assertContentPath?.(W(d,t))}catch(e){return c(),{ok:!1,kind:`dest-validation-error`,cause:e,destDir:d}}return c(),{ok:!0,src:t,path:lG(U(e.contentDir,W(d,t))),deduped:!0,mime:m??null}}}let g;if(!a||a===`upload`||FCt.test(a)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=a?Ws(a).slice(1):``,n=h??t??``;g=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else g=nlt(a);try{e.assertContentPath?.(W(d,g));let t=kmt(n,d,g);return{ok:!0,src:t,path:lG(U(e.contentDir,W(d,t))),deduped:!1,mime:m??null}}catch(e){return c(),{ok:!1,kind:`write-failed`,reason:e instanceof U4?e.reason:`urn:ok:error:storage-error`,cause:e,filename:g}}}return{resolveServableAsset(t){if(!t||t.includes(`\0`))return{ok:!1,reason:`missing-path`};if(!PCt(t))return{ok:!1,reason:`unsupported-type`};let r=n(t);if(!r.ok)return r;if(e.isPathIgnored?.(r.relativePath))return{ok:!1,reason:`not-found`};let i=NCt(r.relativePath),a=Ws(r.relativePath).slice(1).toLowerCase();return!i||!ia.has(a)?{ok:!1,reason:`unsupported-type`}:{ok:!0,asset:{canonicalPath:r.canonicalPath,relativePath:r.relativePath,size:r.size,contentType:i,...MCt(a,Ba)}}},resolveTextAsset(e){if(!e||e.includes(`\0`))return{ok:!1,reason:`missing-path`};let t=n(e);return t.ok?{ok:!0,canonicalPath:t.canonicalPath,size:t.size}:t},storeUpload:r}}const I8=q(`search`);let VCt=null;function L8(){return VCt||=PU().createCounter(`ok.search.corpus_update_total`,{description:`Count of workspace search corpus builds, by mode (cold | incremental | rebuild) and, for rebuilds, the bounded fallback reason.`}),VCt}let HCt=null;function UCt(){return HCt||=PU().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of corpus builds whose name-only file tier was truncated at OK_SEARCH_MAX_ENTRIES.`}),HCt}const R8=new Map;function WCt(e){let t=new Map;for(let n of e){let e=n.path.split(`/`).filter(Boolean);e.pop();for(let r=1;r<=e.length;r++){let i=e.slice(0,r).join(`/`);t.set(i,Math.max(t.get(i)??0,n.modifiedTs))}}return[...t.entries()].map(([e,t])=>ne({kind:`folder`,path:e,modifiedTs:t}))}function GCt(e,t){let n=t.trim().toLowerCase();if(!n||!e)return;let r=e.toLowerCase().indexOf(n);if(r<0)return;let i=Math.max(0,r-80),a=Math.min(e.length,r+n.length+120),o=i>0?`…`:``,s=a<e.length?`…`:``;return`${o}${e.slice(i,a).replace(/\s+/g,` `).trim()}${s}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function KCt(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?GCt(e.document.content,t):void 0}}function qCt(e,t,n){let{resolved:r,members:i}=lX(e,t,n),a=i.filter(e=>e.role===`symlink`).map(e=>e.path).join(`\0`),o=r?i.map(e=>e.path).toSorted().join(`\0`):``;return`${n.modified}\0${n.size}\0${n.canonicalPath}\0${n.inode}\0${a}\0${o}`}function JCt(e,t,n){return lX(e,t,n).members.map(e=>e.path)}function YCt(e){let{contentDir:t,projectDir:n,getAllFilesIndex:r,getFileIndexGeneration:i,semanticSearch:a,getSemanticSimilarityFloor:o,ready:s}=e;async function c(e,t,n,r){let i=r.documents.filter(e=>!Nne(e.path)),s=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!a?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:s,capable:!1};a.embedCorpus(i);let c,l=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await a.queryScores(e,i);if(l=performance.now()-t,n&&n.size>0){let e=o?.();c=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let u=a.getStatus(),d=(Mne(u,`query`)?ere(u):null)??(u.ready?u.capable?u.embeddedCount===0?`warming`:e.trim().length<3?`query_too_short`:`no_match`:`incapable`:`warming`);return{input:c,status:{capable:u.capable,applied:!1,outcome:d,providerErrorReason:u.providerErrorReason,coverage:{embedded:u.embeddedCount,total:s}},queryEmbedMs:l,pageTotal:s,capable:u.capable}}function l(){let n=[],r=new Set;for(let e of U1(t)){let i=W(t,e.dir,`SKILL.md`);try{let t=yc(i);n.push({name:e.name,absolutePath:i,docPath:`${e.dir}/SKILL`,mtimeMs:t.mtimeMs,size:t.size}),r.add(e.name)}catch{}}let i=e.getProjectSkillsRoot();if(!G(i))return n;let a;try{a=mc(i,{withFileTypes:!0})}catch{return n}for(let e of a.sort((e,t)=>e.name.localeCompare(t.name))){if(!e.isDirectory()||!Ce.test(e.name)||r.has(e.name))continue;let t=W(i,e.name,`SKILL.md`);try{let r=yc(t);n.push({name:e.name,absolutePath:t,docPath:`${y}/${e.name}/SKILL`,mtimeMs:r.mtimeMs,size:r.size})}catch{}}return n}function u(){let t=[];for(let n of l()){let r=n.name,i=``;try{let{frontmatter:t,body:a}=e.parseFrontmatterDoc(K(n.absolutePath,`utf-8`));typeof t.name==`string`&&t.name&&(r=t.name),i=`${typeof t.description==`string`?t.description:``}\n\n${a}`.trim()}catch{}t.push(ne({kind:`page`,path:n.docPath,title:r,content:i,modifiedTs:n.mtimeMs}))}return t}let d=new Map;async function f(){let n=[],i=[],a=new Set;for(let[e,o]of r()){if(_U(e)||vU(e)||di(e)?.kind===`skill`||e.startsWith(`.ok/skills/`))continue;if(o.kind===`file`){i.push(ne({kind:`file`,path:e,modifiedTs:Date.parse(o.modified),aliases:JCt(t,e,o)}));continue}a.add(e);let r=qCt(t,e,o),s=d.get(e);if(s&&s.key===r){n.push(s.doc);continue}let c=``,l=e,u=!1;try{c=await jc(o.canonicalPath,`utf-8`)}catch(t){u=!0,I8.warn({docName:e,err:t},`[search] Failed to read ${e}`)}if(!u)try{l=JY(c,e)}catch(t){I8.warn({docName:e,err:t},`[search] Failed to extract title for ${e}`)}let f=ne({kind:`page`,path:e,title:l,content:c,modifiedTs:Date.parse(o.modified),aliases:JCt(t,e,o)});u||d.set(e,{key:r,doc:f}),n.push(f)}for(let e of d.keys())a.has(e)||d.delete(e);let o=e.getSearchMaxEntries(),s=i,c=!1;return i.length>o&&(c=!0,s=[...i].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,o),I8.warn({dropped:i.length-s.length,retained:s.length,limit:o},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),UCt().add(1)),{documents:[...n,...u(),...s,...WCt([...n,...s])],truncated:c}}function p(){return l().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function m(){return i?`gen:${i()}|skills${p()}`:`${[...r()].filter(([e])=>!_U(e)&&!vU(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>`${e}\0${qCt(t,e,n)}`).join(``)}|skills${p()}`}let h=s===void 0;s?.then(()=>{h=!0},e=>{h=!0,I8.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function g(){return!h}async function _(){let e=`${t} ${n??``}`,r=m(),i=R8.get(e);if(i?.fingerprint===r&&i.corpus)return{corpus:i.corpus,truncated:i.truncated??!1};if(i?.fingerprint===r&&i.pending)return i.pending;let a=i?.corpus,o=i?.pending,s=(async()=>{let e=o?await o.then(e=>e.corpus,()=>void 0):a,{documents:t,truncated:n}=await f();if(!e)return L8().add(1,{mode:`cold`}),{corpus:Iie(t),truncated:n};let r=yt(e,t);if(r.rebuilt){L8().add(1,{mode:`rebuild`,reason:r.rebuildReason});let e=r.rebuildReason===`mutation-failed`?`warn`:`debug`;I8[e]({reason:r.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else L8().add(1,{mode:`incremental`}),I8.debug({inserted:r.inserted,updated:r.updated,removed:r.removed},`[search] corpus updated incrementally`);return{corpus:r.corpus,truncated:n}})();R8.set(e,{fingerprint:r,pending:s});try{let t=await s;return R8.get(e)?.pending===s&&R8.set(e,{fingerprint:r,corpus:t.corpus,truncated:t.truncated}),t}catch(t){throw R8.get(e)?.pending===s&&R8.delete(e),t}}return{async buildSearchResponse(e){let t=performance.now();if(g())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _(),i=await c(e.query,e.intent,e.semanticParam,n),a=vi(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>KCt(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0,r=n?`applied`:i.status.outcome;o={...i.status,applied:n,outcome:r},Zft({outcome:r,source:e.source,capable:i.capable,embedded:i.status.coverage.embedded,total:i.pageTotal,queryEmbedMs:i.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:a,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...o?{semantic:o}:{},...r?{truncated:!0}:{}}},prewarm(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_().catch(e=>{I8.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}}}const z8=q(`skill-install`);function XCt(e){let t=t=>t===`project`?U1(e.contentDir):W1(e.skillsHome);return{resolveFork(n){let{scope:r,name:i,fork:a,inPlaceEntry:o}=n,s=r===`project`?e.contentDir:e.skillsHome,c=[],l=r===`project`?Ur:je,u=a.editor===`agents`?ki:l[a.editor]??null;if(u===null)return{ok:!1,kind:`unknown-editor`,editor:a.editor};let d=W(s,u,i),f=W(s,o.dir),p=XM(d);if(p===null||d===f)return{ok:!1,kind:`fork-absent`};if(p.contentHash===o.contentHash)return{ok:!1,kind:`not-a-fork`};let m=new Date().toISOString().replace(/[:.]/g,`-`),h=(t,n)=>{try{let r=W(sS(e.skillsHome),`edit-backups`,`forks`,`${i}-${n}-${m}`);XU(W(r,`..`),{recursive:!0}),QU(t,r,{recursive:!0})}catch(e){z8.warn({name:i,err:e},`[skill-fork] stash failed`)}};if(a.action===`align`)h(d,a.editor),iW(d,{recursive:!0,force:!0}),y0({canonicalAbs:f,canonicalHash:o.contentHash,canonicalRootRel:V(o.dir),name:i,cwd:s,targets:[a.editor].filter(Li),roots:u0(r)});else if(a.action===`make-source`){let e=o.hosts.filter(Li);h(f,`source`),S0({canonicalAbs:f,canonicalHash:o.contentHash,name:i,cwd:s,targets:e,roots:u0(r)}),iW(f,{recursive:!0,force:!0});let n=t(r).find(e=>e.name===i);n&&y0({canonicalAbs:W(s,n.dir),canonicalHash:n.contentHash,canonicalRootRel:V(n.dir),name:i,cwd:s,targets:e,roots:u0(r)})}else{let e=a.toName;if(!Ce.test(e))return{ok:!1,kind:`invalid-new-name`,toName:e};if(t(r).some(t=>t.name===e))return{ok:!1,kind:`name-taken`,toName:e};let n=W(s,u,e);ZU(d,n);let i=x1({skillDir:n,toName:e});i.ok||(i.stage===`patch`?(z8.warn({name:e,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),c.push(`Renamed the folder to "${e}", but its SKILL.md still declares the old name — edit the frontmatter to match.`)):(z8.warn({name:e,err:i.cause},`[skill-fork] frontmatter rename failed`),c.push(`Renamed the folder to "${e}", but its SKILL.md could not be updated — edit the frontmatter to match.`)))}return{ok:!0,warnings:c}},async applyAddRemove(t){let{scope:n,name:r,inPlaceEntry:i}=t,a=n===`project`?e.contentDir:e.skillsHome,o=[],s=[],c=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),l=i.hosts[0];if(l!==void 0&&(t.remove??[]).some(e=>c(e)===l))return{ok:!1,kind:`remove-source`,sourceId:l};let u=new Set(i.hosts.filter(e=>Li(e)));for(let e of t.add??[])Li(e)?u.add(e):o.push(c(e));let d=P1(a,n),f=[],p=[];for(let e of t.add??[])if(Li(e)&&d[e]!==void 0&&!G(W(a,d[e],r,`SKILL.md`))){let t=e===`agents`?ki:u0(n)[e]??null;t!==null&&p.push(t)}for(let e of t.remove??[])if(Li(e)){if(!u.has(e)&&d[e]!==void 0&&G(W(a,d[e],r,`SKILL.md`))){let t=e===`agents`?ki:u0(n)[e]??null;t!==null&&f.push(t)}u.delete(e)}else s.push(c(e));for(let{subRoot:e,exclude:t}of[...p.map(e=>({subRoot:e,exclude:void 0})),...f.map(e=>({subRoot:e,exclude:[r]}))]){let n=aCt({base:a,folderRel:e,...t===void 0?{}:{exclude:t}});if(n.ok&&await Tct(a,e,{expect:`own`}),!n.ok)return{ok:!1,kind:`unfollow-failed`,subRoot:e,reason:n.reason}}return{ok:!0,targets:[...u],rootAdds:o,rootRemoves:s}},async promoteStoreBackedSource(n){let{scope:r,name:i,base:a,skillDir:o,newSource:s}=n,c=r===`project`?e.contentDir:e.skillsHome,l=b0({canonicalAbs:o,canonicalHash:XM(o)?.contentHash??``,name:i,cwd:c,newTarget:s,roots:u0(r)});if(!l.ok)return{ok:!1,kind:`source-occupied`,reason:l.reason};await Z1(a,i),await r0(c,i,s);let u=t(r).find(e=>e.name===i);return{ok:!0,hosts:u?[...u.hosts]:[],sourceMovedTo:U(c,l.newAbs).split(Ys).join(`/`)}},async promoteInPlaceSource(n){let{scope:r,name:i,base:a,prefBase:o,skillDir:s,inPlaceEntry:c,newSource:l}=n,u=r===`project`?e.contentDir:e.skillsHome,d=o??a,f=c.hosts[0],p=Li(l),m;if(!p){let e=l.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),t=n0(e),n=W(a,e,i);if(e===``||t||!n.startsWith(W(a)+Ys))return{ok:!1,kind:`invalid-target`,target:l};m=n}let h;if(f!==void 0&&l!==f){let t=U(u,W(s)).split(Ys).join(`/`),n=b0({canonicalAbs:s,canonicalHash:c.contentHash,name:i,cwd:a,newTarget:p?l:`agents`,...m===void 0?{}:{destDirAbs:m},leaveLinkBehind:!0,roots:u0(r)});if(!n.ok)return{ok:!1,kind:`source-occupied`,reason:n.reason};h=U(u,n.newAbs).split(Ys).join(`/`);let o=W(u,t);if(e.effectiveInstallMode(r,i,{hosts:c.hosts,linkedHosts:c.linkedHosts??[]})===`copy`)try{cc(o).isSymbolicLink()&&(iW(o,{recursive:!0,force:!0}),QU(n.newAbs,o,{recursive:!0,dereference:!0}))}catch{}let f=!1;try{f=cc(o).isSymbolicLink()}catch{f=!0}await a0(d,i,f?{path:t,mode:`link`}:{path:t,mode:`copy`,hash:c.contentHash});let g=new Set(Hct(a,i,u0(r)).map(e=>W(e)));x0({name:i,cwd:a,roots:u0(r),target:n.newAbs,slots:(i0(d)[i]??[]).map(e=>W(d,e.path)).filter(e=>!g.has(e)),skip:[n.newAbs,W(s)],alsoClaim:[W(s),n.newAbs]}),await a0(d,i,{path:h,mode:`copy`}),await r0(d,i,l)}let g=t(r).find(e=>e.name===i);return{ok:!0,hosts:g?[...g.hosts]:[...c.hosts],...h===void 0?{}:{sourceMovedTo:h}}},async fanOutInPlace(n){let{scope:r,name:i,base:a,prefBase:o,inPlaceEntry:s,inPlaceTargets:c}=n,l=r===`project`?e.contentDir:e.skillsHome,u=o??a,{skillDir:d}=n,f=[],p=[],m=s.hosts.filter(e=>Li(e)),h=s.hosts[0],g;if(n.setExact&&h!==void 0&&!h.includes(`/`)&&c.length>0&&!c.includes(h)){let e=c[0],t=b0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,newTarget:e,roots:u0(r)});if(!t.ok)return{ok:!1,kind:`source-occupied`,reason:t.reason};d=t.newAbs,g=U(l,t.newAbs).split(Ys).join(`/`),await a0(u,i,{path:g,mode:`copy`}),await r0(u,i,e)}let _=g?g.split(`/`).slice(0,-1).join(`/`):n.canonicalRootRel;S0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,targets:n.setExact?m.filter(e=>!c.includes(e)):[],roots:u0(r)});let v=y0({canonicalAbs:d,canonicalHash:s.contentHash,canonicalRootRel:_,name:i,cwd:a,targets:c,mode:n.installMode,convertLinks:n.linkModeReq===!1,convertCopies:n.linkModeReq===!0,roots:u0(r)}),y=new Set(v.linkFallbacks);for(let e of v.conflicted)f.push(`A different skill named "${i}" already exists in the ${e} skills folder — left untouched.`),p.push(`name-conflict`);if(n.linkModeReq!==void 0&&o&&n.rootAdds.length>0){let e=new Set((i0(o)[i]??[]).map(e=>e.path));for(let t of n.rootAdds){if(!e.has(`${t}/${i}`))continue;let r=W(o,t,i);if(r===W(d))continue;let a=v0(r,W(d),s.contentHash);n.linkModeReq===!0&&a===`same-copy`?(iW(r,{recursive:!0,force:!0}),h0(U(V(r),W(d)),r,W(d))===`copy`&&y.add(t)):n.linkModeReq===!1&&a===`link-to-canonical`&&(iW(r,{recursive:!0,force:!0}),QU(W(d),r,{recursive:!0,dereference:!0}))}}for(let e of v.hosts){let t=e===`agents`?ki:u0(r)[e];if(t===null||t===n.canonicalRootRel)continue;let o=W(a,t,i),c=!1;try{c=cc(o).isSymbolicLink()}catch{continue}if(c){n.installMode===`link`&&await a0(u,i,{path:`${t}/${i}`,mode:`link`});continue}let l=G(H(o,`SKILL.md`))?XM(o)?.contentHash:void 0;l!==void 0&&l===s.contentHash&&await a0(u,i,{path:`${t}/${i}`,mode:`copy`,hash:l})}if((n.rootAdds.length>0||n.rootRemoves.length>0)&&o){let e=W(d);for(let t of n.rootAdds){let r=n0(t),a=W(o,t),c=l1(o,`${t}/${i}`);if(t===``||r||c===null||c===e){f.push(`"${t}" is not a placeable custom root — skipped.`),p.push(`place-path-invalid`);continue}let l=v0(c,e,s.contentHash);if(l===`different`){f.push(`A different "${i}" already exists at ${t} — left untouched.`),p.push(`name-conflict`);continue}l===`absent`&&(XU(a,{recursive:!0}),n.installMode===`link`?h0(U(a,e),c,e)===`copy`&&y.add(t):QU(e,c,{recursive:!0,dereference:!0}));let u=cc(c).isSymbolicLink()?`link`:`copy`;await a0(o,i,{path:`${t}/${i}`,mode:u,...u===`copy`?{hash:s.contentHash}:{}})}for(let t of n.rootRemoves){let n=`${t}/${i}`,r=i0(o)[i]?.find(e=>e.path===n),a=l1(o,n);if(a===null){f.push(`"${t}" is not a placeable custom root — skipped.`),p.push(`place-path-invalid`);continue}let c=v0(a,e,s.contentHash);if(c===`different`){f.push(`The copy at ${n} differs from the current source and was preserved. Inspect both versions before removing it.`),p.push(`place-fork-refused`);continue}c!==`absent`&&c!==`canonical-dir`&&iW(a,{recursive:!0,force:!0}),r&&await kct(o,i,n)}}y.size>0&&(f.push(zct([...y])),p.push(`links-not-permitted`));let b=t(r).find(e=>e.name===i);return{ok:!0,hosts:b?[...b.hosts]:v.hosts,warnings:f,warningCodes:p,...g===void 0?{}:{sourceMovedTo:g}}}}}function ZCt(){return{async place(e){let t=e.rawDir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),n=W(e.placeBase,t),r=`${t}/${e.name}`,i=l1(e.placeBase,r),a=W(e.placeBase),o=n0(t);if(t===``||i===null||!i.startsWith(a+Ys)||o)return{ok:!1,kind:`invalid-path`};if(i===W(e.skillDir))return{ok:!0,alreadyAtSource:!0,placedAt:r};if(G(i))return{ok:!1,kind:`dest-exists`};XU(n,{recursive:!0});let s=e.mode;return e.mode===`link`?s=h0(U(n,W(e.skillDir)),i,W(e.skillDir)):QU(e.skillDir,i,{recursive:!0,dereference:!0}),await a0(e.placeBase,e.name,{path:r,mode:s,...s===`copy`?{hash:XM(e.skillDir)?.contentHash}:{}}),{ok:!0,placedAt:r,...e.mode===`link`&&s===`copy`?{copiedInsteadOfLinked:!0}:{}}},async unplace(e){let t=e.rawPath.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!i0(e.placeBase)[e.name]?.find(e=>e.path===t))return{ok:!1,kind:`not-recorded`,path:t};let n=l1(e.placeBase,t);if(n===null)return{ok:!1,kind:`unsafe-path`};let r=XM(e.skillDir)?.contentHash??``;switch(v0(n,W(e.skillDir),r)){case`different`:return{ok:!1,kind:`forked`,path:t};case`canonical-dir`:return{ok:!1,kind:`canonical-dir`,path:t};case`absent`:break;default:iW(n,{recursive:!0,force:!0})}return await kct(e.placeBase,e.name,t),{ok:!0}},async convert(e){let t=u0(e.scope),n=Li(e.target)?e.target===`agents`?ki:t[e.target]:e.target.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),r=n===null||n===``?null:l1(e.ledgerBase,`${n}/${e.name}`);if(n===null||n===``||r===null)return{ok:!1,kind:`invalid-location`};let i=W(e.skillDir),a=v0(r,i,e.canonicalHash);if(a===`canonical-dir`)return{ok:!1,kind:`canonical-dir`};if(a===`different`)return{ok:!1,kind:`forked`};if(a===`absent`)return{ok:!1,kind:`not-installed`};if(!(e.mode===`link`&&a===`link-to-canonical`||e.mode===`copy`&&a===`same-copy`)){let t=V(r);if(iW(r,{recursive:!0,force:!0}),XU(t,{recursive:!0}),e.mode===`link`){if(h0(U(t,i),r,i)===`copy`)return{ok:!1,kind:`links-not-permitted`}}else QU(i,r,{recursive:!0,dereference:!0})}return await a0(e.ledgerBase,e.name,{path:`${n}/${e.name}`,mode:e.mode,...e.mode===`copy`?{hash:e.canonicalHash}:{}}),{ok:!0}}}}const B8=q(`write-advisory`);let QCt=null;function $Ct(){return QCt||=PU().createCounter(`ok.write_advisory.deferred`,{description:`Post-write advisories that depend on the derived document index and were omitted from a write response: reason=deadline when the index did not answer within the write-advisory deadline, reason=busy when an earlier advisory was still waiting past its deadline so this one was not started. The write itself was durable either way.`,unit:`{advisory}`}),QCt}const ewt=Symbol(`write-advisory-deadline`);function twt(e={}){let t=e.deadlineMs??1500,n=0,r=0,i,a=0,o=0,s=0,c,l,u=()=>{let e=Date.now();c=e;let l=n>0,u={closings:a,busySkipped:o,closedMs:l?s+e-r:s};a=0,o=0,s=0,r=e,l?B8.warn({advisory:i,deadlineMs:t,...u},`[write-advisory] document index did not answer within the write-advisory deadline; skipping index-backed write advisories until it catches up`):B8.info(u,`[write-advisory] document index caught up; index-backed write advisories resumed`)},d=()=>{if(l!==void 0)return;let e=Date.now(),t=c===void 0?e:c+6e4;if(e>=t){u();return}l=setTimeout(()=>{l=void 0,u()},t-e),l.unref()},f=e=>{n+=1,!(n>1)&&(r=Date.now(),i=e,a+=1,d())},p=()=>{--n,!(n>0)&&(s+=Date.now()-r,d())},m=(e,t,n)=>($Ct().add(1,{advisory:e,reason:t}),n());return{async run(e,r,i){if(n>0)return o+=1,m(e,`busy`,i);let a=!1,s=!1,c=Promise.resolve().then(r),l=()=>{a=!0,s&&p()};c.then(l,l);let u,d=new Promise(e=>{u=setTimeout(()=>e(ewt),t)});try{let t=await Promise.race([c,d]);return t===ewt?(a||(s=!0,f(e)),c.catch(t=>{B8.warn({err:t,advisory:e},`[write-advisory] deferred advisory failed after its deadline`)}),m(e,`deadline`,i)):t}finally{clearTimeout(u)}}}}function nwt(e,t){let{reason:n,targetKind:r}=t,i=e.fileExists!==null&&e.fileExcluded!==null;switch(n){case`no-such-doc`:return e.folderExists!==null&&(!t.mayNameFile||i);case`no-such-file`:return i&&(!t.wikiAsset||e.resolveWikiFile!==null);case`excluded`:return i;case`unresolvable`:return r!==`file`||e.fileExists!==null;default:return n}}function rwt(e,t,n,r){let i=r.fileExists??void 0,a=r.fileExcluded??void 0,{folderExists:o,resolveWikiFile:s,resolveFileByBasename:c}=r,l=Ji(`document`,n),u=Ja(Ea(`folder`),l),d=e=>u.resolve(e)??(o?.(e)===!0?e:void 0),f=e=>d(e)!==void 0,p=Iut(e,t,{resolveDocument:e=>l.resolve(e),resolveFile:e=>i?.(e)?e:void 0,resolveFileByBasename:c,...a?{isExcludedFile:a}:{},...s?{resolveWikiFile:s}:{},resolveTolerantDocument:r2(l),resolveFolder:d}),m=new Set(p.filter(({occurrence:e})=>e.sourceForm===`markdown-inline`&&e.role===`link`).map(({occurrence:e})=>e.href)),h=bdt(e,t,l,i,f,a).filter(e=>e.sourceForm===`jsx`||e.href.startsWith(`[[`)||m.has(e.href)),g=new Set(h.map(e=>e.href)),_=h.filter(e=>nwt(r,{reason:e.reason,targetKind:null,wikiAsset:!1,mayNameFile:e.sourceForm!==`jsx`&&!e.href.startsWith(`[[`)})),v=new Set;for(let e of p){if(e.reason===null||!nwt(r,{reason:e.reason,targetKind:e.targetKind,wikiAsset:s2(e.occurrence)!==null,mayNameFile:!c2(e.occurrence.sourceForm)}))continue;let{href:t,role:n,sourceForm:i,range:a,reference:o}=e.occurrence;if(n===`link`&&i===`markdown-inline`&&g.has(t))continue;let s=Lut(e,e.reason);if(s===null)continue;let c=o?.definition.repairRange??a,l=`${c.start}:${c.end}`;v.has(l)||(v.add(l),_.push({href:t,resolvedTo:e.resolvedTarget,reason:e.reason,localTarget:s}))}return _}let iwt=null;function awt(){return iwt||=PU().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),iwt}let owt=null;function swt(){return owt||=PU().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, acp-document-write, agent-write-batch, agent-patch, rollback}.`}),owt}let cwt=null;function lwt(){return cwt||=PU().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, acp-document-write, agent-write-batch, agent-patch, rollback}, divergence_type.`}),cwt}function uwt(e,t){swt().add(1,{handler:e}),t!==void 0&&lwt().add(1,{handler:e,divergence_type:t.divergenceType})}const V8={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},H8=q(`api`),dwt=e=>e instanceof Error&&e.message.startsWith(`Refusing to rewrite `)?e.message:void 0;function U8(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let n=t===`.`?``:t.replace(/^\.\//,``),r=n6(e);if(r.managed&&r.versioned)return{path:n?`${n}/${r.filePath}`:r.filePath};let i=qH(e);return{path:n?`${n}/${e}${i}`:`${e}${i}`}}function fwt(e,t){let n=U8(e,t);if(`error`in n)return[`${e}.md`];let r=UXe(n.path,e);return r?[n.path,r]:[n.path]}function pwt(e,t){let n=W(e,t);if(!uG(n,e))throw Error(`Invalid directory: ${t}`);return n}function mwt(e,t){let n,r;try{n=hc(e),r=hc(t)}catch{return null}return uG(n,r)?U(r,n).split(Ys).join(`/`):null}async function hwt(e,t,n){if(!t)return!1;let r=[...e].sort().join(`\0`);if(r===n.lastKey||(n.lastKey=r,!e.some(e=>t.isExcluded(e))))return!1;try{return await t.rebuildIgnorePatterns(),!0}catch{return!1}}function W8(e){let t=Ws(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const gwt=5e4;function _wt(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return gwt;let t=Number(e);return Number.isInteger(t)&&t>0?t:gwt}const vwt=5e4;function ywt(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return vwt;let t=Number(e);return Number.isInteger(t)&&t>0?t:vwt}let G8=0,K8=0;function bwt(){return{invocations:G8,aborts:K8}}function xwt(){G8=0,K8=0}async function*q8(e){let{contentDir:t,contentFilter:n,dirFilter:r,maxEntries:i,signal:a,showOk:o}=e,s=e.maxDepth??1/0,c={bypassFilters:!0,respectOkignore:!0,showOk:o};G8+=1;let l=0,u=!1,d=!1,f=e=>!r||e===r||e.startsWith(`${r}/`),p;try{p=await Nc(t)}catch{p=t}let m=e=>uG(e,p),h=async(e,t,r)=>{let i=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!BH(t.name))continue;let e=UH(r?`${r}/${t.name}`:t.name);i.set(e,(i.get(e)??0)+1)}let a=new Set([...i].filter(([,e])=>e>1).map(([e])=>e));if(a.size===0)return new Map;let o=new Map;for(let i of e){if(!i.isFile()&&!i.isSymbolicLink()||!BH(i.name))continue;let e=r?`${r}/${i.name}`:i.name,s=UH(e);if(a.has(s)&&!n.isExcluded(e,c)&&f(e)){if(i.isSymbolicLink()){let e=H(t,i.name),n;try{n=await Nc(e)}catch{continue}if(!m(n))continue;let r;try{r=await Fc(n)}catch{continue}if(!r.isFile())continue}else try{await Fc(H(t,i.name))}catch{continue}o.set(s,(o.get(s)??0)+1)}}return o},g=(e,t)=>{let n=UH(e);return(t.get(n)??0)>1?e:n};async function _(e,t){let r;try{r=await Mc(e,{withFileTypes:!0})}catch(t){return H8.warn({dir:e,err:t},`[document-list][showAll] probe readdir failed for ${e}`),!1}for(let i of r){let r=t?`${t}/${i.name}`:i.name;if(i.isDirectory()){if(n.isDirExcluded(r,c))continue;try{let t=await Nc(H(e,i.name));if(!m(t))continue}catch(t){H8.warn({path:`${e}/${i.name}`,err:t},`[document-list][showAll] probe realpath failed for ${e}/${i.name}`);continue}return!0}if(i.isFile()&&!n.isExcluded(r,c))return!0}return!1}async function*v(e,r,o){let p=[{absDir:e,relDir:r,depth:o}];for(let e=0;e<p.length;e++){if(a?.aborted){d=!0;return}let{absDir:r,relDir:o,depth:v}=p[e],y;try{y=await Mc(r,{withFileTypes:!0})}catch(e){H8.warn({dir:r,err:e},`[document-list][showAll] readdir failed for ${r}`);continue}let b=await h(y,r,o);for(let e of y){if(a?.aborted){d=!0;return}if(l>=i){u=!0;return}let h=o?`${o}/${e.name}`:e.name;if(e.isDirectory()){if(n.isDirExcluded(h,c))continue;let t=H(r,e.name),i;try{i=await Nc(t)}catch(e){H8.warn({path:t,err:e},`[document-list][showAll] realpath failed for ${t}`);continue}if(!m(i)){H8.warn({path:t,canonical:i},`[document-list][showAll] refusing symlink-escape ${t} -> ${i}`);continue}if(f(h)){let e=null;try{e=await Fc(t)}catch(e){H8.warn({path:t,err:e},`[document-list][showAll] stat failed for ${t}`)}l+=1;let n=v>=s?await _(t,h):void 0;yield{kind:`folder`,path:h,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...n===void 0?{}:{hasChildren:n}}}v<s&&p.push({absDir:t,relDir:h,depth:v+1});continue}if(e.isSymbolicLink()){let i=H(r,e.name),a;try{a=await Nc(i)}catch(e){H8.warn({path:i,err:e},`[document-list][showAll] symlink realpath failed for ${i}`);continue}if(!m(a)){H8.warn({path:i,canonical:a},`[document-list][showAll] refusing symlink-escape ${i} -> ${a}`);continue}let o;try{o=await Fc(a)}catch(e){H8.warn({path:i,err:e},`[document-list][showAll] symlink target stat failed for ${i}`);continue}let s=lG(U(t,a));if(o.isDirectory()){if(n.isDirExcluded(h,c)||!f(h))continue;l+=1,yield{kind:`folder`,path:h,size:0,modified:o.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:s,hasChildren:await _(a,h)};continue}if(!o.isFile()||n.isExcluded(h,c)||!f(h))continue;if(l+=1,BH(e.name))yield{kind:`document`,docName:g(h,b),docExt:Ws(e.name),size:o.size,modified:o.mtime.toISOString(),isSymlink:!0,canonicalDocName:s.replace(/\.(md|mdx)$/i,``),targetPath:s};else{let t=W8(e.name);yield{kind:`asset`,docName:h,docExt:t,path:h,assetExt:t,mediaKind:Da(t),referencedBy:[],size:o.size,modified:o.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:s}}continue}if(!e.isFile()||n.isExcluded(h,c)||!f(h))continue;let y=null;try{y=await Fc(H(r,e.name))}catch(t){H8.warn({path:`${r}/${e.name}`,err:t},`[document-list][showAll] stat failed for ${r}/${e.name}`);continue}if(BH(e.name)){let t=g(h,b),n=Ws(e.name);l+=1,yield{kind:`document`,docName:t,docExt:n,size:y.size,modified:y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let x=W8(e.name),S=Da(x);l+=1,yield{kind:`asset`,docName:h,docExt:x,path:h,assetExt:x,mediaKind:S,referencedBy:[],size:y.size,modified:y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*v(r?H(t,r):t,r??``,1),d&&(K8+=1),{truncated:u}}async function Swt(e){let{documents:t,...n}=e,r=q8(n),i=await r.next();for(;!i.done;)t.push(i.value),i=await r.next();return i.value}function Cwt(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function wwt(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function J8(e,t,n){return e!==void 0&&e.length>0?e:(X(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:n}),null)}function Y8(e,t,n){if(!N8(n))throw new NK(`path must be a relative content path`);let r=W(e),i=t===`file`?XH(n):n,a=W(r,i);if(a!==r&&!a.startsWith(`${r}${Ys}`))throw new NK(`path must not escape content directory`);return jK(a,r),a}function X8(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function Twt(e,t){return e?`${e}/${t}`:t}function Ewt(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}function Z8(e,t){return Q8(e,t)!==null}function Q8(e,t){if(BH(t))return G(W(e,t))?t:null;for(let n of ae)if(G(W(e,`${t}${n}`)))return`${t}${n}`;return null}function Dwt(e,t){if(!BH(t))return!1;let n=UH(t),r=Ws(t).toLowerCase();return ae.some(t=>t.toLowerCase()!==r&&G(W(e,`${n}${t}`)))}function $8(e,t){let n=UH(t);return BH(t)&&Dwt(e,t)?t:n}function Owt(e,t,n){if(!N8(t))throw new NK(`path must be a relative content path`);let r=W(e),i=W(r,`${t}${n}`);if(i!==r&&!i.startsWith(`${r}${Ys}`))throw new NK(`path must not escape content directory`);return jK(i,r),i}function kwt(e,t){let{parent:n,basename:r}=X8(t);for(let t=1;t<=1e4;t+=1){let i=Twt(n,Ewt(r,t));if(!Z8(e,i))return{docName:i,attempt:t}}throw new V4(t)}function Awt(e,t){let{parent:n,basename:r}=X8(t);for(let t=1;t<=1e4;t+=1){let i=Twt(n,Ewt(r,t)),a=Y8(e,`folder`,i);if(!G(a))return{folderPath:i,attempt:t}}throw new V4(t)}function jwt(e,t){let n=Y8(e,`folder`,t),r=[];function i(t,n){for(let a of mc(t,{withFileTypes:!0})){let o=W(t,a.name),s=n?`${n}/${a.name}`:a.name;if(a.isDirectory()){i(o,s);continue}!a.isFile()||!BH(s)||r.push({docName:$8(e,s),fullPath:o,content:K(o,`utf-8`)})}}return i(n,t),r.sort((e,t)=>e.docName.localeCompare(t.docName)),r}function Mwt(e,t){let n=Y8(e,`folder`,t),r=[t];function i(e,t){for(let n of mc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let a=W(e,n.name),o=t?`${t}/${n.name}`:n.name;r.push(o),i(a,o)}}return i(n,t),r.sort((e,t)=>e.localeCompare(t)),r}function e5(e,t){let n=W(e),r=W(t);return r!==n&&!r.startsWith(`${n}${Ys}`)?null:U(n,r).split(Ys).join(`/`)}function t5(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function n5(e,t){return t5(W(e),W(t))}function Nwt(e,t){if(!n5(e,t)||!G(e)||!G(t))return!1;try{let n=yc(e,{bigint:!0}),r=yc(t,{bigint:!0});return nS(n)===nS(r)}catch{return!1}}function Pwt(e){let t=V(e);for(let e=0;e<10;e+=1){let e=W(t,`.ok-case-rename-${zc()}`);if(!G(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function r5(e,t){return(G(e)?K(e,`utf-8`):null)!==t&&(JU(e,t,`utf-8`),!0)}function i5(e,t){if(XU(V(t),{recursive:!0}),!n5(e,t)){ZU(e,t);return}let n=Pwt(e);ZU(e,n);try{ZU(n,t)}catch(t){try{let t=G(n),r=G(e);t&&!r?ZU(n,e):H8.warn({tempExists:t,sourceExists:r},`[renamePathOnDisk] skipped case-only rollback due to unexpected state`)}catch(e){H8.warn({err:e},`[renamePathOnDisk] failed to roll back temporary case-only rename`)}throw t}}async function a5(e,t,n){if(!e)return!1;let r=e5(e,t),i=e5(e,n);return!r||!i?!1:await hK(async()=>{let a=tM({baseDir:e,timeout:{block:15e3}}),o;try{o=await _ft(a,e,r)}catch(t){return H8.warn({err:t,projectDir:e,path:r},`[renameTrackedPathInGit] tracked-path lookup failed, falling back to fs rename`),!1}if(!o)return!1;lc(V(n),{recursive:!0});let s=!1;try{if(n5(t,n)){let n=e5(e,Pwt(t));if(!n)return!1;await a.raw(`mv`,`--`,r,n);try{await a.raw(`mv`,`--`,n,i)}catch(e){try{await a.raw(`mv`,`--`,n,r)}catch(e){H8.warn({err:e},`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged`),s=!0}throw e}}else await a.raw(`mv`,`--`,r,i);return!0}catch(e){if(s)throw e;return H8.warn({err:e},`[renameTrackedPathInGit] git mv failed, falling back to fs rename`),!1}})}function Fwt(e){let{body:t}=ka(e),n=[],r=new Map,i=io();for(let e of t.split(`
2089
- `)){if(i(e))continue;let t=Woe(e,r);t&&n.push(t)}return n}function o5(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function Iwt(e,t){let n=t();n instanceof Map&&mZ(e,n)}function Lwt(e){switch(e.removal?.kind){case`path-occupied`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the file now at this path is not loaded into the document.`,detail:`${e.message}. Retrying will not help until the server reloads this document from disk, for example after Open Knowledge restarts; tell the user instead of retrying.`};case`renamed`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document was renamed.`,detail:`${e.message}. Retrying will not help: re-read the document at ${e.removal.renamedTo} and re-apply your change there.`};case`deleted-outside`:return{type:`urn:ok:error:doc-removed`,title:`Edit not saved to disk: the document was deleted outside the app, and the edit went to its history.`,detail:`${e.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; tell the user the file was deleted, and do not re-create the document on your own.`};case void 0:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document is no longer on disk.`,detail:`${e.message}. Retrying will not help: tell the user the file is no longer on disk.`}}}function Rwt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:`its new name`;return{type:`urn:ok:error:doc-moved`,title:`Edit kept: the document was moved outside the app, and the edit moved with it.`,detail:`${e.message}. Do not repeat the edit: it is in ${t}, which saves it under that name. Re-read ${t} to confirm.`}}function zwt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:void 0;return{type:`urn:ok:error:server-stopped`,title:`Edit not saved to disk: the server stopped before the edit reached disk.`,detail:t===void 0?`${e.message}. After OpenKnowledge restarts, the edit is in the document's history (the timeline); tell the user.`:`${e.message}. After OpenKnowledge restarts, re-read the document at ${t} to see whether it holds the edit, and re-apply the edit there if it is missing. Do not re-create the document under its old name.`}}function Bwt(e){return{type:`urn:ok:error:path-escape`,title:`Edit applied in memory; disk write refused because the document path could not be resolved.`,detail:`${e.message}. Retrying will not help: tell the user the path has to be repaired on disk before this content can be written.`}}const Vwt={"legacy-name":`Write the skill or template by its file path instead; that write is saved to the file.`,unresolvable:`Retrying will not help until the path resolves again. Tell the user which document it is.`,"container-gone":`OpenKnowledge does not re-create a skill folder that was deleted or moved. Tell the user which skill it is.`,"intake-landed":`Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing.`};function Hwt(e){let t=e.dropped===void 0?Vwt.unresolvable:Vwt[e.dropped];return{type:`urn:ok:error:write-dropped`,title:`Edit not saved: OpenKnowledge did not write this document's file.`,detail:`${e.message}. The edit is only in the open document. ${t}`}}function Uwt(e){return{type:`urn:ok:error:write-replaced`,title:`Edit not saved: the file on disk replaced the document, and the edit went to its history.`,detail:`${e.message}. OpenKnowledge had no agreed version of the file to merge the edit with, so it took the file in as it is and saved the document as it was, this edit included, to the document's history (the timeline). Re-read the document, and re-apply the edit if it is still needed.`}}function Wwt(e,t){switch(t.kind){case`branch-switch`:return{code:yG,message:`A Git branch switch discarded the pending save of ${e}`};case`renamed-outside`:return{code:hG,message:`${e} was moved outside the app to ${t.to}, and its open document followed`,removal:{kind:`renamed`,renamedTo:t.to,...t.carry?{carry:t.carry}:{}}};case`deleted-outside`:return{code:hG,message:`${e} was deleted outside the app before the edit reached disk`,removal:{kind:`deleted-outside`}};case`shutdown`:return{code:xG,message:`The server stopped while the file of ${e} was missing`};default:throw Error(`unhandled discard cause: ${JSON.stringify(t)}`)}}function Gwt(e){return{type:`urn:ok:error:branch-switched`,title:`Edit kept in the open document: the Git branch changed before it reached disk.`,detail:`${e.message}. The edit stays in the open document, merged with the checked-out branch's version of the file, and is saved with the document's next save; do not repeat the edit. Re-read the document to confirm it.`}}const Kwt={"pending-unreadable":{retryWhen:`next-save`,sentence:`A later save writes it once the file can be read again: the next edit to this document, or the idle save within a few minutes.`},"pending-exhausted":{retryWhen:`next-save`,sentence:`A later save writes it once the file stops changing: the next edit to this document, or the idle save within a few minutes.`},"pending-base-moved":{retryWhen:`next-save`,sentence:`A later save writes it once the outside changes have been taken in: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed-no-base":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-no-intake":{retryWhen:`next-edit`,sentence:`The next edit to this document tries the save again.`},"pending-conflict":{retryWhen:`conflict-resolved`,sentence:`It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.`},"pending-no-history-or-backup":{retryWhen:`next-save`,sentence:`The file is not written over until its outside version is saved to the document history or the backup folder; a later save tries again: the next edit to this document, or the idle save within a few minutes.`},"pending-not-utf8":{retryWhen:void 0,sentence:`OpenKnowledge does not write over it, and no save runs until someone saves the file as text again. Tell the user which file it is.`},"pending-unsettled":{retryWhen:`next-save`,sentence:`The save was still running when the write stopped waiting for it, and it finishes on its own.`},"pending-rename":{retryWhen:`next-save`,sentence:`The edit goes with the document to its new name, or to its history if the move cannot carry it. Do not repeat this write, and do not re-create the document under its old name: re-read it at its new name.`}};function qwt(e,t,n){if(n)return`${e.message}. This edit is in the document but is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. Any further write to this document, yours included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history (timeline). Do not write to this document again; tell the user that its file changed outside OpenKnowledge.`;let{sentence:r}=Kwt[t];return t===`pending-rename`?`${e.message}. ${r}`:x2e(t)?`${e.message}. The edit is kept in the document. ${r} Do not repeat this write.`:`${e.message}. The edit is kept in the document. ${r} Do not repeat this write: re-read the document before editing it further.`}function Jwt(e){let t=e.held?.reason??`pending-unreadable`,n=e.held?.noBase===!0,r=n?`replaced-on-next-edit`:Kwt[t].retryWhen;return{type:`urn:ok:error:save-held`,title:`Edit applied in memory; its save to disk is held.`,detail:qwt(e,t,n),reason:t,...r===void 0?{}:{retryWhen:r},...e.held?.causeCode===void 0?{}:{causeCode:e.held.causeCode}}}function Ywt(e){return{type:`urn:ok:error:store-refused`,title:`Edit applied in memory; disk write refused because the duplication baseline could not be read.`,detail:`${e.message}. The edit is applied in collaborative state and the document file on disk was not updated; a copy of the edited document is preserved in the server's recovery buffer unless that buffer is unavailable or unwritable. Do not repeat the write now: once the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.`}}function Xwt(e){let t=FG(e),n=(e,n)=>({status:e,problem:{...n,...t}});switch(e.code){case _G:return n(503,Ywt(e));case vG:return n(503,Jwt(e));case hG:return n(409,Lwt(e));case yG:return n(409,Gwt(e));case bG:return n(409,Rwt(e));case xG:return n(503,zwt(e));case gG:return n(400,Bwt(e));case SG:return n(409,Uwt(e));case CG:return n(409,Hwt(e));default:return}}function Zwt(e){let{outcome:t,saved:n,nextStep:r,...i}=e;return i}function Qwt(e){let t=Xwt(e);return t?Zwt(t.problem):{type:G4({code:e.code}),title:`Write applied in memory but failed to persist to disk.`,detail:`${e.code??`unknown error`}: ${e.message}. The content was NOT saved and will be lost if the server restarts.`}}function s5(e,t,n){let r=Xwt(t);if(r){let{type:t,title:i,detail:a,...o}=r.problem;X(e,r.status,t,i,{handler:n,...a===void 0?{}:{detail:a},extensions:o});return}let i=G4({code:t.code});X(e,W4(i),i,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:n,extensions:{...FG(t)}})}function $wt(e){let{durabilityState:t}=e,n=!1,r=new Set;async function i(e,i){if(n)throw new JK(i.startsWith(`/api/local-op/`));let a=t.runWithinWriteWaitBudget(e);r.add(a);try{await a}finally{r.delete(a)}}let a=e.assertContentSubtree,o=e.ingressPolicy??BQ({}),s=(e,t,n)=>Lit(e,t,{...n,policy:o}),c=e=>HQ(e,o),l=e=>VQ(e,o),{hocuspocus:u,sessionManager:d,contentDir:f,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m,serverInstanceId:h,getFileIndex:g,getAttachmentFolderPath:_,getAllFilesIndex:v=g,mutateFileIndex:b=e=>Iwt(e,v),getFileIndexGeneration:x,getFolderIndex:S,onReferencedAssetsCacheInvalidator:C,getAliasMap:w,getFolderAliasIndex:T,resolveTrackedFile:E,rescanFiles:O,localOpConcurrencyGuard:k,enableTestRoutes:A=!1,shadowRef:j,flushGitCommit:M,flushContributors:N,getCurrentBranch:P,getReportedBranch:te,getDiskAckSVs:F,getCollabClientCount:ne,contentRoot:re,derivedDocumentIndex:ie,signalChannel:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,onAgentWrite:ce,getSyncEngine:le,conflicts:ue,setBatchInProgress:de,localOpCliArgs:fe,authStreamHeartbeatMs:pe,projectDir:me,getBridgeLossReporter:he,getPrincipal:ge,homeDirOverride:_e,resetSettingsForTest:ve,settleDiskEventsForTest:be,agentIntegrations:xe,savedThemeLockTimeoutMs:Se,acpRegistry:we,loadAcpCustomAgents:Te,acpHarnessAvailability:Ee=Oot(),contentFilter:De,installedAgentsProbe:Oe,forceUnloadDocument:ke,onNamespaceCreateAccepted:Ae,captureNamespaceMove:je,capturePublicationReceipt:Me,onResidentAdopted:Ne,ready:Pe,recentlyRemovedDocs:Fe,serializeDoc:Ie,evictManagedArtifactLkg:Le,semanticSearch:ze,getSemanticSimilarityFloor:Be,embeddingsSecretsFile:Ve,readSemanticProviderConfig:He,getLinterBaseConfig:Ue,getLinkAdvisoryPolicy:We,getProjectConfigEpoch:Ge,ephemeral:Ke=!1,linkPreviewFetch:qe,getLinkPreviewsEnabled:Je,resolveGitHubToken:Ye,githubReferenceFetch:Xe,getConfigDiagnostics:Ze}=e,Qe=e.docNotices,I=e.declaredGitHubHosts??x6(_e),$e=e.resolveSyncCredentialConfig??Bvt({projectDir:me??f,tokenStore:null,localOpCliArgs:fe,declaredGitHubHosts:I});function et(t,n,r){let i=Y8(t,n,r);return e.assertContentPath?.(i),i}let tt=$dt({homeDirOverride:_e,log:H8}),{bumpSkillsCatalogGen:nt,enumerateInstalledSkillsCached:rt,pluginSkillsByName:it}=tt,at=ae?e=>{e===`files`&&nt(),ae(e)}:void 0,ot=k??Rit(),st=hmt({hocuspocus:u,conflicts:ue,contentDir:f,isSafeDocName:o5,resolveAlias:wt,resolveContentEntryPath:et,resolveDocPath:ht,extractHeadings:Fwt,getFileIndex:g,getFileIndexGeneration:x,log:H8,ready:Pe,contentFilter:De,safeSubdir:pwt,getShowAllMaxEntries:_wt,streamShowAllEntries:q8,walkContentDirForShowAll:Swt,synthesizeShowAllAssetExt:W8,getAllFilesIndex:v,getFolderIndex:S,getFolderAliasIndex:T,onReferencedAssetsCacheInvalidator:C}),{invalidateReferencedAssetsCache:ct}=st;function lt(){let e=S?.();return e instanceof Map?e:null}function ut(e){let t=lt();if(t)try{let n=yc(e,{bigint:!0});AX(t,f,e,n,e)}catch(t){H8.warn({path:e,err:t},`folder index stat failed for ${e}`)}}function dt(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)ut(W(f,t.slice(0,e).join(`/`)))}function ft(e){let t=lt();t&&jX(t,e)}function pt(e,t){let n=lt();if(!n)return;let r=[];for(let[i,a]of n.entries()){if(i!==e&&!i.startsWith(`${e}/`))continue;n.delete(i);let o=i.slice(e.length);r.push([`${t}${o}`,a])}if(r.length===0){let e=et(f,`folder`,t);G(e)&&ut(e);return}for(let[e,t]of r)n.set(e,{...t,modified:new Date().toISOString(),canonicalPath:W(f,e)})}let mt=Hot({probe:Oe??i1(process.platform)});function ht(e){if(rn(e))try{return r6(e,{projectDir:me??f,homedirOverride:_e})}catch{return null}if(!o5(e))return null;let t=W(f),n=XH(e),r=W(t,n);return uG(r,t)?r:null}let gt=new Iot({store:new Lot(W(f,`.ok`,wi),H8),index:new kot,getDocBody:e=>{try{let t=u.documents.get(e);if(t)return ka(t.getText(`source`).toString()).body}catch{}try{let t=ht(e);if(t&&G(t))return ka(K(t,`utf-8`)).body}catch{}return null},getDocFrontmatter:e=>{try{let t=u.documents.get(e);if(t)return D(t.getText(`source`).toString())??{}}catch{}try{let t=ht(e);if(t&&G(t))return D(K(t,`utf-8`))??{}}catch{}return null}});e.commentDocHooksRef&&(e.commentDocHooksRef.current={changed:e=>{gt.refindDoc(e).then(e=>{e&&at?.(`comments`)}).catch(t=>{H8.warn({err:t,docName:e},`[comments] re-anchor after document change failed`)})},deleted:e=>{gt.deleteDoc(e).then(e=>{e>0&&at?.(`comments`)}).catch(t=>{H8.warn({err:t,docName:e},`[comments] cleanup after document delete failed`)})}});function _t(e){let t=ht(e);if(!t||!G(t))return e;try{return JY(K(t,`utf-8`),e)}catch{return e}}function vt(e,t){return t.has(e)?_t(e):e}let yt={cluster:void 0,category:void 0,tags:void 0};function bt(e){try{let t=u.documents.get(e);if(t){let e=ote(t.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,n=typeof e.category==`string`?e.category:void 0,r;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);r=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(r=[e.tags]);return{cluster:t,category:n,tags:r}}}}catch{}try{let t=ht(e);if(!t||!G(t))return yt;let n=K(t,`utf-8`),{frontmatter:r}=ka(n);return r?pet(r):yt}catch{return yt}}function xt(e,t){return t.has(e)?bt(e):yt}let St=twt();async function Ct(e){if(ie?.isReady())try{let t=await St.run(`orphan-hints`,()=>ie.getBacklinks(e),()=>void 0);if(t===void 0||t.length>0)return;let n=performance.now(),r=Mlt(e,g()),i=performance.now()-n;return i>5&&H8.debug({docName:e,elapsedMs:i,candidateCount:r.length},`[orphan-hint] findHubCandidates slow`),r.length===0?void 0:[{type:`orphan`,parentCandidates:r,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${r.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){H8.warn({err:e},`[orphan-hint] computeOrphanHints failed`);return}}function wt(e){return w?.().get(e)??e}function Tt(e,t){let n=`onStoreDocument-${e}`;(u.debouncer.isDebounced(n)?u.debouncer.executeNow(n):Promise.resolve()).then(()=>M?.()).catch(e=>{H8.warn({err:e},`[${t}] post-write flush failed`)})}function Et(e,t){let n=`onStoreDocument-${e}`;u.debouncer.isDebounced(n)&&u.debouncer.executeNow(n).catch(e=>{H8.warn({err:e},`[${t}] post-write disk flush failed`)})}function Dt(e,t,n){return{kind:`failure`,failure:{code:vG,message:`${e} ${n}`,held:{reason:t}}}}async function Ot(e,n,r){if(n.code!==`OK_DOC_REMOVED`||n.removal?.kind!==`renamed`)return{kind:`failure`,failure:n};let i=await t.awaitRenameCarry(e,n.removal.carry),a=n.removal.renamedTo;switch(i.kind){case`unsettled`:return Dt(e,`pending-rename`,`was still being moved outside the app to ${a} when the write stopped waiting`);case`stopped`:return{kind:`failure`,failure:{code:xG,message:`The server stopped while ${e} was being moved outside the app to ${a}`,removal:{kind:`renamed`,renamedTo:a}}};case`settled`:return{kind:`failure`,failure:a2e(r,i.carried)?{...n,code:bG}:n};default:throw Error(`unhandled rename carry answer: ${JSON.stringify(i)}`)}}function kt(e){let t=u.documents.get(e);return t?mG(t):void 0}async function At(e){let t=u.documents.get(e);t!==void 0&&await u.storeDocumentHooks(t,{instance:u,clientsCount:t.getConnectionsCount(),document:t,documentName:e,lastContext:{},lastTransactionOrigin:null},!0)}async function jt(e,n=kt(e)){let r=`onStoreDocument-${e}`;u.debouncer.isDebounced(r)?(t.markAgentWriteStore(e),await u.debouncer.executeNow(r)):u.debouncer.isCurrentlyExecuting(r)&&(t.markAgentWriteStore(e),await At(e));let i=Date.now(),a=await t.awaitDeferredStoreOutcome(e),o,s=!1;switch(a?.kind){case void 0:case`completed`:break;case`discarded`:o=Wwt(e,a.cause);break;case`failed`:o=t.takeStoreFailure(e)??a.failure;break;case`unsettled`:{s=!0;let t=Date.now()-i;console.warn(JSON.stringify({event:`agent-write-deferred-store-unsettled`,"doc.name":e,waitedMs:t,timestamp:new Date().toISOString()})),H8.warn({docName:e,waitedMs:t},`[agent-write] deferred store still pending after the wait; answering that the save is held`);break}default:c2e(a)}o??=t.takeStoreFailure(e)??void 0;let c=t.readStoreIntake(e,n);return t.consumeAgentWriteStore(e),o?Ot(e,o,n):t.takeStaleExternalWriteFreeze(e)?{kind:`stale-external-write`}:s?Dt(e,`pending-unsettled`,`was still being saved when the write stopped waiting`):c===`disk-replaced`?{kind:`failure`,failure:{code:SG,message:`${e} changed on disk, and its file replaced the document`}}:c===void 0?null:{kind:`taken-in`,merge:c}}function Mt(e){return{type:`urn:ok:error:stale-external-write`,title:`Edit retained; disk write blocked by a stale external-write conflict.`,detail:`An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: ask the user to resolve the conflict in the OpenKnowledge app, then re-read the document before making further changes.`,file:t.getStaleExternalWrite(e)?.file??U(me??f,GG(e,f)).replaceAll(`\\`,`/`),resolutionOptions:ZJ,...PG[`urn:ok:error:stale-external-write`]}}function Nt(e,t,n){let{type:r,title:i,detail:a,...o}=Mt(n);X(e,409,r,i,{handler:t,detail:a,extensions:o})}let Pt=ACt({getShadow:()=>j?.current,contentRoot:re??``,getBranch:()=>P?.()??null,writeCheckpoint:e.mergeHistoryWriter,notices:e.docNotices});function L(e){if(!De)return!1;let t=XH(e);return De.isExcluded(t)}function Ft(){return ie?.isReady()??!0}let It=async e=>{if(!Ft())return _ut;let t;try{t=await St.run(`link-check`,Lt,()=>null)}catch(e){return H8.warn({err:e},`[link-check] write link advisory failed post-write; skipping link checks`),vut}if(t===null)return vut;for(let n of e)t.add(n);let n={fileExists:Kt(),folderExists:Gt(),fileExcluded:Xt(),resolveWikiFile:Jt(),resolveFileByBasename:Yt()};return(e,r,i)=>({links:yut(rwt(e,r,t,n),r,i),warnings:[]})};async function Lt(){let e=new Set;for(let[t,n]of g()){e.add(t);for(let t of n.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let n=W(t===`global`?Zn:f,`.ok`,Oa);for(let r of gr(n,t).skills)e.add(`${_n}${t}/${r.name}`)}}catch(e){H8.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of await ie?.getIndexedDocNames()??[])e.has(t)||L(t)||e.add(t);return e}async function Rt(e,t){if(!(!ie||e.length===0))try{await ie.recordDirectMutations(e)}catch(n){Vt(n,{count:e.length,reason:t},`[derived-index] failed to project durable document mutations`)}}async function zt(e,t,n){if(ie)try{await ie.recordDirectDocument(e,t)}catch(t){Vt(t,{documentName:e,reason:n},`[derived-index] failed to project durable document`)}}async function Bt(e,t,n){if(ie)try{await ie.recordLinkRewrite(e,t)}catch(t){Vt(t,{documentName:e,reason:n},`[derived-index] failed to project link rewrite`)}}function Vt(e,t,n){if(q2(e)){H8.debug({err:e,...t},`[derived-index] coordinator closed; skipping durable projection`);return}H8.warn({err:e,...t},n)}function Ht(e,t,n){if(q2(t)){X(e,503,`urn:ok:error:derived-index-unavailable`,`Derived index is shutting down.`,{handler:n.handler,cause:t,logLevel:`debug`});return}X(e,500,`urn:ok:error:internal-server-error`,n.failureTitle,{handler:n.handler,cause:t})}async function Wt(e,t){await Rt([...e].map(e=>({kind:`delete`,documentName:e})),t)}function Gt(){let e=S?.();if(!e)return()=>!1;let t=Ji(`folder`,e.keys());return e=>t.resolve(e)!==void 0}function Kt(e=v()){return Bdt(V2(e,T?.()??new Map,f).fileTargets,f,De)}function qt(){return V2(v(),T?.()??new Map,f,S?.())}function Jt(){let e;return t=>(e??=_a(qt().fileTargets),e(t))}function Yt(){let e;return(t,n)=>(e??=zdt(qt().fileTargets),e(t,n))}function Xt(){return e=>N2(f,De,e)}function Zt(e,t){L(e)||b?.({kind:g().has(e)?`update`:`create`,path:et(f,`file`,e),docName:e,content:t})}function Qt(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let $t=Qt(),en=e=>e.endsWith(`.`)?e:`${e}.`;function tn(e){return e instanceof Error?e instanceof PY?{status:404,type:`urn:ok:error:doc-not-found`,error:en(e.message)}:e instanceof FY?{status:409,type:`urn:ok:error:doc-already-exists`,error:en(e.message)}:e instanceof IY||e instanceof LY?{status:400,type:`urn:ok:error:invalid-request`,error:en(e.message)}:e instanceof RY?{status:400,type:`urn:ok:error:reserved-doc-name`,error:en(e.message)}:e instanceof X9e||e instanceof Y9e?{status:404,type:`urn:ok:error:doc-not-found`,error:en(e.message)}:PK(e)?{status:400,type:`urn:ok:error:path-escape`,error:en(e.message)}:e instanceof zY?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:en(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function nn(e,n){let r=new Map;for(let t of e){let e=u.documents.get(t);e&&r.set(t,e.getText(`source`).toString())}for(let t of e){let e=u.documents.get(t);e&&e.getMap(`lifecycle`).set(`status`,n)}for(let t of e)await d.closeAllForDoc(t).catch(e=>{H8.warn({docName:t,err:e},`[file-ops] Failed to close agent session for ${t}`)});for(let n of e){let e=u.documents.get(n);t.deleteReconciledBase(n),Le?.(n),e&&(u.closeConnections(n),await(ke??u.unloadDocument.bind(u))(e))}return r}function an(n,r){let i=u.documents.get(n);pat(t,u,n,r,e.resolveEmbed,void 0,he?.())===`revived`&&i&&Ne?.(i,n)}function on(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=GG(r,f),i=t.get(n);typeof i==`string`&&r5(e,i);let a=typeof i==`string`?i:G(e)?K(e,`utf-8`):null;typeof a==`string`&&(hX(e,dG(a)),an(r,a))}}function sn(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let r=GG(e,f);if(!G(r))throw new Y9e(e);return{docName:e,content:K(r,`utf-8`)}})}function cn(e){let t=u.documents.get(e);if(t)return t.getText(`source`).toString();let n=et(f,`file`,e);return G(n)?K(n,`utf-8`):null}function ln(e,n,r){let i=r?Me?.(r,e):void 0,a=et(f,`file`,e);XU(V(a),{recursive:!0});let o=r5(a,n);hX(a,dG(n)),t.setReconciledBase(e,n),o&&i?.(),b?.({kind:`update`,path:a,docName:e,content:n})}function un(e,t,n){let r=u.documents.get(e);if(!r)throw Error(`Document is not loaded: ${e}`);let i={markdown:``,rewrites:0};return r.transact(()=>{i=fn(r.getText(`source`).toString(),e,n.renames.get(e)??e,t,n),i.rewrites!==0&&Rq(r,i.markdown,`managed-rename`,!1)},V8),i}function dn(e,t,n){let r=e,i=0;for(let{fromPath:e,toPath:a}of n){let n=G9e(r,t,e,a);r=n.markdown,i+=n.rewrites}return{markdown:r,rewrites:i}}function fn(e,t,n,r,i){let a=Q9e(e,t,i),o=dn(a.markdown,n,r);return{markdown:o.markdown,rewrites:o.markdown===e?0:a.rewrites+o.rewrites}}function pn(e,t){let n=u.documents.get(e);if(!n)throw Error(`Document is not loaded: ${e}`);let r={markdown:``,rewrites:0};return n.transact(()=>{r=dn(n.getText(`source`).toString(),e,t),r.rewrites!==0&&Rq(n,r.markdown,`managed-rename`,!1)},V8),r}function mn(e){let t=[];if(e.length===0)return t;let n=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let r of n){let n=cn(r);if(typeof n!=`string`)continue;let i=dn(n,r,e);i.rewrites!==0&&t.push({docName:r,markdown:i.markdown,rewrites:i.rewrites})}return t}function hn(e){for(let t of e){let e=ue.findByDocName(t);if(e!==void 0)throw new QJ({file:e.file})}}async function gn(e,t){let n=[],r=[];for(let i of e){let e=u.documents.get(i.docName),a=e?pn(i.docName,t):i;a.rewrites!==0&&(ln(i.docName,a.markdown,e),r.push({kind:`link-rewrite`,documentName:i.docName,markdown:a.markdown}),n.push({docName:i.docName,rewrites:a.rewrites}))}return{rewrittenDocs:n,derivedMutations:r}}let vn=e=>eft(e,{contentDir:f,contentFilter:De,docNameForPath:e=>$8(f,e)});function yn(e,t,n){let r=[];function i(e){for(let a of mc(e,{withFileTypes:!0})){let o=W(e,a.name),s=U(f,o).split(Ys).join(`/`);if(!H2(s)){if(a.isDirectory()){if(De?.isDirExcluded(s))continue;i(o);continue}!a.isFile()||BH(s)||De?.isExcluded(s)||(s===t?r.push({fromPath:s,toPath:n}):s.startsWith(`${t}/`)&&r.push({fromPath:s,toPath:`${n}${s.slice(t.length)}`}))}}}return i(e),r.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),r}async function bn(e,t){return $t(async()=>FU(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async n=>{if(!ie)throw new zY;let r=Ws(t)?t:`${t}${Ws(e)}`;if(H2(e)||H2(r))throw new RY(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(r))throw new LY(`Destination asset is excluded by the project content config.`);let i=et(f,`folder`,e),a=et(f,`folder`,r);if(i===a)return{renamedAssets:[],rewrittenDocs:[]};if(t5(e,r))throw new LY(`Case-only renames are not supported.`);if(!G(i))throw new PY(`asset`,`Asset does not exist.`);if(G(a))throw new FY;if(!yc(i).isFile())throw new IY(`asset`,`Source path is not an asset file.`);let o=[{fromPath:e,toPath:r}],s=mn(o);n.setAttribute(`rename.rewrite_candidates`,s.length),hn(s.map(e=>e.docName)),await a5(me,i,a)||i5(i,a);let{rewrittenDocs:c,derivedMutations:l}=await gn(s,o);return await Rt(l,`asset-rename`),at?.(`files`),c.sort((e,t)=>e.docName.localeCompare(t.docName)),n.setAttribute(`rename.rewrite_count`,c.length),{renamedAssets:o,rewrittenDocs:c}}))}async function xn(e,n){return $t(async()=>FU(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async r=>{if(!ie)throw new zY;if(!BH(e)||BH(n))throw new LY(`Document-to-file rename requires a markdown source and non-markdown destination.`);let i=UH(e);if(_U(i)||vU(i))throw new RY(`Reserved document names cannot be renamed.`);if(H2(e)||H2(n))throw new RY(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(n))throw new LY(`Destination file is excluded by the project content config.`);let a=et(f,`folder`,e),o=et(f,`folder`,n);if(a===o)return{renamedAssets:[],rewrittenDocs:[]};if(t5(e,n))throw new LY(`Case-only renames are not supported.`);if(!G(a))throw new PY(`file`);if(G(o))throw new FY;if(!yc(a).isFile())throw new IY(`file`,`Source path is not a document file.`);let s=ue.findByDocName(i);if(s!==void 0)throw new QJ({file:s.file});let c=[{fromPath:e,toPath:n}],l=mn(c).filter(e=>e.docName!==i);r.setAttribute(`rename.rewrite_candidates`,l.length),hn(l.map(e=>e.docName)),await T$(t,u,i,f,void 0,he?.(),ue,Pt),Fe&&!_U(i)&&!vU(i)&&Fe.setDeleted(i);let d=(await nn([i],`renamed`)).get(i),p=typeof d==`string`?d:K(a,`utf-8`),m=dCt({fromPath:e,toPath:n,affectedDocs:[{from:i,to:i}],snapshots:[{docName:i,content:p}],cleanupPaths:[n]}),h=[];return await SCt(me??f,m,async()=>{r5(a,p),hX(a,dG(p)),await a5(me,a,o)||i5(a,o),ZH(i),b?.({kind:`delete`,path:a,docName:i});let e=yc(o,{bigint:!0});b?.({kind:`file-create`,path:o,relativePath:n,size:Number(e.size),modifiedTs:rS(e),inode:nS(e)});let t=await gn(l,c);h=t.rewrittenDocs,await Rt([{kind:`delete`,documentName:i},...t.derivedMutations],`document-to-file-rename`),at?.(`files`)}),h.sort((e,t)=>e.docName.localeCompare(t.docName)),r.setAttribute(`rename.rewrite_count`,h.length),{renamedAssets:c,rewrittenDocs:h}}))}async function Sn(e,n,r,i){return $t(async()=>FU(`rename.executeRewrites`,{attributes:{"rename.kind":r}},async o=>{if(!ie)throw new zY;let s=et(f,r,e),c=et(f,r,n);if(s===c)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!G(s))throw new PY(r);if(G(c)&&!Nwt(s,c))throw new FY;let l=yc(s);if(r===`file`&&!l.isFile()||r===`folder`&&!l.isDirectory())throw new IY(r);r===`folder`&&(WG(s,f),a?.(s));let d=r===`folder`?yn(s,e,n):[];o.setAttribute(`rename.affected_assets`,d.length);let p=(r===`file`?[$8(f,e)]:vn(s)).map(t=>({from:t,to:r===`file`?$8(f,n):wwt(t,r,e,n)}));if(o.setAttribute(`rename.affected_docs`,p.length),p.length===0){let t=mn(d);hn(t.map(e=>e.docName)),r===`folder`&&(await a5(me,s,c)||i5(s,c),pt(e,n),at?.(`files`));let{rewrittenDocs:i,derivedMutations:a}=await gn(t,d);return await Rt(a,`asset-only-folder-rename`),i.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:d,rewrittenDocs:i}}let m=Z9e(p),h=z9e(new Set([...g().keys(),...await ie.getIndexedDocNames(),...m.keys()]),m),_=p.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),v=new Set;for(let{from:e}of p)for(let t of await ie.getBacklinks(e))m.has(t.source)||v.add(t.source);let y=new Map,x=new Set,S=await ie.getRenameSourceInventory(),C=new Set(S.map(({docName:e})=>e)),w=new Set(u.documents.keys());for(let e of h.before.pages)C.has(e)||w.add(e);let T=[];for(let{docName:e,wikiTargets:t,indexedMtimeMs:n}of S)t.some(t=>V9e(t,e,h)!==null)&&w.add(e),w.has(e)||T.push({docName:e,indexedMtimeMs:n});for(let e=0;e<T.length;e+=128){let t=T.slice(e,e+128),n=await Promise.allSettled(t.map(async({docName:e,indexedMtimeMs:t})=>{try{let n=et(f,`file`,e);return t===(await Fc(n)).mtimeMs?null:e}catch(t){if(R0(t))return null;let n=t instanceof Error&&`code`in t?t.code:`unknown`;throw Error(`Rename discovery could not check ${e} (${n})`,{cause:t})}}));for(let e of n){if(e.status===`rejected`)throw e.reason;e.value&&w.add(e.value)}}for(let e of w){if(m.has(e)||TU(e)||L(e))continue;let n;try{n=et(f,`file`,e)}catch(e){if(R0(e))continue;throw e}if(!G(n))continue;await T$(t,u,e,f,void 0,he?.(),ue,Pt);let r=cn(e);typeof r==`string`&&H9e(ka(r).body,e,h).rewrites>0&&(v.add(e),y.set(e,r),x.add(e))}let E=[...v].sort((e,t)=>e.localeCompare(t)),D=new Set,O=[];for(let e of[...m.keys(),...E]){if(y.has(e))continue;if(!m.has(e)){let t=et(f,`file`,e);if(!G(t)){O.push(e);continue}}await T$(t,u,e,f,void 0,he?.(),ue,Pt);let n=cn(e);typeof n==`string`?(y.set(e,n),m.has(e)||x.add(e)):m.has(e)||O.push(e)}if(d.length>0){let e=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=y.get(t)??cn(t);typeof e==`string`&&fn(e,t,m.get(t)??t,d,h).rewrites!==0&&(y.has(t)||y.set(t,e),D.add(t),m.has(t)||x.add(t))}}hn(D);for(let{from:e}of p)if(typeof y.get(e)!=`string`)throw new X9e(e);let k=dCt({fromPath:e,toPath:n,affectedDocs:[...p],snapshots:sn([...y.keys()],y)}),A=[],M=[...x].sort((e,t)=>e.localeCompare(t)),N=[];return await SCt(me??f,k,async()=>{for(let e of O)N.push({kind:`delete`,documentName:e});for(let e of M){let t=u.documents.get(e),n=t?un(e,d,h):fn(y.get(e)??``,e,e,d,h);n.rewrites>0&&(ln(e,n.markdown,t),A.push({docName:e,rewrites:n.rewrites})),N.push({kind:`link-rewrite`,documentName:e,markdown:n.markdown})}if(Fe)for(let{from:e,to:t}of p)_U(e)||vU(e)||(Fe.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let a=et(f,r,e),o=et(f,r,n),s=p.map(({to:e})=>je?.(e));await a5(me,a,o)||i5(a,o);for(let e of s)e?.();r===`folder`&&pt(e,n);let c=await nn([...m.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);IU(`rename.appendLog`,{attributes:{"rename.kind":r}},e=>{let t=i?.actor,n=P8({moves:p,kind:r,branch:P?.()??`main`,writer:t?{writerId:t.writerId,displayName:t.displayName,colorSeed:t.colorSeed,actor:t.actorMetadata}:{writerId:IJ.id,displayName:IJ.name,colorSeed:IJ.id},shadow:j?.current,notices:Qe});e.setAttribute(`rename.entries_appended`,n)});let l=r===`file`&&BH(n)?Ws(n):null;for(let{from:e,to:t}of p){let n=BH(e)?Ws(e):qH(e);ZH(e),KH(t,l??n)}let g=[...p].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:n}of g){let r=et(f,`file`,e),i=et(f,`file`,n),a=fn(c.get(e)??y.get(e)??K(i,`utf-8`),e,n,d,h);on([{fromDocName:e,toDocName:n}],new Map([[e,a.markdown]])),t.setReconciledBase(n,a.markdown),b?.({kind:`rename`,oldPath:r,newPath:i,oldDocName:e,newDocName:n,content:a.markdown}),N.push({kind:`rename`,oldDocumentName:e,newDocumentName:n,markdown:a.markdown});try{await gt.renameDoc(e,n)}catch(t){H8.warn({err:t,fromDocName:e,toDocName:n},`[comments] cover-sheet rename failed; index updated, disk self-corrects at boot`)}a.rewrites>0&&A.push({docName:n,rewrites:a.rewrites})}if(await Rt(N,`document-rename`),process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),at?.(`files`),A.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,A.length),{renamed:_,renamedAssets:d,rewrittenDocs:A}}))}function Cn(e){let t=CXe(e),n=t.suppliedWriterId??`claude-1`;return{rawAgentId:t.rawAgentId,suppliedWriterId:t.suppliedWriterId,agentId:n,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??n,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function wn(e){return{principalId:ge?.()?.id,agentType:AH(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Tn(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function En(e){return{value:e.value}}function Dn(e,t=!1){e.kind===`value`&&(hZe(),e.truncatedFrom!==void 0&&!t&&gZe())}function On(e,t,n,r){if(n.length!==0)switch(e.kind){case`agent`:{let r=e.summary.kind===`value`,i=r?e.summary:PQ(t),a=Tn(i),o=r||!a.response?a.response:En(a.response);for(let t=0;t<n.length;t++){let{docName:r,subject:i}=n[t];c$(r,e.writerId,e.displayName,e.colorSeed,i,e.actor,t===0?a.stored:void 0)}aU(),Dn(i,!r);for(let{docName:e}of n)Tt(e,`rename-path`);return o}case`principal`:{let t=Tn(e.summary);for(let r=0;r<n.length;r++){let{docName:i,subject:a}=n[r];c$(i,e.writerId,e.displayName,e.colorSeed,a,e.actor,r===0?t.stored:void 0)}Dn(e.summary,!1);for(let{docName:e}of n)Tt(e,`rename-path`);return t.response}case`anonymous`:r.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${r.context}: ${String(t.kind)}`)}}}function kn(e,t,n){let r=t.replace(/\/$/,``),i=r===``?``:`${r}/`;return e===`template`?`${i}.ok/templates/${n}`:e===`skill`?`${rr(String(n))}/SKILL`:e===`folder-frontmatter`?`${i}.ok/frontmatter`:r===``?`.`:r}function An(e,t,n,r){if(e.kind!==`agent`&&e.kind!==`principal`)return;let i=Tn(e.summary);c$(t,e.writerId,e.displayName,e.colorSeed,n,e.actor,i.stored,r)}let jn=null;function Mn(){De&&(jn!==null&&clearTimeout(jn),jn=setTimeout(()=>{jn=null,De?.rebuildIgnorePatterns().catch(()=>{})},12e4))}function Nn(){nt(),De?.refreshInPlaceSkillDirs(),Mn()}function Pn(){Nn(),at?.(`files`)}let Fn=Promise.resolve();function In(e){nt(),Fn=Fn.then(async()=>{await Ln(e)}).catch(()=>{})}async function Ln(e){if(!N)return`unavailable`;try{return await N(),`flushed`}catch(t){return H8.warn({context:e,err:t},`[${e}] flushContributors failed; attribution stays queued for the next flush`),`failed`}}let Rn=Z(tie,async(n,r,i)=>{try{let n=J8(i.docName,r,`agent-write`);if(n===null)return;let a=wt(n),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=Cn(i);if(_U(a)||vU(a)){X(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-write`,extensions:{...PG[`urn:ok:error:reserved-doc-name`]}});return}let g=PQ(i.summary),_=await d.getSession(a,o,{displayName:c,colorSeed:l,clientName:p}),v=await T$(t,u,a,f,e.resolveEmbed,he?.(),ue,Pt),y=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${y}`,{response:x,stored:S}=Tn(g),C,w;try{let n=qn(p),r=uo[n]??Re(l??o);se?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:a,mode:`writing`,ts:Date.now()}),C=o$(_.dc.document.getText(`source`),o,_.origin,l,p),SQ(_.dc.document,`${b}\n`,`append`),_.dc.document.transact(()=>{let t=wQ(_.dc.document);CQ(_.dc.document,`${b}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,void 0,xQ(_),s);let n=$c(t,wQ(_.dc.document))??void 0;_.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${b.slice(0,50)}`,...n===void 0?{}:{changedBlocks:n}})},_.origin),w=mG(_.dc.document),t.markAgentWriteStore(a),c$(a,o,c,l,void 0,wn({clientName:p,clientVersion:m,label:h}),S),aU(),Dn(g)}finally{C?.(),se?.touchMode(o,`idle`)}let T=await jt(a,w);if(T?.kind===`failure`){s5(r,T.failure,`agent-write`);return}if(T?.kind===`stale-external-write`){Nt(r,`agent-write`,a);return}Et(a,`agent-write`),ce?.();let E=S$(v),D={timestamp:y,...x?{summary:x}:{},...E?{warnings:[E]}:{}},O=LG(v,T);if(O.outcome===`both-kept`){H$(r,`agent-write`,D,O);return}Q(r,200,yte,{...D,...O},{handler:`agent-write`})}catch(e){if(e instanceof QJ){$J(r,e,`agent-write`,ue.findByDocName(UH(e.file)));return}if(e instanceof SZ){CZ(r,e,`agent-write`);return}if(e instanceof EQ){V$(r,e,`agent-write`);return}H8.error({err:e,requestId:ZK(n)},`[agent-write] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),zn=Z(cre,async(n,r,i)=>{try{let a=We(),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=Cn(i),g=new Date().toISOString(),_=(e,t,n,r,i,a)=>({status:`error`,docName:e,error:{type:t,title:n,...r===void 0?{}:{detail:r},...i},...a}),v=(e,t)=>{if(t instanceof nq)return j3e(t,`agent-write-batch`),_(e,tq,O3e,A3e,{retryAfterSeconds:3},PG[`urn:ok:error:concurrent-overwrite-refused`]);if(t instanceof QJ){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:`agent-write-batch`,"doc.name":e}));let{detail:t,...n}=E7e(ue.findByDocName(e));return{status:`error`,docName:e,error:{type:`urn:ok:error:doc-in-conflict`,title:`Document is in conflict.`,detail:t,...n},...PG[`urn:ok:error:doc-in-conflict`]}}return t instanceof SZ?(Qtt(t,`agent-write-batch`),_(e,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,Ztt(t),void 0,PG[`urn:ok:error:frontmatter-malformed`])):t instanceof EQ?_(e,oot,sot,cot,lot,PG[`urn:ok:error:too-many-agent-sessions`]):(H8.error({err:t,docName:e,requestId:ZK(n)},`[agent-write-batch] entry failed`),_(e,`urn:ok:error:internal-server-error`,`Internal server error.`))},y=Array(i.docs.length),b=[],x=new Map,S=new Map;try{let n=qn(p),r=uo[n]??Re(l??o);se?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:wt(i.docs[0].docName),mode:`writing`,ts:Date.now()}),await d.withSessions(async n=>{for(let r=0;r<i.docs.length;r++){let a=i.docs[r],d=wt(a.docName);if(_U(d)||vU(d)){y[r]=_(d,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,void 0,void 0,PG[`urn:ok:error:reserved-doc-name`]);continue}try{a.extension!==void 0&&!Z8(f,d)&&KH(d,a.extension);let i=PQ(a.summary),{response:g,stored:_}=Tn(i),v=await n(d,o,{displayName:c,colorSeed:l,clientName:p}),y=await T$(t,u,d,f,e.resolveEmbed,he?.(),ue,Pt),C=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,w=await bQ(v.dc.document,a.markdown,a.position??`append`,C),T,E=o$(v.dc.document.getText(`source`),o,v.origin,l,p);SQ(v.dc.document,a.markdown,a.position??`append`);try{v.dc.document.transact(()=>{let e=wQ(v.dc.document);T=CQ(v.dc.document,a.markdown,a.position??`append`,C,w,xQ(v),s);let t=$c(e,wQ(v.dc.document))??void 0;v.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${a.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},v.origin),x.set(d,mG(v.dc.document)),S.set(d,v.dc.document.getText(`source`).toString()),t.markAgentWriteStore(d)}finally{E()}uwt(`agent-write-batch`,T),c$(d,o,c,l,void 0,wn({clientName:p,clientVersion:m,label:h}),_),aU(),Dn(i);let D=S$(y),O=[...T===void 0?[]:[xZ(T)],...D?[D]:[]];b.push({index:r,docName:d,reconcile:y,summaryResponse:g,warnings:O,diverged:T!==void 0})}catch(e){y[r]=v(d,e)}}let r=new Map,d=new Map;for(let e of b){if(r.has(e.docName))continue;let t=await jt(e.docName,x.get(e.docName));d.set(e.docName,t),t?.kind===`failure`?r.set(e.docName,Qwt(t.failure)):t?.kind===`stale-external-write`?r.set(e.docName,Zwt(Mt(e.docName))):r.set(e.docName,void 0)}let g=await It(b.filter(e=>r.get(e.docName)===void 0).map(e=>e.docName)),C;for(let e of b){let t=r.get(e.docName),n=d.get(e.docName)??null;if(t!==void 0){y[e.index]={status:`error`,docName:e.docName,error:t,...n?.kind===`failure`?FG(n.failure):PG[`urn:ok:error:stale-external-write`]};continue}let i=u.documents.get(e.docName)?.getText(`source`).toString()??S.get(e.docName)??``;Zt(e.docName,i);let o=g(i,e.docName,a.suppressLogLinkAdvisories),s=[...e.warnings,...o.warnings];y[e.index]={status:`written`,docName:e.docName,...LG(e.reconcile,n,e.diverged),...e.summaryResponse?{summary:e.summaryResponse}:{},...s.length>0?{warnings:s}:{},...o.links},C=e.docName}C!==void 0&&(oe?.setFocus(o,{agentName:c,currentDoc:C,writeKind:`write`,ts:Date.now()}),ce?.())})}finally{se?.touchMode(o,`idle`)}let C=y.map((e,t)=>e??_(i.docs[t].docName,`urn:ok:error:internal-server-error`,`Internal server error.`)),w=C.filter(e=>e.status===`written`).length;Q(r,200,Bre,{timestamp:g,results:C,written:w,failed:C.length-w},{handler:`agent-write-batch`})}catch(e){H8.error({err:e,requestId:ZK(n)},`[agent-write-batch] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-batch`,cause:e})}},{handler:`agent-write-batch`,method:`POST`}),Bn=ZCt(),Hn=BCt({contentDir:f,assertContentPath:e.assertContentPath,isPathIgnored:e=>De?.isPathIgnored(e)??!1,getAttachmentFolderPath:_,resolveTrackedFile:E}),Un=Tmt({assertContentSubtree:a,contentDir:f,resolveContentEntryPath:et,docNameForPath:e=>$8(f,e),docNameToRelativePath:XH,listManagedDocNamesUnderFolder:e=>vn(e),listAffectedDocNames:(e,t,n)=>Cwt(e,t,n),getFileIndex:g,conflictFileForDocName:e=>ue.findByDocName(e)?.file??null,captureAndCloseDocuments:nn,markRecentlyRemoved:Fe?e=>Fe.setDeleted(e):void 0,mutateFileIndexDelete:b?({path:e,docName:t})=>b({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:ft,upsertFolderIndexPathSegments:dt,deleteDerivedDocumentsBestEffort:Wt,invalidateReferencedAssetsCache:ct,signalFiles:()=>at?.(`files`),nextAvailableDuplicateDocName:e=>kwt(f,e),nextAvailableDuplicateFolderPath:e=>Awt(f,e),resolveDuplicateDocPath:(t,n)=>{let r=Owt(f,t,n);return e.assertContentPath?.(r),r},collectMarkdownCopies:e=>jwt(f,e),collectFolderPaths:e=>Mwt(f,e),contentFilter:De??void 0,unmarkRecentlyRemoved:Fe?e=>Fe.delete(e):void 0,mutateFileIndexCreate:b?({path:e,docName:t,content:n})=>{Ae?.(t),b({kind:`create`,path:e,docName:t,content:n})}:void 0,recordDerivedDocumentBestEffort:zt,recordDerivedMutationsBestEffort:Rt});function Wn(e,t,n,r,i){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return X(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=W(f),s=a===``?o:W(o,a);if(s!==o&&!s.startsWith(`${o}${Ys}`))return X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;let c=W(s,`.ok`);if(MK(c).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;let l=W(s,`.ok`,`templates`);if(i===`ok-and-templates`&&MK(l).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok/templates is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;try{jK(c,o),i===`ok-and-templates`&&jK(l,o)}catch(e){return PK(e)?(X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(X(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:a,resolvedContentDir:o}}function Gn(e,t,n){let r=ue.findByDocName(e);return r!==void 0&&($J(n,new QJ({file:r.file}),t,r),!0)}let Kn=e=>{let{body:t}=ka(e);return{frontmatter:D(e)??{},body:t}};function Jn(e){return!!e&&e.length<=64&&Ce.test(e)}function Yn(e,t,n,r){return Jn(e)?!0:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n,...r?{extensions:r}:{}}),!1)}function Xn(e,t,n){let r=vie.safeParse(e??`project`);return r.success?r.data:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Zn=_e??wc(),Qn=XCt({contentDir:f,skillsHome:Zn,effectiveInstallMode:nr});function $n(e){return W(e===`global`?Zn:f,`.ok`,Oa)}function er(e,t,n){let r=W($n(e),t);if(e===`global`){if(n!==void 0){let e=W1(Zn).find(e=>e.name===t&&e.hosts.includes(n));return e?W(Zn,e.dir):null}let e=K1(Zn,t);return e===null?G(H(r,`SKILL.md`))?r:null:e}let i=U1(f).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?W(f,i.dir):n===void 0&&G(H(r,`SKILL.md`))?r:null}function tr(e,t){let n=e.searchParams;return FQ({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function nr(e,t,n){let r=e===`project`?me:Zn;return(r?Oct(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function rr(e){let t=er(`project`,e);return t?U(f,t).split(Ys).join(`/`):`${y}/${e}`}function ir(e,t,n,r){let i=[],a=null,o=u0(n),s=[...d0(n).map(e=>({id:e,root:o[e]??``})),{id:`agents`,root:ki}];for(let{id:n,root:o}of s){if(!o)continue;let s=W(e,...o.split(`/`),t);G(W(s,`SKILL.md`))&&(i.push(n),(r===void 0?a===null:n===r)&&(a=s))}if(a===null)return null;let c=W(a,`SKILL.md`);return{dir:a,skillMd:c,hosts:i,relPath:U(e,c).split(/[\\/]/).filter(Boolean).join(`/`)}}function ar(e){let t=cFe(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function or(e,t,n){if(!FH(t))return null;let r=ir(e,t,n);if(!r)return null;let i=XM(r.dir)?.contentHash??``,a;try{a=yc(r.skillMd).mtime.toISOString()}catch{a=new Date(0).toISOString()}return{source:Ci,skill:t,contentHash:i,autoUpdate:!1,importedAt:a}}function sr(e,t){return it(t).get(e)?.contentHash??null}function cr(e,t,n){let r=it(t).get(e);if(!r)return null;try{if(hc(n)!==hc(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function lr(e,t,n){let r=it(t).get(e);if(!r)return null;if(n!==void 0)try{if(hc(n)===hc(r.home))return null}catch{}let i;try{i=yc(H(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){H8.warn({err:e,home:r.home},`plugin bundle unreadable; origin dated epoch`),i=new Date(0).toISOString()}return{source:r.home,skill:e,contentHash:r.contentHash,autoUpdate:!1,importedAt:i}}function R(e,t){let n=IH.find(t=>NH[t]===e);if(n===void 0||t!==void 0&&LH[n]!==(t===`global`?`user`:`project`))return null;try{let e=zH(n,{checkDesktop:!0}),t=W(e,`SKILL.md`);return G(t)?t:null}catch(t){return H8.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function ur(e,t,n){let r=ir(e,t,n),i=r?.skillMd??R(t);if(i===null)return null;let a;try{let{frontmatter:e}=Kn(K(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=or(e,t,n),s=XM(V(i));return{name:t,...a===void 0?{}:{description:a},scope:n,path:r?.relPath??i,absolutePath:i,installed:(r?.hosts.length??0)>0,hosts:r?.hosts??[],managed:!0,...s?{size:ca(s)}:{},...o?{origin:ar(o)}:{}}}function dr(e,t,n){return FH(e)?(X(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function fr(e,t){return U(t===`global`?Zn:f,e).split(/[\\/]/).filter(Boolean).join(`/`)}function pr(e){return e===`global`?Zn:me}function mr(e,t,n,r){let i=n===`project`?f:Zn;if(r.purge!==void 0){C0(t,e,d0(n),u0(n));for(let e of Kst(i,n,t,r.purge.contentHash))iW(e,{recursive:!0,force:!0});return}if(!G(W($n(n),t,`SKILL.md`))){let r=(n===`project`?U1(f):W1(Zn)).find(e=>e.name===t);if(r){let i=n===`project`?f:Zn,a=W(i,r.dir),o=W(i,`.agents`,`skills`),s=H(o,t);if(G(o)&&!G(H(s,`SKILL.md`))){let e=!1;try{e=hc(a)===hc(s)}catch{e=!1}e||QU(a,s,{recursive:!0,dereference:!0})}S0({canonicalAbs:G(H(s,`SKILL.md`))?s:a,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...d0(n)],roots:u0(n)});return}}C0(t,e,d0(n),u0(n))}async function hr(e,t,n,r={}){return mr(e,t,n,r),await Z1(e,t)!==null}function gr(e,t){let n=[];if(!G(e))return{skills:n,truncated:!1};let r;try{r=mc(e,{withFileTypes:!0})}catch(r){return q(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Ce.test(a.name))continue;if(n.length>=500){i=!0;break}let r=W(e,a.name,`SKILL.md`);if(!G(r))continue;let o;try{let{frontmatter:e}=Kn(K(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:fr(r,t),absolutePath:r})}return{skills:n,truncated:i}}function _r(e,t,n){let r=e===`project`?f:Zn,i=er(e,t,n);return{root:i===null?$n(e):V(i),dirRel:i===null?`.ok/skills/${t}`:U(r,i).split(Ys).join(`/`),realDir:i}}function vr(e,t){return XM(W(e,t))?.contentHash}async function yr(e,t){let n=j?.current;if(!(!n||!e))try{let r=OJ(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
2089
+ `)){if(i(e))continue;let t=Woe(e,r);t&&n.push(t)}return n}function o5(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function Iwt(e,t){let n=t();n instanceof Map&&mZ(e,n)}function Lwt(e){switch(e.removal?.kind){case`path-occupied`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the file now at this path is not loaded into the document.`,detail:`${e.message}. Retrying will not help until the server reloads this document from disk, for example after Open Knowledge restarts; tell the user instead of retrying.`};case`renamed`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document was renamed.`,detail:`${e.message}. Retrying will not help: re-read the document at ${e.removal.renamedTo} and re-apply your change there.`};case`deleted-outside`:return{type:`urn:ok:error:doc-removed`,title:`Edit not saved to disk: the document was deleted outside the app, and the edit went to its history.`,detail:`${e.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; tell the user the file was deleted, and do not re-create the document on your own.`};case void 0:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document is no longer on disk.`,detail:`${e.message}. Retrying will not help: tell the user the file is no longer on disk.`}}}function Rwt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:`its new name`;return{type:`urn:ok:error:doc-moved`,title:`Edit kept: the document was moved outside the app, and the edit moved with it.`,detail:`${e.message}. Do not repeat the edit: it is in ${t}, which saves it under that name. Re-read ${t} to confirm.`}}function zwt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:void 0;return{type:`urn:ok:error:server-stopped`,title:`Edit not saved to disk: the server stopped before the edit reached disk.`,detail:t===void 0?`${e.message}. After OpenKnowledge restarts, the edit is in the document's history (the timeline); tell the user.`:`${e.message}. After OpenKnowledge restarts, re-read the document at ${t} to see whether it holds the edit, and re-apply the edit there if it is missing. Do not re-create the document under its old name.`}}function Bwt(e){return{type:`urn:ok:error:path-escape`,title:`Edit applied in memory; disk write refused because the document path could not be resolved.`,detail:`${e.message}. Retrying will not help: tell the user the path has to be repaired on disk before this content can be written.`}}const Vwt={"legacy-name":`Write the skill or template by its file path instead; that write is saved to the file.`,unresolvable:`Retrying will not help until the path resolves again. Tell the user which document it is.`,"container-gone":`OpenKnowledge does not re-create a skill folder that was deleted or moved. Tell the user which skill it is.`,"intake-landed":`Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing.`};function Hwt(e){let t=e.dropped===void 0?Vwt.unresolvable:Vwt[e.dropped];return{type:`urn:ok:error:write-dropped`,title:`Edit not saved: OpenKnowledge did not write this document's file.`,detail:`${e.message}. The edit is only in the open document. ${t}`}}function Uwt(e){return{type:`urn:ok:error:write-replaced`,title:`Edit not saved: the file on disk replaced the document, and the edit went to its history.`,detail:`${e.message}. OpenKnowledge had no agreed version of the file to merge the edit with, so it took the file in as it is and saved the document as it was, this edit included, to the document's history (the timeline). Re-read the document, and re-apply the edit if it is still needed.`}}function Wwt(e,t){switch(t.kind){case`branch-switch`:return{code:yG,message:`A Git branch switch discarded the pending save of ${e}`};case`renamed-outside`:return{code:hG,message:`${e} was moved outside the app to ${t.to}, and its open document followed`,removal:{kind:`renamed`,renamedTo:t.to,...t.carry?{carry:t.carry}:{}}};case`deleted-outside`:return{code:hG,message:`${e} was deleted outside the app before the edit reached disk`,removal:{kind:`deleted-outside`}};case`shutdown`:return{code:xG,message:`The server stopped while the file of ${e} was missing`};default:throw Error(`unhandled discard cause: ${JSON.stringify(t)}`)}}function Gwt(e){return{type:`urn:ok:error:branch-switched`,title:`Edit kept in the open document: the Git branch changed before it reached disk.`,detail:`${e.message}. The edit stays in the open document, merged with the checked-out branch's version of the file, and is saved with the document's next save; do not repeat the edit. Re-read the document to confirm it.`}}const Kwt={"pending-unreadable":{retryWhen:`next-save`,sentence:`A later save writes it once the file can be read again: the next edit to this document, or the idle save within a few minutes.`},"pending-exhausted":{retryWhen:`next-save`,sentence:`A later save writes it once the file stops changing: the next edit to this document, or the idle save within a few minutes.`},"pending-base-moved":{retryWhen:`next-save`,sentence:`A later save writes it once the outside changes have been taken in: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed-no-base":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-no-intake":{retryWhen:`next-edit`,sentence:`The next edit to this document tries the save again.`},"pending-conflict":{retryWhen:`conflict-resolved`,sentence:`It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.`},"pending-no-history-or-backup":{retryWhen:`next-save`,sentence:`The file is not written over until its outside version is saved to the document history or the backup folder; a later save tries again: the next edit to this document, or the idle save within a few minutes.`},"pending-not-utf8":{retryWhen:void 0,sentence:`OpenKnowledge does not write over it, and no save runs until someone saves the file as text again. Tell the user which file it is.`},"pending-unsettled":{retryWhen:`next-save`,sentence:`The save was still running when the write stopped waiting for it, and it finishes on its own.`},"pending-rename":{retryWhen:`next-save`,sentence:`The edit goes with the document to its new name, or to its history if the move cannot carry it. Do not repeat this write, and do not re-create the document under its old name: re-read it at its new name.`}};function qwt(e,t,n){if(n)return`${e.message}. This edit is in the document but is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. Any further write to this document, yours included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history (timeline). Do not write to this document again; tell the user that its file changed outside OpenKnowledge.`;let{sentence:r}=Kwt[t];return t===`pending-rename`?`${e.message}. ${r}`:x2e(t)?`${e.message}. The edit is kept in the document. ${r} Do not repeat this write.`:`${e.message}. The edit is kept in the document. ${r} Do not repeat this write: re-read the document before editing it further.`}function Jwt(e){let t=e.held?.reason??`pending-unreadable`,n=e.held?.noBase===!0,r=n?`replaced-on-next-edit`:Kwt[t].retryWhen;return{type:`urn:ok:error:save-held`,title:`Edit applied in memory; its save to disk is held.`,detail:qwt(e,t,n),reason:t,...r===void 0?{}:{retryWhen:r},...e.held?.causeCode===void 0?{}:{causeCode:e.held.causeCode}}}function Ywt(e){return{type:`urn:ok:error:store-refused`,title:`Edit applied in memory; disk write refused because the duplication baseline could not be read.`,detail:`${e.message}. The edit is applied in collaborative state and the document file on disk was not updated; a copy of the edited document is preserved in the server's recovery buffer unless that buffer is unavailable or unwritable. Do not repeat the write now: once the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.`}}function Xwt(e){let t=FG(e),n=(e,n)=>({status:e,problem:{...n,...t}});switch(e.code){case _G:return n(503,Ywt(e));case vG:return n(503,Jwt(e));case hG:return n(409,Lwt(e));case yG:return n(409,Gwt(e));case bG:return n(409,Rwt(e));case xG:return n(503,zwt(e));case gG:return n(400,Bwt(e));case SG:return n(409,Uwt(e));case CG:return n(409,Hwt(e));default:return}}function Zwt(e){let{outcome:t,saved:n,nextStep:r,...i}=e;return i}function Qwt(e){let t=Xwt(e);return t?Zwt(t.problem):{type:G4({code:e.code}),title:`Write applied in memory but failed to persist to disk.`,detail:`${e.code??`unknown error`}: ${e.message}. The content was NOT saved and will be lost if the server restarts.`}}function s5(e,t,n){let r=Xwt(t);if(r){let{type:t,title:i,detail:a,...o}=r.problem;X(e,r.status,t,i,{handler:n,...a===void 0?{}:{detail:a},extensions:o});return}let i=G4({code:t.code});X(e,W4(i),i,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:n,extensions:{...FG(t)}})}function $wt(e){let{durabilityState:t}=e,n=!1,r=new Set;async function i(e,i){if(n)throw new JK(i.startsWith(`/api/local-op/`));let a=t.runWithinWriteWaitBudget(e);r.add(a);try{await a}finally{r.delete(a)}}let a=e.assertContentSubtree,o=e.ingressPolicy??BQ({}),s=(e,t,n)=>Lit(e,t,{...n,policy:o}),c=e=>HQ(e,o),l=e=>VQ(e,o),{hocuspocus:u,sessionManager:d,contentDir:f,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m,serverInstanceId:h,getFileIndex:g,getAttachmentFolderPath:_,getAllFilesIndex:v=g,mutateFileIndex:b=e=>Iwt(e,v),getFileIndexGeneration:x,getFolderIndex:S,onReferencedAssetsCacheInvalidator:C,getAliasMap:w,getFolderAliasIndex:T,resolveTrackedFile:E,rescanFiles:O,localOpConcurrencyGuard:k,enableTestRoutes:A=!1,shadowRef:j,flushGitCommit:M,flushContributors:N,getCurrentBranch:P,getReportedBranch:te,getDiskAckSVs:F,getCollabClientCount:ne,contentRoot:re,derivedDocumentIndex:ie,signalChannel:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,onAgentWrite:ce,getSyncEngine:le,conflicts:ue,setBatchInProgress:de,localOpCliArgs:fe,authStreamHeartbeatMs:pe,projectDir:me,getBridgeLossReporter:he,getPrincipal:ge,homeDirOverride:_e,resetSettingsForTest:ve,settleDiskEventsForTest:be,agentIntegrations:xe,savedThemeLockTimeoutMs:Se,acpRegistry:we,loadAcpCustomAgents:Te,acpHarnessAvailability:Ee=Oot(),contentFilter:De,installedAgentsProbe:Oe,forceUnloadDocument:ke,onNamespaceCreateAccepted:Ae,captureNamespaceMove:je,capturePublicationReceipt:Me,onResidentAdopted:Ne,ready:Pe,recentlyRemovedDocs:Fe,serializeDoc:Ie,evictManagedArtifactLkg:Le,semanticSearch:ze,getSemanticSimilarityFloor:Be,embeddingsSecretsFile:Ve,readSemanticProviderConfig:He,getLinterBaseConfig:Ue,getLinkAdvisoryPolicy:We,getProjectConfigEpoch:Ge,ephemeral:Ke=!1,linkPreviewFetch:qe,getLinkPreviewsEnabled:Je,resolveGitHubToken:Ye,githubReferenceFetch:Xe,getConfigDiagnostics:Ze}=e,Qe=e.docNotices,I=e.declaredGitHubHosts??x6(_e),$e=e.resolveSyncCredentialConfig??Bvt({projectDir:me??f,tokenStore:null,localOpCliArgs:fe,declaredGitHubHosts:I});function et(t,n,r){let i=Y8(t,n,r);return e.assertContentPath?.(i),i}let tt=$dt({homeDirOverride:_e,log:H8}),{bumpSkillsCatalogGen:nt,enumerateInstalledSkillsCached:rt,pluginSkillsByName:it}=tt,at=ae?e=>{e===`files`&&nt(),ae(e)}:void 0,ot=k??Rit(),st=hmt({hocuspocus:u,conflicts:ue,contentDir:f,isSafeDocName:o5,resolveAlias:wt,resolveContentEntryPath:et,resolveDocPath:ht,extractHeadings:Fwt,getFileIndex:g,getFileIndexGeneration:x,log:H8,ready:Pe,contentFilter:De,safeSubdir:pwt,getShowAllMaxEntries:_wt,streamShowAllEntries:q8,walkContentDirForShowAll:Swt,synthesizeShowAllAssetExt:W8,getAllFilesIndex:v,getFolderIndex:S,getFolderAliasIndex:T,onReferencedAssetsCacheInvalidator:C}),{invalidateReferencedAssetsCache:ct}=st;function lt(){let e=S?.();return e instanceof Map?e:null}function ut(e){let t=lt();if(t)try{let n=yc(e,{bigint:!0});AX(t,f,e,n,e)}catch(t){H8.warn({path:e,err:t},`folder index stat failed for ${e}`)}}function dt(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)ut(W(f,t.slice(0,e).join(`/`)))}function ft(e){let t=lt();t&&jX(t,e)}function pt(e,t){let n=lt();if(!n)return;let r=[];for(let[i,a]of n.entries()){if(i!==e&&!i.startsWith(`${e}/`))continue;n.delete(i);let o=i.slice(e.length);r.push([`${t}${o}`,a])}if(r.length===0){let e=et(f,`folder`,t);G(e)&&ut(e);return}for(let[e,t]of r)n.set(e,{...t,modified:new Date().toISOString(),canonicalPath:W(f,e)})}let mt=Hot({probe:Oe??i1(process.platform)});function ht(e){if(rn(e))try{return r6(e,{projectDir:me??f,homedirOverride:_e})}catch{return null}if(!o5(e))return null;let t=W(f),n=XH(e),r=W(t,n);return uG(r,t)?r:null}let gt=new Iot({store:new Lot(W(f,`.ok`,wi),H8),index:new kot,getDocBody:e=>{try{let t=u.documents.get(e);if(t)return ka(t.getText(`source`).toString()).body}catch{}try{let t=ht(e);if(t&&G(t))return ka(K(t,`utf-8`)).body}catch{}return null},getDocFrontmatter:e=>{try{let t=u.documents.get(e);if(t)return D(t.getText(`source`).toString())??{}}catch{}try{let t=ht(e);if(t&&G(t))return D(K(t,`utf-8`))??{}}catch{}return null}});e.commentDocHooksRef&&(e.commentDocHooksRef.current={changed:e=>{gt.refindDoc(e).then(e=>{e&&at?.(`comments`)}).catch(t=>{H8.warn({err:t,docName:e},`[comments] re-anchor after document change failed`)})},deleted:e=>{gt.deleteDoc(e).then(e=>{e>0&&at?.(`comments`)}).catch(t=>{H8.warn({err:t,docName:e},`[comments] cleanup after document delete failed`)})}});function _t(e){let t=ht(e);if(!t||!G(t))return e;try{return JY(K(t,`utf-8`),e)}catch{return e}}function vt(e,t){return t.has(e)?_t(e):e}let yt={cluster:void 0,category:void 0,tags:void 0};function bt(e){try{let t=u.documents.get(e);if(t){let e=ote(t.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,n=typeof e.category==`string`?e.category:void 0,r;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);r=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(r=[e.tags]);return{cluster:t,category:n,tags:r}}}}catch{}try{let t=ht(e);if(!t||!G(t))return yt;let n=K(t,`utf-8`),{frontmatter:r}=ka(n);return r?pet(r):yt}catch{return yt}}function xt(e,t){return t.has(e)?bt(e):yt}let St=twt();async function Ct(e){if(ie?.isReady())try{let t=await St.run(`orphan-hints`,()=>ie.getBacklinks(e),()=>void 0);if(t===void 0||t.length>0)return;let n=performance.now(),r=Mlt(e,g()),i=performance.now()-n;return i>5&&H8.debug({docName:e,elapsedMs:i,candidateCount:r.length},`[orphan-hint] findHubCandidates slow`),r.length===0?void 0:[{type:`orphan`,parentCandidates:r,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${r.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){H8.warn({err:e},`[orphan-hint] computeOrphanHints failed`);return}}function wt(e){return w?.().get(e)??e}function Tt(e,t){let n=`onStoreDocument-${e}`;(u.debouncer.isDebounced(n)?u.debouncer.executeNow(n):Promise.resolve()).then(()=>M?.()).catch(e=>{H8.warn({err:e},`[${t}] post-write flush failed`)})}function Et(e,t){let n=`onStoreDocument-${e}`;u.debouncer.isDebounced(n)&&u.debouncer.executeNow(n).catch(e=>{H8.warn({err:e},`[${t}] post-write disk flush failed`)})}function Dt(e,t,n){return{kind:`failure`,failure:{code:vG,message:`${e} ${n}`,held:{reason:t}}}}async function Ot(e,n,r){if(n.code!==`OK_DOC_REMOVED`||n.removal?.kind!==`renamed`)return{kind:`failure`,failure:n};let i=await t.awaitRenameCarry(e,n.removal.carry),a=n.removal.renamedTo;switch(i.kind){case`unsettled`:return Dt(e,`pending-rename`,`was still being moved outside the app to ${a} when the write stopped waiting`);case`stopped`:return{kind:`failure`,failure:{code:xG,message:`The server stopped while ${e} was being moved outside the app to ${a}`,removal:{kind:`renamed`,renamedTo:a}}};case`settled`:return{kind:`failure`,failure:a2e(r,i.carried)?{...n,code:bG}:n};default:throw Error(`unhandled rename carry answer: ${JSON.stringify(i)}`)}}function kt(e){let t=u.documents.get(e);return t?mG(t):void 0}async function At(e){let t=u.documents.get(e);t!==void 0&&await u.storeDocumentHooks(t,{instance:u,clientsCount:t.getConnectionsCount(),document:t,documentName:e,lastContext:{},lastTransactionOrigin:null},!0)}async function jt(e,n=kt(e)){let r=`onStoreDocument-${e}`;u.debouncer.isDebounced(r)?(t.markAgentWriteStore(e),await u.debouncer.executeNow(r)):u.debouncer.isCurrentlyExecuting(r)&&(t.markAgentWriteStore(e),await At(e));let i=Date.now(),a=await t.awaitDeferredStoreOutcome(e),o,s=!1;switch(a?.kind){case void 0:case`completed`:break;case`discarded`:o=Wwt(e,a.cause);break;case`failed`:o=t.takeStoreFailure(e)??a.failure;break;case`unsettled`:{s=!0;let t=Date.now()-i;console.warn(JSON.stringify({event:`agent-write-deferred-store-unsettled`,"doc.name":e,waitedMs:t,timestamp:new Date().toISOString()})),H8.warn({docName:e,waitedMs:t},`[agent-write] deferred store still pending after the wait; answering that the save is held`);break}default:c2e(a)}o??=t.takeStoreFailure(e)??void 0;let c=t.readStoreIntake(e,n);return t.consumeAgentWriteStore(e),o?Ot(e,o,n):t.takeStaleExternalWriteFreeze(e)?{kind:`stale-external-write`}:s?Dt(e,`pending-unsettled`,`was still being saved when the write stopped waiting`):c===`disk-replaced`?{kind:`failure`,failure:{code:SG,message:`${e} changed on disk, and its file replaced the document`}}:c===void 0?null:{kind:`taken-in`,merge:c}}function Mt(e){return{type:`urn:ok:error:stale-external-write`,title:`Edit retained; disk write blocked by a stale external-write conflict.`,detail:`An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: ask the user to resolve the conflict in the OpenKnowledge app, then re-read the document before making further changes.`,file:t.getStaleExternalWrite(e)?.file??U(me??f,GG(e,f)).replaceAll(`\\`,`/`),resolutionOptions:ZJ,...PG[`urn:ok:error:stale-external-write`]}}function Nt(e,t,n){let{type:r,title:i,detail:a,...o}=Mt(n);X(e,409,r,i,{handler:t,detail:a,extensions:o})}let Pt=ACt({getShadow:()=>j?.current,contentRoot:re??``,getBranch:()=>P?.()??null,writeCheckpoint:e.mergeHistoryWriter,notices:e.docNotices});function L(e){if(!De)return!1;let t=XH(e);return De.isExcluded(t)}function Ft(){return ie?.isReady()??!0}let It=async e=>{if(!Ft())return _ut;let t;try{t=await St.run(`link-check`,Lt,()=>null)}catch(e){return H8.warn({err:e},`[link-check] write link advisory failed post-write; skipping link checks`),vut}if(t===null)return vut;for(let n of e)t.add(n);let n={fileExists:Kt(),folderExists:Gt(),fileExcluded:Xt(),resolveWikiFile:Jt(),resolveFileByBasename:Yt()};return(e,r,i)=>({links:yut(rwt(e,r,t,n),r,i),warnings:[]})};async function Lt(){let e=new Set;for(let[t,n]of g()){e.add(t);for(let t of n.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let n=W(t===`global`?Zn:f,`.ok`,Oa);for(let r of gr(n,t).skills)e.add(`${_n}${t}/${r.name}`)}}catch(e){H8.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of await ie?.getIndexedDocNames()??[])e.has(t)||L(t)||e.add(t);return e}async function Rt(e,t){if(!(!ie||e.length===0))try{await ie.recordDirectMutations(e)}catch(n){Vt(n,{count:e.length,reason:t},`[derived-index] failed to project durable document mutations`)}}async function zt(e,t,n){if(ie)try{await ie.recordDirectDocument(e,t)}catch(t){Vt(t,{documentName:e,reason:n},`[derived-index] failed to project durable document`)}}async function Bt(e,t,n){if(ie)try{await ie.recordLinkRewrite(e,t)}catch(t){Vt(t,{documentName:e,reason:n},`[derived-index] failed to project link rewrite`)}}function Vt(e,t,n){if(q2(e)){H8.debug({err:e,...t},`[derived-index] coordinator closed; skipping durable projection`);return}H8.warn({err:e,...t},n)}function Ht(e,t,n){if(q2(t)){X(e,503,`urn:ok:error:derived-index-unavailable`,`Derived index is shutting down.`,{handler:n.handler,cause:t,logLevel:`debug`});return}X(e,500,`urn:ok:error:internal-server-error`,n.failureTitle,{handler:n.handler,cause:t})}async function Wt(e,t){await Rt([...e].map(e=>({kind:`delete`,documentName:e})),t)}function Gt(){let e=S?.();if(!e)return()=>!1;let t=Ji(`folder`,e.keys());return e=>t.resolve(e)!==void 0}function Kt(e=v()){return Bdt(V2(e,T?.()??new Map,f).fileTargets,f,De)}function qt(){return V2(v(),T?.()??new Map,f,S?.())}function Jt(){let e;return t=>(e??=_a(qt().fileTargets),e(t))}function Yt(){let e;return(t,n)=>(e??=zdt(qt().fileTargets),e(t,n))}function Xt(){return e=>N2(f,De,e)}function Zt(e,t){L(e)||b?.({kind:g().has(e)?`update`:`create`,path:et(f,`file`,e),docName:e,content:t})}function Qt(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let $t=Qt(),en=e=>e.endsWith(`.`)?e:`${e}.`;function tn(e){return e instanceof Error?e instanceof PY?{status:404,type:`urn:ok:error:doc-not-found`,error:en(e.message)}:e instanceof FY?{status:409,type:`urn:ok:error:doc-already-exists`,error:en(e.message)}:e instanceof IY||e instanceof LY?{status:400,type:`urn:ok:error:invalid-request`,error:en(e.message)}:e instanceof RY?{status:400,type:`urn:ok:error:reserved-doc-name`,error:en(e.message)}:e instanceof X9e||e instanceof Y9e?{status:404,type:`urn:ok:error:doc-not-found`,error:en(e.message)}:PK(e)?{status:400,type:`urn:ok:error:path-escape`,error:en(e.message)}:e instanceof zY?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:en(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function nn(e,n){let r=new Map;for(let t of e){let e=u.documents.get(t);e&&r.set(t,e.getText(`source`).toString())}for(let t of e){let e=u.documents.get(t);e&&e.getMap(`lifecycle`).set(`status`,n)}for(let t of e)await d.closeAllForDoc(t).catch(e=>{H8.warn({docName:t,err:e},`[file-ops] Failed to close agent session for ${t}`)});for(let n of e){let e=u.documents.get(n);t.deleteReconciledBase(n),Le?.(n),e&&(u.closeConnections(n),await(ke??u.unloadDocument.bind(u))(e))}return r}function an(n,r){let i=u.documents.get(n);pat(t,u,n,r,e.resolveEmbed,void 0,he?.())===`revived`&&i&&Ne?.(i,n)}function on(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=GG(r,f),i=t.get(n);typeof i==`string`&&r5(e,i);let a=typeof i==`string`?i:G(e)?K(e,`utf-8`):null;typeof a==`string`&&(hX(e,dG(a)),an(r,a))}}function sn(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let r=GG(e,f);if(!G(r))throw new Y9e(e);return{docName:e,content:K(r,`utf-8`)}})}function cn(e){let t=u.documents.get(e);if(t)return t.getText(`source`).toString();let n=et(f,`file`,e);return G(n)?K(n,`utf-8`):null}function ln(e,n,r){let i=r?Me?.(r,e):void 0,a=et(f,`file`,e);XU(V(a),{recursive:!0});let o=r5(a,n);hX(a,dG(n)),t.setReconciledBase(e,n),o&&i?.(),b?.({kind:`update`,path:a,docName:e,content:n})}function un(e,t,n){let r=u.documents.get(e);if(!r)throw Error(`Document is not loaded: ${e}`);let i={markdown:``,rewrites:0};return r.transact(()=>{i=fn(r.getText(`source`).toString(),e,n.renames.get(e)??e,t,n),i.rewrites!==0&&Rq(r,i.markdown,`managed-rename`,!1)},V8),i}function dn(e,t,n){let r=e,i=0;for(let{fromPath:e,toPath:a}of n){let n=G9e(r,t,e,a);r=n.markdown,i+=n.rewrites}return{markdown:r,rewrites:i}}function fn(e,t,n,r,i){let a=Q9e(e,t,i),o=dn(a.markdown,n,r);return{markdown:o.markdown,rewrites:o.markdown===e?0:a.rewrites+o.rewrites}}function pn(e,t){let n=u.documents.get(e);if(!n)throw Error(`Document is not loaded: ${e}`);let r={markdown:``,rewrites:0};return n.transact(()=>{r=dn(n.getText(`source`).toString(),e,t),r.rewrites!==0&&Rq(n,r.markdown,`managed-rename`,!1)},V8),r}function mn(e){let t=[];if(e.length===0)return t;let n=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let r of n){let n=cn(r);if(typeof n!=`string`)continue;let i=dn(n,r,e);i.rewrites!==0&&t.push({docName:r,markdown:i.markdown,rewrites:i.rewrites})}return t}function hn(e){for(let t of e){let e=ue.findByDocName(t);if(e!==void 0)throw new QJ({file:e.file})}}async function gn(e,t){let n=[],r=[];for(let i of e){let e=u.documents.get(i.docName),a=e?pn(i.docName,t):i;a.rewrites!==0&&(ln(i.docName,a.markdown,e),r.push({kind:`link-rewrite`,documentName:i.docName,markdown:a.markdown}),n.push({docName:i.docName,rewrites:a.rewrites}))}return{rewrittenDocs:n,derivedMutations:r}}let vn=e=>eft(e,{contentDir:f,contentFilter:De,docNameForPath:e=>$8(f,e)});function yn(e,t,n){let r=[];function i(e){for(let a of mc(e,{withFileTypes:!0})){let o=W(e,a.name),s=U(f,o).split(Ys).join(`/`);if(!H2(s)){if(a.isDirectory()){if(De?.isDirExcluded(s))continue;i(o);continue}!a.isFile()||BH(s)||De?.isExcluded(s)||(s===t?r.push({fromPath:s,toPath:n}):s.startsWith(`${t}/`)&&r.push({fromPath:s,toPath:`${n}${s.slice(t.length)}`}))}}}return i(e),r.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),r}async function bn(e,t){return $t(async()=>FU(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async n=>{if(!ie)throw new zY;let r=Ws(t)?t:`${t}${Ws(e)}`;if(H2(e)||H2(r))throw new RY(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(r))throw new LY(`Destination asset is excluded by the project content config.`);let i=et(f,`folder`,e),a=et(f,`folder`,r);if(i===a)return{renamedAssets:[],rewrittenDocs:[]};if(t5(e,r))throw new LY(`Case-only renames are not supported.`);if(!G(i))throw new PY(`asset`,`Asset does not exist.`);if(G(a))throw new FY;if(!yc(i).isFile())throw new IY(`asset`,`Source path is not an asset file.`);let o=[{fromPath:e,toPath:r}],s=mn(o);n.setAttribute(`rename.rewrite_candidates`,s.length),hn(s.map(e=>e.docName)),await a5(me,i,a)||i5(i,a);let{rewrittenDocs:c,derivedMutations:l}=await gn(s,o);return await Rt(l,`asset-rename`),at?.(`files`),c.sort((e,t)=>e.docName.localeCompare(t.docName)),n.setAttribute(`rename.rewrite_count`,c.length),{renamedAssets:o,rewrittenDocs:c}}))}async function xn(e,n){return $t(async()=>FU(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async r=>{if(!ie)throw new zY;if(!BH(e)||BH(n))throw new LY(`Document-to-file rename requires a markdown source and non-markdown destination.`);let i=UH(e);if(_U(i)||vU(i))throw new RY(`Reserved document names cannot be renamed.`);if(H2(e)||H2(n))throw new RY(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(n))throw new LY(`Destination file is excluded by the project content config.`);let a=et(f,`folder`,e),o=et(f,`folder`,n);if(a===o)return{renamedAssets:[],rewrittenDocs:[]};if(t5(e,n))throw new LY(`Case-only renames are not supported.`);if(!G(a))throw new PY(`file`);if(G(o))throw new FY;if(!yc(a).isFile())throw new IY(`file`,`Source path is not a document file.`);let s=ue.findByDocName(i);if(s!==void 0)throw new QJ({file:s.file});let c=[{fromPath:e,toPath:n}],l=mn(c).filter(e=>e.docName!==i);r.setAttribute(`rename.rewrite_candidates`,l.length),hn(l.map(e=>e.docName)),await T$(t,u,i,f,void 0,he?.(),ue,Pt),Fe&&!_U(i)&&!vU(i)&&Fe.setDeleted(i);let d=(await nn([i],`renamed`)).get(i),p=typeof d==`string`?d:K(a,`utf-8`),m=dCt({fromPath:e,toPath:n,affectedDocs:[{from:i,to:i}],snapshots:[{docName:i,content:p}],cleanupPaths:[n]}),h=[];return await SCt(me??f,m,async()=>{r5(a,p),hX(a,dG(p)),await a5(me,a,o)||i5(a,o),ZH(i),b?.({kind:`delete`,path:a,docName:i});let e=yc(o,{bigint:!0});b?.({kind:`file-create`,path:o,relativePath:n,size:Number(e.size),modifiedTs:rS(e),inode:nS(e)});let t=await gn(l,c);h=t.rewrittenDocs,await Rt([{kind:`delete`,documentName:i},...t.derivedMutations],`document-to-file-rename`),at?.(`files`)}),h.sort((e,t)=>e.docName.localeCompare(t.docName)),r.setAttribute(`rename.rewrite_count`,h.length),{renamedAssets:c,rewrittenDocs:h}}))}async function Sn(e,n,r,i){return $t(async()=>FU(`rename.executeRewrites`,{attributes:{"rename.kind":r}},async o=>{if(!ie)throw new zY;let s=et(f,r,e),c=et(f,r,n);if(s===c)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!G(s))throw new PY(r);if(G(c)&&!Nwt(s,c))throw new FY;let l=yc(s);if(r===`file`&&!l.isFile()||r===`folder`&&!l.isDirectory())throw new IY(r);r===`folder`&&(WG(s,f),a?.(s));let d=r===`folder`?yn(s,e,n):[];o.setAttribute(`rename.affected_assets`,d.length);let p=(r===`file`?[$8(f,e)]:vn(s)).map(t=>({from:t,to:r===`file`?$8(f,n):wwt(t,r,e,n)}));if(o.setAttribute(`rename.affected_docs`,p.length),p.length===0){let t=mn(d);hn(t.map(e=>e.docName)),r===`folder`&&(await a5(me,s,c)||i5(s,c),pt(e,n),at?.(`files`));let{rewrittenDocs:i,derivedMutations:a}=await gn(t,d);return await Rt(a,`asset-only-folder-rename`),i.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:d,rewrittenDocs:i}}let m=Z9e(p),h=z9e(new Set([...g().keys(),...await ie.getIndexedDocNames(),...m.keys()]),m),_=p.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),v=new Set;for(let{from:e}of p)for(let t of await ie.getBacklinks(e))m.has(t.source)||v.add(t.source);let y=new Map,x=new Set,S=await ie.getRenameSourceInventory(),C=new Set(S.map(({docName:e})=>e)),w=new Set(u.documents.keys());for(let e of h.before.pages)C.has(e)||w.add(e);let T=[];for(let{docName:e,wikiTargets:t,indexedMtimeMs:n}of S)t.some(t=>V9e(t,e,h)!==null)&&w.add(e),w.has(e)||T.push({docName:e,indexedMtimeMs:n});for(let e=0;e<T.length;e+=128){let t=T.slice(e,e+128),n=await Promise.allSettled(t.map(async({docName:e,indexedMtimeMs:t})=>{try{let n=et(f,`file`,e);return t===(await Fc(n)).mtimeMs?null:e}catch(t){if(R0(t))return null;let n=t instanceof Error&&`code`in t?t.code:`unknown`;throw Error(`Rename discovery could not check ${e} (${n})`,{cause:t})}}));for(let e of n){if(e.status===`rejected`)throw e.reason;e.value&&w.add(e.value)}}for(let e of w){if(m.has(e)||TU(e)||L(e))continue;let n;try{n=et(f,`file`,e)}catch(e){if(R0(e))continue;throw e}if(!G(n))continue;await T$(t,u,e,f,void 0,he?.(),ue,Pt);let r=cn(e);typeof r==`string`&&H9e(ka(r).body,e,h).rewrites>0&&(v.add(e),y.set(e,r),x.add(e))}let E=[...v].sort((e,t)=>e.localeCompare(t)),D=new Set,O=[];for(let e of[...m.keys(),...E]){if(y.has(e))continue;if(!m.has(e)){let t=et(f,`file`,e);if(!G(t)){O.push(e);continue}}await T$(t,u,e,f,void 0,he?.(),ue,Pt);let n=cn(e);typeof n==`string`?(y.set(e,n),m.has(e)||x.add(e)):m.has(e)||O.push(e)}if(d.length>0){let e=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=y.get(t)??cn(t);typeof e==`string`&&fn(e,t,m.get(t)??t,d,h).rewrites!==0&&(y.has(t)||y.set(t,e),D.add(t),m.has(t)||x.add(t))}}hn(D);for(let{from:e}of p)if(typeof y.get(e)!=`string`)throw new X9e(e);let k=dCt({fromPath:e,toPath:n,affectedDocs:[...p],snapshots:sn([...y.keys()],y)}),A=[],M=[...x].sort((e,t)=>e.localeCompare(t)),N=[];return await SCt(me??f,k,async()=>{for(let e of O)N.push({kind:`delete`,documentName:e});for(let e of M){let t=u.documents.get(e),n=t?un(e,d,h):fn(y.get(e)??``,e,e,d,h);n.rewrites>0&&(ln(e,n.markdown,t),A.push({docName:e,rewrites:n.rewrites})),N.push({kind:`link-rewrite`,documentName:e,markdown:n.markdown})}if(Fe)for(let{from:e,to:t}of p)_U(e)||vU(e)||(Fe.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let a=et(f,r,e),o=et(f,r,n),s=p.map(({to:e})=>je?.(e));await a5(me,a,o)||i5(a,o);for(let e of s)e?.();r===`folder`&&pt(e,n);let c=await nn([...m.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);IU(`rename.appendLog`,{attributes:{"rename.kind":r}},e=>{let t=i?.actor,n=P8({moves:p,kind:r,branch:P?.()??`main`,writer:t?{writerId:t.writerId,displayName:t.displayName,colorSeed:t.colorSeed,actor:t.actorMetadata}:{writerId:IJ.id,displayName:IJ.name,colorSeed:IJ.id},shadow:j?.current,notices:Qe});e.setAttribute(`rename.entries_appended`,n)});let l=r===`file`&&BH(n)?Ws(n):null;for(let{from:e,to:t}of p){let n=BH(e)?Ws(e):qH(e);ZH(e),KH(t,l??n)}let g=[...p].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:n}of g){let r=et(f,`file`,e),i=et(f,`file`,n),a=fn(c.get(e)??y.get(e)??K(i,`utf-8`),e,n,d,h);on([{fromDocName:e,toDocName:n}],new Map([[e,a.markdown]])),t.setReconciledBase(n,a.markdown),b?.({kind:`rename`,oldPath:r,newPath:i,oldDocName:e,newDocName:n,content:a.markdown}),N.push({kind:`rename`,oldDocumentName:e,newDocumentName:n,markdown:a.markdown});try{await gt.renameDoc(e,n)}catch(t){H8.warn({err:t,fromDocName:e,toDocName:n},`[comments] cover-sheet rename failed; index updated, disk self-corrects at boot`)}a.rewrites>0&&A.push({docName:n,rewrites:a.rewrites})}if(await Rt(N,`document-rename`),process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),at?.(`files`),A.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,A.length),{renamed:_,renamedAssets:d,rewrittenDocs:A}}))}function Cn(e){let t=CXe(e),n=t.suppliedWriterId??`claude-1`;return{rawAgentId:t.rawAgentId,suppliedWriterId:t.suppliedWriterId,agentId:n,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??n,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function wn(e){return{principalId:ge?.()?.id,agentType:AH(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Tn(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function En(e){return{value:e.value}}function Dn(e,t=!1){e.kind===`value`&&(hZe(),e.truncatedFrom!==void 0&&!t&&gZe())}function On(e,t,n,r){if(n.length!==0)switch(e.kind){case`agent`:{let r=e.summary.kind===`value`,i=r?e.summary:PQ(t),a=Tn(i),o=r||!a.response?a.response:En(a.response);for(let t=0;t<n.length;t++){let{docName:r,subject:i}=n[t];c$(r,e.writerId,e.displayName,e.colorSeed,i,e.actor,t===0?a.stored:void 0)}aU(),Dn(i,!r);for(let{docName:e}of n)Tt(e,`rename-path`);return o}case`principal`:{let t=Tn(e.summary);for(let r=0;r<n.length;r++){let{docName:i,subject:a}=n[r];c$(i,e.writerId,e.displayName,e.colorSeed,a,e.actor,r===0?t.stored:void 0)}Dn(e.summary,!1);for(let{docName:e}of n)Tt(e,`rename-path`);return t.response}case`anonymous`:r.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${r.context}: ${String(t.kind)}`)}}}function kn(e,t,n){let r=t.replace(/\/$/,``),i=r===``?``:`${r}/`;return e===`template`?`${i}.ok/templates/${n}`:e===`skill`?`${rr(String(n))}/SKILL`:e===`folder-frontmatter`?`${i}.ok/frontmatter`:r===``?`.`:r}function An(e,t,n,r){if(e.kind!==`agent`&&e.kind!==`principal`)return;let i=Tn(e.summary);c$(t,e.writerId,e.displayName,e.colorSeed,n,e.actor,i.stored,r)}let jn=null;function Mn(){De&&(jn!==null&&clearTimeout(jn),jn=setTimeout(()=>{jn=null,De?.rebuildIgnorePatterns().catch(()=>{})},12e4))}function Nn(){nt(),De?.refreshInPlaceSkillDirs(),Mn()}function Pn(){Nn(),at?.(`files`)}let Fn=Promise.resolve();function In(e){nt(),Fn=Fn.then(async()=>{await Ln(e)}).catch(()=>{})}async function Ln(e){if(!N)return`unavailable`;try{return await N(),`flushed`}catch(t){return H8.warn({context:e,err:t},`[${e}] flushContributors failed; attribution stays queued for the next flush`),`failed`}}let Rn=Z(tie,async(n,r,i)=>{try{let n=J8(i.docName,r,`agent-write`);if(n===null)return;let a=wt(n),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=Cn(i);if(_U(a)||vU(a)){X(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-write`,extensions:{...PG[`urn:ok:error:reserved-doc-name`]}});return}let g=PQ(i.summary),_=await d.getSession(a,o,{displayName:c,colorSeed:l,clientName:p}),v=await T$(t,u,a,f,e.resolveEmbed,he?.(),ue,Pt),y=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${y}`,{response:x,stored:S}=Tn(g),C,w;try{let n=qn(p),r=uo[n]??Re(l??o);se?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:a,mode:`writing`,ts:Date.now()}),C=o$(_.dc.document.getText(`source`),o,_.origin,l,p),SQ(_.dc.document,`${b}\n`,`append`),_.dc.document.transact(()=>{let t=wQ(_.dc.document);CQ(_.dc.document,`${b}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,void 0,xQ(_),s);let n=$c(t,wQ(_.dc.document))??void 0;_.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${b.slice(0,50)}`,...n===void 0?{}:{changedBlocks:n}})},_.origin),w=mG(_.dc.document),t.markAgentWriteStore(a),c$(a,o,c,l,void 0,wn({clientName:p,clientVersion:m,label:h}),S),aU(),Dn(g)}finally{C?.(),se?.touchMode(o,`idle`)}let T=await jt(a,w);if(T?.kind===`failure`){s5(r,T.failure,`agent-write`);return}if(T?.kind===`stale-external-write`){Nt(r,`agent-write`,a);return}Et(a,`agent-write`),ce?.();let E=S$(v),D={timestamp:y,...x?{summary:x}:{},...E?{warnings:[E]}:{}},O=LG(v,T);if(O.outcome===`both-kept`){H$(r,`agent-write`,D,O);return}Q(r,200,yte,{...D,...O},{handler:`agent-write`})}catch(e){if(e instanceof QJ){$J(r,e,`agent-write`,ue.findByDocName(UH(e.file)));return}if(e instanceof SZ){CZ(r,e,`agent-write`);return}if(e instanceof EQ){V$(r,e,`agent-write`);return}H8.error({err:e,requestId:ZK(n)},`[agent-write] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),zn=Z(cre,async(n,r,i)=>{try{let a=We(),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=Cn(i),g=new Date().toISOString(),_=(e,t,n,r,i,a)=>({status:`error`,docName:e,error:{type:t,title:n,...r===void 0?{}:{detail:r},...i},...a}),v=(e,t)=>{if(t instanceof nq)return j3e(t,`agent-write-batch`),_(e,tq,O3e,A3e,{retryAfterSeconds:3},PG[`urn:ok:error:concurrent-overwrite-refused`]);if(t instanceof QJ){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:`agent-write-batch`,"doc.name":e}));let{detail:t,...n}=E7e(ue.findByDocName(e));return{status:`error`,docName:e,error:{type:`urn:ok:error:doc-in-conflict`,title:`Document is in conflict.`,detail:t,...n},...PG[`urn:ok:error:doc-in-conflict`]}}return t instanceof SZ?(Qtt(t,`agent-write-batch`),_(e,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,Ztt(t),void 0,PG[`urn:ok:error:frontmatter-malformed`])):t instanceof EQ?_(e,oot,sot,cot,lot,PG[`urn:ok:error:too-many-agent-sessions`]):(H8.error({err:t,docName:e,requestId:ZK(n)},`[agent-write-batch] entry failed`),_(e,`urn:ok:error:internal-server-error`,`Internal server error.`))},y=Array(i.docs.length),b=[],x=new Map,S=new Map;try{let n=qn(p),r=uo[n]??Re(l??o);se?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:wt(i.docs[0].docName),mode:`writing`,ts:Date.now()}),await d.withSessions(async n=>{for(let r=0;r<i.docs.length;r++){let a=i.docs[r],d=wt(a.docName);if(_U(d)||vU(d)){y[r]=_(d,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,void 0,void 0,PG[`urn:ok:error:reserved-doc-name`]);continue}try{a.extension!==void 0&&!Z8(f,d)&&KH(d,a.extension);let i=PQ(a.summary),{response:g,stored:_}=Tn(i),v=await n(d,o,{displayName:c,colorSeed:l,clientName:p}),y=await T$(t,u,d,f,e.resolveEmbed,he?.(),ue,Pt),C=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,w=await bQ(v.dc.document,a.markdown,a.position??`append`,C),T,E=o$(v.dc.document.getText(`source`),o,v.origin,l,p);SQ(v.dc.document,a.markdown,a.position??`append`);try{v.dc.document.transact(()=>{let e=wQ(v.dc.document);T=CQ(v.dc.document,a.markdown,a.position??`append`,C,w,xQ(v),s);let t=$c(e,wQ(v.dc.document))??void 0;v.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${a.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},v.origin),x.set(d,mG(v.dc.document)),S.set(d,v.dc.document.getText(`source`).toString()),t.markAgentWriteStore(d)}finally{E()}uwt(`agent-write-batch`,T),c$(d,o,c,l,void 0,wn({clientName:p,clientVersion:m,label:h}),_),aU(),Dn(i);let D=S$(y),O=[...T===void 0?[]:[xZ(T)],...D?[D]:[]];b.push({index:r,docName:d,reconcile:y,summaryResponse:g,warnings:O,diverged:T!==void 0})}catch(e){y[r]=v(d,e)}}let r=new Map,d=new Map;for(let e of b){if(r.has(e.docName))continue;let t=await jt(e.docName,x.get(e.docName));d.set(e.docName,t),t?.kind===`failure`?r.set(e.docName,Qwt(t.failure)):t?.kind===`stale-external-write`?r.set(e.docName,Zwt(Mt(e.docName))):r.set(e.docName,void 0)}let g=await It(b.filter(e=>r.get(e.docName)===void 0).map(e=>e.docName)),C;for(let e of b){let t=r.get(e.docName),n=d.get(e.docName)??null;if(t!==void 0){y[e.index]={status:`error`,docName:e.docName,error:t,...n?.kind===`failure`?FG(n.failure):PG[`urn:ok:error:stale-external-write`]};continue}let i=u.documents.get(e.docName)?.getText(`source`).toString()??S.get(e.docName)??``;Zt(e.docName,i);let o=g(i,e.docName,a.suppressLogLinkAdvisories),s=[...e.warnings,...o.warnings];y[e.index]={status:`written`,docName:e.docName,...LG(e.reconcile,n,e.diverged),...e.summaryResponse?{summary:e.summaryResponse}:{},...s.length>0?{warnings:s}:{},...o.links},C=e.docName}C!==void 0&&(oe?.setFocus(o,{agentName:c,currentDoc:C,writeKind:`write`,ts:Date.now()}),ce?.())})}finally{se?.touchMode(o,`idle`)}let C=y.map((e,t)=>e??_(i.docs[t].docName,`urn:ok:error:internal-server-error`,`Internal server error.`)),w=C.filter(e=>e.status===`written`).length;Q(r,200,Bre,{timestamp:g,results:C,written:w,failed:C.length-w},{handler:`agent-write-batch`})}catch(e){H8.error({err:e,requestId:ZK(n)},`[agent-write-batch] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-batch`,cause:e})}},{handler:`agent-write-batch`,method:`POST`}),Bn=ZCt(),Hn=BCt({contentDir:f,assertContentPath:e.assertContentPath,isPathIgnored:e=>De?.isPathIgnored(e)??!1,getAttachmentFolderPath:_,resolveTrackedFile:E}),Un=Tmt({assertContentSubtree:a,contentDir:f,resolveContentEntryPath:et,docNameForPath:e=>$8(f,e),docNameToRelativePath:XH,listManagedDocNamesUnderFolder:e=>vn(e),listAffectedDocNames:(e,t,n)=>Cwt(e,t,n),getFileIndex:g,conflictFileForDocName:e=>ue.findByDocName(e)?.file??null,captureAndCloseDocuments:nn,markRecentlyRemoved:Fe?e=>Fe.setDeleted(e):void 0,mutateFileIndexDelete:b?({path:e,docName:t})=>b({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:ft,upsertFolderIndexPathSegments:dt,deleteDerivedDocumentsBestEffort:Wt,invalidateReferencedAssetsCache:ct,signalFiles:()=>at?.(`files`),nextAvailableDuplicateDocName:e=>kwt(f,e),nextAvailableDuplicateFolderPath:e=>Awt(f,e),resolveDuplicateDocPath:(t,n)=>{let r=Owt(f,t,n);return e.assertContentPath?.(r),r},collectMarkdownCopies:e=>jwt(f,e),collectFolderPaths:e=>Mwt(f,e),contentFilter:De??void 0,unmarkRecentlyRemoved:Fe?e=>Fe.delete(e):void 0,mutateFileIndexCreate:b?({path:e,docName:t,content:n})=>{Ae?.(t),b({kind:`create`,path:e,docName:t,content:n})}:void 0,recordDerivedDocumentBestEffort:zt,recordDerivedMutationsBestEffort:Rt});function Wn(e,t,n,r,i){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return X(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=W(f),s=a===``?o:W(o,a);if(s!==o&&!s.startsWith(`${o}${Ys}`))return X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;let c=W(s,`.ok`);if(MK(c).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;let l=W(s,`.ok`,`templates`);if(i===`ok-and-templates`&&MK(l).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok/templates is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;try{jK(c,o),i===`ok-and-templates`&&jK(l,o)}catch(e){return PK(e)?(X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(X(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:U(o,s).split(Ys).join(`/`),resolvedContentDir:o}}function Gn(e,t,n){let r=ue.findByDocName(e);return r!==void 0&&($J(n,new QJ({file:r.file}),t,r),!0)}let Kn=e=>{let{body:t}=ka(e);return{frontmatter:D(e)??{},body:t}};function Jn(e){return!!e&&e.length<=64&&Ce.test(e)}function Yn(e,t,n,r){return Jn(e)?!0:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n,...r?{extensions:r}:{}}),!1)}function Xn(e,t,n){let r=vie.safeParse(e??`project`);return r.success?r.data:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Zn=_e??wc(),Qn=XCt({contentDir:f,skillsHome:Zn,effectiveInstallMode:nr});function $n(e){return W(e===`global`?Zn:f,`.ok`,Oa)}function er(e,t,n){let r=W($n(e),t);if(e===`global`){if(n!==void 0){let e=W1(Zn).find(e=>e.name===t&&e.hosts.includes(n));return e?W(Zn,e.dir):null}let e=K1(Zn,t);return e===null?G(H(r,`SKILL.md`))?r:null:e}let i=U1(f).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?W(f,i.dir):n===void 0&&G(H(r,`SKILL.md`))?r:null}function tr(e,t){let n=e.searchParams;return FQ({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function nr(e,t,n){let r=e===`project`?me:Zn;return(r?Oct(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function rr(e){let t=er(`project`,e);return t?U(f,t).split(Ys).join(`/`):`${y}/${e}`}function ir(e,t,n,r){let i=[],a=null,o=u0(n),s=[...d0(n).map(e=>({id:e,root:o[e]??``})),{id:`agents`,root:ki}];for(let{id:n,root:o}of s){if(!o)continue;let s=W(e,...o.split(`/`),t);G(W(s,`SKILL.md`))&&(i.push(n),(r===void 0?a===null:n===r)&&(a=s))}if(a===null)return null;let c=W(a,`SKILL.md`);return{dir:a,skillMd:c,hosts:i,relPath:U(e,c).split(/[\\/]/).filter(Boolean).join(`/`)}}function ar(e){let t=cFe(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function or(e,t,n){if(!FH(t))return null;let r=ir(e,t,n);if(!r)return null;let i=XM(r.dir)?.contentHash??``,a;try{a=yc(r.skillMd).mtime.toISOString()}catch{a=new Date(0).toISOString()}return{source:Ci,skill:t,contentHash:i,autoUpdate:!1,importedAt:a}}function sr(e,t){return it(t).get(e)?.contentHash??null}function cr(e,t,n){let r=it(t).get(e);if(!r)return null;try{if(hc(n)!==hc(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function lr(e,t,n){let r=it(t).get(e);if(!r)return null;if(n!==void 0)try{if(hc(n)===hc(r.home))return null}catch{}let i;try{i=yc(H(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){H8.warn({err:e,home:r.home},`plugin bundle unreadable; origin dated epoch`),i=new Date(0).toISOString()}return{source:r.home,skill:e,contentHash:r.contentHash,autoUpdate:!1,importedAt:i}}function R(e,t){let n=IH.find(t=>NH[t]===e);if(n===void 0||t!==void 0&&LH[n]!==(t===`global`?`user`:`project`))return null;try{let e=zH(n,{checkDesktop:!0}),t=W(e,`SKILL.md`);return G(t)?t:null}catch(t){return H8.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function ur(e,t,n){let r=ir(e,t,n),i=r?.skillMd??R(t);if(i===null)return null;let a;try{let{frontmatter:e}=Kn(K(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=or(e,t,n),s=XM(V(i));return{name:t,...a===void 0?{}:{description:a},scope:n,path:r?.relPath??i,absolutePath:i,installed:(r?.hosts.length??0)>0,hosts:r?.hosts??[],managed:!0,...s?{size:ca(s)}:{},...o?{origin:ar(o)}:{}}}function dr(e,t,n){return FH(e)?(X(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function fr(e,t){return U(t===`global`?Zn:f,e).split(/[\\/]/).filter(Boolean).join(`/`)}function pr(e){return e===`global`?Zn:me}function mr(e,t,n,r){let i=n===`project`?f:Zn;if(r.purge!==void 0){C0(t,e,d0(n),u0(n));for(let e of Kst(i,n,t,r.purge.contentHash))iW(e,{recursive:!0,force:!0});return}if(!G(W($n(n),t,`SKILL.md`))){let r=(n===`project`?U1(f):W1(Zn)).find(e=>e.name===t);if(r){let i=n===`project`?f:Zn,a=W(i,r.dir),o=W(i,`.agents`,`skills`),s=H(o,t);if(G(o)&&!G(H(s,`SKILL.md`))){let e=!1;try{e=hc(a)===hc(s)}catch{e=!1}e||QU(a,s,{recursive:!0,dereference:!0})}S0({canonicalAbs:G(H(s,`SKILL.md`))?s:a,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...d0(n)],roots:u0(n)});return}}C0(t,e,d0(n),u0(n))}async function hr(e,t,n,r={}){return mr(e,t,n,r),await Z1(e,t)!==null}function gr(e,t){let n=[];if(!G(e))return{skills:n,truncated:!1};let r;try{r=mc(e,{withFileTypes:!0})}catch(r){return q(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Ce.test(a.name))continue;if(n.length>=500){i=!0;break}let r=W(e,a.name,`SKILL.md`);if(!G(r))continue;let o;try{let{frontmatter:e}=Kn(K(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:fr(r,t),absolutePath:r})}return{skills:n,truncated:i}}function _r(e,t,n){let r=e===`project`?f:Zn,i=er(e,t,n);return{root:i===null?$n(e):V(i),dirRel:i===null?`.ok/skills/${t}`:U(r,i).split(Ys).join(`/`),realDir:i}}function vr(e,t){return XM(W(e,t))?.contentHash}async function yr(e,t){let n=j?.current;if(!(!n||!e))try{let r=OJ(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
2090
2090
  `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,...Ut([t]))).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Ln(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let br=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function xr(e){try{let t=pr(e.scope);if(!t)return;let n=l0(t);if(n.length===0)return;let r=_0(W(e.skillsRoot,e.name),e.name,t,n,`copy`,u0(e.scope));if(r.length===0)return;await X1(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){H8.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}let Sr=olt({contentDir:f,skillsHome:Zn,...me===void 0?{}:{projectDir:me},resolveSkillDirForRead:er,parseFrontmatterDoc:Kn,attributeOkArtifactWrite:An,commitOkArtifactWrite:Ln,shadowHeadSha:yr,artifactWriterId:br,effectiveInstallMode:nr,signalFiles:()=>at?.(`files`)}),Cr=flt({contentDir:f,skillsHome:Zn,...me===void 0?{}:{projectDir:me},legacyStoreRoot:y,effectiveSkillRoot:_r,parseFrontmatterDoc:Kn,attributeOkArtifactWrite:An,commitOkArtifactWrite:Ln,shadowHeadSha:yr,artifactWriterId:br,skillArtifactKey:e=>kn(`skill`,``,e),captureAndCloseDocuments:nn,projectImportedSkillCopy:xr,signalFiles:()=>at?.(`files`)}),wr=Z(ye,async(e,t,n)=>{try{if(!Yn(n.name,t,`skill-uninstall`))return;let e=pr(n.scope);if(!e){X(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await hr(e,n.name,n.scope);at?.(`files`),Q(t,200,Vn,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,...dwt(e)===void 0?{}:{detail:dwt(e)},cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Tr=YCt({contentDir:f,projectDir:me,getAllFilesIndex:v,getFileIndexGeneration:x,getSearchMaxEntries:ywt,semanticSearch:ze,getSemanticSimilarityFloor:Be,ready:Pe,getProjectSkillsRoot:()=>$n(`project`),parseFrontmatterDoc:Kn});Tr.prewarm();let Er=0;function Dr(){Er+=1,at?.(`lint-config`)}let Or=()=>eut({lintConfigEpoch:Er,projectConfigEpoch:Ge(),activeBranch:t.getActiveBranch(),localTargetGeneration:ie?.readLocalTargetGeneration?.()??0});async function kr(e,t,n){let r=Ue?.()??ga;try{let i=J0(f,r,{docName:t,projectDir:me??f,onProblem:e=>H8.warn({problem:e,docName:t},`[lint] native config problem`)}),a=await ee(e,i,t),o=[];if(ie?.isReady()&&n.links!==`off`&&!wU(t)){let i=ie;o=await St.run(`lint-links`,async()=>{await Bt(t,e,`lint-validation`);let a=Gdt({projectDir:me??f,contentDir:f,baseConfig:r,derivedDocumentIndex:i,linkPolicy:n,admittedDocNames:Lt,docFilePathFor:e=>Q8(f,e),localTargetInventory:qt}).find(e=>e.id===`links`);return a?(await a.run({targetPath:Q8(f,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics):[]},()=>[])}return[...a,...o].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return H8.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ar(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=X0({projectDir:me??f,contentDir:f});return zlt(t.schemas,n)}let jr={"/api/skill/uninstall":wr,"/api/agent-write":Rn,"/api/agent-write-batch":zn},Mr=new Set([`/api/agent-write`,`/api/agent-write-batch`,`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/skill/uninstall`]),Nr={resolve(e){let t=jr[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>Mr.has(e)},Pr=Jit({log:H8,policy:o,ephemeral:Ke,table:Nr,dispatchMutation:i}),Fr=nvt({hocuspocus:u,derivedDocumentIndex:ie,getFileIndex:g,isSafeDocName:o5,readPageTitleForDocName:_t,readPageTitleForLinkedDocName:vt,readFrontmatterMetadataForLinkedDocName:xt,collectAdmittedDocNames:Lt,resolveAlias:wt,respondToDerivedIndexQueryFailure:Ht}),Ir=Iyt({hocuspocus:u,agentPresenceBroadcaster:se,isAllowedWorkspaceHostHeader:c,log:H8}),Lr=Xpt({contentDir:f,projectDir:me,ephemeral:Ke,log:H8,ready:Pe,serverInstanceId:h,getDiskAckSVs:F,getCollabClientCount:ne,getConfigDiagnostics:Ze,acpRegistry:we,loadAcpCustomAgents:Te,acpHarnessAvailability:Ee,isRoutePeerAdmitted:l,isAllowedWorkspaceHostHeader:c,checkLocalOpSecurity:s,getPrincipal:ge,semanticSearch:ze,readSemanticProviderConfig:He,embeddingsSecretsFile:Ve,getFileIndex:g,shadowRef:j,getCurrentBranch:P,getReportedBranch:te,installedAgentsCache:mt}),Rr=rvt({hocuspocus:u,contentDir:f,projectDir:me,contentFilter:De,isSafeDocName:o5,resolveDocFilePath:Q8,isValidRelativeContentPath:N8,streamShowAllEntries:q8,getLinterBaseConfig:Ue,getLinkAdvisoryPolicy:We,derivedDocumentIndex:ie,collectAdmittedDocNames:Lt,unmatchedGlobProblems:Ar,readAuditGeneration:Or,localTargetInventory:qt}),zr=gvt({conflicts:ue,contentDir:f,projectDir:me,signalLintConfigChanged:Dr,getLinterBaseConfig:Ue,unmatchedGlobProblems:Ar,signalChannel:at,requireNonEmptyDocName:J8,resolveAlias:wt,getPrincipal:ge,resolveDocFilePath:Q8,summaryResponseFields:Tn,sessionManager:d,options:e,agentPresenceBroadcaster:se,buildAgentActor:wn,flushDiskAndDetectOutcome:jt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondPersistenceFailure:s5,respondStaleExternalWrite:Nt,flushDocToDisk:Et,log:H8}),Br=b_t({contentRoot:re,log:H8,shadowRef:j,flushGitCommit:M,commitOkArtifactWrite:Ln,getCurrentBranch:P,validateFolderRel:Wn,safeDocPath:U8,docTreePathCandidates:fwt}),Vr=Zct({validateSkillName:Yn,parseSkillScope:Xn,skillsHome:Zn,projectDir:me,resolveBuiltinSkillDir:ir,resolveSkillDirForRead:er,resolveSkillsRoot:$n,getPrincipal:ge,rejectReservedBuiltinSkill:dr,contentDir:f,checkSkillDocConflictGate:Gn,extractAgentIdentity:Cn,sessionManager:d,flushDiskAndDetectOutcome:jt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondStaleExternalWrite:Nt,respondPersistenceFailure:s5,attributeOkArtifactWrite:An,okArtifactKey:kn,commitOkArtifactWrite:Ln,signalChannel:at,extractActorIdentityFromQuery:tr,captureAndCloseDocuments:nn,derivedDocumentIndex:ie,log:H8,recordDerivedMutationsBestEffort:Rt}),Hr=_lt({projectDir:me,getPrincipal:ge,skillImportService:Sr,bumpSkillsCatalogGen:nt,contentFilter:De,scheduleDeferredIgnoreRebuild:Mn,signalChannel:at,parseSkillScope:Xn}),Ur=Yct({validateSkillName:Yn,parseSkillScope:Xn,skillsHome:Zn,projectDir:me,resolveBuiltinSkillDir:ir,parseFrontmatterDoc:Kn,resolveSkillDirForRead:er,skillRelPath:fr,derivedDocumentIndex:ie,contentFilter:De,bumpSkillsCatalogGen:nt,settleSkillCatalog:Pn,invalidateSkillCatalog:Nn,scheduleDeferredIgnoreRebuild:Mn,recordDerivedDocumentBestEffort:zt,getPrincipal:ge,rejectReservedBuiltinSkill:dr,contentDir:f,attributeOkArtifactWrite:An,scheduleOkArtifactFlush:In,signalChannel:at,checkSkillDocConflictGate:Gn,extractAgentIdentity:Cn,sessionManager:d,flushDiskAndDetectOutcome:jt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondStaleExternalWrite:Nt,respondPersistenceFailure:s5,okArtifactKey:kn,resolveSkillsRoot:$n,extractActorIdentityFromQuery:tr,captureAndCloseDocuments:nn,log:H8,commitOkArtifactWrite:Ln,skillInstallBase:pr,uninstallSkillFromHostDirs:hr,renameTrackedPathInGit:a5,renamePathOnDisk:i5,localSkillHash:vr,shadowHeadSha:yr,artifactWriterId:br,checkLocalOpSecurity:s,effectiveSkillRoot:_r}),Wr=wlt({contentDir:f,projectDir:me,skillsHome:Zn,contentFilter:De,catalogCache:tt,resolveSkillsRoot:$n,resolveSkillsList:gr,skillOriginFor:ar,localSkillHash:vr,effectiveInstallMode:nr,pluginSelfIdentity:cr,synthBuiltinLockEntry:or,synthPluginLockEntry:lr,pluginUpstreamHash:sr,builtinSkillListEntry:ur,indexedSkillContentPath:mwt,healUnservableSkillAdmission:hwt}),Gr=Tbt({contentDir:f,projectDir:me,homeDirOverride:_e,skillsHome:Zn,isSafeDocName:o5,commentService:gt,enumerateInstalledSkillsCached:rt,checkLocalOpSecurity:s}),Kr=Lbt({log:H8,skillsHome:Zn,projectDir:me,contentDir:f,resolveSkillDirForRead:er}),qr=lCt({contentDir:f,projectDir:me,skillsHome:Zn,homeDirOverride:_e,savedThemeLockTimeoutMs:Se,ephemeral:Ke,log:H8,signalChannel:at,searchService:Tr,linkPreviewFetch:qe,getLinkPreviewsEnabled:Je,declaredGitHubHosts:I,resolveGitHubToken:Ye,githubReferenceFetch:Xe,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m}),Jr=Eft({commentService:gt,getPrincipal:ge,signalChannel:at}),Yr=Zpt({docNotices:e.docNotices??null,getBranch:()=>P?.()??`main`,checkLocalOpSecurity:s}),Xr=Rbt({projectDir:me,contentDir:f,getPrincipal:ge,hocuspocus:u,log:H8,checkLocalOpSecurity:s,getSyncEngine:le,conflicts:ue,serializeDoc:Ie,setBatchInProgress:de}),Zr=wbt({declaredGitHubHosts:I,projectDir:me,contentDir:f,log:H8,checkLocalOpSecurity:s,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,resolveCredentialConfig:$e,toGitRelativePath:e5}),Qr=ygt({projectDir:me,contentDir:f,contentFilter:De,getFileIndex:g,checkLocalOpSecurity:s,getSyncEngine:le,getPrincipal:ge,resolveCredentialConfig:$e}),$r=Fyt({declaredGitHubHosts:I,projectDir:me,contentDir:f,log:H8,checkLocalOpSecurity:s,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,authStreamHeartbeatMs:pe,embeddingsSecretsFile:Ve,readSemanticProviderConfig:He,semanticSearch:ze}),ei=Pmt({contentDir:f,projectDir:me,log:H8,getPrincipal:ge,contentFilter:De,signalChannel:at,conflicts:ue,commitOkArtifactWrite:Ln,fileOpsService:Un,assetService:Hn,extractAgentIdentity:Cn,recordDerivedDocumentBestEffort:zt,invalidateReferencedAssetsCache:ct,listManagedDocNamesUnderFolderFromDisk:vn,resolveContentEntryPath:et,docNameForFileOperationPath:$8,withPeriod:en,toManagedRenamePublicError:tn,attributeRenameWriteToActor:On,renameAttributionCounter:awt,_performAssetRename:bn,_performDocumentToFileRename:xn,_performManagedRenameForDocs:Sn,isValidRelativeContentPath:N8}),ti=gbt({contentDir:f,checkLocalOpSecurity:s}),ni=Qbt({contentDir:f,log:H8,checkLocalOpSecurity:s,installedAgentsCache:mt,agentIntegrations:xe}),ri=igt({contentDir:f,projectDir:me,ephemeral:Ke,log:H8,hocuspocus:u,sessionManager:d,getPrincipal:ge,signalChannel:at,conflicts:ue,recentlyRemovedDocs:Fe,isSafeDocName:o5,resolveAlias:wt,resolveContentEntryPath:et,validateFolderRel:Wn,extractAgentIdentity:Cn,extractActorIdentityFromQuery:tr,okArtifactKey:kn,attributeOkArtifactWrite:An,scheduleOkArtifactFlush:In,flushDiskAndDetectOutcome:jt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondPersistenceFailure:s5,respondStaleExternalWrite:Nt,registerWrittenDocInFileIndex:Zt,captureAndCloseDocuments:nn,captureNamespaceMove:je,renameTrackedPathInGit:a5,renamePathOnDisk:i5,splitContentPath:X8,mutateFileIndex:b}),ii=vft({assetService:Hn,log:H8}),ai=$it({log:H8,checkLocalOpSecurity:s,getPrincipal:ge,homeDirOverride:_e,projectDir:me,agentIntegrations:xe}),oi=Ost({checkLocalOpSecurity:s}),si=Qpt({refreshDocumentsFromDisk:e.refreshDocumentsFromDisk}),ci=vlt({resolveSkillsRoot:$n,validateSkillName:Yn,projectDir:me,skillInstallBase:pr,contentDir:f,skillsHome:Zn,shippedBundleSkillMd:R,flushDiskAndDetectOutcome:jt,respondStaleExternalWrite:Nt,respondPersistenceFailure:s5,skillInstallOps:Qn,skillPlacementOps:Bn,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:De,scheduleDeferredIgnoreRebuild:Mn,effectiveInstallMode:nr,log:H8}),li=klt({synthPluginLockEntry:lr,synthBuiltinLockEntry:or,isValidSkillName:Jn,getPrincipal:ge,validateSkillName:Yn,rejectReservedBuiltinSkill:dr,shadowRef:j,contentDir:f,contentRoot:re,projectDir:me,skillsHome:Zn,projectSkillDirRel:rr,attributeOkArtifactWrite:An,okArtifactKey:kn,commitOkArtifactWrite:Ln,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:De,scheduleDeferredIgnoreRebuild:Mn,effectiveSkillRoot:_r,skillReimportService:Cr,localSkillHash:vr,resolveSkillsRoot:$n,projectImportedSkillCopy:xr}),ui=Alt({contentDir:f,projectDir:me,contentFilter:De,validateSkillName:Yn,indexedSkillContentPath:mwt,bumpSkillsCatalogGen:nt,signalChannel:at}),di=_ot({conflicts:ue,getLinkAdvisoryPolicy:We,respondStaleExternalWrite:Nt,requireNonEmptyDocName:J8,resolveAlias:wt,extractAgentIdentity:Cn,docNameExistsWithAnySupportedExtension:Z8,findMissingDocCandidates:e=>Nlt(e,g()),contentDir:f,summaryResponseFields:Tn,sessionManager:d,durabilityState:t,hocuspocus:u,options:e,getBridgeLossReporter:he,mergeHistory:Pt,agentPresenceBroadcaster:se,recordContentDivergenceGate:uwt,buildAgentActor:wn,countNormalizedSummary:Dn,flushDiskAndDetectOutcome:jt,respondPersistenceFailure:s5,flushDocToDisk:Et,agentFocusBroadcaster:oe,onAgentWrite:ce,computeOrphanHints:Ct,registerWrittenDocInFileIndex:Zt,prepareWriteLinkAdvisory:It,buildReconcileWarning:S$,computeLintViolations:kr,log:H8,flushDocToGit:Tt,flushGitCommit:M,commitOkArtifactWrite:Ln,isSafeDocName:o5,shadowRef:j,getPrincipal:ge,contentRoot:re,safeDocPath:U8,getCurrentBranch:P,docTreePathCandidates:fwt,stripDefaultPathTruncation:En,renameAttributionCounter:awt}),fi=Sot({agentPresence:se,resetSettingsForTest:ve,settleDiskEvents:be,recentlyRemovedDocs:Fe,conflicts:ue,durabilityState:t,resolveAlias:wt,contentDir:f,log:H8,sessionManager:d,hocuspocus:u,forceUnloadDocument:ke,derivedDocumentIndex:ie,contentFilter:De,bumpSkillsCatalogGen:nt,signalChannel:at,flushGitCommit:async()=>{await Fn,await M?.()},rescanFiles:O}),pi=[ii,ai,di,...A?[fi]:[],ui,li,ci,oi,Hr,Vr,Fr,Ir,st,si,Lr,Rr,zr,Br,Ur,Wr,Gr,Kr,qr,Jr,Xr,Yr,Zr,Qr,$r,ei,ti,ni,ri],mi=pi.flatMap(e=>[...e.paths]);x_t(mi,jr);let hi=pi.map(e=>Jit({log:H8,policy:o,ephemeral:Ke,table:e.table,dispatchMutation:i})),gi={paths:mi,dispatch:async(e,t)=>{for(let n of hi)if(await n(e,t))return!0;return!1}},_i=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]),eee=pi.map(e=>e.table),vi=e=>{for(let t of eee){let n=t.resolve(e)?.dispatch;if(n!==void 0)return t.isMutating(e)?(t,r)=>i(()=>n(t,r),e):n}};for(let e of _i)if(jr[e]===void 0&&vi(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);let yi=new Map([[rq,di.acpDocumentWrite]]);return{priority:100,async onRequest({request:e,response:t}){await Pr(e,t)},nativeApi:gi,localApi:yvt({resolve:e=>{let t=yi.get(e);if(t!==void 0)return(n,r)=>i(async()=>t(n,r),e);if(!_i.has(e))return;let n=jr[e];return n===void 0?vi(e):Nr.isMutating(e)?(t,r)=>i(()=>n(t,r),e):n}}),shutdownLocalOps:async()=>{n=!0;let e=(await Promise.allSettled([...r,$r.shutdown()])).at(-1);if(e?.status===`rejected`)throw e.reason}}}function c5(e){let t=e;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(t=t.slice(0,e));let n=t.indexOf(`?`,1);n!==-1&&(t=t.slice(0,n))}if(!t.includes(`%`))return t;try{return decodeURI(t)}catch{return t}}function eTt(e,t){let n;try{n=encodeURI(e)}catch{return null}let r=t.indexOf(`?`),i=`/${n}${r===-1?``:t.slice(r)}`;return c5(i)===`/${e}`?i:null}function tTt(e,t){let n=W(e),r=Ks(H(`${n}${Ys}`,c5(t)));if(!r.startsWith(`${n}${Ys}`))return!1;try{let e=hc(n),t=hc(r);return yc(t).isFile()&&KG(t,e)&&!kK(H(e,U(n,r)),t,e)}catch{return!1}}function nTt(e){let{contentDir:t,contentFilter:n,contentSirv:r,inlineExtensions:i,assetExtensions:a,blocklistExtensions:o,ingressPolicy:s,resolveTrackedFile:c}=e,l=e=>Ws(e).slice(1).toLowerCase(),u=(e,r)=>{let i=c?.(e);if(i===void 0||i===e)return null;let o=l(i);if(n.isPathIgnored(i)||!a.has(o))return null;let s=eTt(i,r);return s!==null&&tTt(t,s)?{url:s,ext:o}:null};return(e,c,d)=>{let f=e.url??``,p;try{p=decodeURIComponent(f.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return d()}let m=c5(f)===`/${p}`&&N8(p),h=l(p),g=h===`md`||h===`mdx`;if(!p||n.isPathIgnored(p)||!g&&!a.has(h))return d();let _=e.socket?.remoteAddress;if(_!==void 0&&!VQ(_,s)){X(c,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!HQ(e.headers.host,s)){X(c,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:zQ});return}let v=m&&tTt(t,f),y=!m||v||g?null:u(p,f),b=y?.ext??h;c.setHeader(`X-Content-Type-Options`,`nosniff`);let x=MCt(b,i);g||c.setHeader(`Content-Disposition`,x.disposition),x.csp!==null&&c.setHeader(`Content-Security-Policy`,x.csp),x.sandboxedHtml&&c.setHeader(`Cache-Control`,`no-store`);let S=()=>{if(c.headersSent)return;e.url=f;let t=lre.has(b);if(!t&&(a.has(b)||o.has(b))){c.statusCode=404,c.end();return}t&&(c.removeHeader(`Content-Security-Policy`),c.removeHeader(`Content-Disposition`),c.removeHeader(`X-Content-Type-Options`),c.removeHeader(`Cache-Control`)),d()};if(!v&&y===null){S();return}y!==null&&(e.url=y.url),r(e,c,S)}}function l5(e){let t=e?.code;return typeof t==`string`?t:void 0}function rTt(e){let t;try{t=mc(e.contentDir,{withFileTypes:!0})}catch(t){let n=l5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&HH(n.name,ia)&&e.basenameIndex.add(n.name)}async function u5(e){let t=zG(e.contentDir,{root:`content`,component:`asset-walk`}),n=new Set;async function r(i){let a;try{a=await Mc(i,{withFileTypes:!0})}catch(t){let n=l5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=H(i,o.name),s=lG(U(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await kc(a,{bigint:!0})}catch(t){let n=l5(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Nc(a)}catch(t){let n=l5(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!uG(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Fc(i,{bigint:!0})}catch(t){let n=l5(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(nS(o)))continue;n.add(nS(o)),o.isDirectory()?await r(i):o.isFile()&&HH(a,va)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(nS(c)))continue;n.add(nS(c)),await r(a);continue}c.isFile()&&HH(a,va)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s)}}await r(t)}const iTt=L({principalId:R().optional(),tabSessionId:R().optional(),expectedServerInstanceId:R().optional(),expectedBranch:R().optional(),expectedDocLineageEpoch:R().optional(),clientProtocolVersion:Ia().optional(),clientRuntimeVersion:R().optional(),clientKind:R().optional()}).loose(),aTt=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function oTt(e){return aTt.includes(e)}function sTt(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function cTt(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!oTt(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var d5=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=sTt(e,this.payload)}};function f5(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=iTt.safeParse(t);return n.success?n.data:void 0}var lTt=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function uTt(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function dTt(e,t){let n=qJ(e);try{lc(n,{recursive:!0}),xc(H(n,gte),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Ix(e);lc(V(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};xc(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const p5=new Map;let fTt=!1;function pTt(e,t){try{let n=uTt(e,t);for(let e of p5.keys())dTt(e,n)}catch{}}function mTt(e){p5.set(e,(p5.get(e)??0)+1),fTt||(fTt=!0,process.on(`uncaughtExceptionMonitor`,pTt));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=p5.get(e)??0;n<=1?p5.delete(e):p5.set(e,n-1)}}}function hTt(e){let t=Rve(e,({err:e,root:t,file:n},r)=>q(`shell-csp`).warn({err:e,root:t,file:n},r));return(e,n,r,i)=>{let a=t({file:i,stats:r});a!==void 0&&e.setHeader(`Content-Security-Policy`,a)}}function m5(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function gTt(e){let t=e.scheduler??mn,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??m5(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function h5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _Tt(e){if(!G(e))return{};let t;try{let n=K(e,`utf-8`);t=(0,rl.parse)(n)}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!h5(t))return{};let n=t.telemetry;if(!h5(n))return{};let r=n.localSink;return h5(r)?r:{}}function vTt(e){return typeof e==`boolean`?e:void 0}function yTt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function bTt(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function g5(e){if(h5(e))return yTt(e.maxBytes)}function xTt(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=_Tt(pS(`project`,e.projectDir)),n=_Tt(pS(`project-local`,e.projectDir));if((vTt(n.enabled)??vTt(t.enabled)??!0)===!1)return null;let r=g5(n.spans)??g5(t.spans)??52428800,i=g5(n.logs)??g5(t.logs)??26214400,a=bTt(n.attributeDenylist)??bTt(t.attributeDenylist)??An;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}const _5=`https://json-schema.org/draft/2020-12/schema`,STt=`tools/list`;function CTt(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(STt);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${STt} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`);return}e.server.setRequestHandler(ZR,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=_5),e.outputSchema&&(e.outputSchema.$schema=_5);return r}),t.__jsonSchemaDialectInstalled=!0}function wTt(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!TTt(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=Pne(i.error);throw new cz(cR.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function TTt(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const v5=2e3,ETt=2e3,DTt=[`-iTCP`,`-sTCP:LISTEN`,`-nP`],OTt=[/^open-knowledge-server(?:\s|$)/,/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function kTt(e){return OTt.some(t=>t.test(e))}function ATt(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return Gs(e)?e:null}catch{return null}}function jTt(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&Gs(a)?a:null}function MTt(e){let t=[];for(let n of e.split(`
2091
2091
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&kTt(a)&&t.push({pid:o,command:a})}return t}function NTt(e,t,n){return new Promise((r,i)=>{let a=zs(e,t,cW({...sW,timeout:v5,env:{...process.env,LC_CTYPE:process.env.LC_ALL||process.env.LC_CTYPE,LC_ALL:void 0,LC_MESSAGES:`C`}})),o=!1,s=!1,c=``;a.once(`error`,i);let l=(e,t)=>{let n=``;e.once(`error`,i),e.setEncoding(`utf8`),e.on(`data`,e=>{n+=e;let r=n.indexOf(`
2092
2092
  `);for(;r!==-1;)t(n.slice(0,r)),n=n.slice(r+1),r=n.indexOf(`