@inkeep/open-knowledge 0.84.0-beta.4 → 0.84.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-BtCOaUme.mjs +1 -0
- package/dist/{dist-BWAvfDuW.mjs → dist-D1o6pKga.mjs} +1 -1
- package/dist/{dist-C01O4iH2.mjs → dist-x9nvg4Ph.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-BxVdZi-q.mjs → init-59Snc9gC.mjs} +2 -2
- package/dist/init-D5pU8BuW.mjs +1 -0
- package/dist/{launch-json-removal-DCpJPTRd.mjs → launch-json-removal-BJaxF9cc.mjs} +1 -1
- package/dist/loader-C-gQIVWe.mjs +1 -0
- package/dist/{loader-D8c6sLKH.mjs → loader-D5ZhJefp.mjs} +1 -1
- package/dist/{open-browser-etXAlZ_w.mjs → open-browser-01vmbshY.mjs} +1 -1
- package/dist/preview-Den1q1sh.mjs +1 -0
- package/dist/{preview-B6BmcZp2.mjs → preview-b8wh0O3R.mjs} +1 -1
- package/dist/public/assets/AccountSection-0E97n-0_.js +1 -0
- package/dist/public/assets/{ActivityModeContent-DUZhyjXJ.js → ActivityModeContent-odTxEiim.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-BYfH1-WT.js → AddPropertiesButton-DoGP0vFR.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-Bbzn3FVb.js → AgentDiffPane-DZDCUUwt.js} +1 -1
- package/dist/public/assets/{AppMenubar-Dgz756Er.js → AppMenubar-T02G39JR.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-DUlkIP4l.js → AttachmentsSection-DsqKlbYV.js} +1 -1
- package/dist/public/assets/{BugReportHistory-B0y8PoGi.js → BugReportHistory-NHfvhaO9.js} +1 -1
- package/dist/public/assets/{BugReportHistoryDialog-Dqm3l3bd.js → BugReportHistoryDialog-BY5kdvm_.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-Drb1OUJC.js → CodeMirrorPropInput-811lAGx5.js} +1 -1
- package/dist/public/assets/{ConsentDialogBody-TWGdET4r.js → ConsentDialogBody-Dlrq2Y9r.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-LsFc1XAM.js → ContentRulesSection-Ds6ZMxEt.js} +1 -1
- package/dist/public/assets/{DiffViewBoundary-CQwFsSb2.js → DiffViewBoundary-DfFItnz0.js} +1 -1
- package/dist/public/assets/{DocumentContext-Dkr34TWR.js → DocumentContext-DREA0AAo.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-Do7kGUFS.js → EditorModeToggle-Dx5kkbjM.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-madW2o5c.js → ExcalidrawDocEditor-CbS3NOdI.js} +1 -1
- package/dist/public/assets/FeedbackForm-CUAGYJAL.js +1 -0
- package/dist/public/assets/{ImageAttachments-By1ZcRNT.js → ImageAttachments-Dovmnniy.js} +1 -1
- package/dist/public/assets/{ImportSkillDialog-DQlC1UVZ.js → ImportSkillDialog-Ti39qGmm.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-BGwx2pBe.js → LinkPreviewsSection-CSnOZVhW.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-CnJnzFnT.js → LintConfigEditor-DRhKEBr2.js} +1 -1
- package/dist/public/assets/{LintingSection-Bz-f01q8.js → LintingSection-DnGyMgRR.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-BFid5qqh.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-BRRc9Nck.js → ManagedArtifactProperties-CB26JLki.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-D00SA4S5.js → MermaidDocEditor-Du06Otit.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-BrQ04PAl.js → NetworkAccessSection-BsPOyp5k.js} +1 -1
- package/dist/public/assets/{OkignoreSection-B65Debem.js → OkignoreSection-PgIvzNbG.js} +1 -1
- package/dist/public/assets/{ProjectTemplatesSection-Cgz1Gipq.js → ProjectTemplatesSection--LdpxkrE.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-CejfREf8.js → PropertyDisplayRow-C6fCnEMm.js} +2 -2
- package/dist/public/assets/{PublishToGitHubDialog-C3G5gU4a.js → PublishToGitHubDialog-CvngeZb5.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-xJE9h5I4.js → ReportBugDialogBody-DNZtJiE1.js} +1 -1
- package/dist/public/assets/{ReportBugMenuTrigger-BcNRdrQT.js → ReportBugMenuTrigger-DIsDu8Oo.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-DfNwto81.js → SchemaConfigEditor-D1u-On5t.js} +1 -1
- package/dist/public/assets/{SearchSection-6N-xV3m6.js → SearchSection-1Vu1ko_e.js} +1 -1
- package/dist/public/assets/{SessionsHost-Dt0YX7e4.js → SessionsHost-Cz0APgNL.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-CX3cuu2A.js → SettingsDialogBody-BxIkdYbp.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-bUB0ammT.js → ShareReceiveMissDialog-D_0W8GUR.js} +1 -1
- package/dist/public/assets/{SkillEditBanner-CwGW7u29.js → SkillEditBanner-L7pyMGIi.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-syd5rOWa.js → SkillInstallMenu-CDYwn4cO.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-ek2j3kre.js → SkillOriginInline-MFoSrL6C.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-Cs2gtZl9.js → SkillToolbarControls-DfKRIwfj.js} +1 -1
- package/dist/public/assets/{SkillsManagerSection-C6lWLXvH.js → SkillsManagerSection-Bj9MjUN8.js} +1 -1
- package/dist/public/assets/{SlidesPluginSection-Bk1073RP.js → SlidesPluginSection-gB_5IAe_.js} +1 -1
- package/dist/public/assets/{SourceEditor-DCI5wuU2.js → SourceEditor-C42Iffnh.js} +1 -1
- package/dist/public/assets/{SpellingSettings-AV7ODzdq.js → SpellingSettings-C02qSUzm.js} +1 -1
- package/dist/public/assets/{SyncSection-Dy1x052n.js → SyncSection-BS4HBraZ.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-CI4kJKJz.js → SyncStatusBadge-QCsrzBFK.js} +1 -1
- package/dist/public/assets/{TemplateRow-CKPSBcvy.js → TemplateRow-SOJ_mM7J.js} +1 -1
- package/dist/public/assets/{TerminalSection-DhkctuaS.js → TerminalSection-Dj31h5X4.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BiHTk4jD.js → TerminalWindowApp-BkyTDdLj.js} +1 -1
- package/dist/public/assets/{TextDocEditor-MTT9X-UX.js → TextDocEditor-WgOTsJ2-.js} +1 -1
- package/dist/public/assets/{ThemePluginSection-Bmm0ezpW.js → ThemePluginSection-kDCNVKiQ.js} +1 -1
- package/dist/public/assets/{ThreadView-CTTrHNJC.js → ThreadView-fknHeEPv.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-q_M_-BhG.js → TimelineDiffPane-BjwTL55D.js} +1 -1
- package/dist/public/assets/{calendar-U3XIfpfI.js → calendar-B94KcaTl.js} +1 -1
- package/dist/public/assets/{card-BDi8CQBG.js → card-C9KUHBo3.js} +1 -1
- package/dist/public/assets/{comment-chips-CoLxBx92.js → comment-chips-B-lJxcWw.js} +1 -1
- package/dist/public/assets/{config-provider-DXmc67dU.js → config-provider-DlBeMuUR.js} +1 -1
- package/dist/public/assets/config-schema-yBuT6Kw2.js +1 -0
- package/dist/public/assets/{doc-undo-manager-C_pnWJYM.js → doc-undo-manager-BW8JWjHx.js} +1 -1
- package/dist/public/assets/field-controls-CPGfvl4b.js +1 -0
- package/dist/public/assets/{field-controls-hlVaDlD0.js → field-controls-DJ9Xc2lP.js} +1 -1
- package/dist/public/assets/{index-DlH3oHvT.js → index-CkezNoQ6.js} +75 -75
- package/dist/public/assets/{input-group-D_ozMCmW.js → input-group-CvtNBDpz.js} +1 -1
- package/dist/public/assets/{lint-config-client-Dris_9kn.js → lint-config-client-Cw1iU1nz.js} +1 -1
- package/dist/public/assets/{lint-plugins-CINC49yJ.js → lint-plugins-WdO2CPIC.js} +1 -1
- package/dist/public/assets/{markdown-lint-tXEf2MDv.js → markdown-lint-CA9Voa_6.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-DQbNHswB.js → markdownlint-rule-browser-Xp4EWBSS.js} +1 -1
- package/dist/public/assets/messages-B873lb17.js +1 -0
- package/dist/public/assets/messages-BNkn5D4f.js +1 -0
- package/dist/public/assets/messages-BUvJUm4Q.js +1 -0
- package/dist/public/assets/messages-BWsM3wpe.js +1 -0
- package/dist/public/assets/messages-BfSogmKY.js +1 -0
- package/dist/public/assets/messages-Bn9WWUVr.js +1 -0
- package/dist/public/assets/messages-C572XTjB.js +1 -0
- package/dist/public/assets/messages-CDXbN2TY.js +1 -0
- package/dist/public/assets/messages-COfCWPbk.js +1 -0
- package/dist/public/assets/messages-D41opmU0.js +1 -0
- package/dist/public/assets/messages-D4Jxk56m.js +1 -0
- package/dist/public/assets/messages-D9BcyLGO.js +1 -0
- package/dist/public/assets/messages-Dgr-iymI.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-Dx3tjU3M.js → pending-receive-nav-store-a7bRJTor.js} +1 -1
- package/dist/public/assets/{preferred-session-events-UCAyZlN5.js → preferred-session-events-C6ADVRVP.js} +1 -1
- package/dist/public/assets/{progress-kP97a1rO.js → progress-jkYP8dgI.js} +1 -1
- package/dist/public/assets/{saved-themes-client-Cx7GJLm9.js → saved-themes-client-i6giWyrX.js} +1 -1
- package/dist/public/assets/{schema-section-CVZJtaH2.js → schema-section-DNfBEQnt.js} +1 -1
- package/dist/public/assets/{selection-context-C6c6vB_u.js → selection-context-CjlE8wWY.js} +1 -1
- package/dist/public/assets/{src-DmaohtEC.js → src-DXhMPcM3.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-DrGckpC8.js → typing-burst-detector-D-bemn9V.js} +1 -1
- package/dist/public/assets/{uninstall-DiNfurw6.js → uninstall-Q2nzmrZ_.js} +1 -1
- package/dist/public/assets/{use-activity-panel-CkJrJb3b.js → use-activity-panel-7mB7mu3r.js} +1 -1
- package/dist/public/assets/{use-apply-config-language-BvXQKexF.js → use-apply-config-language-4xYH56WJ.js} +2 -2
- package/dist/public/assets/{use-installed-clis-Bq2JB-bo.js → use-installed-clis-Cr70uJek.js} +2 -2
- package/dist/public/assets/{use-open-skill-BfvvQFrP.js → use-open-skill-EymTxyOn.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-Bux88unS.js → use-terminal-enabled-dMzCCT1n.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CQd38y1M.js → use-timeline-entry-diff-C5-tqjEY.js} +1 -1
- package/dist/public/index.html +41 -41
- package/dist/public/uninstall.html +4 -4
- package/dist/{registry-probes-CetDjX_j.mjs → registry-probes-aXTkGZJh.mjs} +1 -1
- package/dist/{removal-file-path-Djea2-om.mjs → removal-file-path-Dz8upF6X.mjs} +1 -1
- package/dist/{repair-launch-json-BNvTpRS_.mjs → repair-launch-json-qspE1kMU.mjs} +1 -1
- package/dist/{repair-mcp-configs-CxYH74IT.mjs → repair-mcp-configs-BZoZnYv0.mjs} +1 -1
- package/dist/src-CyTi8lqj.mjs +1 -0
- package/dist/{src-BILMinJo.mjs → src-DlxYZ4f8.mjs} +1 -1
- package/dist/{start-lJXFuEW7.mjs → start-Bkj3Zr3c.mjs} +3 -3
- package/dist/start-xlfsKg2e.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-DVqvzhbh.mjs +0 -1
- package/dist/init-CflGUOQW.mjs +0 -1
- package/dist/loader-BBciDpto.mjs +0 -1
- package/dist/preview-Olt-dcII.mjs +0 -1
- package/dist/public/assets/AccountSection-BQs9T7Qi.js +0 -1
- package/dist/public/assets/FeedbackForm-DgHrtWvi.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-CRowlH3M.js +0 -1
- package/dist/public/assets/config-schema-D59L2aVm.js +0 -1
- package/dist/public/assets/field-controls-CKm3BgiK.js +0 -1
- package/dist/public/assets/messages-9pu0eKMD.js +0 -1
- package/dist/public/assets/messages-BCv3uDH5.js +0 -1
- package/dist/public/assets/messages-BGib4TMp.js +0 -1
- package/dist/public/assets/messages-BOWt1g5R.js +0 -1
- package/dist/public/assets/messages-BtwWpZz0.js +0 -1
- package/dist/public/assets/messages-BtzlQnhk.js +0 -1
- package/dist/public/assets/messages-BxPgHAGT.js +0 -1
- package/dist/public/assets/messages-C_IQGWPh.js +0 -1
- package/dist/public/assets/messages-CgvGzWvU.js +0 -1
- package/dist/public/assets/messages-CmBBJ_lX.js +0 -1
- package/dist/public/assets/messages-D07eucGp.js +0 -1
- package/dist/public/assets/messages-DHQmHLsP.js +0 -1
- package/dist/public/assets/messages-R6IvK1vE.js +0 -1
- package/dist/src-BUgL_R1i.mjs +0 -1
- package/dist/start-_aKlfpQ5.mjs +0 -1
- /package/dist/public/assets/{ChangedOutsideBadge-BB-SCUmw.js → ChangedOutsideBadge-Dzr-p6dI.js} +0 -0
- /package/dist/public/assets/{DeleteConfirmationDialog-DrwlL-Hc.js → DeleteConfirmationDialog-BXUDIZYO.js} +0 -0
- /package/dist/public/assets/{SkillCostValue-tiv0OMS7.js → SkillCostValue-DsQH45sT.js} +0 -0
- /package/dist/public/assets/{SkillModeBanner-DaZYmbfZ.js → SkillModeBanner-DcxGGSM7.js} +0 -0
- /package/dist/public/assets/{alert-BY4HHcfV.js → alert-rmEQg7oS.js} +0 -0
- /package/dist/public/assets/{folder-config-api-CX9qXRQC.js → folder-config-api-DEVs3afn.js} +0 -0
- /package/dist/public/assets/{format-Yv4YAHdV.js → format-INdUJq6M.js} +0 -0
- /package/dist/public/assets/{platform-labels-BPRIEv67.js → platform-labels-bKkrtmmV.js} +0 -0
- /package/dist/public/assets/{sortable.esm-DuJVOTXv.js → sortable.esm-k5B4BkZq.js} +0 -0
- /package/dist/public/assets/{textarea-qPZDtk8V.js → textarea-CWb90goJ.js} +0 -0
- /package/dist/public/assets/{use-skill-origin-ywt3YYti.js → use-skill-origin-D21QwcNC.js} +0 -0
- /package/dist/public/assets/{use-skill-targets-RLdS0VLQ.js → use-skill-targets-k1ci94K-.js} +0 -0
|
@@ -1047,7 +1047,7 @@ ${wW.join(`
|
|
|
1047
1047
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
1048
1048
|
`)}return{content:i}}async handleFsWrite(e,t,n){this.touchTurnActivity(e);let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel},a=OH(t);try{t.dc.document.transact(()=>{let r=cQ(t.dc.document);sQ(t.dc.document,n,`replace`,i,void 0,aQ(t),a);let o=Oc(r,cQ(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...o===void 0?{}:{changedBlocks:o}})},t.origin)}catch(e){throw e instanceof cJ?(lJ(e,`acp-fs-write`),new $C(-32009,oJ,{type:iJ,file:e.file,retryable:!0,retryAfterSeconds:3})):e}this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await Promise.resolve().then(()=>aU);await e(V(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return m8e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new g$(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&iJe(n[n.length-1],t,e.info.agent))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>$6e){let t=e.events.length-$6e;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){if(S$(e)){(t===`error`||t===`auth_required`?this.opts.log.warn:this.opts.log.info).call(this.opts.log,{threadId:e.info.threadId,agentId:e.info.agent.id,status:t,suppressed:!0,detail:n===void 0?void 0:OQ(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:OQ(r.machineDetail)},`[acp-threads] status suppressed after thread close`);return}this.recordTerminalStatus(e,t,n,r)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),t===`error`&&r!==void 0&&$3e(r.reason)&&n6e(this.opts.localDir,{at:new Date,threadId:e.info.threadId,agentId:e.info.agent.id,agentSource:e.info.agent.source,reason:r.reason,detail:n,machineDetail:r.machineDetail}).catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] launch failure log write failed`)}),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){this.failPendingPermissions(e),this.failPendingConsents(e),e.lastInit=null,e.sessionId=null,e.info.contextWindow=null,await this.stopAgentProcess(e,`[acp-threads] terminal cleanup on failed-agent teardown failed`)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,stalledSince:i,chatGrants:a,...o}=e.info;return{version:1,info:o,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName,contextWindow:e.confirmedContextWindow??null,browserNotice:e.browserNotice}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingConsents(e){for(let t of[e.pendingRuntimeConsent,e.pendingPiBridgeConsent]){for(let e of t.values())clearTimeout(e.timer),e.resolve(`closed`);t.clear()}}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=Oe(e.info.agent.id),i=ge[r]??Tr(e.agentSessionId);n.setPresence(SH(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now(),docTs:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function m8e(e,t,n){let r=await $s(e),i=gs(hs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await $s(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||hs(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(vs).join(`/`),t=s.split(vs).join(`/`);!pG(e)&&!mG(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(vs).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=V(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):H(a.slice(t.length+1),o),a=t}}function h8e(e){let t=e.info.status===`error`?`error`:`exited`;return{confirmedContextWindow:e.contextWindow??null,launchSettings:e.contextWindow==null?void 0:{contextWindow:e.contextWindow},info:{...e.info,contextWindow:null,status:t,archived:!0,resumable:e.info.resumable!==!1&&e.sessionId!==null,queue:void 0,steer:void 0,signInOutput:void 0,chatGrants:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,terminalAuthBase:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,reportedToolCalls:new Map,toolCallReportWaiters:new Map,browserInjected:!1,browserNotice:e.browserNotice??null,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:Date.now(),unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1,projectSkill:null,chatGrants:new Set}}function v$(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function g8e(e){let t=r$(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function _8e(e){let t=r$(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. The offer to download a private copy of ${t.displayName} expired before it was answered — start the agent again to get it back, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function v8e(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.code===-32e3||typeof t.data==`object`&&t.data!==null&&t.data.errorKind===`authentication_failed`}function y$(e){return e instanceof Error?e.message:String(e)}function b$(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return OQ(JSON.stringify(t)).slice(0,300)}catch{return}}function y8e(e){return c$(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function x$(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(n!==void 0&&n.kind===`status`&&(n.status===`error`||n.status===`auth_required`))return n.detail??n.failure?.agentMessage}}async function b8e(e,t){return{reason:`connect`,agentMessage:e instanceof PQ||e instanceof g$?e.message:String(e),machineDetail:w$({primary:e instanceof PQ?e.machineDetail:void 0,tail:await C$(t)})}}function x8e(e){let t={id:crypto.randomUUID(),content:e.content,ts:e.ts};return e.attachments!==void 0&&e.attachments.length>0&&(t.attachments=e.attachments),t}function S$(e){return e.closed||e.info.archived===!0}async function C$(e){let t=e.stderrTail;await e.drainStderr?.();let n=OQ(t.join(`
|
|
1049
1049
|
`)).slice(-16e3);return n===``?void 0:n}function w$({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,DQ);let n=Math.min(t.length,1024),r=DQ-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=DQ-i.length-1;return`${i}\n${t.slice(-a)}`}function T$(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
1050
|
-
`);return w$({primary:b$(e),tail:n})}function S8e(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function C8e(e,t){let n=bS(e?._meta),r=bS(t._meta);return{title:t.title??e?.title??null,kind:t.kind??e?.kind??null,rawInput:t.rawInput??e?.rawInput,...n!==null||r!==null?{_meta:{...n,...r}}:{}}}function w8e(e,t){let n=C8e(e.reportedToolCalls.get(t.toolCallId),t);if(e.reportedToolCalls.delete(t.toolCallId),e.reportedToolCalls.set(t.toolCallId,n),e.reportedToolCalls.size>256){let t=e.reportedToolCalls.keys().next().value;t!==void 0&&e.reportedToolCalls.delete(t)}let r=e.toolCallReportWaiters.get(t.toolCallId);if(r!==void 0){e.toolCallReportWaiters.delete(t.toolCallId);for(let e of r)e()}}async function T8e(e,t,n,r){let i=t.toolCallId,a=e.reportedToolCalls.get(i);return a!==void 0||!e.browserInjected||!T4e(t,n,e.info.agent.id)?a:(await new Promise(t=>{let n=e.toolCallReportWaiters.get(i)??[],a=()=>{clearTimeout(o);let n=(e.toolCallReportWaiters.get(i)??[]).filter(e=>e!==a);n.length>0?e.toolCallReportWaiters.set(i,n):e.toolCallReportWaiters.delete(i),t()},o=setTimeout(()=>{r.warn({threadId:e.info.threadId,toolCallId:i},`[acp-threads] no tool call report arrived for a permission request in a chat with the browser; asking with no option to always allow it`),a()},1e3);o.unref?.(),n.push(a),e.toolCallReportWaiters.set(i,n)}),e.reportedToolCalls.get(i))}function E8e(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(D8e(e,t,n));e.on(`message`,e=>{let s=ESe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,attachments:s.attachments,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt,s.attachments);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`terminal_auth_launch`:{let e=t.terminalAuthLaunch(s.threadId,s.methodId);i({op:`terminal_auth_launch_ready`,reqId:s.reqId,launch:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content,s.attachments);return;case`steer`:t.steerPrompt(s.threadId,s.content,s.attachments);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`queue_send_now`:t.sendQueuedNow(s.threadId,s.id);return;case`set_chat_grant`:t.setChatGrant(s.threadId,s.grant,s.enabled);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`pi_bridge_consent_response`:t.respondPiBridgeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:{let e=await t.renameThread(s.threadId,s.title);r.has(s.threadId)||i({op:`info`,info:e});return}case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`set_context_window`:{let e=await t.setContextWindow(s.threadId,s.tokens);i({op:`context_window_set`,reqId:s.reqId,info:e});return}case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof g$?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof g$)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function D8e(e,t,n){return{op:`error`,code:e,message:t,...n}}var O8e=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){CH(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){CH(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(Hi);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),k8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function k8e(e){return e?.awareness??null}var A8e=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!CH(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!CH(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!CH(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!CH(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return BXe(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Hi);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),j8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function j8e(e){return e?.awareness??null}function M8e(e){let{env:t,resolve:n}=e;return e=>n===void 0?null:t===`remote-web`&&e.scope===`user`?{state:`unprobed`}:n(e)}async function E$(e){return{probes:await kee({env:e.env,resolve:M8e(e)}),detection:Ca}}const N8e=dc(gae);function D$(e){return H(DS(e),Vee)}async function O$(e,t){let n=D$(e);await hU(V(n),{recursive:!0});try{return await PS(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const P8e={warn:(e,t)=>q(`skills`).warn(e,t)};async function k$(e,t=P8e){let n=D$(e),r;try{r=await N8e(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,Fc.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=gi.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function A$(e,t){let n=gi.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=D$(e);await hU(V(r),{recursive:!0});let i=(0,Fc.parseDocument)(``);i.contents=i.createNode(n.data),await MS(r,i.toString(),{fs:EU})}async function j$(e,t,n){let r=await k$(e,n);return r===null?null:r.targets[t]?.version??null}async function F8e(e,t,n){let r=await k$(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function M$(e,t,n,r,i){if(!fie.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await O$(e,async()=>{let a=await k$(e,i)??_(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await A$(e,{...a,targets:{...a.targets,[t]:l}})})}async function I8e(e,t,n){let r=(await k$(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function L8e(e,t,n,r){await O$(e,async()=>{let i=await k$(e,r)??_();await A$(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function R8e(e,t){let n=await k$(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function z8e(e,t,n){t.length!==0&&await O$(e,async()=>{let r=await k$(e,n)??_(),i=new Set([...r.installsReported??[],...t]);await A$(e,{...r,installsReported:[...i].sort()})})}async function B8e(e,t,n){t.length!==0&&await O$(e,async()=>{let r=await k$(e,n);if(!r?.installsReported?.length)return;let i=new Set(t),a=r.installsReported.filter(e=>!i.has(e));a.length!==r.installsReported.length&&await A$(e,{...r,installsReported:a})})}async function N$(){let e=new URL(`../package.json`,import.meta.url),t=await N8e(ys(e),`utf-8`),n=JSON.parse(t);if(typeof n.version!=`string`||n.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return n.version}async function V8e(e,t){let[n,r]=await Promise.all([N$(),H8e(e,t)]);return{currentVersion:n,targets:r}}async function H8e(e,t=P8e){let n=null;try{n=await k$(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:D$(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=Hre.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const U8e=q(`agent-registry-apply`);function W8e(e){return{probes:Bee(e),detection:Ca}}const G8e=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function K8e(e,t){try{return await e()}catch(e){return U8e.warn({err:e},`host snapshot failed; claiming nothing`),W8e(t)}}async function q8e(e,t){let n=await K8e(t.snapshot,t.env),r=Pee({probes:n.probes,detection:n.detection}),i=g(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await rr(i,t.execute??G8e),{decisionHome:o}=t,s=J8e(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await L8e(o,dQ.discovery,c).catch(e=>{U8e.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await K8e(t.snapshot,t.env)}}function J8e(e){let t=e.actions.filter(e=>e.piece===`skill`&&e.scope===`user`);return t.some(e=>e.action===`written`||e.action===`overwritten`)?`installed`:t.some(e=>e.action===`removed`)?`removed`:null}const Y8e=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function P$(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(Y8e,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function F$(e,t){let n=P$(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=kH(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.suppliedWriterId!==void 0?{kind:`agent`,writerId:r.suppliedWriterId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:wH(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}const X8e=new Set([`GET`,`HEAD`,`OPTIONS`]);function Z8e(e){return X8e.has(e??`GET`)}function Q8e(e){return e===`null`||e.toLowerCase().startsWith(`file:`)}function $8e(e){if(e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function I$(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function e5e(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function L$(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function t5e(e,t){return e!==void 0&&L$(e)===t}const n5e=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function R$(e){return n5e.some(t=>e.headers[t]!==void 0)}const z$=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var r5e=class extends Error{};const i5e=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function a5e(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function B$(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(a5e).filter(e=>!i5e.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:L$(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function V$(e,t){return I$(e)?!0:t.allowExternal&&e!==void 0}function o5e(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function H$(e,t){if(e5e(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=o5e(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&t5e(e,t.externalOrigin.host)}function U$(e,t){if($8e(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&L$(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=a5e(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function s5e(e,t,n){if(e===void 0)return{admitted:!0,corsGrant:!0};let r=Q8e(e);return!U$(e,n)||r&&!Z8e(t)?{admitted:!1,detail:r?`Requests from a null origin, and writes from a file: origin, are refused. Send the request from a loopback page, the OpenKnowledge app, or a client that sends no Origin header.`:void 0}:{admitted:!0,corsGrant:!r}}function W$(e,t){return!t.tolerateForwardedHeaders&&R$(e)}let c5e=!1;function G$(e,t){c5e||(c5e=!0,e.warn({handler:t},`[ingress] refused a request carrying a forwarding header (X-Forwarded-For etc.) — without external-exposure consent, every surface except the /healthz + /readyz probes refuses proxied requests (APIs 403, /collab upgrades dropped). To front this server with a proxy, set server.externalUrl to the public origin in .ok/config.yml (or OK_EXTERNAL_URL) AND consent with server.allowExternal: true in .ok/local/config.yml (or OK_ALLOW_EXTERNAL=1) — the keys live in different files because consent is per-machine and never travels. allowExternal consents to exposure on a server with NO authentication — restrict access at the edge. Removing server.externalUrl does not lift this refusal (it fires on the header, not the URL) and would un-admit that Host/Origin everywhere else. Warned once per process; every refusal is still logged at warn level (HTTP refusals additionally as api.error, counted in ok.api.error.count).`))}const l5e=new WeakMap;function u5e(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:I$(n)?`loopback`:`external`,actor:void 0};return l5e.set(e,r),r}function d5e(e){return l5e.get(e)}const K$=q(`local-op-security`),f5e=Gj,p5e=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function q$(e){return!e||typeof e!=`string`||p5e.some(t=>t.test(e))?!1:f5e.some(t=>t.test(e))}function J$(e){return e===`~`?Us():e.startsWith(`~/`)?H(Us(),e.slice(2)):e}function m5e(e,t){let n=V(e);for(;n!==t&&n!==V(n);){let e;try{e=Ds(n)}catch(e){let t=DG(e);return K$.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return K$.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=V(n)}return!1}function h5e(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=Ps(t)}catch(e){let n=DG(e);return K$.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=W(J$(e)),i=[],a=r;for(;;){let e=null;try{e=Ds(a)}catch(e){let t=DG(e);if(t!==`ENOENT`)return K$.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=Ps(a)}catch(n){let i=DG(n);if(e.isSymbolicLink())return K$.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(m5e(a,t))return K$.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;K$.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return K$.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:H(r,...i),s=U(n,o);return s===``||!s.startsWith(`..`)&&!hs(s)}let r=V(a);if(r===a)return!1;i.unshift(fs(a)),a=r}}function Y$(e){return h5e(e,Us())}function g5e(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function _5e(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&v5e(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function v5e(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function y5e(e,t,n){let r=n.policy??B$({});return!g5e(e)&&!V$(e.socket.remoteAddress,r)?(X(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):_5e(e,r)?!0:(X(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function b5e(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const x5e=new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256);function S5e(e){x5e.push(e)}const C5e=jc.cursor,w5e=jc.codex,T5e=jc[`claude-desktop`],E5e={app:null,signals_fired:[]};function D5e(e){if(!e)return{...E5e};let t=[],n=e.ua,r=e.referer,i=!!n&&C5e.test(n),a=!!r&&r.includes(`?strategy=C_iframe`);if(i&&t.push(`cursor_ua_regex`),a&&t.push(`cursor_referer_strategy_iframe`),i||a)return{app:`cursor`,signals_fired:t};let o=!!n&&w5e.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&T5e.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...E5e}}const O5e=new Set([`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/agent-write-batch`,`/api/comments`,`/api/comment`,`/api/client-logs`,`/api/frontmatter-patch`,`/api/save-version`,`/api/rollback`,`/api/lint/fix`,`/api/folder-config`,`/api/template`,`/api/agent-integrations/apply`]);function X$(e,t={}){let{dynamic:n}=t,r=new Set(t.mutating??[]),i=t.mutatingPrefixes??[],a=Object.keys(e);if(n!==void 0&&!n.prefix.endsWith(`/`))throw Error(`dynamic.prefix '${n.prefix}' must end in '/' — a bare prefix mounts a wildcard that also swallows unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);for(let e of i){if(!e.endsWith(`/`))throw Error(`mutatingPrefixes entry '${e}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);if(e!==n?.prefix&&!a.some(t=>t.startsWith(e)))throw Error(`mutatingPrefixes entry '${e}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`)}let o=new Map(Object.entries(e)),s={resolve(e){let t=o.get(e);return t?{template:e,dispatch:(e,n)=>t(e,n)}:n!==void 0&&e.startsWith(n.prefix)?{template:n.template,dispatch:n.dispatch(e.slice(n.prefix.length))}:null},isMutating:e=>r.has(e)||i.some(t=>e.startsWith(t))};return{paths:n===void 0?a:[...a.filter(e=>!e.startsWith(n.prefix)),`${n.prefix}*`],table:s}}let Z$=null;BH(()=>{Z$=null});function k5e(){return Z$||=UH().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),Z$}function A5e(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??B$({}),a=e=>H$(e,i);return async(o,s)=>{let c=o.url?.split(`?`)[0];if(!c)return!1;let l=r.resolve(c);if(!l)return!1;let u=e=>{let t=o.headers[e];if(t!==void 0)return Array.isArray(t)?t.join(`, `):t};S5e({ts:Date.now(),url:c,method:o.method??``,ua:u(`user-agent`),origin:u(`origin`),referer:u(`referer`),host:u(`host`),remote:o.socket?.remoteAddress,secChUa:u(`sec-ch-ua`),secChUaMobile:u(`sec-ch-ua-mobile`),secChUaPlatform:u(`sec-ch-ua-platform`),secFetchSite:u(`sec-fetch-site`),secFetchDest:u(`sec-fetch-dest`),secFetchMode:u(`sec-fetch-mode`),secFetchUser:u(`sec-fetch-user`)});let d=o.method??`GET`,f=l.template,p=c.startsWith(`/api/`)?BQe(o):void 0;if(u5e(o,{requestId:p}),p!==void 0&&(VQe(o,p),typeof s.setHeader==`function`&&s.setHeader(Xq,p),typeof s.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:p,method:d,route:f,status:s.statusCode,durationMs:Date.now()-e,...s.writableFinished?{}:{aborted:!0}},`${d} ${f} ${s.statusCode}`))};s.once(`finish`,r),s.once(`close`,r)}if(c.startsWith(`/api/`)){let e=o.headers.origin,t=s5e(e,d,i);if(!t.admitted)return X(s,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`,detail:t.detail}),!0;if(typeof s.setHeader==`function`&&(e!==void 0&&s.setHeader(`Vary`,`Origin`),t.corsGrant&&(e!==void 0&&s.setHeader(`Access-Control-Allow-Origin`,e),s.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${Xq}, ${yc.protocol}, ${yc.runtime}, ${yc.kind}`),s.setHeader(`Access-Control-Expose-Headers`,Xq))),o.method===`OPTIONS`)return s.writeHead(204),s.end(),!0}if(r.isMutating(c)){if(n&&l.dispatch!==void 0&&(d===`POST`||d===`PUT`||d===`DELETE`)&&!O5e.has(c))return X(s,403,`urn:ok:error:single-file-mode`,`Single-file previews cannot manage project files.`,{handler:`api-preview-content-scope`}),!0;let e=o.socket?.remoteAddress;if(e!==void 0&&!V$(e,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:z$}),!0}if(c.startsWith(`/api/`)){let e=n?`api-ephemeral-gate`:`api-read-gate`,t=o.socket?.remoteAddress;if(t!==void 0&&!V$(t,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:e}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:e,detail:z$}),!0}if(!c.startsWith(`/api/`))return!1;let m=po.extract(co.active(),o.headers),h=HH(),g=Date.now();return await co.with(m,()=>h.startActiveSpan(`HTTP ${d} ${f}`,{kind:Oie.SERVER,attributes:{[rb]:d,[ab]:f,[lb]:c,[ub]:`http`,[db]:o.headers[`user-agent`]??``,"ok.request.id":p}},async t=>{try{let n=l.dispatch;n===void 0?X(s,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${d} ${c}`}):r.isMutating(c)&&e.dispatchMutation!==void 0?await e.dispatchMutation(()=>n(o,s),c):await n(o,s);let i=s.statusCode;t.setAttribute(ib,i),i>=500&&t.setStatus({code:mo.ERROR,message:`status ${i}`})}catch(e){throw t.recordException(e),t.setStatus({code:mo.ERROR,message:e instanceof Error?e.message:String(e)}),!s.headersSent&&!s.writableEnded&&!s.destroyed&&X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:f,cause:e}),t.setAttribute(ib,s.statusCode),e}finally{t.end();let e=(Date.now()-g)/1e3;k5e().record(e,{[rb]:d,[ab]:f,[ib]:s.statusCode})}})),!0}}function Q$(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof ea||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;X(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function j5e(e){return $$(e,{maxBytes:1048576,timeoutMs:3e4})}function M5e(e){let t=e?.split(`;`,1)[0]?.trim().toLowerCase();return t===void 0?!1:t===`application/json`||/^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(t)}function N5e(e){return e.headers[`transfer-encoding`]!==void 0||Number(e.headers[`content-length`]??0)>0}async function $$(e,t){if(N5e(e)&&!M5e(e.headers[`content-type`]))throw new e1;let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new r1(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new n1(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var e1=class extends Error{constructor(){super(`Request body is not labeled as JSON`),this.name=`UnsupportedMediaTypeError`}};function t1(e,t){X(e,415,`urn:ok:error:unsupported-media-type`,`Request body must be JSON.`,{handler:t,detail:`Send the request body as JSON with the header Content-Type: application/json.`})}var n1=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${P5e(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},r1=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function P5e(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function i1(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return X(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:a}),{ok:!1}}function Z(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=i1(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await j5e(r)}catch(e){if(e instanceof e1){t1(i,n.handler);return}if(e instanceof n1){X(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof r1){X(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}X(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=i1(e,o,i,n);s.ok&&await t(r,i,s.value)}}const a1=()=>q(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){a1().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),tJ().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){a1().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){a1().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function F5e(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return X$({"/api/agent-integrations/apply":Z(kte,Q$(async(e,n,s)=>{let c=F$(s,r);if(c.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`agent-integrations-apply`});return}let l=g5e(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await q8e(s.intents,{execute:o?.execute,env:l,snapshot:()=>E$({env:l,resolve:o?.probe}),decisionHome:i??Us(),...o?.userSkillPresentAnywhere===void 0?{}:{userSkillPresentAnywhere:o.userSkillPresentAnywhere},projectDir:a});t.info({actor:c.kind,applied:u.actions.length,failed:u.actions.filter(e=>e.errorId!==void 0).length,conflicts:u.conflicts.map(e=>e.kind)},`[agent-integrations] batch applied`),Q(n,200,Are,{...u,snapshot:d},{handler:`agent-integrations-apply`})},{handler:`agent-integrations-apply`,title:`Failed to apply AI tool connections.`}),{handler:`agent-integrations-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`agent-integrations-apply`})})},{mutating:[`/api/agent-integrations/apply`]})}let I5e=0;const L5e=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function o1(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++I5e,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},L5e)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),zXe(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}let s1=new Map;function c1(e,t,n,r,i,a,o,s){let c=s1.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},s1.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function R5e(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of s1){for(let e of t)n.docs.delete(e);n.docs.size===0&&s1.delete(e)}}function z5e(){let e=s1;return s1=new Map,e}function B5e(e){for(let[t,n]of e){let e=s1.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},s1.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function V5e(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1050
|
+
`);return w$({primary:b$(e),tail:n})}function S8e(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function C8e(e,t){let n=bS(e?._meta),r=bS(t._meta);return{title:t.title??e?.title??null,kind:t.kind??e?.kind??null,rawInput:t.rawInput??e?.rawInput,...n!==null||r!==null?{_meta:{...n,...r}}:{}}}function w8e(e,t){let n=C8e(e.reportedToolCalls.get(t.toolCallId),t);if(e.reportedToolCalls.delete(t.toolCallId),e.reportedToolCalls.set(t.toolCallId,n),e.reportedToolCalls.size>256){let t=e.reportedToolCalls.keys().next().value;t!==void 0&&e.reportedToolCalls.delete(t)}let r=e.toolCallReportWaiters.get(t.toolCallId);if(r!==void 0){e.toolCallReportWaiters.delete(t.toolCallId);for(let e of r)e()}}async function T8e(e,t,n,r){let i=t.toolCallId,a=e.reportedToolCalls.get(i);return a!==void 0||!e.browserInjected||!T4e(t,n,e.info.agent.id)?a:(await new Promise(t=>{let n=e.toolCallReportWaiters.get(i)??[],a=()=>{clearTimeout(o);let n=(e.toolCallReportWaiters.get(i)??[]).filter(e=>e!==a);n.length>0?e.toolCallReportWaiters.set(i,n):e.toolCallReportWaiters.delete(i),t()},o=setTimeout(()=>{r.warn({threadId:e.info.threadId,toolCallId:i},`[acp-threads] no tool call report arrived for a permission request in a chat with the browser; asking with no option to always allow it`),a()},1e3);o.unref?.(),n.push(a),e.toolCallReportWaiters.set(i,n)}),e.reportedToolCalls.get(i))}function E8e(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(D8e(e,t,n));e.on(`message`,e=>{let s=ESe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,attachments:s.attachments,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt,s.attachments);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`terminal_auth_launch`:{let e=t.terminalAuthLaunch(s.threadId,s.methodId);i({op:`terminal_auth_launch_ready`,reqId:s.reqId,launch:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content,s.attachments);return;case`steer`:t.steerPrompt(s.threadId,s.content,s.attachments);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`queue_send_now`:t.sendQueuedNow(s.threadId,s.id);return;case`set_chat_grant`:t.setChatGrant(s.threadId,s.grant,s.enabled);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`pi_bridge_consent_response`:t.respondPiBridgeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:{let e=await t.renameThread(s.threadId,s.title);r.has(s.threadId)||i({op:`info`,info:e});return}case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`set_context_window`:{let e=await t.setContextWindow(s.threadId,s.tokens);i({op:`context_window_set`,reqId:s.reqId,info:e});return}case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof g$?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof g$)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function D8e(e,t,n){return{op:`error`,code:e,message:t,...n}}var O8e=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){CH(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){CH(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(Hi);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),k8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function k8e(e){return e?.awareness??null}var A8e=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!CH(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!CH(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!CH(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!CH(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return BXe(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Hi);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),j8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function j8e(e){return e?.awareness??null}function M8e(e){let{env:t,resolve:n}=e;return e=>n===void 0?null:t===`remote-web`&&e.scope===`user`?{state:`unprobed`}:n(e)}async function E$(e){return{probes:await kee({env:e.env,resolve:M8e(e)}),detection:Ca}}const N8e=dc(gae);function D$(e){return H(DS(e),Vee)}async function O$(e,t){let n=D$(e);await hU(V(n),{recursive:!0});try{return await PS(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const P8e={warn:(e,t)=>q(`skills`).warn(e,t)};async function k$(e,t=P8e){let n=D$(e),r;try{r=await N8e(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,Fc.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=gi.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function A$(e,t){let n=gi.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=D$(e);await hU(V(r),{recursive:!0});let i=(0,Fc.parseDocument)(``);i.contents=i.createNode(n.data),await MS(r,i.toString(),{fs:EU})}async function j$(e,t,n){let r=await k$(e,n);return r===null?null:r.targets[t]?.version??null}async function F8e(e,t,n){let r=await k$(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function M$(e,t,n,r,i){if(!fie.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await O$(e,async()=>{let a=await k$(e,i)??_(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await A$(e,{...a,targets:{...a.targets,[t]:l}})})}async function I8e(e,t,n){let r=(await k$(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function L8e(e,t,n,r){await O$(e,async()=>{let i=await k$(e,r)??_();await A$(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function R8e(e,t){let n=await k$(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function z8e(e,t,n){t.length!==0&&await O$(e,async()=>{let r=await k$(e,n)??_(),i=new Set([...r.installsReported??[],...t]);await A$(e,{...r,installsReported:[...i].sort()})})}async function B8e(e,t,n){t.length!==0&&await O$(e,async()=>{let r=await k$(e,n);if(!r?.installsReported?.length)return;let i=new Set(t),a=r.installsReported.filter(e=>!i.has(e));a.length!==r.installsReported.length&&await A$(e,{...r,installsReported:a})})}async function N$(){let e=new URL(`../package.json`,import.meta.url),t=await N8e(ys(e),`utf-8`),n=JSON.parse(t);if(typeof n.version!=`string`||n.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return n.version}async function V8e(e,t){let[n,r]=await Promise.all([N$(),H8e(e,t)]);return{currentVersion:n,targets:r}}async function H8e(e,t=P8e){let n=null;try{n=await k$(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:D$(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=Hre.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const U8e=q(`agent-registry-apply`);function W8e(e){return{probes:Bee(e),detection:Ca}}const G8e=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function K8e(e,t){try{return await e()}catch(e){return U8e.warn({err:e},`host snapshot failed; claiming nothing`),W8e(t)}}async function q8e(e,t){let n=await K8e(t.snapshot,t.env),r=Pee({probes:n.probes,detection:n.detection}),i=g(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await rr(i,t.execute??G8e),{decisionHome:o}=t,s=J8e(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await L8e(o,dQ.discovery,c).catch(e=>{U8e.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await K8e(t.snapshot,t.env)}}function J8e(e){let t=e.actions.filter(e=>e.piece===`skill`&&e.scope===`user`);return t.some(e=>e.action===`written`||e.action===`overwritten`)?`installed`:t.some(e=>e.action===`removed`)?`removed`:null}const Y8e=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function P$(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(Y8e,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function F$(e,t){let n=P$(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=kH(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.suppliedWriterId!==void 0?{kind:`agent`,writerId:r.suppliedWriterId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:wH(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}const X8e=new Set([`GET`,`HEAD`,`OPTIONS`]);function Z8e(e){return X8e.has(e??`GET`)}function Q8e(e){return e===`null`||e.toLowerCase().startsWith(`file:`)}function $8e(e){if(e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function I$(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function e5e(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function L$(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function t5e(e,t){return e!==void 0&&L$(e)===t}const n5e=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function R$(e){return n5e.some(t=>e.headers[t]!==void 0)}const z$=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var r5e=class extends Error{};const i5e=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function a5e(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function B$(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(a5e).filter(e=>!i5e.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:L$(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function V$(e,t){return I$(e)?!0:t.allowExternal&&e!==void 0}function o5e(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function H$(e,t){if(e5e(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=o5e(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&t5e(e,t.externalOrigin.host)}function U$(e,t){if($8e(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&L$(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=a5e(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function s5e(e,t,n){if(e===void 0)return{admitted:!0,corsGrant:!0};let r=Q8e(e);return!U$(e,n)||r&&!Z8e(t)?{admitted:!1,detail:r?`Requests from a null origin, and writes from a file: origin, are refused. Send the request from a loopback page, the OpenKnowledge app, or a client that sends no Origin header.`:void 0}:{admitted:!0,corsGrant:!r}}function W$(e,t){return!t.tolerateForwardedHeaders&&R$(e)}let c5e=!1;function G$(e,t){c5e||(c5e=!0,e.warn({handler:t},`[ingress] refused a request carrying a forwarding header (X-Forwarded-For etc.) — without external-exposure consent, every surface except the /healthz + /readyz probes refuses proxied requests (APIs 403, /collab upgrades dropped). To front this server with a proxy, set server.externalUrl to the public origin in .ok/config.yml (or OK_EXTERNAL_URL) AND consent with server.allowExternal: true in .ok/local/config.yml (or OK_ALLOW_EXTERNAL=1) — the keys live in different files because consent is per-machine and never travels. allowExternal consents to exposure on a server with NO authentication — restrict access at the edge. Removing server.externalUrl does not lift this refusal (it fires on the header, not the URL) and would un-admit that Host/Origin everywhere else. Warned once per process; every refusal is still logged at warn level (HTTP refusals additionally as api.error, counted in ok.api.error.count).`))}const l5e=new WeakMap;function u5e(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:I$(n)?`loopback`:`external`,actor:void 0};return l5e.set(e,r),r}function d5e(e){return l5e.get(e)}const K$=q(`local-op-security`),f5e=Gj,p5e=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function q$(e){return!e||typeof e!=`string`||p5e.some(t=>t.test(e))?!1:f5e.some(t=>t.test(e))}function J$(e){return e===`~`?Us():e.startsWith(`~/`)?H(Us(),e.slice(2)):e}function m5e(e,t){let n=V(e);for(;n!==t&&n!==V(n);){let e;try{e=Ds(n)}catch(e){let t=DG(e);return K$.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return K$.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=V(n)}return!1}function h5e(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=Ps(t)}catch(e){let n=DG(e);return K$.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=W(J$(e)),i=[],a=r;for(;;){let e=null;try{e=Ds(a)}catch(e){let t=DG(e);if(t!==`ENOENT`)return K$.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=Ps(a)}catch(n){let i=DG(n);if(e.isSymbolicLink())return K$.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(m5e(a,t))return K$.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;K$.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return K$.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:H(r,...i),s=U(n,o);return s===``||!s.startsWith(`..`)&&!hs(s)}let r=V(a);if(r===a)return!1;i.unshift(fs(a)),a=r}}function Y$(e){return h5e(e,Us())}function g5e(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function _5e(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&v5e(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function v5e(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function y5e(e,t,n){let r=n.policy??B$({});return!g5e(e)&&!V$(e.socket.remoteAddress,r)?(X(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):_5e(e,r)?!0:(X(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function b5e(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const x5e=new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256);function S5e(e){x5e.push(e)}const C5e=jc.cursor,w5e=jc.codex,T5e=jc[`claude-desktop`],E5e={app:null,signals_fired:[]};function D5e(e){if(!e)return{...E5e};let t=[],n=e.ua,r=e.referer,i=!!n&&C5e.test(n),a=!!r&&r.includes(`?strategy=C_iframe`);if(i&&t.push(`cursor_ua_regex`),a&&t.push(`cursor_referer_strategy_iframe`),i||a)return{app:`cursor`,signals_fired:t};let o=!!n&&w5e.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&T5e.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...E5e}}const O5e=new Set([`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/agent-write-batch`,`/api/comments`,`/api/comment`,`/api/client-logs`,`/api/frontmatter-patch`,`/api/save-version`,`/api/rollback`,`/api/lint/fix`,`/api/folder-config`,`/api/template`,`/api/agent-integrations/apply`]);function X$(e,t={}){let{dynamic:n}=t,r=new Set(t.mutating??[]),i=t.mutatingPrefixes??[],a=Object.keys(e);if(n!==void 0&&!n.prefix.endsWith(`/`))throw Error(`dynamic.prefix '${n.prefix}' must end in '/' — a bare prefix mounts a wildcard that also swallows unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);for(let e of i){if(!e.endsWith(`/`))throw Error(`mutatingPrefixes entry '${e}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);if(e!==n?.prefix&&!a.some(t=>t.startsWith(e)))throw Error(`mutatingPrefixes entry '${e}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`)}let o=new Map(Object.entries(e)),s={resolve(e){let t=o.get(e);return t?{template:e,dispatch:(e,n)=>t(e,n)}:n!==void 0&&e.startsWith(n.prefix)?{template:n.template,dispatch:n.dispatch(e.slice(n.prefix.length))}:null},isMutating:e=>r.has(e)||i.some(t=>e.startsWith(t))};return{paths:n===void 0?a:[...a.filter(e=>!e.startsWith(n.prefix)),`${n.prefix}*`],table:s}}let Z$=null;BH(()=>{Z$=null});function k5e(){return Z$||=UH().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),Z$}function A5e(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??B$({}),a=e=>H$(e,i);return async(o,s)=>{let c=o.url?.split(`?`)[0];if(!c)return!1;let l=r.resolve(c);if(!l)return!1;let u=e=>{let t=o.headers[e];if(t!==void 0)return Array.isArray(t)?t.join(`, `):t};S5e({ts:Date.now(),url:c,method:o.method??``,ua:u(`user-agent`),origin:u(`origin`),referer:u(`referer`),host:u(`host`),remote:o.socket?.remoteAddress,secChUa:u(`sec-ch-ua`),secChUaMobile:u(`sec-ch-ua-mobile`),secChUaPlatform:u(`sec-ch-ua-platform`),secFetchSite:u(`sec-fetch-site`),secFetchDest:u(`sec-fetch-dest`),secFetchMode:u(`sec-fetch-mode`),secFetchUser:u(`sec-fetch-user`)});let d=o.method??`GET`,f=l.template,p=c.startsWith(`/api/`)?BQe(o):void 0;if(u5e(o,{requestId:p}),p!==void 0&&(VQe(o,p),typeof s.setHeader==`function`&&s.setHeader(Xq,p),typeof s.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:p,method:d,route:f,status:s.statusCode,durationMs:Date.now()-e,...s.writableFinished?{}:{aborted:!0}},`${d} ${f} ${s.statusCode}`))};s.once(`finish`,r),s.once(`close`,r)}if(c.startsWith(`/api/`)){typeof s.setHeader==`function`&&s.setHeader(`Cache-Control`,`no-store`);let e=o.headers.origin,t=s5e(e,d,i);if(!t.admitted)return X(s,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`,detail:t.detail}),!0;if(typeof s.setHeader==`function`&&(e!==void 0&&s.setHeader(`Vary`,`Origin`),t.corsGrant&&(e!==void 0&&s.setHeader(`Access-Control-Allow-Origin`,e),s.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${Xq}, ${yc.protocol}, ${yc.runtime}, ${yc.kind}`),s.setHeader(`Access-Control-Expose-Headers`,Xq))),o.method===`OPTIONS`)return s.writeHead(204),s.end(),!0}if(r.isMutating(c)){if(n&&l.dispatch!==void 0&&(d===`POST`||d===`PUT`||d===`DELETE`)&&!O5e.has(c))return X(s,403,`urn:ok:error:single-file-mode`,`Single-file previews cannot manage project files.`,{handler:`api-preview-content-scope`}),!0;let e=o.socket?.remoteAddress;if(e!==void 0&&!V$(e,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:z$}),!0}if(c.startsWith(`/api/`)){let e=n?`api-ephemeral-gate`:`api-read-gate`,t=o.socket?.remoteAddress;if(t!==void 0&&!V$(t,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:e}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:e,detail:z$}),!0}if(!c.startsWith(`/api/`))return!1;let m=po.extract(co.active(),o.headers),h=HH(),g=Date.now();return await co.with(m,()=>h.startActiveSpan(`HTTP ${d} ${f}`,{kind:Oie.SERVER,attributes:{[rb]:d,[ab]:f,[lb]:c,[ub]:`http`,[db]:o.headers[`user-agent`]??``,"ok.request.id":p}},async t=>{try{let n=l.dispatch;n===void 0?X(s,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${d} ${c}`}):r.isMutating(c)&&e.dispatchMutation!==void 0?await e.dispatchMutation(()=>n(o,s),c):await n(o,s);let i=s.statusCode;t.setAttribute(ib,i),i>=500&&t.setStatus({code:mo.ERROR,message:`status ${i}`})}catch(e){throw t.recordException(e),t.setStatus({code:mo.ERROR,message:e instanceof Error?e.message:String(e)}),!s.headersSent&&!s.writableEnded&&!s.destroyed&&X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:f,cause:e}),t.setAttribute(ib,s.statusCode),e}finally{t.end();let e=(Date.now()-g)/1e3;k5e().record(e,{[rb]:d,[ab]:f,[ib]:s.statusCode})}})),!0}}function Q$(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof ea||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;X(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function j5e(e){return $$(e,{maxBytes:1048576,timeoutMs:3e4})}function M5e(e){let t=e?.split(`;`,1)[0]?.trim().toLowerCase();return t===void 0?!1:t===`application/json`||/^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(t)}function N5e(e){return e.headers[`transfer-encoding`]!==void 0||Number(e.headers[`content-length`]??0)>0}async function $$(e,t){if(N5e(e)&&!M5e(e.headers[`content-type`]))throw new e1;let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new r1(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new n1(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var e1=class extends Error{constructor(){super(`Request body is not labeled as JSON`),this.name=`UnsupportedMediaTypeError`}};function t1(e,t){X(e,415,`urn:ok:error:unsupported-media-type`,`Request body must be JSON.`,{handler:t,detail:`Send the request body as JSON with the header Content-Type: application/json.`})}var n1=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${P5e(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},r1=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function P5e(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function i1(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return X(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:a}),{ok:!1}}function Z(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=i1(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await j5e(r)}catch(e){if(e instanceof e1){t1(i,n.handler);return}if(e instanceof n1){X(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof r1){X(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}X(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=i1(e,o,i,n);s.ok&&await t(r,i,s.value)}}const a1=()=>q(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){a1().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),tJ().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){a1().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){a1().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function F5e(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return X$({"/api/agent-integrations/apply":Z(kte,Q$(async(e,n,s)=>{let c=F$(s,r);if(c.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`agent-integrations-apply`});return}let l=g5e(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await q8e(s.intents,{execute:o?.execute,env:l,snapshot:()=>E$({env:l,resolve:o?.probe}),decisionHome:i??Us(),...o?.userSkillPresentAnywhere===void 0?{}:{userSkillPresentAnywhere:o.userSkillPresentAnywhere},projectDir:a});t.info({actor:c.kind,applied:u.actions.length,failed:u.actions.filter(e=>e.errorId!==void 0).length,conflicts:u.conflicts.map(e=>e.kind)},`[agent-integrations] batch applied`),Q(n,200,Are,{...u,snapshot:d},{handler:`agent-integrations-apply`})},{handler:`agent-integrations-apply`,title:`Failed to apply AI tool connections.`}),{handler:`agent-integrations-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`agent-integrations-apply`})})},{mutating:[`/api/agent-integrations/apply`]})}let I5e=0;const L5e=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function o1(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++I5e,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},L5e)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),zXe(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}let s1=new Map;function c1(e,t,n,r,i,a,o,s){let c=s1.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},s1.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function R5e(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of s1){for(let e of t)n.docs.delete(e);n.docs.size===0&&s1.delete(e)}}function z5e(){let e=s1;return s1=new Map,e}function B5e(e){for(let[t,n]of e){let e=s1.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},s1.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function V5e(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1051
1051
|
`)}function H5e(e,t){let n=s1.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},s1.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries]),t.previousPaths.length>0&&(n.previousPaths=[...t.previousPaths,...n.previousPaths])}function l1(){return s1.size}function U5e(e){return s1.has(e)}const u1={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function d1(e,t,n,r,i,a,o){ZH(e,t,`file-watcher`,n&&r?{resolveEmbed:n,resolveSize:i,sourcePath:r}:void 0,o,a)}const W5e=q(`external-change-attribution`),f1=new Map;function G5e(e){for(let[t,n]of f1)n.expiresAtMs<=e&&f1.delete(t)}function K5e(e,t,n=Date.now(),r=3e4){if(G5e(n),f1.size>=256&&!f1.has(e)){let e=f1.keys().next();e.done||f1.delete(e.value)}f1.set(e,{...t,expiresAtMs:n+r})}function q5e(e,t=Date.now()){let n=f1.get(e);if(!n)return;if(f1.delete(e),n.expiresAtMs<=t){W5e.debug({docName:e},`external-change claim expired before its write arrived`);return}let{expiresAtMs:r,...i}=n;return i}function J5e(e){f1.delete(e)}function Y5e(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`;return e instanceof ea?e.toLog({verbose:t}):e instanceof Ci?hne(e.violation,{verbose:t}):e instanceof Error?e.message:String(e)}function p1(e,t,n,r,i,a,o,s){if(pG(n)||mG(n)||gG(n)||_G(n)||vG(n))return;let c=t.documents.get(n);if(!c)return;let l=c.getText(`source`).toString(),u=l===r,d=Nr(l).frontmatter,{frontmatter:f}=Nr(r),p=o&&ZW(u1.context.origin)?{report:e=>o(n,e,RW.id,`file-watcher-intake`),baselineFullMd:l}:void 0;try{c.transact(()=>{d1(c,r,i,n,a,p,s)},u1)}catch(t){try{e.setReconciledBase(n,c.getText(`source`).toString())}catch(e){q(`reconcile`).error({err:e,originalError:Y5e(t),docName:n},`Unable to persist the reconciled base after an external-change failure`)}throw t}if(d!==f&&cZ(`file-watcher`),!u){let e=q5e(n)??{writerId:RW.id,displayName:RW.name,colorSeed:RW.id};c1(n,e.writerId,e.displayName,e.colorSeed,pS(n))}e.setReconciledBase(n,r)}function X5e(e,t,n,r,i){return async(a,o)=>{try{p1(e,t,a,o,n,r,i),q(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof Ci||e instanceof ea)throw e;SXe(),q(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const m1=`stale-external-write`;function h1(e,t,n,r){let i=e.getStaleExternalWrite(n)?.retainedContent;if(i!==void 0&&i!==e.getReconciledBase(n))return;e.clearStaleExternalWrite(n),r?.dissolveReconcile(n,m1);let a=t?.getMap(`lifecycle`);a?.get(`reason`)===m1&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`))}function Z5e(e){switch(e){case`conflict-markers`:return`refused-conflict-markers`;case`no-base`:return`refused-no-base`;case`too-large`:return`refused-too-large`;default:throw Error(`unhandled reconcile refusal reason: ${String(e)}`)}}function g1(e,t,n,r,i,a){let o=e.getReconciledBase(n),s=e.getStaleExternalWrite(n),c=(r,a)=>{let s=e.recordStaleExternalWrite(n,r,a);i&&i.raise({kind:`reconcile`,file:i.fileOf(n),reason:m1,detectedAt:s.detectedAt,stages:{base:o??r,ours:s.retainedContent??(t===void 0?o??r:v1(t)),theirs:s.diskContent}})};return s?.retainedContent!==void 0&&s.retainedContent!==o?(c(r,a??s.retainedContent),!0):o===r?(h1(e,t,n,i),!1):e.staleExternalWriteMatches(n,r)?(c(r,a??s?.retainedContent),!0):e.isDisplacedVersion(n,r)?(q(`reconcile`).warn({docName:n,diskBytes:r.length},`[reconcile] refused stale external write for ${n}; disk restores a version this server already displaced`),c(r,a),!0):(h1(e,t,n,i),!1)}const _1={reconciled:!1,baseBytes:0,diskBytes:0};function v1(e){let t=e.getText(`source`).toString(),{frontmatter:n,body:r}=Nr(t);return mt(n,r)}function y1(e,t,n,r,i,a,o){if(pG(n)||mG(n)||gG(n)||_G(n)||vG(n))return _1;let s=t.documents.get(n);if(s&&rZ(s)&&s.getMap(`lifecycle`).get(`reason`)!==m1)return _1;let c=e.getReconciledBase(n);if(c===void 0)return _1;let l,u;try{if(l=zG(n,r),!G(l))return _1;u=Ps(l)}catch{return _1}if(xq(l,u,r))return q(`reconcile`).warn({docName:n,canonical:u,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),_1;let d;try{d=K(u,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&q(`reconcile`).warn({docName:n,canonical:u,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),_1}let f=Re(d);if(d===c)return h1(e,s,n,o),_1;let p=e.inFlightFlushCount(n);if(p>0){if(e.hasInFlightFlush(n,f))return CXe(),q(`reconcile`).debug({docName:n,diskBytes:d.length,pendingFlushes:p},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),_1;wXe(),q(`reconcile`).warn({docName:n,diskBytes:d.length,pendingFlushes:p},`[reconcile] disk matches none of ${p} in-flight flush snapshot(s) for ${n}; falling through to merge`)}if(!s||g1(e,s,n,d,o)||f===Re(c))return _1;let m=v1(s),h=DJ({docName:n,base:c,ours:m,theirs:d});switch(q(`reconcile`).info({docName:n,result:h.kind,baseBytes:c.length,diskBytes:d.length},`[reconcile] before-agent-write ${n} result=${h.kind}`),h.kind){case`noop`:return _1;case`conflicts`:case`refused`:return o.raise({kind:`reconcile`,file:o.fileOf(n),reason:h.kind===`conflicts`?`merged-with-markers`:Z5e(h.reason),stages:{base:c,ours:m,theirs:d}}),_1;case`clean`:case`merged`:{let r=h.kind===`clean`?d:h.newContent;return h.kind===`merged`&&h.dedupSkipped&&(JU(),q(`reconcile`).warn({docName:n},`[reconcile] ${n} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`)),p1(e,t,n,r,i,void 0,a),h.kind===`merged`&&e.setReconciledBase(n,d),{reconciled:!0,baseBytes:Buffer.byteLength(c,`utf8`),diskBytes:Buffer.byteLength(d,`utf8`),mergeOutcome:h.kind}}}}const b1=q(`mermaid-validator`);let Q5e=null;function $5e(e){let t=[],n=e.split(`
|
|
1052
1052
|
`),r=e=>e.endsWith(`\r`)?e.slice(0,-1):e,i=0;for(;i<n.length;){let e=r(n[i]??``),a=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!a){i++;continue}let o=a[1]??``,s=o[0]??"`";if(s==="`"&&e.slice(e.indexOf(o)+o.length).includes("`")){i++;continue}let c=a[2]??``,l=RegExp(`^ {0,3}\\${s}{${o.length},}[ \t]*$`),u=[],d=i+1;for(;d<n.length&&!l.test(r(n[d]??``));)u.push(n[d]??``),d++;if(c===`mermaid`){let e=u.join(`
|
|
1053
1053
|
`),n=(u.find(e=>e.trim().length>0)?.trim()??``).slice(0,200);t.push({firstLine:n,body:e})}i=d+1}return t}async function e7e(){let{Window:e}=await import(`./lib-CLRUBb2o.mjs`),t=new e({url:`http://localhost/`}),n={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},r=new Map;try{for(let[e,t]of Object.entries(n))r.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-NW5-Y1wO.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
|
|
@@ -1114,7 +1114,7 @@ ${wW.join(`
|
|
|
1114
1114
|
`).replaceAll(`\r`,`
|
|
1115
1115
|
`).split(`
|
|
1116
1116
|
`))n(i)||mot(hot(i,r).replace(/`[^`]*`/g,``),t);return[...t.values()]}function _ot(e){let t=cot(e.href);if(!t||sot(t))return null;let n=Wa(t,e.fromDocName,{literal:e.literal});if(!n)return null;let r=ms(n).slice(1).toLowerCase();if(!cr.has(r))return null;let i=W(e.contentDir,n),a,o;try{if(a=gs(Ps(i)),!BG(a,e.contentDir))return null;o=Rs(a)}catch(t){let n=pot(t);return n!==`ENOENT`&&n!==`ENOTDIR`&&aot.warn({href:e.href,err:t},`unexpected error resolving asset`),null}return o.isFile()?{absolutePath:a,relativePath:vot(e.contentDir,a),stat:o}:null}function vot(e,t){let n=gs(Ps(e));return gs(t).slice(n.length+ +!n.endsWith(vs)).split(vs).join(`/`)}function yot(e){let t;try{t=gs(Ps(e.contentDir))}catch(e){return aot.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 got(a)){let a=_ot({contentDir:t,fromDocName:r,href:i.href,literal:i.literal});if(!a||e.isExcluded?.(a.relativePath))continue;let o=fot(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:ms(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 bot(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}function xot(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:x,onReferencedAssetsCacheInvalidator:S}=e,C=new Map,w=null;function T(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1117
|
-
`)}function E(){w=null}S?.(E);function D(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 O=Z(yr,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=lG(a(s));if(pG(c)||mG(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,Gre,{docName:c,content:u.getText(`source`).toString(),lifecycle:D(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,Gre,{docName:c,content:t,lifecycle:D(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}),k=Z(yr,async(e,t)=>{try{f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});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&&bot(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-cache`});let n=rJ(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=C.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;C.set(e,c),a.finally(()=>{C.get(e)===c&&C.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(),C.get(e)===a&&C.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,di,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}let c=l(),S=[...y()],E=b?.()??new Map,D=x?.()??new Map,O=[];for(let[e,t]of E)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=T(c),t=u?.();(!w||w.signature!==e||w.generation!==t||w.assets.some(e=>p?.isPathIgnored(e.path)))&&(w={signature:e,generation:t,assets:yot({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=w?.assets??[]}catch(e){w=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 S){if(t.kind===`markdown`){let n=sG(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 UY(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 UY(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=E.get(n),a=t?WY(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 E)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:WY(r,t.canonicalPath,e)})});for(let[e,t]of S){let{resolved:i,members:a}=UY(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:sG(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,di,{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}),A=Z(yr,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,$ne,{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}),j={"/api/document":O,"/api/documents":k,"/api/pages":Z(yr,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=sG(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=MY(i,t),o=PY(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,wre,{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":A};return{paths:Object.keys(j),table:{resolve(e){let t=j[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:E}}const Sot=[`date`,`user`],Cot=/\{\{([^{}\n]+?)\}\}/g;function wot(e){let t=[];for(let n of e.matchAll(Cot)){let e=(n[1]??``).trim();Eot(e)||t.push({token:e,offset:n.index??0})}return t}function Tot(e,t){return e.replace(Cot,(e,n)=>{let r=n.trim();return Eot(r)?t[r]:e})}function Eot(e){return Sot.includes(e)}function Dot(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}function D3(e,t,n={}){let r=Aot(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;k3(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)k3(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&k3(e,``,`inherited`,a,o,s),o}async function Oot(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++>=O3){a=!0,q(`templates`).warn({projectDir:e,cap:O3,queueDepth:o.length},`project scan hit the ${O3}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}k3(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Qs(s,{withFileTypes:!0})}catch(e){if(DG(e)!==`ENOENT`&&!A3.has(s)){A3.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(kot.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await tc(n)).isDirectory()}catch(e){if(DG(e)!==`ENOENT`&&!A3.has(n)){A3.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?_s.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const O3=2e3,kot=new Set([`node_modules`,`dist`,`build`]);function k3(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(Cq(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),A3.has(o)||(A3.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=Ds(s)}catch(e){let n=DG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!A3.has(s)){A3.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`}),A3.has(s)||(A3.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=Ns(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=Rs(c)}catch{continue}if(!l.isFile())continue;try{Sq(c,s),Sq(c,e)}catch(e){if(e instanceof _q){A3.has(c)||(A3.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(DG(e)!==`ENOENT`&&!A3.has(c)){A3.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=jot(c),d={name:o,path:t?_s.join(t,`.ok`,`templates`,a):_s.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 Aot(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const A3=new Set;function jot(e){let t;try{t=K(e,`utf-8`)}catch(t){if(DG(t)!==`ENOENT`&&!A3.has(e)){A3.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}=Pr(t);typeof n.title!=`string`&&!A3.has(e)&&(A3.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 j3=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const M3=q(`file-ops`);function Mot(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)pG(r)||mG(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;vU(V(n),{recursive:!0});try{gU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(Oq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),XY(n,BY(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`}:(vU(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=Rs(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(RG(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`?xU(s):(wU(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)&&Rs(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=Rs(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(RG(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=ms(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(pG(n)||mG(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{vU(s,{recursive:!0}),gU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(Oq(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{TU(s)}catch(e){let t=DG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&M3.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{oG(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),XY(r,BY(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{wU(r,{force:!0})}catch(e){M3.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw fG(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{bU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(Oq(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=ms(n.fullPath);oG(tG(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),XY(n.fullPath,BY(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){M3.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&&fG(tG(t.docName))}e.removeFolderIndexEntries(l);try{wU(u,{recursive:!0,force:!0})}catch(e){M3.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 N3=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function P3(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 Lte(e)}}function F3(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 I3(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 Lte(e)}}const L3=q(`upload-streaming`);var Not=class extends Oae{hash=oc(`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 Pot(e){return W(dJ(e),`tmp`)}function Fot(e){let t=Pot(e);return vU(t,{recursive:!0}),W(t,`upload-${sc()}`)}function Iot(e,t,n){let r=ms(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{SU(e,r);try{xU(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{xU(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new N3(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new N3(`urn:ok:error:storage-readonly`,t):new N3(`urn:ok:error:storage-error`,t)}}try{xU(e)}catch{}throw new N3(`urn:ok:error:collision-exhaustion`)}function Lot(e,{ageMs:t=864e5}={}){let n=Pot(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=Ns(n)}catch(e){return L3.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(Rs(t).mtimeMs>=a)continue;xU(t),r.deleted++}catch(e){L3.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&L3.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 Rot(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function zot(e){let t=DG(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 Bot(e,t){return new Promise((n,r)=>{let i;try{i=dtt(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new N3(`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{zs(e)}catch{}})}if(d?.destroy(),u)try{zs(u)}catch{}r(t instanceof N3?t:new N3(e,t))}},h=F3;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=Fot(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Not;d=Es(g),hc(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 Vot(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:w}=e,T=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof vq}return w4(Dq(n,W(t),r))};function E(e,t){if(!w(t))return;let n=W(e);if(QW(t)){let e=tG(t);for(let t of Ki){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${vs}`)||G(r)&&oG(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${vs}`)&&G(r)&&oG(e,ms(t));return}for(let e of Ki){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${vs}`))&&G(r)){oG(t,e);return}}}function D(e){if(ms(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=Ns(a,{withFileTypes:!0})}catch(t){let n=DG(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=>eG(e,cr));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let O=Z(xte,async(e,n,a)=>{try{let e=F$(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(!QW(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(Tq(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=tG(s);if(pG(d)||mG(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=Dq(u,c,r);if(w4(s)||w4(p)||ci(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(!/^[A-Za-z0-9_-]+$/.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=D3(c,t),i=r.find(e=>e.name===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=ht(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=Tot(l,{date:Dot(),user:u}),_=i.scope}let v=tG(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`:c1(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,Ite,{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`}),k=Z(kne,async(e,t,n)=>{try{if(F$(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(!w(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(w4(e)||T(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,Lre,{path:e},{handler:`create-folder`})}catch(e){if(Tq(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`}),A=Z(gie,async(e,n,r)=>{try{let e=F$(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`?tG(c):c;if(!w(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(w4(c)||T(c)||a===`file`&&(pG(u)||mG(u))||a===`folder`&&Rot(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&E(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`:bJ(n,new vJ({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)c1(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,ate,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof j3){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=zot(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(Tq(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`}),j=Z(Cte,async(e,n,o)=>{try{let e=F$(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(!w(u)||!w(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(pG(u)||pG(d)||mG(u)||mG(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(w4(u)||w4(d)||T(u)||T(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,Pi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&QW(u)&&QW(d)?`file`:l;if(f===`asset`){let t;try{t=QW(u)&&!QW(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof vJ){bJ(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,Pi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&E(t,u);let D=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of D){let t=s.findByDocName(e);if(t!==void 0){bJ(n,new vJ({file:t.file}),`rename-path`,t);return}}if(a){let e=QW(u)?ms(u):sG(u);if(f===`file`?a.isExcluded(QW(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 vJ){bJ(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof pY){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,Pi,{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:hS(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,Pi,{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`}),M=Z(Ine,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!w(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?D(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`&&QW(o)?`file`:e;if(c===`file`&&E(t,o),w4(o)||T(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`}):bJ(n,new vJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Yte,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(Tq(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`}),N=Z(Ze,async(e,n,r)=>WH(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":oU(r.path),"ok.cleanup.path.role":sU(r.path)}},async()=>{try{if(F$(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(!w(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&QW(a)?`file`:e,s=tG(a);o===`file`&&E(t,a);let c=o===`folder`&&Rot(a);if(o===`file`&&(pG(s)||mG(s))||c||w4(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,Bt,{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 P(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 Bot(e,n??t)}catch(e){if(e instanceof N3){X(i,P3(e.reason),e.reason,I3(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{zs(s)}catch{}},h=i1(wte,{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!==`.`&&!w(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(w4(g)||b!==`.`&&T(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,Bre,{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,P3(x.reason),x.reason,I3(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:Qq(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:P3(x.reason),err:x.cause},`[upload] write failed`),X(i,P3(x.reason),x.reason,I3(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return X$({"/api/create-page":O,"/api/create-folder":k,"/api/duplicate-path":A,"/api/rename-path":j,"/api/delete-path":M,"/api/trash/cleanup":N,"/api/upload":P},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Hot(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||hs(e)}function R3(e,t){if(typeof e!=`string`||!hs(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:``}:Hot(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function z3(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const B3=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Uot=`Canonical ids: ${_n().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.`,V3=F().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Wot="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.",Got=F().length(40).regex(/^[0-9a-f]+$/i).describe(Wot),H3=F().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),U3=F().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),Kot=F().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),W3=I({value:F(),truncatedFrom:Qa().optional(),hint:F().optional()}).describe(`Normalized change-note summary, when one was recorded.`),G3=z(L(F(),R())),qot=L(F(),R()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Jot=z(oi).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. 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.'),Yot=$n.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 Xot(e,t){for(let n of Ki){let r=R3(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Zot={summary:W3.optional(),warnings:z(oo).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 — 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:Jot,brokenLinkSuppression:Yot,templateHint:z(I({name:F(),description:F().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 Qot(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 K3(e){let t=typeof e.detail==`string`?` (${e.detail})`:``;return`Error: ${typeof e.error==`string`?e.error:`request failed`}${t}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const $ot=F().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 q3(e){return{text:$ot,...e}}function J3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}const Y3="Error: Hocuspocus server is not running. Start it with `ok 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 est(e,t){return typeof e==`function`?await e(t):e}async function tst(e,t){return typeof e==`function`?await e(t):e}async function X3(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 tst(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 Z3(e,t,n,r){let i=await Q3(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:$(Y3,!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function Q3(e,t,n,r){let i=await X3(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 est(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function $3(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 e6(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=zee(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function t6(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 n6(e,t){return t?{url:e,local:t}:e}function r6(e){return e instanceof Error&&e.name===`TimeoutError`}function i6(e,t){let n=e instanceof Error?e.message:String(e);if(!r6(e))return`${Vne} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Dre} ${n}.${r}`}async function nst(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:i6(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=t6({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function a6(e,t){if(typeof e!=`string`){let n=await nst(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:i6(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(r6(e))return{ok:!1,httpStatus:n.status,error:i6(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{...t6(n,r),httpStatus:n.status}}async function o6(e,t,n){let r=await a6(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 s6(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 nst(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:i6(e)}}let o;try{o=await a.json()}catch(e){if(r6(e))return{ok:!1,error:i6(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 t6(a,o)}function c6(e,t,n){return s6(`POST`,e,t,n)}function l6(e,t,n){return s6(`PUT`,e,t,n)}function u6(e,t){return s6(`DELETE`,e,t)}function rst(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 d6(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[lre]};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 ist(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 f6=ist(`the server`);function ast(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 p6=ast(`the server`),m6="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",ost="`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.",sst=/^(?:source(?: family)?|validator) "/;function cst(e){let t=[],n=[];for(let r of e)(sst.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function h6(e,t,n=0){let r=t.filter(e=>!cie(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 lst(e,t,n,r){if(t===0&&n.some(cie))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 g6(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 _6(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 ust(e,t){let n=hst(e,t,`frontmatter.yml`);if(Cq(V(n)).kind===`symlink`)return y6(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=Cq(n);if(r.kind===`symlink`)return y6(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return y6(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{Sq(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return y6(Tq(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=mst(n);return i==null?{}:dst(i)}function dst(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 fst=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],v6=new Set;function y6(e,t,n){let r=`${e}:${t}`;v6.has(r)||(v6.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function pst(e){for(let t of fst)v6.delete(`${t}:${e}`)}function mst(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,Fc.parse)(t)}catch(t){return y6(`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:(pst(e),n)}function hst(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function gst(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function _st(e){try{return Rs(W(e,`.git`)).isDirectory()}catch{return!1}}function vst(e){return Vj({baseDir:W(e),timeout:{block:5e3}})}async function yst(e,t,n=5){if(!_st(e))return{commits:[],source:`git-absent`};let r=vst(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...qe([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1117
|
+
`)}function E(){w=null}S?.(E);function D(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 O=Z(yr,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=lG(a(s));if(pG(c)||mG(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,Gre,{docName:c,content:u.getText(`source`).toString(),lifecycle:D(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,Gre,{docName:c,content:t,lifecycle:D(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}),k=Z(yr,async(e,t)=>{try{f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});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&&bot(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=rJ(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=C.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;C.set(e,c),a.finally(()=>{C.get(e)===c&&C.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(),C.get(e)===a&&C.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,di,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}let c=l(),S=[...y()],E=b?.()??new Map,D=x?.()??new Map,O=[];for(let[e,t]of E)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=T(c),t=u?.();(!w||w.signature!==e||w.generation!==t||w.assets.some(e=>p?.isPathIgnored(e.path)))&&(w={signature:e,generation:t,assets:yot({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=w?.assets??[]}catch(e){w=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 S){if(t.kind===`markdown`){let n=sG(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 UY(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 UY(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=E.get(n),a=t?WY(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 E)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:WY(r,t.canonicalPath,e)})});for(let[e,t]of S){let{resolved:i,members:a}=UY(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:sG(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,di,{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}),A=Z(yr,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,$ne,{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}),j={"/api/document":O,"/api/documents":k,"/api/pages":Z(yr,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=sG(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=MY(i,t),o=PY(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,wre,{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":A};return{paths:Object.keys(j),table:{resolve(e){let t=j[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:E}}const Sot=[`date`,`user`],Cot=/\{\{([^{}\n]+?)\}\}/g;function wot(e){let t=[];for(let n of e.matchAll(Cot)){let e=(n[1]??``).trim();Eot(e)||t.push({token:e,offset:n.index??0})}return t}function Tot(e,t){return e.replace(Cot,(e,n)=>{let r=n.trim();return Eot(r)?t[r]:e})}function Eot(e){return Sot.includes(e)}function Dot(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}function D3(e,t,n={}){let r=Aot(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;k3(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)k3(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&k3(e,``,`inherited`,a,o,s),o}async function Oot(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++>=O3){a=!0,q(`templates`).warn({projectDir:e,cap:O3,queueDepth:o.length},`project scan hit the ${O3}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}k3(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Qs(s,{withFileTypes:!0})}catch(e){if(DG(e)!==`ENOENT`&&!A3.has(s)){A3.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(kot.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await tc(n)).isDirectory()}catch(e){if(DG(e)!==`ENOENT`&&!A3.has(n)){A3.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?_s.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const O3=2e3,kot=new Set([`node_modules`,`dist`,`build`]);function k3(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(Cq(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),A3.has(o)||(A3.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=Ds(s)}catch(e){let n=DG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!A3.has(s)){A3.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`}),A3.has(s)||(A3.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=Ns(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=Rs(c)}catch{continue}if(!l.isFile())continue;try{Sq(c,s),Sq(c,e)}catch(e){if(e instanceof _q){A3.has(c)||(A3.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(DG(e)!==`ENOENT`&&!A3.has(c)){A3.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=jot(c),d={name:o,path:t?_s.join(t,`.ok`,`templates`,a):_s.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 Aot(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const A3=new Set;function jot(e){let t;try{t=K(e,`utf-8`)}catch(t){if(DG(t)!==`ENOENT`&&!A3.has(e)){A3.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}=Pr(t);typeof n.title!=`string`&&!A3.has(e)&&(A3.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 j3=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const M3=q(`file-ops`);function Mot(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)pG(r)||mG(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;vU(V(n),{recursive:!0});try{gU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(Oq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),XY(n,BY(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`}:(vU(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=Rs(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(RG(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`?xU(s):(wU(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)&&Rs(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=Rs(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(RG(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=ms(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(pG(n)||mG(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{vU(s,{recursive:!0}),gU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(Oq(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{TU(s)}catch(e){let t=DG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&M3.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{oG(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),XY(r,BY(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{wU(r,{force:!0})}catch(e){M3.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw fG(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{bU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(Oq(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=ms(n.fullPath);oG(tG(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),XY(n.fullPath,BY(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){M3.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&&fG(tG(t.docName))}e.removeFolderIndexEntries(l);try{wU(u,{recursive:!0,force:!0})}catch(e){M3.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 N3=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function P3(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 Lte(e)}}function F3(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 I3(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 Lte(e)}}const L3=q(`upload-streaming`);var Not=class extends Oae{hash=oc(`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 Pot(e){return W(dJ(e),`tmp`)}function Fot(e){let t=Pot(e);return vU(t,{recursive:!0}),W(t,`upload-${sc()}`)}function Iot(e,t,n){let r=ms(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{SU(e,r);try{xU(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{xU(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new N3(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new N3(`urn:ok:error:storage-readonly`,t):new N3(`urn:ok:error:storage-error`,t)}}try{xU(e)}catch{}throw new N3(`urn:ok:error:collision-exhaustion`)}function Lot(e,{ageMs:t=864e5}={}){let n=Pot(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=Ns(n)}catch(e){return L3.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(Rs(t).mtimeMs>=a)continue;xU(t),r.deleted++}catch(e){L3.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&L3.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 Rot(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function zot(e){let t=DG(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 Bot(e,t){return new Promise((n,r)=>{let i;try{i=dtt(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new N3(`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{zs(e)}catch{}})}if(d?.destroy(),u)try{zs(u)}catch{}r(t instanceof N3?t:new N3(e,t))}},h=F3;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=Fot(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Not;d=Es(g),hc(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 Vot(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:w}=e,T=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof vq}return w4(Dq(n,W(t),r))};function E(e,t){if(!w(t))return;let n=W(e);if(QW(t)){let e=tG(t);for(let t of Ki){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${vs}`)||G(r)&&oG(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${vs}`)&&G(r)&&oG(e,ms(t));return}for(let e of Ki){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${vs}`))&&G(r)){oG(t,e);return}}}function D(e){if(ms(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=Ns(a,{withFileTypes:!0})}catch(t){let n=DG(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=>eG(e,cr));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let O=Z(xte,async(e,n,a)=>{try{let e=F$(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(!QW(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(Tq(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=tG(s);if(pG(d)||mG(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=Dq(u,c,r);if(w4(s)||w4(p)||ci(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(!/^[A-Za-z0-9_-]+$/.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=D3(c,t),i=r.find(e=>e.name===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=ht(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=Tot(l,{date:Dot(),user:u}),_=i.scope}let v=tG(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`:c1(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,Ite,{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`}),k=Z(kne,async(e,t,n)=>{try{if(F$(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(!w(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(w4(e)||T(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,Lre,{path:e},{handler:`create-folder`})}catch(e){if(Tq(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`}),A=Z(gie,async(e,n,r)=>{try{let e=F$(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`?tG(c):c;if(!w(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(w4(c)||T(c)||a===`file`&&(pG(u)||mG(u))||a===`folder`&&Rot(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&E(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`:bJ(n,new vJ({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)c1(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,ate,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof j3){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=zot(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(Tq(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`}),j=Z(Cte,async(e,n,o)=>{try{let e=F$(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(!w(u)||!w(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(pG(u)||pG(d)||mG(u)||mG(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(w4(u)||w4(d)||T(u)||T(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,Pi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&QW(u)&&QW(d)?`file`:l;if(f===`asset`){let t;try{t=QW(u)&&!QW(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof vJ){bJ(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,Pi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&E(t,u);let D=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of D){let t=s.findByDocName(e);if(t!==void 0){bJ(n,new vJ({file:t.file}),`rename-path`,t);return}}if(a){let e=QW(u)?ms(u):sG(u);if(f===`file`?a.isExcluded(QW(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 vJ){bJ(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof pY){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,Pi,{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:hS(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,Pi,{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`}),M=Z(Ine,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!w(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?D(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`&&QW(o)?`file`:e;if(c===`file`&&E(t,o),w4(o)||T(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`}):bJ(n,new vJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Yte,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(Tq(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`}),N=Z(Ze,async(e,n,r)=>WH(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":oU(r.path),"ok.cleanup.path.role":sU(r.path)}},async()=>{try{if(F$(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(!w(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&QW(a)?`file`:e,s=tG(a);o===`file`&&E(t,a);let c=o===`folder`&&Rot(a);if(o===`file`&&(pG(s)||mG(s))||c||w4(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,Bt,{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 P(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 Bot(e,n??t)}catch(e){if(e instanceof N3){X(i,P3(e.reason),e.reason,I3(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{zs(s)}catch{}},h=i1(wte,{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!==`.`&&!w(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(w4(g)||b!==`.`&&T(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,Bre,{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,P3(x.reason),x.reason,I3(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:Qq(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:P3(x.reason),err:x.cause},`[upload] write failed`),X(i,P3(x.reason),x.reason,I3(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return X$({"/api/create-page":O,"/api/create-folder":k,"/api/duplicate-path":A,"/api/rename-path":j,"/api/delete-path":M,"/api/trash/cleanup":N,"/api/upload":P},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Hot(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||hs(e)}function R3(e,t){if(typeof e!=`string`||!hs(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:``}:Hot(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function z3(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const B3=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Uot=`Canonical ids: ${_n().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.`,V3=F().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Wot="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.",Got=F().length(40).regex(/^[0-9a-f]+$/i).describe(Wot),H3=F().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),U3=F().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),Kot=F().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),W3=I({value:F(),truncatedFrom:Qa().optional(),hint:F().optional()}).describe(`Normalized change-note summary, when one was recorded.`),G3=z(L(F(),R())),qot=L(F(),R()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Jot=z(oi).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. 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.'),Yot=$n.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 Xot(e,t){for(let n of Ki){let r=R3(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Zot={summary:W3.optional(),warnings:z(oo).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 — 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:Jot,brokenLinkSuppression:Yot,templateHint:z(I({name:F(),description:F().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 Qot(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 K3(e){let t=typeof e.detail==`string`?` (${e.detail})`:``;return`Error: ${typeof e.error==`string`?e.error:`request failed`}${t}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const $ot=F().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 q3(e){return{text:$ot,...e}}function J3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}const Y3="Error: Hocuspocus server is not running. Start it with `ok 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 est(e,t){return typeof e==`function`?await e(t):e}async function tst(e,t){return typeof e==`function`?await e(t):e}async function X3(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 tst(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 Z3(e,t,n,r){let i=await Q3(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:$(Y3,!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function Q3(e,t,n,r){let i=await X3(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 est(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function $3(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 e6(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=zee(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function t6(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 n6(e,t){return t?{url:e,local:t}:e}function r6(e){return e instanceof Error&&e.name===`TimeoutError`}function i6(e,t){let n=e instanceof Error?e.message:String(e);if(!r6(e))return`${Vne} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Dre} ${n}.${r}`}async function nst(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:i6(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=t6({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function a6(e,t){if(typeof e!=`string`){let n=await nst(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:i6(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(r6(e))return{ok:!1,httpStatus:n.status,error:i6(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{...t6(n,r),httpStatus:n.status}}async function o6(e,t,n){let r=await a6(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 s6(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 nst(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:i6(e)}}let o;try{o=await a.json()}catch(e){if(r6(e))return{ok:!1,error:i6(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 t6(a,o)}function c6(e,t,n){return s6(`POST`,e,t,n)}function l6(e,t,n){return s6(`PUT`,e,t,n)}function u6(e,t){return s6(`DELETE`,e,t)}function rst(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 d6(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[lre]};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 ist(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 f6=ist(`the server`);function ast(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 p6=ast(`the server`),m6="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",ost="`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.",sst=/^(?:source(?: family)?|validator) "/;function cst(e){let t=[],n=[];for(let r of e)(sst.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function h6(e,t,n=0){let r=t.filter(e=>!cie(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 lst(e,t,n,r){if(t===0&&n.some(cie))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 g6(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 _6(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 ust(e,t){let n=hst(e,t,`frontmatter.yml`);if(Cq(V(n)).kind===`symlink`)return y6(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=Cq(n);if(r.kind===`symlink`)return y6(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return y6(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{Sq(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return y6(Tq(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=mst(n);return i==null?{}:dst(i)}function dst(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 fst=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],v6=new Set;function y6(e,t,n){let r=`${e}:${t}`;v6.has(r)||(v6.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function pst(e){for(let t of fst)v6.delete(`${t}:${e}`)}function mst(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,Fc.parse)(t)}catch(t){return y6(`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:(pst(e),n)}function hst(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function gst(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function _st(e){try{return Rs(W(e,`.git`)).isDirectory()}catch{return!1}}function vst(e){return Vj({baseDir:W(e),timeout:{block:5e3}})}async function yst(e,t,n=5){if(!_st(e))return{commits:[],source:`git-absent`};let r=vst(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...qe([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1118
1118
|
`)){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 bst=5e3;async function xst(e){try{let t=(await Vj({baseDir:e,timeout:{block:bst}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Sst(e,t){return Vj({baseDir:t,timeout:{block:bst}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Cst(e,t){let n=oS(t);return e.startsWith(n)?e.slice(n.length):e}async function wst(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`,...qe([n]))}catch{return[]}let o=Cst(t,r),s=vS(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:dS(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function Tst(e,t,n,r,i){let a;try{a=await iU(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`,...qe([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=Xge(u),p=f?.writer_id??``,m=vS(p);i.add(d),s.push({hash:d,date:o,writerName:f?.display_name??c,message:l,contributors:dS(u),writerId:p,isAgent:m.isAgent,writerClassification:m.classification,branch:t})}return s}async function Est(e,t,n=5){let r=qge(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await xst(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Sst(r,W(e)),o=``;try{o=await a.raw(`for-each-ref`,oS(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
|
|
1119
1119
|
`).map(e=>e.trim()).filter(Boolean),c=(s.length===0?[]:await Promise.all(s.map(e=>wst(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 Tst(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 Dst=1e3,Ost=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),kst=/\.(md|mdx)$/i;function Ast(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 jst(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&&ya(e.appliesTo).matches(i)&&(a.includes(e.file)||a.push(e.file));return a}function Mst(e,t){return jst(e,t===``?`⁂`:`${t}/⁂`)}function b6(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const Nst=new Set;async function Pst(e){try{let t=await Zs(e,`utf-8`);return{frontmatter:ro(t)??{},firstHeading:NY(Nr(t).body)}}catch(t){if(t?.code!==`ENOENT`&&!Nst.has(e)){Nst.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 Fst(e,t){if(!e)return null;let n=await a6(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 Ist(e,t){if(!e)return null;let n=await a6(e,`/api/comments?doc=${encodeURIComponent(t)}`);return n.ok?Lst(n.threads):null}function Lst(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 Rst(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 a6(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 zst(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 Vst(await Promise.all(r.map(async t=>{let n=await a6(e,`/api/comment-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})))}async function Bst(e,t){if(!e)return null;let n=await a6(e,`/api/comment-counts?prefix=${encodeURIComponent(t)}`);return n.ok?Vst([n.counts??{}]):null}function Vst(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 Hst(e,t){if(!e)return null;let n=await a6(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 Ust(e,t){let n=e?.title;if(typeof n!=`string`)return t;let r=n.trim();return r===``?t:r}function Wst(e,t){let n=e??{};return{title:Ust(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 Gst(e,t,n={}){let r=R3(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=Pst(a),l=jst(t,i),u=l.length>0?{schemas_applicable:l}:{};if(!s){let e=await c,t=Wst(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,Fst(t.serverUrl,b6(i)).catch(()=>null),Hst(t.serverUrl,b6(i)).catch(()=>null),Est(t.projectDir,i,o).catch(()=>({commits:[],source:`shadow-repo`})),yst(t.projectDir,i,o).catch(()=>({commits:[],source:`git`})),Ist(t.serverUrl,b6(i)).catch(()=>null)]),_=Wst(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:Ast(f?.length??null,p?.length??null),commentCount:g?.length??null,comments:g,...u}}async function Kst(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>=Dst){n.truncated=!0;break}let a;try{a=await Qs(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=Dst){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Ost.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&kst.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await tc(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 qst(e,t,n={}){let r=R3(t.projectDir,e);if(!r.ok)throw Error(`enrichDirectory: ${r.reason}`);let i=r.rel,a=r.abs,o=await Kst(a,t.projectDir),s;if(o.mostRecent){let e=await Pst(o.mostRecent.absPath);s={path:o.mostRecent.relPath,title:Ust(e?.frontmatter,e?.firstHeading)??fs(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=ust(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=D3(t.projectDir,i,{onRefused:n.onTemplateRefused});u.length>0&&(c.templates_available=u);let d=Mst(t,i);d.length>0&&(c.schemas_applicable=d);let f=await Bst(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,Jst).map(([e,t])=>({docName:e,count:t}))}return c}const Jst=5;async function Yst(e,t,n){let r=await qst(e,n);if(t<=1)return r;let i=r.path,a=W(n.projectDir,i),o;try{o=await Qs(a,{withFileTypes:!0})}catch{return r}let s=[];for(let e of o){if(!e.isDirectory()||Xst.has(e.name)||e.name.startsWith(`.`))continue;let r=await Yst(i?`${i}/${e.name}`:e.name,t-1,n);s.push(r)}return s.length>0&&(r.subfolders=s),r}const Xst=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 x6(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(r!==void 0){if(Zst(r)){delete n[e];continue}n[e]=r}return n}function Zst(e){return qt(e)}function Qst(e){if(!hs(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+vs))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(Cq(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=$st(a),r=Object.keys(e.patch).length===0?{}:x6(n,e.patch);if(Object.keys(r).length===0)return G(a)?(zs(a),ect(i),{ok:!0,path:S6(t,a),action:`deleted`}):{ok:!0,path:S6(t,a),action:`noop`};Os(i,{recursive:!0});let o=(0,Fc.stringify)(r),s=AS(a);return Bs(s,o,`utf-8`),Fs(s,a),{ok:!0,path:S6(t,a),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${n||`.`}": ${e.message}`}}}}function $st(e){if(!G(e))return{};let t=K(e,`utf-8`),n=(0,Fc.parse)(t);return typeof n!=`object`||!n||Array.isArray(n)?{}:{...n}}function ect(e){if(!G(e))return;let t;try{t=Ns(e)}catch{return}if(t.length===0)try{Ls(e)}catch{}}function S6(e,t){return t.startsWith(e+vs)?t.slice(e.length+1).split(vs).join(`/`):t}const tct=jn;function C6(e){if(!tct.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=oct(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let n=sct(e.body);if(!n.ok)return{ok:!1,error:n.error};let r=cct(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=Ae(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 nct(e){let t=w6(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let n=C6({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}=T6(e.projectDir,t.folderRel,e.name);try{Os(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${E6(e.projectDir,a)}: ${t.message}`}}}let s=!G(o),c=AS(o);try{Bs(c,r,`utf-8`),Fs(c,o)}catch(t){try{zs(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${E6(e.projectDir,o)}: ${t.message}`}}}return{ok:!0,path:E6(e.projectDir,o),created:s,warnings:i}}function rct(e){let t=w6(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:n,okDir:r,filePath:i}=T6(e.projectDir,t.folderRel,e.name),a=G(i);if(a)try{zs(i)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${E6(e.projectDir,i)}: ${t.message}`}}}return{ok:!0,path:E6(e.projectDir,i),existed:a,cleanedEmpty:ict(n,r)}}function ict(e,t){let n=!1,r=!1;if(G(e)&&lct(e))try{Ls(e),n=!0}catch{}if(G(t)&&lct(t))try{Ls(t),r=!0}catch{}return{templatesDir:n,okDir:r}}async function act(e){let t=w6(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let n=w6(e.projectDir,e.toFolder,e.toName);if(!n.ok)return{ok:!1,error:n.error};let r=T6(e.projectDir,t.folderRel,e.fromName),i=T6(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 ${E6(e.projectDir,r.filePath)}.`}};if(G(i.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${E6(e.projectDir,i.filePath)}.`}};try{Os(i.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${E6(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=ict(r.templatesDir,r.okDir);return{ok:!0,fromPath:E6(e.projectDir,r.filePath),toPath:E6(e.projectDir,i.filePath),committed:a,cleanedEmpty:o}}function w6(e,t,n){if(!hs(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!tct.test(n))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(n)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};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+vs)&&i!==a?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${i}`}}:{ok:!0,folderRel:r}}function oct(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 sct(e){let t=wot(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 T6(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 E6(e,t){let n=t.startsWith(e+vs)?t.slice(e.length+1):t;return gs(n).split(vs).join(`/`)}function cct(e){let{frontmatter:t}=Nr(e);if(t===``)return{ok:!0};let n=qr(t);return RegExp(`^template:`,`m`).test(n)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${rie}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function lct(e){try{return Ns(e).length===0}catch{return!1}}const uct={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 dct(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,respondPersistenceFailure:x,respondDiskDivergence:S,respondStaleExternalWrite:C,registerWrittenDocInFileIndex:w,captureAndCloseDocuments:T,renameTrackedPathInGit:E,renamePathOnDisk:D,splitContentPath:O,mutateFileIndex:k}=e;function A(e,t,n=`template`){return!e||!jn.test(e)?(X(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function j(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}${vs}`))continue;let o=W(a,`.ok`),s=Cq(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=Cq(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 M(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 N(e,t){return iee(e,t)}let P=m2({GET:Z(yr,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 qst(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=Cq(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 Zs(o,`utf-8`),t=(0,Fc.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,fe,{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($re,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=F$(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=Qst({anchorDir:i.resolvedContentDir,folderRel:i.folderRel,patch:n.frontmatter});if(!r.ok){let{status:e,urn:n}=uct[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,see,{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 ee(e,t,n){let r=l.findByDocName(e);return r!==void 0&&(bJ(n,new vJ({file:r.file}),t,r),!0)}let te=Z(yr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!A(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=j(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(Cq(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{Sq(c,o)}catch(e){if(Tq(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 Zs(c,`utf-8`),f=Pr(d),p=f.identity,h=f.starterContent,g=U(o,c).split(/[\\/]/).filter(Boolean).join(`/`);Q(t,200,un,{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}),ne=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=F$(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(!A(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(Cq(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(ee(N(a.folderRel,i),`template-put`,t))return;let l=C6({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:M(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=N(a.folderRel,i),{agentId:p,agentName:g,colorSeed:T,clientName:E}=h(n),D=await o.getSession(f,p,{displayName:g,colorSeed:T,clientName:E});D.dc.document.transact(()=>{ZH(D.dc.document,l.content,`agent`)},D.origin);let O=await b(f);if(O?.kind===`failure`){x(t,O.failure,`template-put`);return}if(O?.kind===`divergence`){S(t,`template-put`);return}if(O?.kind===`stale-external-write`){C(t,`template-put`,f);return}w(f,l.content),v(e,_(`template`,a.folderRel,i),`${u?`template-create`:`template-edit`}: ${d}`),y(`template-put`),Q(t,200,sr,{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`}),re=Z(yr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!A(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(ee(N(i.folderRel,r),`template-delete`,t))return;await T([N(i.folderRel,r)],`deleted-upstream`);let o=rct({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(N(i.folderRel,r))),Q(t,200,lne,{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 X$({"/api/folder-config":P,"/api/template":m2({GET:te,PUT:ne,POST:Z(Be,async(e,t,r)=>{try{let e=F$(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(!A(r.fromName,t,`template-move`)||!A(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||ee(N(a.folderRel,r.fromName),`template-move`,t))return;await T([N(a.folderRel,r.fromName)],`renamed`);let l=await act({projectDir:a.resolvedContentDir,fromFolder:a.folderRel,fromName:r.fromName,toFolder:o.folderRel,toName:r.toName,relocate:async(e,t)=>{let r=await E(n,e,t);return r||D(e,t),r}});if(!l.ok){if(l.error.code===`TEMPLATE_NOT_FOUND`){let e=j(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:l.error.message});return}if(l.error.code===`TEMPLATE_EXISTS`){X(t,409,`urn:ok:error:doc-already-exists`,l.error.message,{handler:`template-move`,detail:l.error.code});return}let e=l.error.code===`WRITE_ERROR`||l.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:l.error.code,cause:Error(l.error.message)});return}u?.setDeleted(N(a.folderRel,r.fromName));let d=W(o.resolvedContentDir,l.toPath),f=Cq(d).kind===`symlink`;if(v(e,_(`template`,o.folderRel,r.toName),`template-rename: ${l.fromPath} -> ${l.toPath}`,[{from:l.fromPath,to:l.toPath}]),y(`template-move`),c?.(`files`),f){if(i.warn({path:d,folder:o.folderRel||`.`},`[template-move] moved template "${l.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 "${l.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,yt,{from:l.fromPath,to:l.toPath,committed:l.committed},{handler:`template-move`});return}let p=null;if(r.body!==void 0||r.frontmatter!==void 0){let e;if(typeof r.body==`string`)e=r.body;else try{e=ht(K(d,`utf-8`))}catch{e=null}if(e===null)p={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=nct({projectDir:o.resolvedContentDir,folder:o.folderRel,name:r.toName,body:e,frontmatter:M(r.frontmatter)});t.ok||(p=t.error)}}try{w(N(o.folderRel,r.toName),K(d,`utf-8`))}catch{}if(p){let e=p.code===`WRITE_ERROR`||p.code===`READ_FAILED`;X(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${l.toPath}", but updating its content failed.`,{handler:`template-move`,detail:p.code,cause:Error(p.message)});return}Q(t,200,yt,{from:l.fromPath,to:l.toPath,committed:l.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:re},{handler:`template`}),"/api/template/import":Z(xn,async(e,n,i)=>{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=F$(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 g=i.sourcePath;if(!d(g)){X(n,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let E=f(g);if(pG(E)||mG(E)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`template-import`});return}let D=p(t,`file`,E);if(!G(D)){X(n,404,`urn:ok:error:doc-not-found`,`Source document not found: ${E}.`,{handler:`template-import`});return}let j=a.documents.get(E);if(i.deleteSource){let e=l.findByDocName(E);if(e!==void 0){bJ(n,new vJ({file:e.file}),`template-import`,e);return}}let M=``;if(j)M=j.getText(`source`).toString();else{let e=await a.openDirectConnection(E);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}=O(g);P=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),P=P.replace(/^[-_]+|[-_]+$/g,``),P||=`imported-template`}if(!A(P,n,`template-import`))return;let te=m(i.targetFolder,n,`folder`,`template-import`,`ok-and-templates`);if(!te)return;let ne=W(te.resolvedContentDir,te.folderRel,`.ok`,`templates`,`${P}.md`);if(Cq(ne).kind===`symlink`){X(n,400,`urn:ok:error:symlink-refused`,`${te.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:te.folderRel||`.`});return}if(ee(N(te.folderRel,P),`template-import`,n))return;let{frontmatter:re,body:ie}=Nr(M),ae=qr(re),oe={};try{ae.trim()&&(oe=(0,Fc.parse)(ae))}catch{}let se=i.title||oe?.title||MY(M,P),ce=oe?.description||``,le=Array.isArray(oe?.tags)?oe.tags:[],ue={...oe};delete ue.template,delete ue.title;let de=``;Object.keys(ue).length>0&&(de=`${(0,Fc.stringify)(ue).trim()}\n`),de=de?`---\n${de}---\n${ie}`:ie;let fe=C6({name:P,body:de,frontmatter:{title:se,description:ce,tags:le}});if(!fe.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:fe.error.code,cause:Error(fe.error.message)});return}let pe=!G(ne),me=U(te.resolvedContentDir,ne).split(/[\\/]/).filter(Boolean).join(`/`),he=N(te.folderRel,P),{agentId:ge,agentName:_e,colorSeed:ve,clientName:ye}=h(i),be=await o.getSession(he,ge,{displayName:_e,colorSeed:ve,clientName:ye});be.dc.document.transact(()=>{ZH(be.dc.document,fe.content,`agent`)},be.origin);let xe=await b(he);if(xe?.kind===`failure`){x(n,xe.failure,`template-import`);return}if(xe?.kind===`divergence`){S(n,`template-import`);return}if(xe?.kind===`stale-external-write`){C(n,`template-import`,he);return}w(he,fe.content),v(e,_(`template`,te.folderRel,P),`template-import: ${me}`),i.deleteSource&&(await T([E],`deleted-upstream`),u&&u.setDeleted(E),xU(D),k?.({kind:`delete`,path:D,docName:E})),y(`template-import`),c?.(`files`),Q(n,200,Hn,{path:me,created:pe,warnings:fe.warnings},{handler:`template-import`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`})},{mutating:[`/api/folder-config`,`/api/template`,`/api/template/import`]})}function D6(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function fct(e,t){let{git:n}=jK(e,{credentialConfig:[]}),[r,i]=await Promise.allSettled([sYe(n,DU),AU(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 pct(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 mct(e,t,n,r){let{git:i}=jK(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=fct(e,t).catch(e=>(hct(e)||q(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${D6(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 O6=`git-branch-info`;function hct(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const k6=q(`git-checkout`),gct=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function _ct(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(gct);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=Ps(n)}catch{r=n}return{held:!0,path:r}}const A6=`git-checkout`,vct=Gt;async function yct(e,t,n){if(n.fastForward&&await bct(e,t,n.credentialConfig)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r,env:i}=jK(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:vct(e)?`branch-not-found`:`fetch-failed`}}let o;try{o=await cq(r,a?`refs/heads/${t}`:`refs/remotes/origin/${t}`)}catch(e){return k6.warn({branch:t,err:e},`action=checkout-failed branch=${t}`),{ok:!1,reason:`checkout-failed`}}let s=await fct(e,o);if(s.conflicts)return{ok:!1,reason:`dirty-conflict`,files:s.files};try{await dq(r,o,`checkout`,i)}catch(e){return e instanceof uq?(k6.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()}):(k6.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 k6.warn({branch:t,target:o,err:e},`action=checkout-hook-failed branch=${t} error=${D6(e)}`),{ok:!0};d&&await r.raw([`branch`,`-D`,t]).catch(e=>{k6.warn({branch:t,target:o,err:e},`action=checkout-cleanup-failed branch=${t}`)});let n=_ct(e);return n.held?(k6.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}):(k6.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${D6(e)}`),{ok:!1,reason:`checkout-failed`})}}async function bct(e,t,n){let{git:r}=jK(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 k6.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${D6(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 k6.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${D6(e)}`),`unavailable`}return await i(`refs/heads/${t}`)===a?`advanced`:`unavailable`}return s===a?`up-to-date`:`diverged`}const j6=q(`git-worktree-status`);function M6(e){return we.includes(e)?e:`M`}function xct(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:M6(a.x),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}),a.y!==` `&&a.y!==``&&r.push({path:a.path,code:M6(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 Sct=[`unknown revision or path not in the working tree`,`no upstream configured for branch`,`does not point to a branch`,`no such branch`];function Cct(e){let t=e instanceof Error?e.message:String(e??``);return Sct.some(e=>t.includes(e))}async function wct(e,t){let n;try{n=await MU(e,[`diff`,`--name-status`,`HEAD...@{upstream}`])}catch(e){return!t?.aborted&&!Cct(e)&&j6.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:M6(e.status.charAt(0)),syncScoped:!0,...e.status.charAt(0)===`R`||e.status.charAt(0)===`C`?{origPath:e.from}:{}}))}async function Tct(e,t,n,r={}){let i={readable:!0,branch:null,detached:!1,upstream:null,staged:[],notStaged:[],untracked:[],incoming:[],truncated:!1},{git:a}=jK(e,{credentialConfig:[],timeoutMs:r.timeoutMs??1e4,...r.abortSignal===void 0?{}:{abortSignal:r.abortSignal}}),o=Date.now(),[s,c,l,u]=await Promise.allSettled([jU(a,DU),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`HEAD`]),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`@{upstream}`]),wct(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||Cct(e.reason)||j6.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||j6.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=xct(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 Ect(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=wG(U(n,a));if(!o||o.startsWith(`..`))return;let s=tG(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 Tct(t??n,e?t=>e.isSyncScopedPath(t):()=>!1,l,{abortSignal:i.signal});if(r.writableEnded||r.destroyed)return;Q(r,200,une,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 X$({"/api/git/branch-info":Z(yr,async(e,n)=>{try{if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:O6});return}let r=EG(e),i=r.get(`branch`),a=r.get(`path`),o=r.get(`kind`)===`folder`?`folder`:`doc`;if(!Ft(i)){X(n,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:O6});return}if(!pct(a,o)){X(n,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:O6});return}let s=await mct(t,i,a,o);Q(n,200,ire,s,{handler:O6})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:O6,cause:e})}},{handler:O6,method:`GET`,skipBodyParse:!0}),"/api/git/worktree-status":u,"/api/git/checkout":Z(Zte,async(e,n,r)=>{if(F$(r,s).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:A6});return}if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:A6});return}try{let e=await c(),i=await AK(()=>yct(t,r.branch,{fastForward:r.fastForward===!0,credentialConfig:e}));Q(n,200,Ute,i,{handler:A6})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:A6,cause:e})}},{handler:A6,method:`POST`})},{mutating:[`/api/git/checkout`]})}function Dct(){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}}}const N6=q(`managed-artifact-persistence`);function P6(e){return e.homedirOverride??Us()}function Oct(e){let t=_i(e);return t===null||t.kind!==`skill`||t.scope!==`project`?null:{docKey:`${Ti}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}}function F6(e){if(!_i(e))return{managed:!1};let t=Oct(e);return t?{managed:!0,versioned:!0,docKey:t.docKey,filePath:`${t.docKey}/SKILL.md`}:{managed:!0,versioned:!1}}function kct(e){let t=P6(e);return uet(t).filter(e=>G(W(t,Mi(U(t,e).split(vs).join(`/`)))))}function Act(e){return G(`${e}.md`)?`${e}.md`:G(`${e}.mdx`)?`${e}.mdx`:`${e}.md`}function jct(e,t,n,r=null){if(!to.test(t)||t.length>64)throw Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(t)}`);if(r!==null&&(!to.test(r)||r.length>64))throw Error(`managedSkillBundleDir: invalid host qualifier: ${JSON.stringify(r)}`);let i=e===`global`?P6(n):n.projectDir;if(e!==`global`)return W(i,`.ok`,`skills`,t);if(r!==null){let e=E0(i,`global`).find(e=>e.editor===r);return e===void 0?null:W(i,e.root,t)}let a=N0(i,t),o=W(i,`.ok`,`skills`,t);if(a!==null)return a;if(G(W(o,`SKILL.md`)))return o;let s=k0(i,`global`);return s===null?null:W(i,s,t)}function Mct(e,t){let n=Va(e);if(n!==null){let e=x0(n.name,null);return e===null?null:V(e)}let r=_i(e);return r===null||r.kind!==`skill`?null:jct(r.scope,r.name,t,r.host)}function I6(e,t){let n=Va(e);if(n!==null){let t=x0(n.name,n.rel);if(t===null)throw Error(`managedArtifactAbsPath: external skill not registered: ${e}`);return n.rel===null?t:Act(t)}let r=_i(e);if(r===null||r.kind!==`skill`)throw Error(`managedArtifactAbsPath: not a managed skill doc name: ${e}`);let i=jct(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=Act(W(i,...t))}if(!a.startsWith(i+vs))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return a}function Nct(e,t){let n=W(e),r=P6(t),i=E0(r,`global`);for(let e of uet(r)){let t=W(e);if(!n.startsWith(t+vs))continue;let a=n.slice(t.length+1).split(vs),o=a[0];if(o&&to.test(o)&&o.length<=64&&a.length>=2){let e=W(t,o),n=N0(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`${ji}global/${o}${s}`;let l=c[c.length-1]??``;if(/\.mdx?$/i.test(l)&&!c.includes(`..`)){let e=c.join(`/`).replace(/\.mdx?$/i,``);return`${ji}global/${o}${s}/${e}`}}return null}return null}function Pct(e,t,n){let r=_i(t);if(r?.kind===`skill`&&r.scope===`project`||t.startsWith(`__template__/`))return;let i=Va(t);if(i&&x0(i.name,i.rel)===null||e.getXmlFragment(`default`).length>0)return;let a=I6(t,n);if(!G(a))return;let o;try{o=K(a,`utf-8`)}catch(e){N6.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}e.transact(()=>{d1(e,o,void 0,t),e.getMap(`lifecycle`).set(kc,crypto.randomUUID())},u1),n.setReconciledBase(t,o),n.lkgCache.set(t,o)}async function Fct(e,t,n){try{let r=e.replace(/[^A-Za-z0-9._-]+/g,`__`),i=W(DS(P6(n)),`edit-backups`,`discarded`,r);await hU(i,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,`-`);await MS(W(i,`${a}.md`),t,{fs:EU});let o=Ns(i).sort();for(let e of o.slice(0,Math.max(0,o.length-5)))try{xU(W(i,e))}catch{}}catch(t){N6.warn({documentName:e,err:t},`discarded-edit stash failed`)}}async function Ict(e,t,n){if(t.rel===null)try{if(!G(e))return;let r=W(DS(P6(n)),`edit-backups`,t.name),i=W(r,`SKILL.md.bak`);if(G(i))return;await hU(r,{recursive:!0}),await MS(i,K(e,`utf-8`),{fs:EU})}catch(e){N6.warn({name:t.name,err:e},`external-skill backup failed`)}}async function Lct(e,t,n,r){let i=_i(t);if(i?.kind===`skill`&&i.scope===`project`||t.startsWith(`__template__/`))return`no-op`;let a=Va(t);if(a&&x0(a.name,a.rel)===null||n===u1)return`no-op`;let o=e.getText(`source`).toString(),s=r.lkgCache.get(t);if(o===s)return`no-op`;let c=Mct(t,r);if(c===null)return`no-op`;if(!G(c))return N6.warn({documentName:t,containerDir:c},`store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it`),`no-op`;let l=I6(t,r);try{return await hU(W(l,`..`),{recursive:!0}),a&&await Ict(l,a,r),await PS(`${l}.lock`,async()=>{if(G(l)){let n=null;try{n=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&N6.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==s&&n!==o){hXe();let i=r.beforeReconcileDivergence?.(e,t,o,n);return await Fct(t,o,r),e.transact(()=>{d1(e,n,void 0,t,void 0,i)},u1),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`reconciled`}}return await MS(l,o,{fs:EU}),r.lkgCache.set(t,o),r.setReconciledBase(t,o),`persisted`})}catch(e){return e instanceof NS?(N6.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(N6.warn({documentName:t,err:e},`store: write failed`),`write-failed`)}}function Rct(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);return i!==void 0&&i===n?`no-op`:(e.transact(()=>{d1(e,n,void 0,t)},u1),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`applied`)}function zct(e){return e<=0?`0`:e===1?`1`:e<=5?`2-5`:e<=20?`6-20`:e<=50?`21-50`:`50+`}function Bct(e){return e<=0?`0`:e<=50?`1-50`:e<=200?`51-200`:e<=500?`201-500`:`500+`}let Vct=null,Hct=null;function Uct(){return Vct||=UH().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`}),Vct}function Wct(){return Hct||=UH().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.`}),Hct}function Gct(e){Uct().record(Math.max(0,e.durationMs),{width_bucket:zct(e.width),commits_bucket:Bct(e.commits),capped:e.capped,error:e.error??!1})}function Kct(e){Wct().add(1,{mode:e})}const L6=q(`timeline`);function qct(e,t){return Math.min(500,3*(Math.max(0,e)+Math.max(1,t)))}const R6=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,z6={entries:[],total:0,hasMore:!1},Jct=/^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;function Yct(e){return Jct.test(e)}function Xct(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function B6(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=Xct(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:dS(s),checkpoint:c===`checkpoint`?Pa(s):null,rawBody:s}}).filter(e=>e!==null&&e.sha.length===40):[]}function V6(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let Zct=null;function Qct(){return Zct||=UH().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),Zct}let $ct=null;function elt(){return $ct||=UH().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),$ct}function H6(e,t){return t.length===0||t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function tlt(e,t,n){return e.length===0||t.length===0?e:e.filter(e=>{let r=uS(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 nlt(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 A1(e,t.renameCommit,r,o);return n.length===0?new Set:M1(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 w7e(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 rlt(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 T7e(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 ilt(e,t,n=`.`,r){if(!G(e.workTree)||!G(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return z6;let i=t.branch??`main`,a=Math.max(1,t.limit??50),o=Math.max(0,t.offset??0),s=qct(o,a),c=performance.now(),l=!1,u=(e,t,n=!1)=>Gct({durationMs:performance.now()-c,width:e,commits:t,capped:l,error:n}),d=V6(t.type),f=V6(t.author),p=V6(t.excludeAuthor),m=t.includeAutoCheckpoints??!1,h=n===`.`?``:n.replace(/^\.\//,``),g=e=>h?`${h}/${e}${sG(e)}`:`${e}${sG(e)}`,_=e=>{let t=g(e),n=dG(t,e);return n?[t,n]:[t]},v=t.docName?F6(t.docName):{managed:!1};if(v.managed&&!v.versioned)return z6;let 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??D1(e.gitDir),{chain:c,skipped:h}=await WH(`rename.expandPredecessors`,void 0,async()=>t.docName?v7e(b,i,n):{chain:[],skipped:0}),v=c.length>1;t.docName&&Qct().record(c.length),h>0&&elt().add(h);let y=y7e(),S=k1(),C=OW(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(`
|
|
1120
1120
|
`).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(`
|