@inkeep/open-knowledge 0.88.3-beta.0 → 0.88.3-beta.2
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-Da5RhJ7X.mjs +1 -0
- package/dist/{dist-DZ47D2ZS.mjs → dist-C-GaD236.mjs} +1 -1
- package/dist/{dist-CqRTItlw.mjs → dist-RdM5Fw_L.mjs} +13 -13
- package/dist/index.mjs +3 -3
- package/dist/{init-DcojktK8.mjs → init-Cd6oP-kq.mjs} +2 -2
- package/dist/init-DhE5XRbh.mjs +1 -0
- package/dist/{launch-json-removal-CZJIrfQI.mjs → launch-json-removal-DRju3ap6.mjs} +1 -1
- package/dist/loader-BE58pU2K.mjs +1 -0
- package/dist/{loader-BiwGF8bz.mjs → loader-iDsMCsZZ.mjs} +1 -1
- package/dist/{open-browser-Bc67k1xM.mjs → open-browser-BdzTIyUA.mjs} +1 -1
- package/dist/{preview-B6_6Xw8I.mjs → preview-ByjB2wel.mjs} +1 -1
- package/dist/preview-Dn3TTgnr.mjs +1 -0
- package/dist/public/assets/{AccountSection-BN4Cw37c.js → AccountSection-Dc9XGWwh.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-DOQAQjfZ.js → ActivityModeContent-c8oBo3ki.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-Bl5CfmF_.js → AddPropertiesButton-RUwj1tJ-.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CtSQuPtF.js → AgentDiffPane-YKfNYHmm.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-D-TjxoWL.js → AgentThreadClientBinder-hJ0m3JAT.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-C8Kht0A-.js → AttachmentsSection-QbFytzkP.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-BzqkkbNX.js → CodeMirrorPropInput-D4MxcCFI.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-cZPJ290U.js → ContentRulesSection-C7vZnHQR.js} +1 -1
- package/dist/public/assets/{DocumentContext-DY2SpfLc.js → DocumentContext-CqvJqVjH.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-DDWiImgF.js → EditorModeToggle-Dqsv7TMp.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-CQfnUtWJ.js → ExcalidrawDocEditor-_P9P0Fpt.js} +1 -1
- package/dist/public/assets/FeedbackForm-1NIcUlbh.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-BRbHATtN.js → ImportSkillDialog-DxP0wxPs.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-CaVr6XOD.js → LinkPreviewsSection-ODBVPCUg.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-DaWYe45j.js → LintConfigEditor-C2Bo-l7H.js} +1 -1
- package/dist/public/assets/{LintingSection-D8iY3BeV.js → LintingSection-D30Wf3Mw.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-Ds7bk2Cg.js → ManagedArtifactProperties-CUijT2BA.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DzGV0HZd.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-D5p_P15E.js → MermaidDocEditor-DowGKXN1.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-CdPfWL-6.js → NetworkAccessSection-KjLozjO7.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-CGtf6FxV.js → PropertyDisplayRow-CnMuPR6s.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-C966LBq0.js → PublishToGitHubDialog-Cz8mNX6J.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-DV-OqSmg.js → SchemaConfigEditor-Dk4Oxl-I.js} +1 -1
- package/dist/public/assets/{SearchSection-B6rHqfp_.js → SearchSection-B7EiUwt_.js} +1 -1
- package/dist/public/assets/{SessionsHost-C80PQ9Ji.js → SessionsHost-Ct1Bd0RN.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-DpdBlukg.js → SettingsDialogBody-CqjtJ2Y_.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-bsQuI8F-.js → ShareReceiveMissDialog-BrvDDH3J.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-C7VMQV0g.js → SkillToolbarControls-COywdY4G.js} +1 -1
- package/dist/public/assets/{SourceEditor-3mT49S9c.js → SourceEditor-K04YB264.js} +1 -1
- package/dist/public/assets/{SpellingSettings-D30VvdF4.js → SpellingSettings-ojjyX__V.js} +1 -1
- package/dist/public/assets/{SyncSection--UJ18oO3.js → SyncSection-Ce0rWnNc.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-a4kNafeZ.js → SyncStatusBadge-BGntj5r3.js} +1 -1
- package/dist/public/assets/{TerminalSection-RYIum5Rn.js → TerminalSection-DuLbTdnw.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-HOVOYe31.js → TerminalWindowApp-BVslLfxF.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Bnv8NUnt.js → TextDocEditor-uDvCXPa5.js} +1 -1
- package/dist/public/assets/{ThemePluginSection-C-7r58fl.js → ThemePluginSection-DnaaY8Z2.js} +1 -1
- package/dist/public/assets/{ThreadView-B65BxjmT.js → ThreadView-CbAfcKP_.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-DFsTESmd.js → TimelineDiffPane-CF3XlUaV.js} +1 -1
- package/dist/public/assets/{client-version-BDuwu8nN.js → client-version-HuzEdqH8.js} +1 -1
- package/dist/public/assets/{comment-chips-CmVjOzx9.js → comment-chips-BPXFj1Ko.js} +1 -1
- package/dist/public/assets/{config-provider-B9LKWNeQ.js → config-provider-CNGnzKrZ.js} +1 -1
- package/dist/public/assets/config-schema-B392I0mu.js +1 -0
- package/dist/public/assets/{doc-undo-manager-g1jPjDAZ.js → doc-undo-manager-C2XaTOtO.js} +1 -1
- package/dist/public/assets/field-controls-BLuu0LLy.js +1 -0
- package/dist/public/assets/{field-controls-BQEIzg0e.js → field-controls-xmZJD7CS.js} +1 -1
- package/dist/public/assets/{globals-CUNJ93ve.css → globals-DybYFSHD.css} +1 -1
- package/dist/public/assets/{index-DZ5ANdd4.js → index-CQE6b1mI.js} +7 -7
- package/dist/public/assets/{lint-config-client-BrVeQOG-.js → lint-config-client-Cvaam883.js} +1 -1
- package/dist/public/assets/{lint-plugins-Dztmq1iU.js → lint-plugins-BPfYX7TD.js} +1 -1
- package/dist/public/assets/{markdown-lint-C8vEJEsc.js → markdown-lint-BwsN6kr-.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-Bobt53lD.js → markdownlint-rule-browser-COUuCPT4.js} +1 -1
- package/dist/public/assets/messages--wX-6jvz.js +1 -0
- package/dist/public/assets/messages-BWH6xaIt.js +1 -0
- package/dist/public/assets/messages-Bl6RVy5f.js +1 -0
- package/dist/public/assets/messages-C12CEVlb.js +1 -0
- package/dist/public/assets/messages-C72PW9gH.js +1 -0
- package/dist/public/assets/messages-DnkP1Emg.js +1 -0
- package/dist/public/assets/messages-DpgtXjLB.js +1 -0
- package/dist/public/assets/messages-F_TitmhP.js +1 -0
- package/dist/public/assets/messages-LMNA06Bk.js +1 -0
- package/dist/public/assets/messages-l6-R7kj0.js +1 -0
- package/dist/public/assets/messages-oVKfHfSb.js +1 -0
- package/dist/public/assets/messages-r7y_qPx0.js +1 -0
- package/dist/public/assets/messages-uuZvac8w.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-BG9-tW7s.js → pending-receive-nav-store-C9BFWQV8.js} +1 -1
- package/dist/public/assets/{preferred-session-events-CiOjVspY.js → preferred-session-events-ByImVALs.js} +1 -1
- package/dist/public/assets/{progress-HDmUIvkS.js → progress-nu-_nhl1.js} +1 -1
- package/dist/public/assets/{saved-themes-client-CqJpWEsN.js → saved-themes-client-BeMdeoNG.js} +1 -1
- package/dist/public/assets/{schema-section-DMJAJ2yT.js → schema-section-wsqWXSSM.js} +1 -1
- package/dist/public/assets/{selection-context-CXsG3XPe.js → selection-context-D8Lln530.js} +1 -1
- package/dist/public/assets/{sign-in-terminal-events-CuDNhwoI.js → sign-in-terminal-events-0j7V6VMs.js} +1 -1
- package/dist/public/assets/{src-Dx3dqWI2.js → src-CsC9h70J.js} +1 -1
- package/dist/public/assets/{telemetry-impl-Yh79UJVk.js → telemetry-impl-Dn_ybOMj.js} +1 -1
- package/dist/public/assets/{telemetry-startup-DCztiQrG.js → telemetry-startup-Cmks2qiX.js} +1 -1
- package/dist/public/assets/{thread-client-B0xaHedQ.js → thread-client-BTPcAbbi.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Cua3oA5j.js → typing-burst-detector-COsUk7Rh.js} +1 -1
- package/dist/public/assets/{uninstall-DkOvQ2C2.js → uninstall-gnyatfna.js} +1 -1
- package/dist/public/assets/{use-activity-panel-WNt6B2Wq.js → use-activity-panel-Df-mDMb-.js} +1 -1
- package/dist/public/assets/{use-apply-config-language-Ir0QsEhN.js → use-apply-config-language-GGKe-kOK.js} +2 -2
- package/dist/public/assets/{use-open-skill-g8pBIBzf.js → use-open-skill-UuIFDTF5.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-D1gCuuSr.js → use-terminal-enabled-DHq_Ocew.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-BjRr2sCn.js → use-timeline-entry-diff-a9ktdQim.js} +1 -1
- package/dist/public/index.html +26 -26
- package/dist/public/uninstall.html +5 -5
- package/dist/{registry-probes-BB52WJE5.mjs → registry-probes-pR3SIlM-.mjs} +1 -1
- package/dist/{removal-file-path-CGfVL-G_.mjs → removal-file-path-Be0A5MI3.mjs} +1 -1
- package/dist/{repair-launch-json-C6Z8Lt66.mjs → repair-launch-json-Dy7qtSP9.mjs} +1 -1
- package/dist/{repair-mcp-configs-Ho22omwW.mjs → repair-mcp-configs-CVrL4J2U.mjs} +1 -1
- package/dist/{src-DbQpB5ed.mjs → src-BNx_mFCJ.mjs} +1 -1
- package/dist/src-XNN_KSg-.mjs +1 -0
- package/dist/{start-DW9nXQC_.mjs → start-CKDlexiA.mjs} +3 -3
- package/dist/start-CNRONL5E.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-iKekN_P_.mjs +0 -1
- package/dist/init-D3X4bUI7.mjs +0 -1
- package/dist/loader-6aogCPbH.mjs +0 -1
- package/dist/preview-C8jLntfA.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DqvCDmlT.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-BtDc4gv6.js +0 -1
- package/dist/public/assets/config-schema-DJX8I1Ej.js +0 -1
- package/dist/public/assets/field-controls-UxpzH3V6.js +0 -1
- package/dist/public/assets/messages-3dJtj02e.js +0 -1
- package/dist/public/assets/messages-5bhssbPQ.js +0 -1
- package/dist/public/assets/messages-B2HQ5CjQ.js +0 -1
- package/dist/public/assets/messages-B5yKhGi7.js +0 -1
- package/dist/public/assets/messages-B6uzAK9y.js +0 -1
- package/dist/public/assets/messages-BYcsBE5B.js +0 -1
- package/dist/public/assets/messages-CBj3OWaO.js +0 -1
- package/dist/public/assets/messages-CZy4eoUg.js +0 -1
- package/dist/public/assets/messages-CoD5aflo.js +0 -1
- package/dist/public/assets/messages-D9XSrnti.js +0 -1
- package/dist/public/assets/messages-DVUICFLH.js +0 -1
- package/dist/public/assets/messages-Dy25Wk4T.js +0 -1
- package/dist/public/assets/messages-TJg6Q0gk.js +0 -1
- package/dist/src-BC52Vdpm.mjs +0 -1
- package/dist/start-B4pN-Gox.mjs +0 -1
- /package/dist/public/assets/{globals-BaU1-QGZ.js → globals-BImPEKZ5.js} +0 -0
|
@@ -920,7 +920,7 @@ ${e.terminator}`}function vqe(e){return`(${jV(e.body)})${AV(e.redirections)}`}fu
|
|
|
920
920
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
921
921
|
`)}return{content:i}}async handleFsWrite(e,t,n){this.touchTurnActivity(e);let r=await this.confinePath(t);if(r.docName!==null){if(this.opts.localApi===void 0)throw Error(`document writes are not available here: ${t}`);let i=await N3e(this.opts.localApi,{docName:r.docName,file:r.rel,markdown:n,agentId:e.agentSessionId,agentName:e.info.agent.name,clientName:e.info.agent.id});return this.setPresence(e,r.docName),i}if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:i,tracedWriteFile:a}=await Promise.resolve().then(()=>RU);return await i(V(r.abs),{recursive:!0}),await a(r.abs,n),{}}confinePath(e){return o8e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new xq(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&tYe(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>K6e){let t=e.events.length-K6e;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(Oq(e)){this.logSuppressedStatus(e,t,n,r);return}this.recordTerminalStatus(e,t,n,r)}logSuppressedStatus(e,t,n,r){(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:CW(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:CW(r.machineDetail)},Oq(e)?`[acp-threads] status suppressed after thread close`:`[acp-threads] status suppressed for a superseded launch`)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.launchTicket!==null&&e.launchTicket.initialPrompt!==null&&(t===`exited`||t===`error`||t===`auth_required`)&&(e.launchTicket.initialPrompt=null,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,status:t},`[acp-threads] pending first message dropped: the launch settled without starting a turn`)),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&&K3e(r.reason)&&Y3e(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 failLaunch(e,t,n,r){if(!Aq(e,t)){this.logSuppressedStatus(e,`error`,n,r);return}this.emitStatus(e,`error`,n,r),Aq(e,t)&&await this.teardownFailedAgent(e)}async teardownFailedAgent(e){e.sessionId=null,e.info.resumable=!1,e.info.contextWindow=null,await this.stopFailedAgent(e)}endRestart(e){let t=e.sessionBeforeRestart;return e.sessionBeforeRestart=null,t===null||e.sessionId!==null?!1:(Oq(e)&&(e.sessionId=t.sessionId,e.info.resumable=t.resumable,e.info.contextWindow=t.contextWindow),!0)}async stopFailedAgent(e){this.failPendingPermissions(e),this.failPendingConsents(e),e.lastInit=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,s=e.sessionId===null?e.sessionBeforeRestart:null;return{version:1,info:s===null?o:{...o,resumable:s.resumable},sessionId:e.sessionId??s?.sessionId??null,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=qn(e.info.agent.id),i=uo[r]??Re(e.agentSessionId);n.setPresence(OH(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 o8e(e,t,n){let r=await Nc(e),i=Ks(Gs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await Nc(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||Gs(s))throw Error(`path escapes the content directory: ${t}`);let c=s.split(Ys).join(`/`),l=/\.(md|mdx)$/.exec(c),u=l===null?bU(c)||xU(c)||SU(c)?c:null:c.slice(0,-l[0].length);return{abs:i,rel:c,docName:u!==null&&!_U(u)&&!vU(u)&&!n(c)?u:null}}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 s8e(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,sessionBeforeRestart:null,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,launchTicket:null,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 wq(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 c8e(e){let t=sq(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 l8e(e){let t=sq(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 u8e(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 Tq(e){return e instanceof Error?e.message:String(e)}function Eq(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return CW(JSON.stringify(t)).slice(0,300)}catch{return}}function d8e(e){return fq(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function Dq(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 f8e(e,t,n){return{reason:`connect`,agentMessage:e instanceof MW||e instanceof xq?e.message:String(e),machineDetail:Mq({primary:e instanceof MW?e.machineDetail:void 0,tail:n?await jq(t):void 0})}}function p8e(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 Oq(e){return e.closed||e.info.archived===!0}function kq(e,t=null){let n={initialPrompt:t};return e.launchTicket=n,n}function Aq(e,t){return e.launchTicket===t}async function jq(e){let t=e.stderrTail;await e.drainStderr?.();let n=CW(t.join(`
|
|
922
922
|
`)).slice(-16e3);return n===``?void 0:n}function Mq({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,SW);let n=Math.min(t.length,1024),r=SW-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=SW-i.length-1;return`${i}\n${t.slice(-a)}`}function Nq(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
923
|
-
`);return Mq({primary:Eq(e),tail:n})}function m8e(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function h8e(e,t){let n=eS(e?._meta),r=eS(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 g8e(e,t){let n=h8e(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 _8e(e,t,n,r){let i=t.toolCallId,a=e.reportedToolCalls.get(i);return a!==void 0||!e.browserInjected||!V0e(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 v8e(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(y8e(e,t,n));e.on(`message`,e=>{let s=Nwe(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 xq?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 xq)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 y8e(e,t,n){return{op:`error`,code:e,message:t,...n}}var b8e=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){kH(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){kH(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(Ve);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),x8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function x8e(e){return e?.awareness??null}var S8e=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!kH(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(!kH(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(!kH(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(!kH(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 i$e(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Ve);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),C8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function C8e(e){return e?.awareness??null}function w8e(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 Pq(e){return{probes:await Ar({env:e.env,resolve:w8e(e)}),detection:vo}}function Fq(e){let t=ka(e);return t.frontmatter===``?t:wa(ha(t.frontmatter)).map===null?{frontmatter:``,body:e}:t}function T8e(e,t,n,r){let{body:i}=ka(t);return r!==void 0&&r.rawContent===t?r.parsedJson:IU(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Xa.parseWithFallback(i,Iq(n)))}function Iq(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Lq(e){return Xa.serialize(yM(e,ja).toJSON())}function E8e(e,t,n,r,i,a){let o=Lq(r),s=Xa.serialize(n),{body:c}=ka(e.baselineFullMd),l=Xa.serialize(Xa.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:or(i,t).md})}function Rq(e,t,n,r,i,a){IU(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=T8e(e,t,r,i),l=ja.nodeFromJSON(c),u=a?Lq(n):void 0;if(s!==t&&Tn(o,s,t),_M(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=ka(a.baselineFullMd);E8e(a,u,c,n,e,Iq(r))}})}function zq(e,t,n,r,i){IU(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=T8e(e,t,n,r),c=ja.nodeFromJSON(s),l=i?Lq(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),_M(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=ka(i.baselineFullMd);E8e(i,l,s,a,e,Iq(n))}})}function D8e(e,t,n){let r=e.getXmlFragment(`default`),i=e.getText(`source`).toString(),{frontmatter:a,body:o}=ka(i),s=Iq(t),c=Xa.parseWithFallback(o,s),l=ja.nodeFromJSON(c),u=n?Xa.serialize(yM(r,ja).toJSON()):void 0;if(_M(e,r,l,{mapping:new Map,isOMark:new Map}),n&&u!==void 0){let e=Xa.serialize(yM(r,ja).toJSON()),t=Xa.serialize(c),{body:i}=ka(n.baselineFullMd),o=Xa.serialize(Xa.parseWithFallback(i,s));n.report({pendingBody:u,baselineBody:o,ytextDerivedBody:t,rebuiltBody:e,restorePayload:or(a,u).md})}}const O8e=q(`loss-capture`),Bq=`detector-trip`,Vq=`backstop-trip`,Hq=`checkpoint-write`;L({ts:Ia(),schemaVersion:Ia(),seq:Ia(),event:R(),docName:R(),writerId:R().nullable(),site:R().optional(),direction:R().optional(),lostLen:Ia().optional(),digest:R().optional(),checkpointSha:R().optional(),which:R().optional(),witnessAvailable:A().optional(),connections:Ia().optional()});const k8e=[`.ok`,`local`,`loss-capture`];function A8e(e){return H(e,...k8e,`loss-current.jsonl`)}function j8e(e){return H(e,...k8e,`loss-prev.jsonl`)}var M8e=class{#e;#t;#n=new Map;constructor(e){this.#e=new Px({currentPath:A8e(e.projectDir),previousPath:j8e(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha},...e.which===void 0?{}:{which:e.which},...e.witnessAvailable===void 0?{}:{witnessAvailable:e.witnessAvailable},...e.connections===void 0?{}:{connections:e.connections}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{O8e.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const Uq=q(`checkpoint-chain`);async function N8e(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw Uq.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
|
|
923
|
+
`);return Mq({primary:Eq(e),tail:n})}function m8e(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function h8e(e,t){let n=eS(e?._meta),r=eS(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 g8e(e,t){let n=h8e(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 _8e(e,t,n,r){let i=t.toolCallId,a=e.reportedToolCalls.get(i);return a!==void 0||!e.browserInjected||!V0e(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 v8e(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(y8e(e,t,n));e.on(`message`,e=>{let s=Nwe(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,!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 xq?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,threadId:`threadId`in s?s.threadId:void 0}))}})()});let o=async(e,o,s=!1)=>{let c=r.get(e);if(c!==void 0){if(!s)return;t.unsubscribe(e,c),r.delete(e)}let l=t=>{r.get(e)===l&&i(t)};r.set(e,l);try{await t.subscribe(e,o,l),r.get(e)!==l&&t.unsubscribe(e,l)}catch(i){if(t.unsubscribe(e,l),r.get(e)!==l){i instanceof xq||n.error({err:i,threadId:e},`[acp-thread-socket] superseded subscription failed`);return}if(r.delete(e),i instanceof xq)a(i.code,i.message,{threadId:e});else throw i}};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 y8e(e,t,n){return{op:`error`,code:e,message:t,...n}}var b8e=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){kH(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){kH(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(Ve);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),x8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function x8e(e){return e?.awareness??null}var S8e=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!kH(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(!kH(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(!kH(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(!kH(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 i$e(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Ve);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),C8e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function C8e(e){return e?.awareness??null}function w8e(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 Pq(e){return{probes:await Ar({env:e.env,resolve:w8e(e)}),detection:vo}}function Fq(e){let t=ka(e);return t.frontmatter===``?t:wa(ha(t.frontmatter)).map===null?{frontmatter:``,body:e}:t}function T8e(e,t,n,r){let{body:i}=ka(t);return r!==void 0&&r.rawContent===t?r.parsedJson:IU(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Xa.parseWithFallback(i,Iq(n)))}function Iq(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Lq(e){return Xa.serialize(yM(e,ja).toJSON())}function E8e(e,t,n,r,i,a){let o=Lq(r),s=Xa.serialize(n),{body:c}=ka(e.baselineFullMd),l=Xa.serialize(Xa.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:or(i,t).md})}function Rq(e,t,n,r,i,a){IU(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=T8e(e,t,r,i),l=ja.nodeFromJSON(c),u=a?Lq(n):void 0;if(s!==t&&Tn(o,s,t),_M(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=ka(a.baselineFullMd);E8e(a,u,c,n,e,Iq(r))}})}function zq(e,t,n,r,i){IU(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=T8e(e,t,n,r),c=ja.nodeFromJSON(s),l=i?Lq(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),_M(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=ka(i.baselineFullMd);E8e(i,l,s,a,e,Iq(n))}})}function D8e(e,t,n){let r=e.getXmlFragment(`default`),i=e.getText(`source`).toString(),{frontmatter:a,body:o}=ka(i),s=Iq(t),c=Xa.parseWithFallback(o,s),l=ja.nodeFromJSON(c),u=n?Xa.serialize(yM(r,ja).toJSON()):void 0;if(_M(e,r,l,{mapping:new Map,isOMark:new Map}),n&&u!==void 0){let e=Xa.serialize(yM(r,ja).toJSON()),t=Xa.serialize(c),{body:i}=ka(n.baselineFullMd),o=Xa.serialize(Xa.parseWithFallback(i,s));n.report({pendingBody:u,baselineBody:o,ytextDerivedBody:t,rebuiltBody:e,restorePayload:or(a,u).md})}}const O8e=q(`loss-capture`),Bq=`detector-trip`,Vq=`backstop-trip`,Hq=`checkpoint-write`;L({ts:Ia(),schemaVersion:Ia(),seq:Ia(),event:R(),docName:R(),writerId:R().nullable(),site:R().optional(),direction:R().optional(),lostLen:Ia().optional(),digest:R().optional(),checkpointSha:R().optional(),which:R().optional(),witnessAvailable:A().optional(),connections:Ia().optional()});const k8e=[`.ok`,`local`,`loss-capture`];function A8e(e){return H(e,...k8e,`loss-current.jsonl`)}function j8e(e){return H(e,...k8e,`loss-prev.jsonl`)}var M8e=class{#e;#t;#n=new Map;constructor(e){this.#e=new Px({currentPath:A8e(e.projectDir),previousPath:j8e(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha},...e.which===void 0?{}:{which:e.which},...e.witnessAvailable===void 0?{}:{witnessAvailable:e.witnessAvailable},...e.connections===void 0?{}:{connections:e.connections}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{O8e.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const Uq=q(`checkpoint-chain`);async function N8e(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw Uq.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
|
|
924
924
|
`).map(e=>e.trim()).filter(e=>e.length===40);if(r.length===0)return[];let i;try{i=await e.raw(`log`,`--no-walk`,`--format=%H%x00%B%x1e`,...r)}catch(e){throw Uq.warn({branch:t,shaCount:r.length,err:e},`[checkpoint-chain] checkpoint body read failed; anchors are unknown`),e}let a=[];for(let e of i.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,r=``]=t.split(`\0`);n.length===40&&Zr(Ee(r)?.kind??null)&&a.push(n)}if(a.length<=1)return a;try{let t=(await e.raw(`merge-base`,`--independent`,...a)).trim().split(`
|
|
925
925
|
`).map(e=>e.trim()).filter(e=>e.length===40);return t.length>0?t:a}catch(e){return Uq.warn({branch:t,anchorCount:a.length,err:e},`[checkpoint-chain] tip reduction failed; adopting the full anchor set`),a}}function Wq(e){try{return hc(e)}catch{return W(e)}}function P8e(e){return e.replace(/[\\!?*[\]]/g,e=>`\\${e}`)}const Gq=[`status`,`--porcelain`,`-uall`];function Kq(e){return e.split(`\0`).filter(e=>e.length>0)}function F8e(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;r.length<4||(t.push(r.slice(3)),(r[0]===`R`||r[0]===`C`||r[1]===`R`||r[1]===`C`)&&e++)}return t}function I8e(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;if(r.length<4)continue;let i=r[0]??` `,a=r[1]??` `,o={x:i,y:a,path:r.slice(3)};if(i===`R`||i===`C`||a===`R`||a===`C`){let t=n[e+1];t!==void 0&&t.length>0&&(o.origPath=t),e++}t.push(o)}return t}function L8e(e){let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=t[r]??``;if(e===``)break;if(e[0]===`R`||e[0]===`C`)n.push({status:e,from:t[r+1]??``,to:t[r+2]??``}),r+=3;else{let i=t[r+1]??``;n.push({status:e,from:i,to:i}),r+=2}}return n}function R8e(e){let t=[];for(let n of e.split(`\0`)){if(!n)continue;let e=n.indexOf(` `);if(e<0)continue;let[r=``,i=``,a=``,o=`0`]=n.slice(0,e).trim().split(/\s+/),s=Number(o);t.push({mode:r,type:i,object:a,size:Number.isFinite(s)?s:0,path:n.slice(e+1)})}return t}function qq(e,t){let[n=``,...r]=t;return e.raw([n,`-z`,...r])}async function Jq(e,t){return Kq(await qq(e,t))}async function z8e(e,t=Gq){return F8e(await qq(e,t))}async function B8e(e,t=Gq){return I8e(await qq(e,t))}async function Yq(e,t){return L8e(await qq(e,t))}async function V8e(e,t){return R8e(await qq(e,t))}var H8e=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project in your home directory (${e}).\n A project here would run 'git init' in your home directory and write project config\n and skills into your editors' user-global directories (~/.cursor, ~/.codex, ~/.claude).\n Make a folder for this project, then run '${$e()} init' inside it.`),this.name=`HomeProjectRootError`,this.projectRoot=e}},U8e=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project at the top of a drive (${e}).\n A project here would scan every file on the drive and run 'git init' at its root.\n Make a folder for this project, then run '${$e()} init' inside it.`),this.name=`FilesystemRootProjectError`,this.projectRoot=e}};function Xq(e){try{return hc.native(e)}catch{return e}}function W8e(e,t=wc()){return Xq(W(e))===Xq(t)}function G8e(e,t=process.platform){let n=t===`win32`?Xs:Js,r=n.resolve(e),i=t===process.platform?Xq(r):r;return n.dirname(i)===i||t===`darwin`&&i===`/System/Volumes/Data`}function Zq(e,t){if(W8e(e,t))throw new H8e(W(e));if(G8e(e))throw new U8e(W(e))}const Qq=`config.yml`;var K8e=class extends Error{constructor(e,t){super(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`),this.name=`SymlinkRefusedError`}};function $q(e,t){let n;try{n=cc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(n.isSymbolicLink())throw new K8e(e,t)}function q8e(e){let[t=`0`,n=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${n.length>0?n:`0`}`}function J8e(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function Y8e(e,t){let n=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${qi}/config.project.schema.json
|
|
926
926
|
# OpenKnowledge — project configuration
|
|
@@ -1126,7 +1126,7 @@ ${B5e(e).join(`
|
|
|
1126
1126
|
`).replaceAll(`\r`,`
|
|
1127
1127
|
`).split(`
|
|
1128
1128
|
`))n(i)||cmt(lmt(i,r).replace(/`[^`]*`/g,``),t);return[...t.values()]}function dmt(e){let t=nmt(e.href);if(!t||tmt(t))return null;let n=So(t,e.fromDocName,{literal:e.literal});if(!n)return null;let r=Ws(n).slice(1).toLowerCase();if(!va.has(r))return null;let i=W(e.contentDir,n),a,o;try{if(a=Ks(hc(i)),!KG(a,e.contentDir))return null;o=yc(a)}catch(t){let n=smt(t);return n!==`ENOENT`&&n!==`ENOTDIR`&&$pt.warn({href:e.href,err:t},`unexpected error resolving asset`),null}return o.isFile()?{absolutePath:a,relativePath:fmt(e.contentDir,a),stat:o}:null}function fmt(e,t){let n=Ks(hc(e));return Ks(t).slice(n.length+ +!n.endsWith(Ys)).split(Ys).join(`/`)}function pmt(e){let t;try{t=Ks(hc(e.contentDir))}catch(e){return $pt.warn({err:e},`could not resolve content directory`),[]}let n=new Map;for(let[r,i]of e.fileIndex){let a=e.readMarkdown(i.canonicalPath);if(a!==null)for(let i of umt(a)){let a=dmt({contentDir:t,fromDocName:r,href:i.href,literal:i.literal});if(!a||e.isExcluded?.(a.relativePath))continue;let o=omt(a.absolutePath),s=n.get(a.relativePath);if(s){s.referencedBy.includes(r)||s.referencedBy.push(r);continue}n.set(a.relativePath,{kind:`asset`,path:a.relativePath,assetExt:Ws(a.relativePath).toLowerCase(),mediaKind:o,size:a.stat.size,modified:a.stat.mtime.toISOString(),referencedBy:[r]})}}return[...n.values()].sort((e,t)=>e.path.localeCompare(t.path))}function mmt(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}function hmt(e){let{hocuspocus:t,conflicts:n,contentDir:r,isSafeDocName:i,resolveAlias:a,resolveContentEntryPath:o,resolveDocPath:s,extractHeadings:c,getFileIndex:l,getFileIndexGeneration:u,log:d,ready:f,contentFilter:p,safeSubdir:m,getShowAllMaxEntries:h,streamShowAllEntries:g,walkContentDirForShowAll:_,synthesizeShowAllAssetExt:v,getAllFilesIndex:y,getFolderIndex:b,getFolderAliasIndex:S,onReferencedAssetsCacheInvalidator:C}=e,w=new Map,T=null;function E(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1129
|
-
`)}function D(){T=null}C?.(D);function O(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let k=Z(x,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=YH(a(s));if(_U(c)||vU(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,so,{docName:c,content:u.getText(`source`).toString(),lifecycle:O(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,so,{docName:c,content:t,lifecycle:O(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),A=Z(x,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&mmt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=eq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=w.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;w.set(e,c),a.finally(()=>{w.get(e)===c&&w.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),w.get(e)===a&&w.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,ue,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let c=l(),x=[...y()],C=b?.()??new Map,D=S?.()??new Map,O=[];for(let[e,t]of C)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=E(c),t=u?.();(!T||T.signature!==e||T.generation!==t||T.assets.some(e=>p?.isPathIgnored(e.path)))&&(T={signature:e,generation:t,assets:pmt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=T?.assets??[]}catch(e){T=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let A=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(A.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of x){if(t.kind===`markdown`){let n=qH(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of lX(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of lX(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=C.get(n),a=t?uX(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of C)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:uX(r,t.canonicalPath,e)})});for(let[e,t]of x){let{resolved:i,members:a}=lX(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:qH(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,ue,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),j=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,zne,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),M={"/api/document":k,"/api/documents":A,"/api/pages":Z(x,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=qH(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=JY(i,t),o=uet(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Jte,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":j};return{paths:Object.keys(M),table:{resolve(e){let t=M[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:D}}const gmt=[`date`,`user`],_mt=/\{\{([^{}\n]+?)\}\}/g;function vmt(e){let t=[];for(let n of e.matchAll(_mt)){let e=(n[1]??``).trim();bmt(e)||t.push({token:e,offset:n.index??0})}return t}function ymt(e,t){return e.replace(_mt,(e,n)=>{let r=n.trim();return bmt(r)?t[r]:e})}function bmt(e){return gmt.includes(e)}function L4(e,t,n={}){let r=Cmt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;z4(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)z4(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&z4(e,``,`inherited`,a,o,s),o}async function xmt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=R4){a=!0,q(`templates`).warn({projectDir:e,cap:R4,queueDepth:o.length},`project scan hit the ${R4}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}z4(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Mc(s,{withFileTypes:!0})}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Smt.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Fc(n)).isDirectory()}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(n)){B4.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?Js.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const R4=2e3,Smt=new Set([`node_modules`,`dist`,`build`]);function z4(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(MK(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),B4.has(o)||(B4.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=cc(s)}catch(e){let n=cG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),B4.has(s)||(B4.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=mc(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=yc(c)}catch{continue}if(!l.isFile())continue;try{jK(c,s),jK(c,e)}catch(e){if(e instanceof EK){B4.has(c)||(B4.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(cG(e)!==`ENOENT`&&!B4.has(c)){B4.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=wmt(c),d={name:o,path:t?Js.join(t,`.ok`,`templates`,a):Js.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Cmt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const B4=new Set;function wmt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(cG(t)!==`ENOENT`&&!B4.has(e)){B4.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=ct(t);typeof n.title!=`string`&&!B4.has(e)&&(B4.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var V4=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const H4=q(`file-ops`);function Tmt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)_U(r)||vU(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;XU(V(n),{recursive:!0});try{JU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),hX(n,dG(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(XU(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=yc(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(WG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?eW(s):(iW(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&yc(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=yc(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(WG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=Ws(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(_U(n)||vU(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{XU(s,{recursive:!0}),JU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{aW(s)}catch(e){let t=cG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&H4.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{KH(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),hX(r,dG(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{iW(r,{force:!0})}catch(e){H4.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw ZH(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{QU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=Ws(n.fullPath);KH(UH(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),hX(n.fullPath,dG(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){H4.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&ZH(UH(t.docName))}e.removeFolderIndexEntries(l);try{iW(u,{recursive:!0,force:!0})}catch(e){H4.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var U4=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function W4(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return pne(e)}}function G4(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function K4(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return pne(e)}}const q4=q(`upload-streaming`);var Emt=class extends Sae{hash=Rc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Dmt(e){return W(qJ(e),`tmp`)}function Omt(e){let t=Dmt(e);return XU(t,{recursive:!0}),W(t,`upload-${zc()}`)}function kmt(e,t,n){let r=Ws(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{nW(e,r);try{eW(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{eW(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new U4(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new U4(`urn:ok:error:storage-readonly`,t):new U4(`urn:ok:error:storage-error`,t)}}try{eW(e)}catch{}throw new U4(`urn:ok:error:collision-exhaustion`)}function Amt(e,{ageMs:t=864e5}={}){let n=Dmt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=mc(n)}catch(e){return q4.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(yc(t).mtimeMs>=a)continue;eW(t),r.deleted++}catch(e){q4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&q4.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function jmt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function Mmt(e){let t=cG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function Nmt(e,t){return new Promise((n,r)=>{let i;try{i=Qct(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new U4(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{bc(e)}catch{}})}if(d?.destroy(),u)try{bc(u)}catch{}r(t instanceof U4?t:new U4(e,t))}},h=G4;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Omt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Emt;d=oc(g),Wc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function Pmt(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:x,_performDocumentToFileRename:S,_performManagedRenameForDocs:C,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof DK}return H2(FK(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(BH(t)){let e=UH(t);for(let t of ae){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${Ys}`)||G(r)&&KH(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${Ys}`)&&G(r)&&KH(e,Ws(t));return}for(let e of ae){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${Ys}`))&&G(r)){KH(t,e);return}}}function O(e){if(Ws(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=mc(a,{withFileTypes:!0})}catch(t){let n=cG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>HH(e,va));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(mre,async(e,n,a)=>{try{let e=FQ(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!BH(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=UH(s);if(_U(d)||vU(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=FK(u,c,r);if(H2(s)||H2(p)||rn(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!wt.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${sn}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=L4(c,t),i=Gi(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=tn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=ymt(l,{date:Goe(),user:u}),_=i.scope}let v=UH(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:c$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Lne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),A=Z(_te,async(e,t,n)=>{try{if(FQ(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(H2(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Ate,{path:e},{handler:`create-folder`})}catch(e){if(PK(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),j=Z(xe,async(e,n,r)=>{try{let e=FQ(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?UH(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(H2(c)||E(c)||a===`file`&&(_U(u)||vU(u))||a===`folder`&&jmt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:$J(n,new QJ({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)c$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,Un,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof V4){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=Mmt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),M=Z(Oie,async(e,n,o)=>{try{let e=FQ(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(_U(u)||_U(d)||vU(u)||vU(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(H2(u)||H2(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&BH(u)&&BH(d)?`file`:l;if(f===`asset`){let t;try{t=BH(u)&&!BH(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let w=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of w){let t=s.findByDocName(e);if(t!==void 0){$J(n,new QJ({file:t.file}),`rename-path`,t);return}}if(a){let e=BH(u)?Ws(u):qH(u);if(f===`file`?a.isExcluded(BH(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await C(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof J9e){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let A,j=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);j.length>0&&(A=y(e,`Renamed ${u} → ${d}`,j.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:ove(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...A?{summary:A}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),N=Z(Lte,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&BH(o)?`file`:e;if(c===`file`&&D(t,o),H2(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):$J(n,new QJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Mee,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),P=Z(bte,async(e,n,r)=>FU(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":zU(r.path),"ok.cleanup.path.role":BU(r.path)}},async()=>{try{if(FQ(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&BH(a)?`file`:e,s=UH(a);o===`file`&&D(t,a);let c=o===`folder`&&jmt(a);if(o===`file`&&(_U(s)||vU(s))||c||H2(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Vre,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function ee(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await Nmt(e,n??t)}catch(e){if(e instanceof U4){X(i,W4(e.reason),e.reason,K4(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{bc(s)}catch{}},h=i$(w,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(H2(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,Cne,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:ZK(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:W4(x.reason),err:x.cause},`[upload] write failed`),X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return XQ({"/api/create-page":k,"/api/create-folder":A,"/api/duplicate-path":j,"/api/rename-path":M,"/api/delete-path":N,"/api/trash/cleanup":P,"/api/upload":ee},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Fmt(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||Gs(e)}function J4(e,t){if(typeof e!=`string`||!Gs(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:Fmt(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i.split(Ys).join(`/`)}}function Y4(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const X4=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Imt=`Canonical ids: ${Yn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,Z4=R().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Lmt="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",Rmt=R().length(40).regex(/^[0-9a-f]+$/i).describe(Lmt),Q4=R().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),$4=R().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),zmt=R().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),e3=L({value:R(),truncatedFrom:Ia().optional(),hint:R().optional()}).describe(`Normalized change-note summary, when one was recorded.`),t3=To(z(R(),B())),Bmt=z(R(),B()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Vmt=To(_re).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),Hmt=Aa.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function Umt(e,t){for(let n of ae){let r=J4(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Wmt={summary:e3.optional(),warnings:To(Qa).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:Vmt,brokenLinkSuppression:Hmt,templateHint:To(L({name:R(),description:R().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function Gmt(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function n3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function r3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${n3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Kmt=R().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function i3(e){return{text:Kmt,...e}}function a3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function o3(){return`Error: Hocuspocus server is not running. Start it with \`${$e()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function qmt(e,t){return typeof e==`function`?await e(t):e}async function Jmt(e,t){return typeof e==`function`?await e(t):e}async function s3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await Jmt(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function c3(e,t,n,r){let i=await l3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(o3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function l3(e,t,n,r){let i=await s3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await qmt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function u3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function d3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=la(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function f3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function p3(e,t){return t?{url:e,local:t}:e}function m3(e){return e instanceof Error&&e.name===`TimeoutError`}function h3(e,t){let n=e instanceof Error?e.message:String(e);if(!m3(e))return`${gie} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Jee} ${n}.${r}`}async function Ymt(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:h3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=f3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function g3(e,t){if(typeof e!=`string`){let n=await Ymt(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(m3(e))return{ok:!1,httpStatus:n.status,error:h3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...f3(n,r),httpStatus:n.status}}async function _3(e,t,n){let r=await g3(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function v3(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await Ymt(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e)}}let o;try{o=await a.json()}catch(e){if(m3(e))return{ok:!1,error:h3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return f3(a,o)}function y3(e,t,n){return v3(`POST`,e,t,n)}function b3(e,t,n){return v3(`PUT`,e,t,n)}function x3(e,t){return v3(`DELETE`,e,t)}function Xmt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function S3(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[Vne]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function Zmt(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const C3=Zmt(`the server`);function Qmt(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const w3=Qmt(`the server`),T3="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",$mt="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",eht=/^(?:source(?: family)?|validator) "/;function tht(e){let t=[],n=[];for(let r of e)(eht.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function E3(e,t,n=0){let r=t.filter(e=>!Mn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function nht(e,t,n,r){if(t===0&&n.some(Mn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function D3(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function O3(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function rht(e,t){let n=cht(e,t,`frontmatter.yml`);if(MK(V(n)).kind===`symlink`)return A3(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=MK(n);if(r.kind===`symlink`)return A3(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return A3(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{jK(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return A3(PK(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=sht(n);return i==null?{}:iht(i)}function iht(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const aht=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],k3=new Set;function A3(e,t,n){let r=`${e}:${t}`;k3.has(r)||(k3.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function oht(e){for(let t of aht)k3.delete(`${t}:${e}`)}function sht(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,rl.parse)(t)}catch(t){return A3(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(oht(e),n)}function cht(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function lht(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function uht(e){try{return yc(W(e,`.git`)).isDirectory()}catch{return!1}}function dht(e){return tM({baseDir:W(e),timeout:{block:5e3}})}async function fht(e,t,n=5){if(!uht(e))return{commits:[],source:`git-absent`};let r=dht(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Ut([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1129
|
+
`)}function D(){T=null}C?.(D);function O(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let k=Z(x,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=YH(a(s));if(_U(c)||vU(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,so,{docName:c,content:u.getText(`source`).toString(),lifecycle:O(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,so,{docName:c,content:t,lifecycle:O(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),A=Z(x,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&mmt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=eq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=w.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;w.set(e,c),a.finally(()=>{w.get(e)===c&&w.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),w.get(e)===a&&w.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,ue,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let c=l(),x=[...y()],C=b?.()??new Map,D=S?.()??new Map,O=[];for(let[e,t]of C)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=E(c),t=u?.();(!T||T.signature!==e||T.generation!==t||T.assets.some(e=>p?.isPathIgnored(e.path)))&&(T={signature:e,generation:t,assets:pmt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=T?.assets??[]}catch(e){T=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let A=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(A.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of x){if(t.kind===`markdown`){let n=qH(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of lX(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of lX(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=C.get(n),a=t?uX(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of C)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:uX(r,t.canonicalPath,e)})});for(let[e,t]of x){let{resolved:i,members:a}=lX(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:qH(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&A.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,ue,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),j=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,zne,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),M={"/api/document":k,"/api/documents":A,"/api/pages":Z(x,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=qH(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=JY(i,t),o=uet(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Jte,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":j};return{paths:Object.keys(M),table:{resolve(e){let t=M[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:D}}const gmt=[`date`,`user`],_mt=/\{\{([^{}\n]+?)\}\}/g;function vmt(e){let t=[];for(let n of e.matchAll(_mt)){let e=(n[1]??``).trim();bmt(e)||t.push({token:e,offset:n.index??0})}return t}function ymt(e,t){return e.replace(_mt,(e,n)=>{let r=n.trim();return bmt(r)?t[r]:e})}function bmt(e){return gmt.includes(e)}function L4(e,t,n={}){let r=Cmt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;z4(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)z4(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&z4(e,``,`inherited`,a,o,s),o}async function xmt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=R4){a=!0,q(`templates`).warn({projectDir:e,cap:R4,queueDepth:o.length},`project scan hit the ${R4}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}z4(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await Mc(s,{withFileTypes:!0})}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Smt.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Fc(n)).isDirectory()}catch(e){if(cG(e)!==`ENOENT`&&!B4.has(n)){B4.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?Js.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const R4=2e3,Smt=new Set([`node_modules`,`dist`,`build`]);function z4(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(MK(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),B4.has(o)||(B4.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=cc(s)}catch(e){let n=cG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!B4.has(s)){B4.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),B4.has(s)||(B4.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=mc(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=yc(c)}catch{continue}if(!l.isFile())continue;try{jK(c,s),jK(c,e)}catch(e){if(e instanceof EK){B4.has(c)||(B4.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(cG(e)!==`ENOENT`&&!B4.has(c)){B4.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=wmt(c),d={name:o,path:t?Js.join(t,`.ok`,`templates`,a):Js.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Cmt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const B4=new Set;function wmt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(cG(t)!==`ENOENT`&&!B4.has(e)){B4.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=ct(t);typeof n.title!=`string`&&!B4.has(e)&&(B4.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var V4=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const H4=q(`file-ops`);function Tmt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)_U(r)||vU(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;XU(V(n),{recursive:!0});try{JU(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),hX(n,dG(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(XU(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=yc(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(WG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?eW(s):(iW(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&yc(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=yc(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(WG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=Ws(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(_U(n)||vU(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{XU(s,{recursive:!0}),JU(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{aW(s)}catch(e){let t=cG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&H4.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{KH(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),hX(r,dG(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{iW(r,{force:!0})}catch(e){H4.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw ZH(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{QU(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(IK(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=Ws(n.fullPath);KH(UH(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),hX(n.fullPath,dG(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){H4.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&ZH(UH(t.docName))}e.removeFolderIndexEntries(l);try{iW(u,{recursive:!0,force:!0})}catch(e){H4.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var U4=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function W4(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return pne(e)}}function G4(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function K4(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return pne(e)}}const q4=q(`upload-streaming`);var Emt=class extends Sae{hash=Rc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Dmt(e){return W(qJ(e),`tmp`)}function Omt(e){let t=Dmt(e);return XU(t,{recursive:!0}),W(t,`upload-${zc()}`)}function kmt(e,t,n){let r=Ws(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{nW(e,r);try{eW(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{eW(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new U4(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new U4(`urn:ok:error:storage-readonly`,t):new U4(`urn:ok:error:storage-error`,t)}}try{eW(e)}catch{}throw new U4(`urn:ok:error:collision-exhaustion`)}function Amt(e,{ageMs:t=864e5}={}){let n=Dmt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=mc(n)}catch(e){return q4.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(yc(t).mtimeMs>=a)continue;eW(t),r.deleted++}catch(e){q4.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&q4.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function jmt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function Mmt(e){let t=cG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function Nmt(e,t){return new Promise((n,r)=>{let i;try{i=Qct(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new U4(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{bc(e)}catch{}})}if(d?.destroy(),u)try{bc(u)}catch{}r(t instanceof U4?t:new U4(e,t))}},h=G4;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Omt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new Emt;d=oc(g),Wc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function Pmt(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:x,_performDocumentToFileRename:S,_performManagedRenameForDocs:C,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof DK}return H2(FK(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(BH(t)){let e=UH(t);for(let t of ae){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${Ys}`)||G(r)&&KH(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${Ys}`)&&G(r)&&KH(e,Ws(t));return}for(let e of ae){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${Ys}`))&&G(r)){KH(t,e);return}}}function O(e){if(Ws(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=mc(a,{withFileTypes:!0})}catch(t){let n=cG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>HH(e,va));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(mre,async(e,n,a)=>{try{let e=FQ(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!BH(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=UH(s);if(_U(d)||vU(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=FK(u,c,r);if(H2(s)||H2(p)||rn(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!wt.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${sn}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=L4(c,t),i=Gi(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=tn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=ymt(l,{date:Goe(),user:u}),_=i.scope}let v=UH(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:c$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Lne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),A=Z(_te,async(e,t,n)=>{try{if(FQ(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(H2(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Ate,{path:e},{handler:`create-folder`})}catch(e){if(PK(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),j=Z(xe,async(e,n,r)=>{try{let e=FQ(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?UH(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(H2(c)||E(c)||a===`file`&&(_U(u)||vU(u))||a===`folder`&&jmt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:$J(n,new QJ({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)c$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,Un,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof V4){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=Mmt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),M=Z(Oie,async(e,n,o)=>{try{let e=FQ(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(_U(u)||_U(d)||vU(u)||vU(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(H2(u)||H2(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&BH(u)&&BH(d)?`file`:l;if(f===`asset`){let t;try{t=BH(u)&&!BH(d)?await S(u,d):await x(u,d)}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let w=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of w){let t=s.findByDocName(e);if(t!==void 0){$J(n,new QJ({file:t.file}),`rename-path`,t);return}}if(a){let e=BH(u)?Ws(u):qH(u);if(f===`file`?a.isExcluded(BH(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await C(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof QJ){$J(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof J9e){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,Wi,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let A,j=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);j.length>0&&(A=y(e,`Renamed ${u} → ${d}`,j.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:ove(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,Wi,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...A?{summary:A}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),N=Z(Lte,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&BH(o)?`file`:e;if(c===`file`&&D(t,o),H2(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):$J(n,new QJ({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,Mee,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(PK(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),P=Z(bte,async(e,n,r)=>FU(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":zU(r.path),"ok.cleanup.path.role":BU(r.path)}},async()=>{try{if(FQ(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&BH(a)?`file`:e,s=UH(a);o===`file`&&D(t,a);let c=o===`folder`&&jmt(a);if(o===`file`&&(_U(s)||vU(s))||c||H2(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Vre,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function ee(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await Nmt(e,n??t)}catch(e){if(e instanceof U4){X(i,W4(e.reason),e.reason,K4(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{bc(s)}catch{}},h=i$(w,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(H2(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,Cne,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:ZK(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:W4(x.reason),err:x.cause},`[upload] write failed`),X(i,W4(x.reason),x.reason,K4(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return XQ({"/api/create-page":k,"/api/create-folder":A,"/api/duplicate-path":j,"/api/rename-path":M,"/api/delete-path":N,"/api/trash/cleanup":P,"/api/upload":ee},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function Fmt(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||Gs(e)}function J4(e,t){if(typeof e!=`string`||!Gs(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:Fmt(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i.split(Ys).join(`/`)}}function Y4(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const X4=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Imt=`Canonical ids: ${Yn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,Z4=R().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),Lmt="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",Rmt=R().length(40).regex(/^[0-9a-f]+$/i).describe(Lmt),Q4=R().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),$4=R().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),zmt=R().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),e3=L({value:R(),truncatedFrom:Ia().optional(),hint:R().optional()}).describe(`Normalized change-note summary, when one was recorded.`),t3=To(z(R(),B())),Bmt=z(R(),B()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Vmt=To(_re).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),Hmt=Aa.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function Umt(e,t){for(let n of ae){let r=J4(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const Wmt={summary:e3.optional(),warnings:To(Qa).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:Vmt,brokenLinkSuppression:Hmt,templateHint:To(L({name:R(),description:R().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function Gmt(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function n3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function r3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${n3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Kmt=R().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function i3(e){return{text:Kmt,...e}}function a3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function o3(){return`Error: Hocuspocus server is not running. Start it with \`${$e()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function qmt(e,t){return typeof e==`function`?await e(t):e}async function Jmt(e,t){return typeof e==`function`?await e(t):e}async function s3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await Jmt(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function c3(e,t,n,r){let i=await l3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(o3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function l3(e,t,n,r){let i=await s3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await qmt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function u3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function d3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=la(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function f3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function p3(e,t){return t?{url:e,local:t}:e}function m3(e){return e instanceof Error&&(e.name===`TimeoutError`||[e,e.cause].some(e=>e instanceof Error&&`code`in e&&(e.code===`UND_ERR_HEADERS_TIMEOUT`||e.code===`UND_ERR_BODY_TIMEOUT`)))}function h3(e,t){let n=e instanceof Error?e.message:String(e);if(!m3(e))return`${gie} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Jee} ${n}.${r}`}async function Ymt(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:h3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=f3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function g3(e,t,n){if(typeof e!=`string`){let n=await Ymt(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let r;try{r=await fetch(`${e}${t}`,{signal:n??AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e,{mutating:!1})}}let i;try{i=await r.json()}catch(e){if(m3(e))return{ok:!1,httpStatus:r.status,error:h3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return r.ok?{ok:!1,httpStatus:r.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:r.status,error:`Server returned HTTP ${r.status} with non-JSON body: ${t}`}}return{...f3(r,i),httpStatus:r.status}}async function _3(e,t,n){let r=await g3(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function v3(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await Ymt(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:h3(e)}}let o;try{o=await a.json()}catch(e){if(m3(e))return{ok:!1,error:h3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return f3(a,o)}function y3(e,t,n){return v3(`POST`,e,t,n)}function b3(e,t,n){return v3(`PUT`,e,t,n)}function x3(e,t){return v3(`DELETE`,e,t)}function Xmt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function S3(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[Vne]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function Zmt(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const C3=Zmt(`the server`);function Qmt(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const w3=Qmt(`the server`),T3="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",$mt="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",eht=/^(?:source(?: family)?|validator) "/;function tht(e){let t=[],n=[];for(let r of e)(eht.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function E3(e,t,n=0){let r=t.filter(e=>!Mn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function nht(e,t,n,r){if(t===0&&n.some(Mn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function D3(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function O3(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function rht(e,t){let n=cht(e,t,`frontmatter.yml`);if(MK(V(n)).kind===`symlink`)return A3(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=MK(n);if(r.kind===`symlink`)return A3(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return A3(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{jK(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return A3(PK(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=sht(n);return i==null?{}:iht(i)}function iht(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const aht=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],k3=new Set;function A3(e,t,n){let r=`${e}:${t}`;k3.has(r)||(k3.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function oht(e){for(let t of aht)k3.delete(`${t}:${e}`)}function sht(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,rl.parse)(t)}catch(t){return A3(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(oht(e),n)}function cht(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function lht(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function uht(e){try{return yc(W(e,`.git`)).isDirectory()}catch{return!1}}function dht(e){return tM({baseDir:W(e),timeout:{block:5e3}})}async function fht(e,t,n=5){if(!uht(e))return{commits:[],source:`git-absent`};let r=dht(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Ut([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1130
1130
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const pht=5e3;async function mht(e){try{let t=(await tM({baseDir:e,timeout:{block:pht}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function hht(e,t){return tM({baseDir:t,timeout:{block:pht}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function ght(e,t){let n=X_e(t);return e.startsWith(n)?e.slice(n.length):e}async function _ht(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Ut([n]))}catch{return[]}let o=ght(t,r),s=Qx(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:Zx(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function vht(e,t,n,r,i){let a;try{a=await N8e(e,t)}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,err:e},`[shadow-log] chain anchors unresolved; per-path history degraded to empty`),[]}if(a.length===0)return[];let o=``;try{o=await e.raw(`log`,...a,`-${Math.max(r*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Ut([n]))}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,anchorCount:a.length,err:e},`[shadow-log] ancestry walk failed; per-path history degraded to empty`),[]}let s=[];for(let e of o.split(``)){if(s.length>=r)break;let n=e.trimStart();if(!n)continue;let[a=``,o=``,c=``,l=``,u=``]=n.split(`\0`),d=a.trim();if(d.length!==40||i.has(d)||l.startsWith(`checkpoint:`)||l.startsWith(`park:`)||l.startsWith(`import:`)||l.startsWith(`upstream:`))continue;let f=eve(u),p=f?.writer_id??``,m=Qx(p);i.add(d),s.push({hash:d,date:o,writerName:f?.display_name??c,message:l,contributors:Zx(u),writerId:p,isAgent:m.isAgent,writerClassification:m.classification,branch:t})}return s}async function yht(e,t,n=5){let r=Y_e(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await mht(e);if(!i)return{commits:[],source:`shadow-repo`};let a=hht(r,W(e)),o=``;try{o=await a.raw(`for-each-ref`,X_e(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
|
|
1131
1131
|
`).map(e=>e.trim()).filter(Boolean),c=(s.length===0?[]:await Promise.all(s.map(e=>_ht(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n);if(c.length<n){let e=new Set(c.map(e=>e.hash)),r=await vht(a,i,t,n-c.length,e);r.length>0&&(c=[...c,...r].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n))}return{commits:c,source:`shadow-repo`}}const bht=1e3,xht=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Sht=/\.(md|mdx)$/i;function Cht(e,t){if(e===null||t===null)return null;let n=e,r=t;return n===0&&r===0?`orphan`:n>=5?`hub`:n>0&&r>0?`connector`:`leaf`}function wht(e,t){let n=e.frontmatterSchemas;if(!n||n.length===0)return[];let r=e.contentDir??e.projectDir,i=U(r,W(e.projectDir,t));if(i.startsWith(`..`))return[];let a=[];for(let e of n)e.enabled!==!1&&qr(e.appliesTo).matches(i)&&(a.includes(e.file)||a.push(e.file));return a}function Tht(e,t){return wht(e,t===``?`⁂`:`${t}/⁂`)}function j3(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const Eht=new Set;async function Dht(e){try{let t=await jc(e,`utf-8`);return{frontmatter:D(t)??{},firstHeading:cet(ka(t).body)}}catch(t){if(t?.code!==`ENOENT`&&!Eht.has(e)){Eht.add(e);let n=t instanceof Error?t.message:String(t);q(`enrichment`).warn({path:e,reason:n},`failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${n}`)}return null}}async function Oht(e,t){if(!e)return null;let n=await g3(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function kht(e,t){if(!e)return null;let n=await g3(e,`/api/comments?doc=${encodeURIComponent(t)}`);return n.ok?Aht(n.threads):null}function Aht(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=e.state;if(r!==`anchored`&&r!==`orphaned`||typeof e.threadId!=`string`||e.threadId===``)continue;let i=(typeof e.anchor==`object`&&e.anchor!==null?e.anchor:{}).exact;t.push({threadId:e.threadId,body:typeof e.latestComment==`string`?e.latestComment:``,quote:typeof i==`string`?i:``,state:r,queued:e.queued===!0})}return t}async function jht(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await g3(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function Mht(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));return Pht(await Promise.all(r.map(async t=>{let n=await g3(e,`/api/comment-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})))}async function Nht(e,t){if(!e)return null;let n=await g3(e,`/api/comment-counts?prefix=${encodeURIComponent(t)}`);return n.ok?Pht([n.counts??{}]):null}function Pht(e){let t=new Map,n=!1;for(let r of e)if(r){n=!0;for(let[e,n]of Object.entries(r))typeof n==`number`&&Number.isFinite(n)&&t.set(e,n)}return n?t:null}async function Fht(e,t){if(!e)return null;let n=await g3(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function Iht(e,t){let n=e?.title;if(typeof n!=`string`)return t;let r=n.trim();return r===``?t:r}function Lht(e,t){let n=e??{};return{title:Iht(n,t),description:typeof n.description==`string`?n.description:void 0,tags:Array.isArray(n.tags)?n.tags.filter(e=>typeof e==`string`):[],frontmatter:n}}async function Rht(e,t,n={}){let r=J4(t.projectDir,e);if(!r.ok)throw Error(`enrichPath: ${r.reason}`);let i=r.rel,a=r.abs,o=t.historyDepth??5,s=n.includeRichFields===!0,c=Dht(a),l=wht(t,i),u=l.length>0?{schemas_applicable:l}:{};if(!s){let e=await c,t=Lht(e?.frontmatter??null,e?.firstHeading);return{path:i,title:t.title,description:t.description,tags:t.tags,frontmatter:t.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null,...u}}let[d,f,p,m,h,g]=await Promise.all([c,Oht(t.serverUrl,j3(i)).catch(()=>null),Fht(t.serverUrl,j3(i)).catch(()=>null),yht(t.projectDir,i,o).catch(()=>({commits:[],source:`shadow-repo`})),fht(t.projectDir,i,o).catch(()=>({commits:[],source:`git`})),kht(t.serverUrl,j3(i)).catch(()=>null)]),_=Lht(d?.frontmatter??null,d?.firstHeading);return{path:i,title:_.title,description:_.description,tags:_.tags,frontmatter:_.frontmatter,backlinkCount:f?.length??null,backlinks:f,forwardLinkCount:p?.length??null,forwardLinks:p,history:m.commits,historySource:m.source,projectHistory:h.commits,projectHistorySource:h.source,graphRole:Cht(f?.length??null,p?.length??null),commentCount:g?.length??null,comments:g,...u}}async function zht(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=bht){n.truncated=!0;break}let a;try{a=await Mc(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=bht){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(xht.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Sht.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Fc(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:U(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function Bht(e,t,n={}){let r=J4(t.projectDir,e);if(!r.ok)throw Error(`enrichDirectory: ${r.reason}`);let i=r.rel,a=r.abs,o=await zht(a,t.projectDir),s;if(o.mostRecent){let e=await Dht(o.mostRecent.absPath);s={path:o.mostRecent.relPath,title:Iht(e?.frontmatter,e?.firstHeading)??Hs(o.mostRecent.relPath),updatedAt:new Date(o.mostRecent.mtimeMs).toISOString()}}let c={path:i,type:`directory`,directMdCount:o.directMdCount,recursiveMdCount:o.recursiveMdCount,childDirCount:o.childDirCount,mostRecentMd:s,truncated:o.truncated},l=rht(t.projectDir,i);l.title!==void 0&&(c.title=l.title),l.description!==void 0&&(c.description=l.description),(l.tags?.length??0)>0&&(c.tags=l.tags);let u=L4(t.projectDir,i,{onRefused:n.onTemplateRefused});u.length>0&&(c.templates_available=u);let d=Tht(t,i);d.length>0&&(c.schemas_applicable=d);let f=await Nht(t.serverUrl,i).catch(()=>null);if(f&&f.size>0){let e=0;for(let t of f.values())e+=t;c.commentCount=e,c.commentedDocs=[...f].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,Vht).map(([e,t])=>({docName:e,count:t}))}return c}const Vht=5;async function Hht(e,t,n){let r=await Bht(e,n);if(t<=1)return r;let i=r.path,a=W(n.projectDir,i),o;try{o=await Mc(a,{withFileTypes:!0})}catch{return r}let s=[];for(let e of o){if(!e.isDirectory()||Uht.has(e.name)||e.name.startsWith(`.`))continue;let r=await Hht(i?`${i}/${e.name}`:e.name,t-1,n);s.push(r)}return s.length>0&&(r.subfolders=s),r}const Uht=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function M3(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(r!==void 0){if(Wht(r)){delete n[e];continue}n[e]=r}return n}function Wht(e){return iie(e)}function Ght(e){if(!Gs(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=W(e.anchorDir),n=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(n.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let r=n===``?t:W(t,n);if(r!==t&&!r.startsWith(t+Ys))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${r}`}};let i=H(r,`.ok`),a=H(i,`frontmatter.yml`);if(MK(a).kind===`symlink`)return{ok:!1,error:{code:`SYMLINK_REFUSED`,message:`Refusing to operate on "${n===``?``:`${n}/`}.ok/frontmatter.yml": it is a symlink. Replace the symlink with a real file or directory and retry.`}};try{let n=Kht(a),r=Object.keys(e.patch).length===0?{}:M3(n,e.patch);if(Object.keys(r).length===0)return G(a)?(bc(a),qht(i),{ok:!0,path:N3(t,a),action:`deleted`}):{ok:!0,path:N3(t,a),action:`noop`};lc(i,{recursive:!0});let o=(0,rl.stringify)(r),s=lS(a);return xc(s,o,`utf-8`),gc(s,a),{ok:!0,path:N3(t,a),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${n||`.`}": ${e.message}`}}}}function Kht(e){if(!G(e))return{};let t=K(e,`utf-8`),n=(0,rl.parse)(t);return typeof n!=`object`||!n||Array.isArray(n)?{}:{...n}}function qht(e){if(!G(e))return;let t;try{t=mc(e)}catch{return}if(t.length===0)try{vc(e)}catch{}}function N3(e,t){return t.startsWith(e+Ys)?t.slice(e.length+1).split(Ys).join(`/`):t}const Jht=wt;function P3(e){if(!Jht.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${sn} (got: ${JSON.stringify(e.name)}).`}};let t=$ht(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let n=egt(e.body);if(!n.ok)return{ok:!1,error:n.error};let r=tgt(e.body);if(!r.ok)return{ok:!1,error:r.error};let i={};e.frontmatter.title!==void 0&&(i.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(i.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(i.tags=e.frontmatter.tags);let a=ge(i,e.body),o=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&o.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:a,warnings:o}}function Yht(e){let t=F3(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let n=P3({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i}=n,{templatesDir:a,filePath:o}=I3(e.projectDir,t.folderRel,e.name);try{lc(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${L3(e.projectDir,a)}: ${t.message}`}}}let s=!G(o),c=lS(o);try{xc(c,r,`utf-8`),gc(c,o)}catch(t){try{bc(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${L3(e.projectDir,o)}: ${t.message}`}}}return{ok:!0,path:L3(e.projectDir,o),created:s,warnings:i}}function Xht(e){let t=F3(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:n,okDir:r,filePath:i}=I3(e.projectDir,t.folderRel,e.name),a=G(i);if(a)try{bc(i)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${L3(e.projectDir,i)}: ${t.message}`}}}return{ok:!0,path:L3(e.projectDir,i),existed:a,cleanedEmpty:Zht(n,r)}}function Zht(e,t){let n=!1,r=!1;if(G(e)&&ngt(e))try{vc(e),n=!0}catch{}if(G(t)&&ngt(t))try{vc(t),r=!0}catch{}return{templatesDir:n,okDir:r}}async function Qht(e){let t=F3(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let n=F3(e.projectDir,e.toFolder,e.toName);if(!n.ok)return{ok:!1,error:n.error};let r=I3(e.projectDir,t.folderRel,e.fromName),i=I3(e.projectDir,n.folderRel,e.toName);if(r.filePath===i.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!G(r.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${L3(e.projectDir,r.filePath)}.`}};if(G(i.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${L3(e.projectDir,i.filePath)}.`}};try{lc(i.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${L3(e.projectDir,i.templatesDir)}: ${t.message}`}}}let a;try{a=await e.relocate(r.filePath,i.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let o=Zht(r.templatesDir,r.okDir);return{ok:!0,fromPath:L3(e.projectDir,r.filePath),toPath:L3(e.projectDir,i.filePath),committed:a,cleanedEmpty:o}}function F3(e,t,n){if(!Gs(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!Jht.test(n))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${sn} (got: ${JSON.stringify(n)}).`}};let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(r.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let i=r?W(e,r):e,a=W(e);return!i.startsWith(a+Ys)&&i!==a?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${i}`}}:{ok:!0,folderRel:r}}function $ht(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function egt(e){let t=vmt(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function I3(e,t,n){let r=t?H(e,t,`.ok`):H(e,`.ok`),i=H(r,`templates`);return{okDir:r,templatesDir:i,filePath:H(i,`${n}.md`)}}function L3(e,t){let n=t.startsWith(e+Ys)?t.slice(e.length+1):t;return Ks(n).split(Ys).join(`/`)}function tgt(e){let{frontmatter:t}=ka(e);if(t===``)return{ok:!0};let n=ha(t);return RegExp(`^template:`,`m`).test(n)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${mie}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function ngt(e){try{return mc(e).length===0}catch{return!1}}const rgt={BAD_CONTENT_DIR:{status:400,urn:`urn:ok:error:invalid-request`},PATH_ESCAPE:{status:400,urn:`urn:ok:error:path-escape`},SYMLINK_REFUSED:{status:400,urn:`urn:ok:error:symlink-refused`},WRITE_ERROR:{status:500,urn:`urn:ok:error:internal-server-error`}};function igt(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,hocuspocus:a,sessionManager:o,getPrincipal:s,signalChannel:c,conflicts:l,recentlyRemovedDocs:u,isSafeDocName:d,resolveAlias:f,resolveContentEntryPath:p,validateFolderRel:m,extractAgentIdentity:h,extractActorIdentityFromQuery:g,okArtifactKey:_,attributeOkArtifactWrite:v,scheduleOkArtifactFlush:y,flushDiskAndDetectOutcome:b,markAgentWriteStore:S,respondPersistenceFailure:C,respondStaleExternalWrite:w,registerWrittenDocInFileIndex:T,captureAndCloseDocuments:E,captureNamespaceMove:D,renameTrackedPathInGit:O,renamePathOnDisk:k,splitContentPath:A,mutateFileIndex:j}=e;function N(e,t,n=`template`){return!e||!wt.test(e)?(X(t,400,`urn:ok:error:invalid-request`,`Invalid name: must use ${sn}, without the \`.md\` extension.`,{handler:n}),!1):!0}function P(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:W(e,i);if(a!==e&&!a.startsWith(`${e}${Ys}`))continue;let o=W(a,`.ok`),s=MK(o);if(s.kind===`symlink`)return{kind:`refused`,folder:i};if(s.kind===`unverifiable`&&s.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:s.code};let c=W(o,`templates`),l=MK(c);if(l.kind===`symlink`)return{kind:`refused`,folder:i};if(l.kind===`unverifiable`&&l.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:l.code};let u=W(c,`${n}.md`);if(G(u))return{kind:`found`,abs:u,folder:i,scope:t===r.length?`local`:`inherited`}}return{kind:`absent`}}function ee(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function te(e,t){return Qe(e,t)}let F=new Set;function ne(e,t){let n=W(e,`${t}.md`);return F.has(n)||G(n)}let re=D0({GET:Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=m(n.searchParams.get(`path`)??``,t,`path`,`folder-config-get`,`ok`);if(!r)return;let a=W(r.resolvedContentDir,r.folderRel,`.ok`),o=W(a,`frontmatter.yml`),s=[],c=[],l=(e,t)=>{s.push(t),c.push(e)},u=await Bht(r.folderRel,{projectDir:r.resolvedContentDir},{onTemplateRefused:e=>{let t=`${e.folder||`.`}/${e.component}`,n=W(r.resolvedContentDir,e.folder,e.component);switch(e.kind){case`symlink`:l(`templates-symlink-refused`,`${t} is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.`),i.warn({path:n,folder:r.folderRel||`.`},`[folder-config:get] ${t} is a symlink — templates_available skips it.`);break;case`unverifiable`:l(`templates-unverifiable`,`${t} could not be inspected (${e.code??`unknown errno`}) — its templates are not enumerated. The errno may come from ${e.folder||`.`}/.ok itself; check its permissions.`),i.warn({path:n,folder:r.folderRel||`.`,code:e.code},`[folder-config:get] cannot lstat ${t} (${e.code??`unknown errno`}) — templates_available skips it.`);break;default:throw Error(`Unhandled template refusal kind in handleFolderConfigGet: ${String(e.kind)}`)}}}),d=null,f=MK(o);if(f.kind===`symlink`)l(`symlink-refused`,`${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`),i.warn({path:o,folder:r.folderRel||`.`},`[folder-config:get] ${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it.`);else if(f.kind===`unverifiable`)l(`unverifiable`,`${r.folderRel||`.`}/.ok/frontmatter.yml could not be inspected (${f.code??`unknown errno`}) — folder properties skipped.`),i.warn({path:o,code:f.code},`[folder-config:get] cannot lstat ${o} (${f.code??`unknown errno`}) — frontmatter_local skipped.`);else if(G(o))try{let e=await jc(o,`utf-8`),t=(0,rl.parse)(e);d=t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e instanceof Error?e.message:String(e);l(`malformed-yaml`,`${r.folderRel||`.`}/.ok/frontmatter.yml has malformed YAML.`),i.warn({path:o,reason:t},`[folder-config:get] malformed YAML in ${o}: ${t}`),d=null}Q(t,200,une,{folder:u,frontmatter_local:d,...c.length>0?{warnings:s,warningCodes:c}:{}},{handler:`folder-config-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(bn,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=FQ(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let i=m(n.path,t,`path`,`folder-config-put`,`ok`);if(!i)return;let a=[];if(n.frontmatter!==void 0){let r=Ght({anchorDir:i.resolvedContentDir,folderRel:i.folderRel,patch:n.frontmatter});if(!r.ok){let{status:e,urn:n}=rgt[r.error.code];X(t,e,n,e===500?`Failed to write folder config.`:r.error.message,{handler:`folder-config-put`,detail:r.error.code,cause:Error(r.error.message)});return}a.push({path:r.path,action:r.action}),r.action!==`noop`&&(v(e,_(`folder-frontmatter`,i.folderRel),`folder-frontmatter-${r.action===`deleted`?`delete`:`edit`}: ${r.path}`),y(`folder-config-put`))}Q(t,200,jn,{applied:a},{handler:`folder-config-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function ie(e,t,n){let r=l.findByDocName(e);return r!==void 0&&($J(n,new QJ({file:r.file}),t,r),!0)}let ae=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!N(r,t,`template-get`))return;let i=m(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`,`ok-and-templates`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=P(o,a,r);if(s.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${s.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:s.folder||`.`});return}if(s.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${s.folder||`.`}/.ok" (${s.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-get`,detail:s.code??`unknown-errno`});return}if(s.kind===`absent`){X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s;if(MK(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" at "${l||`.`}/.ok/templates/${r}.md" is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}try{jK(c,o)}catch(e){if(PK(e)){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" resolves through a symlink outside the content directory — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}throw e}let d=await jc(c,`utf-8`),f=ct(d),p=f.identity,h=f.starterContent,g=U(o,c).split(/[\\/]/).filter(Boolean).join(`/`);Q(t,200,pi,{template:{name:r,folder:l,scope:u,path:g,frontmatter:p,body:h}},{handler:`template-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),oe=Z(qt,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=FQ(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=n.name;if(!N(i,t,`template-put`))return;let a=m(n.folder,t,`folder`,`template-put`,`ok-and-templates`);if(!a)return;let c=W(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`);if(MK(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`${a.folderRel||`.`}/.ok/templates/${i}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-put`,detail:a.folderRel||`.`});return}if(ie(te(a.folderRel,i),`template-put`,t))return;let l=P3({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:ee(n.frontmatter)});if(!l.ok){X(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:l.error.code,cause:Error(l.error.message)});return}let u=!G(c),d=U(a.resolvedContentDir,c).split(/[\\/]/).filter(Boolean).join(`/`),f=te(a.folderRel,i),{agentId:p,agentName:g,colorSeed:x,clientName:E}=h(n),D=await o.getSession(f,p,{displayName:g,colorSeed:x,clientName:E});D.dc.document.transact(()=>{Rq(D.dc.document,l.content,`agent`)},D.origin),S(f);let O=await b(f);if(O?.kind===`failure`&&!IG(O.failure)){C(t,O.failure,`template-put`);return}if(O?.kind===`stale-external-write`){w(t,`template-put`,f);return}T(f,l.content),v(e,_(`template`,a.folderRel,i),`${u?`template-create`:`template-edit`}: ${d}`),y(`template-put`),Q(t,200,Sre,{...LG(void 0,O),path:d,created:u,warnings:l.warnings},{handler:`template-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),se=Z(x,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!N(r,t,`template-delete`))return;let i=m(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`,`ok-and-templates`);if(!i)return;let a=g(n,s);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ie(te(i.folderRel,r),`template-delete`,t))return;await E([te(i.folderRel,r)],`deleted-upstream`);let o=Xht({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(v(a,_(`template`,i.folderRel,r),`template-delete: ${o.path}`),y(`template-delete`),u?.setDeleted(te(i.folderRel,r))),Q(t,200,M,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});return XQ({"/api/folder-config":re,"/api/template":D0({GET:ae,PUT:oe,POST:Z(tee,async(e,t,r)=>{try{let e=FQ(r,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!N(r.fromName,t,`template-move`)||!N(r.toName,t,`template-move`))return;let a=m(r.fromFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!a)return;let o=m(r.toFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!o||ie(te(a.folderRel,r.fromName),`template-move`,t))return;await E([te(a.folderRel,r.fromName)],`renamed`);let l=D?.(te(o.folderRel,r.toName)),d=await Qht({projectDir:a.resolvedContentDir,fromFolder:a.folderRel,fromName:r.fromName,toFolder:o.folderRel,toName:r.toName,relocate:async(e,t)=>{let r=await O(n,e,t);return r||k(e,t),r}});if(!d.ok){if(d.error.code===`TEMPLATE_NOT_FOUND`){let e=P(a.resolvedContentDir,a.folderRel,r.fromName);if(e.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${e.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-move`,detail:e.folder||`.`});return}if(e.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${e.folder||`.`}/.ok" (${e.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-move`,detail:e.code??`unknown-errno`});return}if(e.kind===`found`&&e.scope===`inherited`){X(t,400,`urn:ok:error:invalid-request`,`Template "${r.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${a.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:d.error.message});return}if(d.error.code===`TEMPLATE_EXISTS`){X(t,409,`urn:ok:error:doc-already-exists`,d.error.message,{handler:`template-move`,detail:d.error.code});return}let e=d.error.code===`WRITE_ERROR`||d.error.code===`MOVE_FAILED`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:d.error.code,cause:Error(d.error.message)});return}l?.(),u?.setDeleted(te(a.folderRel,r.fromName));let f=W(o.resolvedContentDir,d.toPath),p=MK(f).kind===`symlink`;if(v(e,_(`template`,o.folderRel,r.toName),`template-rename: ${d.fromPath} -> ${d.toPath}`,[{from:d.fromPath,to:d.toPath}]),y(`template-move`),c?.(`files`),p){if(i.warn({path:f,folder:o.folderRel||`.`},`[template-move] moved template "${d.toPath}" is a symlink — skipping content read-back and index registration.`),r.body!==void 0||r.frontmatter!==void 0){X(t,400,`urn:ok:error:symlink-refused`,`Template moved to "${d.toPath}", but it is a symlink — refusing to read or rewrite through it. Replace it with a regular file and retry the edit.`,{handler:`template-move`,detail:o.folderRel||`.`});return}Q(t,200,et,{from:d.fromPath,to:d.toPath,committed:d.committed},{handler:`template-move`});return}let h=null;if(r.body!==void 0||r.frontmatter!==void 0){let e;if(typeof r.body==`string`)e=r.body;else try{e=tn(K(f,`utf-8`))}catch{e=null}if(e===null)h={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=Yht({projectDir:o.resolvedContentDir,folder:o.folderRel,name:r.toName,body:e,frontmatter:ee(r.frontmatter)});t.ok||(h=t.error)}}try{T(te(o.folderRel,r.toName),K(f,`utf-8`))}catch{}if(h){let e=h.code===`WRITE_ERROR`||h.code===`READ_FAILED`;X(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${d.toPath}", but updating its content failed.`,{handler:`template-move`,detail:h.code,cause:Error(h.message)});return}Q(t,200,et,{from:d.fromPath,to:d.toPath,committed:d.committed},{handler:`template-move`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:se},{handler:`template`}),"/api/template/import":Z(pt,async(e,n,i)=>{let g;try{if(r){X(n,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=FQ(i,s);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let x=i.sourcePath;if(!d(x)){X(n,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let D=f(x);if(_U(D)||vU(D)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`template-import`});return}let O=p(t,`file`,D);if(!G(O)){X(n,404,`urn:ok:error:doc-not-found`,`Source document not found: ${D}.`,{handler:`template-import`});return}let k=a.documents.get(D);if(i.deleteSource){let e=l.findByDocName(D);if(e!==void 0){$J(n,new QJ({file:e.file}),`template-import`,e);return}}let M=``;if(k)M=k.getText(`source`).toString();else{let e=await a.openDirectConnection(D);try{let t=e.document;if(!t){X(n,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}M=t.getText(`source`).toString()}finally{await e.disconnect()}}let P=i.name;if(!P){let{basename:e}=A(x),t=e.replace(/\.(md|mdx)$/i,``);P=Lee(t).replace(/[^\p{L}\p{M}\p{N}_-]|\p{DI}/gu,`-`).toLowerCase(),P=P.replace(/^[-_]+|[-_]+$/g,``),P||=`imported-template`}if(!N(P,n,`template-import`))return;let ee=m(i.targetFolder,n,`folder`,`template-import`,`ok-and-templates`);if(!ee)return;let re=W(ee.resolvedContentDir,ee.folderRel,`.ok`,`templates`);if(!i.name){let e=P;for(let t=2;ne(re,P);t++)P=`${e}-${t}`}let ae=W(re,`${P}.md`);if(MK(ae).kind===`symlink`){X(n,400,`urn:ok:error:symlink-refused`,`${ee.folderRel||`.`}/.ok/templates/${P}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-import`,detail:ee.folderRel||`.`});return}if(ie(te(ee.folderRel,P),`template-import`,n))return;if(ne(re,P)){X(n,409,`urn:ok:error:doc-already-exists`,`Template "${P}" already exists in "${ee.folderRel||`(root)`}". Choose another name, or edit the existing template instead.`,{handler:`template-import`,detail:`TEMPLATE_EXISTS`});return}F.add(ae),g=ae;let{frontmatter:oe,body:se}=ka(M),ce=ha(oe),le={};try{ce.trim()&&(le=(0,rl.parse)(ce))}catch{}let ue=i.title||le?.title||JY(M,P),de=le?.description||``,fe=Array.isArray(le?.tags)?le.tags:[],pe={...le};delete pe.template,delete pe.title;let me=``;Object.keys(pe).length>0&&(me=`${(0,rl.stringify)(pe).trim()}\n`),me=me?`---\n${me}---\n${se}`:se;let he=P3({name:P,body:me,frontmatter:{title:ue,description:de,tags:fe}});if(!he.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:he.error.code,cause:Error(he.error.message)});return}let ge=!G(ae),_e=U(ee.resolvedContentDir,ae).split(/[\\/]/).filter(Boolean).join(`/`),ve=te(ee.folderRel,P),{agentId:ye,agentName:be,colorSeed:xe,clientName:Se}=h(i),Ce=await o.getSession(ve,ye,{displayName:be,colorSeed:xe,clientName:Se});Ce.dc.document.transact(()=>{Rq(Ce.dc.document,he.content,`agent`)},Ce.origin),S(ve);let we=await b(ve);if(we?.kind===`failure`&&!IG(we.failure)){C(n,we.failure,`template-import`);return}if(we?.kind===`stale-external-write`){w(n,`template-import`,ve);return}T(ve,he.content),v(e,_(`template`,ee.folderRel,P),`template-import: ${_e}`),i.deleteSource&&(await E([D],`deleted-upstream`),u&&u.setDeleted(D),eW(O),j?.({kind:`delete`,path:O,docName:D})),y(`template-import`),c?.(`files`),Q(n,200,ti,{...LG(void 0,we),path:_e,created:ge,warnings:he.warnings},{handler:`template-import`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}finally{g!==void 0&&F.delete(g)}},{handler:`template-import`,method:`POST`})},{mutating:[`/api/folder-config`,`/api/template`,`/api/template/import`]})}function R3(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function agt(e,t){let{git:n}=gK(e,{credentialConfig:[]}),[r,i]=await Promise.allSettled([z8e(n,Gq),Jq(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function ogt(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function sgt(e,t,n,r){let{git:i}=gK(e,{credentialConfig:[]});await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``||i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=agt(e,t).catch(e=>(cgt(e)||q(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${R3(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const z3=`git-branch-info`;function cgt(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const B3=q(`git-checkout`),lgt=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function ugt(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(lgt);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=hc(n)}catch{r=n}return{held:!0,path:r}}const V3=`git-checkout`,dgt=fte;async function fgt(e,t,n){if(n.fastForward&&await pgt(e,t,n.credentialConfig)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r,env:i}=gK(e,{credentialConfig:n.credentialConfig}),a=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!a)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:dgt(e)?`branch-not-found`:`fetch-failed`}}let o;try{o=await SK(r,a?`refs/heads/${t}`:`refs/remotes/origin/${t}`)}catch(e){return B3.warn({branch:t,err:e},`action=checkout-failed branch=${t}`),{ok:!1,reason:`checkout-failed`}}let s=await agt(e,o);if(s.conflicts)return{ok:!1,reason:`dirty-conflict`,files:s.files};try{await wK(r,o,`checkout`,i)}catch(e){return e instanceof CK?(B3.warn({event:`unsafe-incoming-symlinks`,branch:t,target:o,links:e.unsafe.slice(0,50),refusedCount:e.unsafe.length},`action=checkout-refused branch=${t}`),{ok:!1,reason:`unsafe-symlinks`,refusedSymlinkPaths:e.displayPaths()}):(B3.warn({branch:t,target:o,err:e},`action=symlink-check-failed branch=${t}`),{ok:!1,reason:`symlink-check-failed`})}let c=()=>r.raw([`symbolic-ref`,`--quiet`,`HEAD`]).then(e=>e.trim()).catch(()=>``),l=`refs/heads/${t}`,u=await c(),d=!1;try{return a||(await r.raw([`branch`,`--no-track`,t,o]),d=!0,await r.raw([`branch`,`--set-upstream-to=refs/remotes/origin/${t}`,t])),await r.raw([`checkout`,t]),{ok:!0}}catch(e){if(u!==l&&await c()===l)return B3.warn({branch:t,target:o,err:e},`action=checkout-hook-failed branch=${t} error=${R3(e)}`),{ok:!0};d&&await r.raw([`branch`,`-D`,t]).catch(e=>{B3.warn({branch:t,target:o,err:e},`action=checkout-cleanup-failed branch=${t}`)});let n=ugt(e);return n.held?(B3.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(B3.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${R3(e)}`),{ok:!1,reason:`checkout-failed`})}}async function pgt(e,t,n){let{git:r}=gK(e,{timeoutMs:15e3,credentialConfig:n}),i=e=>r.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await r.raw([`fetch`,`origin`,t])}catch(e){return B3.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${R3(e)}`),`unavailable`}let a=await i(`refs/remotes/origin/${t}`);if(!a)return`unavailable`;let o=await i(`refs/heads/${t}`);if(!o||o===a)return`up-to-date`;let s=await r.raw([`merge-base`,o,a]).then(e=>e.trim()).catch(()=>``);if(s===o){try{await r.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return B3.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${R3(e)}`),`unavailable`}return await i(`refs/heads/${t}`)===a?`advanced`:`unavailable`}return s===a?`up-to-date`:`diverged`}const H3=q(`git-worktree-status`);function U3(e){return Ge.includes(e)?e:`M`}function mgt(e,t){let n=[],r=[],i=[];for(let a of e){let e=t(a.path);if(a.x===`?`||a.y===`?`){i.push({path:a.path,code:`?`,syncScoped:e});continue}a.x!==`!`&&a.y!==`!`&&(a.x!==` `&&a.x!==``&&n.push({path:a.path,code:U3(a.x),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}),a.y!==` `&&a.y!==``&&r.push({path:a.path,code:U3(a.y),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}))}let a=n.length>100||r.length>100||i.length>100,o=e=>[...e.filter(e=>e.syncScoped),...e.filter(e=>!e.syncScoped)].slice(0,100);return{staged:o(n),notStaged:o(r),untracked:o(i),truncated:a}}const hgt=[`unknown revision or path not in the working tree`,`no upstream configured for branch`,`does not point to a branch`,`no such branch`];function ggt(e){let t=e instanceof Error?e.message:String(e??``);return hgt.some(e=>t.includes(e))}async function _gt(e,t){let n;try{n=await Yq(e,[`diff`,`--name-status`,`HEAD...@{upstream}`])}catch(e){return!t?.aborted&&!ggt(e)&&H3.warn({event:`worktree-incoming-read-failed`,err:e},`[sync] incoming-change read failed — panel shows nothing incoming`),[]}return n.map(e=>({path:e.to,code:U3(e.status.charAt(0)),syncScoped:!0,...e.status.charAt(0)===`R`||e.status.charAt(0)===`C`?{origPath:e.from}:{}}))}async function vgt(e,t,n,r={}){let i={readable:!0,branch:null,detached:!1,upstream:null,staged:[],notStaged:[],untracked:[],incoming:[],truncated:!1},{git:a}=gK(e,{credentialConfig:[],timeoutMs:r.timeoutMs??1e4,...r.abortSignal===void 0?{}:{abortSignal:r.abortSignal}}),o=Date.now(),[s,c,l,u]=await Promise.allSettled([B8e(a,Gq),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`HEAD`]),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`@{upstream}`]),_gt(a,r.abortSignal)]),d=c.status===`fulfilled`?c.value.trim():``,f=d===`HEAD`,p=f||d===``?null:d,m=r.abortSignal?.aborted===!0,h=s.status===`rejected`,g=(e,t,n)=>{e.status===`rejected`&&(m||h||ggt(e.reason)||H3.warn({event:t,err:e.reason,elapsedMs:Date.now()-o,branch:p},`[sync] ${n}`))};if(g(c,`worktree-branch-read-failed`,`branch read failed — panel shows no branch`),g(l,`worktree-upstream-read-failed`,`upstream read failed — panel shows no upstream`),s.status===`rejected`)return m||H3.error({event:`worktree-read-failed`,err:s.reason,elapsedMs:Date.now()-o,branch:p},`[sync] worktree status read failed — panel listing marked unreadable`),{...i,readable:!1};let _=l.status===`fulfilled`&&l.value.trim()||null,v=u.status===`fulfilled`?u.value:[],y=mgt(s.value,t),b=e=>n?e.map(e=>{let t=n(e.path);return t===void 0?e:{...e,open:t}}):e;return{readable:!0,branch:p,detached:f,upstream:_,staged:b(y.staged),notStaged:b(y.notStaged),untracked:b(y.untracked),truncated:y.truncated||v.length>100,incoming:b(v.slice(0,100))}}function ygt(e){let{projectDir:t,contentDir:n,contentFilter:r,getFileIndex:i,checkLocalOpSecurity:a,getSyncEngine:o,getPrincipal:s,resolveCredentialConfig:c}=e;function l(e){let a=H(t??n,e),o=lG(U(n,a));if(!o||o.startsWith(`..`))return;let s=UH(o);if(i().has(s))return{kind:`doc`,docName:s};if(r&&!r.isExcluded(o,{bypassFilters:!0,showOk:!0})&&G(a))return{kind:`asset`,path:o}}async function u(e,r){if(!a(e,r,{handler:`git-worktree-status`}))return;if(e.method!==`GET`){X(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`git-worktree-status`,extraHeaders:{Allow:`GET`}});return}let i=new AbortController;r.on(`close`,()=>{r.writableEnded||i.abort()});try{let e=o?.(),a=await vgt(t??n,e?t=>e.isSyncScopedPath(t):()=>!1,l,{abortSignal:i.signal});if(r.writableEnded||r.destroyed)return;Q(r,200,Mie,a,{handler:`git-worktree-status`})}catch(e){if(r.writableEnded||r.destroyed)return;X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`git-worktree-status`,cause:e})}}return XQ({"/api/git/branch-info":Z(x,async(e,n)=>{try{if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:z3});return}let r=sG(e),i=r.get(`branch`),a=r.get(`path`),o=r.get(`kind`)===`folder`?`folder`:`doc`;if(!dre(i)){X(n,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:z3});return}if(!ogt(a,o)){X(n,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:z3});return}let s=await sgt(t,i,a,o);Q(n,200,Cn,s,{handler:z3})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:z3,cause:e})}},{handler:z3,method:`GET`,skipBodyParse:!0}),"/api/git/worktree-status":u,"/api/git/checkout":Z(ir,async(e,n,r)=>{if(FQ(r,s).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:V3});return}if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:V3});return}try{let e=await c(),i=await hK(()=>fgt(t,r.branch,{fastForward:r.fastForward===!0,credentialConfig:e}));Q(n,200,Je,i,{handler:V3})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:V3,cause:e})}},{handler:V3,method:`POST`})},{mutating:[`/api/git/checkout`]})}function bgt(){let e=new Map;return{run(t,n){let r=e.get(t);if(r)return{promise:r,coalesced:!0};let i=n();e.set(t,i);let a=()=>{e.get(t)===i&&e.delete(t)};return i.then(a,a),{promise:i,coalesced:!1}},get size(){return e.size}}}function W3(e,t,n){return t!==null&&uG(e,t)?lG(U(t,e)):uG(e,n)?`~/${lG(U(n,e))}`:lG(e)}const xgt=q(`edit-backups`),Sgt=/^(?!.*__)[A-Za-z0-9.-](?:[A-Za-z0-9._-]*[A-Za-z0-9.-])?$/;function Cgt(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`__`),n=[_n,Dn,sne].find(t=>e.startsWith(t));if((n===void 0?e:e.slice(n.length)).split(`/`).every(e=>Sgt.test(e)))return t;let r=e.normalize(`NFC`),i=Rc(`sha256`).update(r).digest(`hex`).slice(0,12);return`${r.replace(/[^A-Za-z0-9._-]+/g,`__`).replace(/^\.+/,`_`).slice(0,100)}-${i}`}function wgt(e,t,n){let r=W(sS(e),`edit-backups`,`discarded`),i=Cgt(n);return t===null?W(r,i):W(r,`projects`,Vi(t),i)}async function Tgt(e,t,n,r,i){try{let a=wgt(e,t,n);await qU(a,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,`-`),s=W(a,`${o}${Ws(i)}`);await uS(s,r,{fs:oW});let c=mc(a).sort();for(let e of c.slice(0,Math.max(0,c.length-5)))try{eW(W(a,e))}catch{}pQe();let l={abs:s,display:W3(s,null,e)};return xgt.info({documentName:n,backup:l.display},`a displaced version was kept in the backup folder`),l}catch(e){return mQe(),xgt.warn({documentName:n,err:e},`a displaced version could not be kept in the backup folder`),null}}function G3(e){return{kind:`held`,cause:e}}function K3(e,t){return{kind:`held`,cause:`not-utf8`,path:e,observation:t}}function Egt(e){switch(e.cause){case`no-history-or-backup`:case`keeps-changing`:case`not-utf8`:case`unreadable`:return e.cause;case`edits-changing`:return null;default:return Dgt(e)}}function Dgt(e){throw Error(`unhandled save hold: ${JSON.stringify(e)}`)}const Ogt=[50,200,800],q3=new Set([`ENOENT`,`ENOTDIR`]),kgt=new Set([`EBUSY`,`EAGAIN`,`EINTR`,`EMFILE`,`ENFILE`]),Agt=new Set([`EPERM`,`EACCES`]);var jgt=class extends Error{code=`EAGAIN`;constructor(){super(`the file changed while it was being read for the pre-write compare`),this.name=`FileChangedDuringReadError`}},J3=class extends Error{constructor(e){super(`the file for ${e} changed between the pre-write compare and the rename`),this.name=`StoreRestatRefusedError`}},Y3=class extends Error{code;constructor(e,t){super(`the file for ${e} could not be re-read before the rename`,{cause:t}),this.name=`StoreRestatFailedError`,this.code=cG(t)}};function Mgt(e){throw Error(`unhandled disk compare outcome: ${e.kind}`)}function Ngt(e,t=process.platform){if(e instanceof jgt)return!0;let n=cG(e);return n===void 0?!1:kgt.has(n)?!0:t===`win32`&&Agt.has(n)}function X3(e){return{size:e.size,mtimeNs:e.mtimeNs,dev:e.dev,ino:e.ino}}function Pgt(e,t){return e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.dev===t.dev&&e.ino===t.ino}function Fgt(e,t=$U,n=process.platform){let r;try{r=t(e.path)}catch(e){let t=cG(e);return t!==void 0&&q3.has(t)?{kind:`absent`}:{kind:`unreadable`,error:e,transient:Ngt(e,n)}}let i=X3(r.before);if(!Pgt(i,X3(r.after))||BigInt(r.bytes.byteLength)!==r.before.size)return{kind:`unreadable`,error:new jgt,transient:!0};let a=r.bytes.toString(`utf8`),o=dG(a),s=e.receiptHash??e.baseHash;return o===e.candidateHash?{kind:`match`,observation:i,alreadyCandidate:!0}:o===s?{kind:`match`,observation:i,alreadyCandidate:!1}:e.baseHash!==void 0&&o===e.baseHash?{kind:`drift`,observation:i}:{kind:`changed`,text:a,lossless:Buffer.from(a,`utf8`).equals(r.bytes),observation:i}}function Z3(e,t=$U){let n;try{n=t(e)}catch(e){let t=cG(e);return t!==void 0&&q3.has(t)?{kind:`absent`}:{kind:`failed`,error:e}}let r=n.bytes.toString(`utf8`);return{kind:`read`,text:r,lossless:Buffer.from(r,`utf8`).equals(n.bytes),observation:X3(n.before)}}function Q3(e,t){let n;try{n=yc(e,{bigint:!0})}catch(e){let t=cG(e);if(t===void 0||!q3.has(t))return{kind:`failed`,error:e};n=void 0}return t===null?n===void 0?{kind:`same`}:{kind:`moved`}:n!==void 0&&Pgt(t,X3(n))?{kind:`same`}:{kind:`moved`}}function $3(e){try{let t=yc(e,{bigint:!0,throwIfNoEntry:!1});return t?X3(t):void 0}catch{return}}function Igt(e){return e.receiptHash===void 0?`outside`:e.eventHash===e.receiptHash?`own-write`:e.isRecentOwnWrite&&e.readDiskHash()===e.receiptHash?`superseded`:`outside`}function Lgt(e){switch(e){case`own-write`:return`echo`;case`superseded`:return`superseded`;case`outside`:return null;default:return Rgt(e)}}function Rgt(e){throw Error(`unhandled receipt intake decision: ${String(e)}`)}const e6=q(`managed-artifact-persistence`);function zgt(e){if(typeof e==`object`)return!1;switch(e){case`persisted`:case`merged`:case`both-kept`:case`kept-live`:case`stash-fallback`:return!0;case`no-op`:case`write-failed`:case`applied`:case`unchanged`:case`outside-taken-in`:case`dropped-legacy-name`:case`dropped-unresolvable`:case`dropped-container-gone`:case`dropped-intake-landed`:return!1;default:return Bgt(e)}}function Bgt(e){throw Error(`unhandled skill store outcome: ${String(e)}`)}function t6(e){return e.homedirOverride??wc()}function Vgt(e){let t=k(e);return t===null||t.kind!==`skill`||t.scope!==`project`?null:{docKey:`${y}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}}function n6(e){if(!k(e))return{managed:!1};let t=Vgt(e);return t?{managed:!0,versioned:!0,docKey:t.docKey,filePath:`${t.docKey}/SKILL.md`}:{managed:!0,versioned:!1}}function Hgt(e){let t=t6(e);return Wst(t).filter(e=>G(W(t,br(U(t,e).split(Ys).join(`/`)))))}function Ugt(e){return G(`${e}.md`)?`${e}.md`:G(`${e}.mdx`)?`${e}.mdx`:`${e}.md`}function Wgt(e,t,n,r=null){if(!Ce.test(t)||t.length>64)throw Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(t)}`);if(r!==null&&(!Ce.test(r)||r.length>64))throw Error(`managedSkillBundleDir: invalid host qualifier: ${JSON.stringify(r)}`);let i=e===`global`?t6(n):n.projectDir;if(e!==`global`)return W(i,`.ok`,`skills`,t);if(r!==null){let e=F1(i,`global`).find(e=>e.editor===r);return e===void 0?null:W(i,e.root,t)}let a=K1(i,t),o=W(i,`.ok`,`skills`,t);if(a!==null)return a;if(G(W(o,`SKILL.md`)))return o;let s=R1(i,`global`);return s===null?null:W(i,s,t)}function Ggt(e,t){let n=yr(e);if(n!==null){let e=A1(n.name,null);return e===null?null:V(e)}let r=k(e);return r===null||r.kind!==`skill`?null:Wgt(r.scope,r.name,t,r.host)}function r6(e,t){let n=yr(e);if(n!==null){let t=A1(n.name,n.rel);if(t===null)throw Error(`managedArtifactAbsPath: external skill not registered: ${e}`);return n.rel===null?t:Ugt(t)}let r=k(e);if(r===null||r.kind!==`skill`)throw Error(`managedArtifactAbsPath: not a managed skill doc name: ${e}`);let i=Wgt(r.scope,r.name,t,r.host);if(i===null)throw Error(`managedArtifactAbsPath: no usable skill home for ${e}`);let a;if(r.rel===null)a=W(i,`SKILL.md`);else{let t=r.rel.split(`/`).filter(e=>e!==``&&e!==`.`);if(t.length===0||t.some(e=>e===`..`))throw Error(`managedArtifactAbsPath: invalid skill file path for ${e}`);a=Ugt(W(i,...t))}if(!a.startsWith(i+Ys))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return a}function Kgt(e,t){let n=W(e),r=t6(t),i=F1(r,`global`);for(let e of Wst(r)){let t=W(e);if(!n.startsWith(t+Ys))continue;let a=n.slice(t.length+1).split(Ys),o=a[0];if(o&&Ce.test(o)&&o.length<=64&&a.length>=2){let e=W(t,o),n=K1(r,o),s=``;if(n!==null&&W(n)!==e){let e=i.find(e=>W(r,e.root)===t)?.editor;e!==void 0&&(s=`@${e}`)}let c=a.slice(1);if(c.length===1&&c[0]===`SKILL.md`)return`${_n}global/${o}${s}`;let l=c[c.length-1]??``;if(/\.mdx?$/i.test(l)&&!c.includes(`..`)){let e=c.join(`/`).replace(/\.mdx?$/i,``);return`${_n}global/${o}${s}/${e}`}}return null}return null}function qgt(e,t,n){let r=k(t);if(r?.kind===`skill`&&r.scope===`project`||t.startsWith(`__template__/`))return;let i=yr(t);if(i&&A1(i.name,i.rel)===null||e.getXmlFragment(`default`).length>0)return;let a=r6(t,n);if(!G(a))return;let o;try{o=K(a,`utf-8`)}catch(e){e6.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}e.transact(()=>{d$(e,o,void 0,t),e.getMap(`lifecycle`).set(el,crypto.randomUUID())},u$),n.setReconciledBase(t,o),n.lkgCache.set(t,o)}async function Jgt(e,t,n){if(t.rel===null)try{if(!G(e))return;let r=W(sS(t6(n)),`edit-backups`,t.name),i=W(r,`SKILL.md.bak`);if(G(i))return;await qU(r,{recursive:!0}),await uS(i,K(e,`utf-8`),{fs:oW})}catch(e){e6.warn({name:t.name,err:e},`external-skill backup failed`)}}function i6(e,t,n,r,i){let a=i.beforeReconcileDivergence?.(e,t,n,r);e.transact(()=>{d$(e,r,void 0,t,void 0,a)},u$)}function a6(e,t,n){n.setReconciledBase(e,t),n.lkgCache.set(e,t)}var Ygt=class extends Error{constructor(e){super(`the version of ${e} here changed while the merge was being written`),this.name=`LiveMovedOnError`}};async function o6(e,t,n,r,i){try{return await uS(e,n,{fs:oW,beforeRename:()=>{let n=Q3(e,r);if(n.kind===`failed`)throw new Y3(t,n.error);if(n.kind===`moved`)throw new J3(t);if(i!==void 0&&!i())throw new Ygt(t)}}),`written`}catch(e){if(e instanceof J3)return sU(),`moved`;if(e instanceof Ygt)return`moved`;if(e instanceof Y3)return`unreadable`;throw e}}async function Xgt(e,t,n,r,i,a){let o=a===`store`?`skill-store`:`skill-intake`,s=e=>(lU(a,e),e),c=e=>(lU(a,`held`),e);if(!n.lossless)return e6.info({documentName:t},`the file changed outside to bytes that are not valid UTF-8; nothing was applied or written so they stay on disk`),c(K3(r,n.observation));let l=e.getText(`source`).toString(),u=i.getReconciledBase(t)??i.lkgCache.get(t)??``;if(l===u)return i6(e,t,l,n.text,i),a6(t,n.text,i),s(`applied`);let d=cY({docName:t,base:u,ours:l,theirs:n.text});switch(d.kind){case`noop`:return s(`unchanged`);case`clean`:return i6(e,t,l,d.newContent,i),a6(t,d.newContent,i),s(`applied`);case`merged`:case`both-kept`:{let a=await o6(r,t,d.newContent,n.observation,()=>e.getText(`source`).toString()===l&&(i6(e,t,l,d.newContent,i),!0));return a===`moved`?`retry`:a===`unreadable`?c(G3(`unreadable`)):(a6(t,d.newContent,i),d.kind===`merged`?s(`merged`):(i.history?.bothKept(t,{ours:l,theirs:n.text},d.kept),v$(t,d.kept,o),s(`both-kept`)))}case`refused`:{_$(t,d,o);let a=i.history!==null&&await i.history.keptLive(t,{side:`theirs`,bytes:n.text},d.reason),l=a?null:await Tgt(t6(i),null,t,n.text,`SKILL.md`);if(!a&&l===null)return e6.warn({documentName:t,reason:d.reason},`the outside version could not be merged or kept in history or the backup folder; nothing was written so it stays on disk`),c(G3(`no-history-or-backup`));l!==null&&i.history?.noticeBackup(t,`theirs`,d.reason,l);let u=Z3(r);if(u.kind!==`read`||u.text!==n.text)return`retry`;let f=await o6(r,t,e.getText(`source`).toString(),u.observation);return f===`moved`?`retry`:f===`unreadable`?c(G3(`unreadable`)):(a6(t,e.getText(`source`).toString(),i),a?(y$(t,d.reason,o),s(`kept-live`)):(e6.warn({documentName:t,reason:d.reason,backup:l?.display},`the outside version could not be merged or saved to history; it was kept in the backup folder and the version here stays`),s(`stash-fallback`)))}default:throw Error(`unhandled reconcile outcome: ${String(d)}`)}}async function Zgt(e,t,n,r){let i=k(t);if(i?.kind===`skill`&&i.scope===`project`||t.startsWith(`__template__/`))return`dropped-legacy-name`;let a=yr(t);if(a&&A1(a.name,a.rel)===null)return`dropped-unresolvable`;let o=e.getText(`source`).toString()===r.lkgCache.get(t);if(n===u$)return o?`outside-taken-in`:`dropped-intake-landed`;if(o)return`no-op`;let s=Ggt(t,r);if(s===null)return`dropped-unresolvable`;if(!G(s))return e6.warn({documentName:t,containerDir:s},`store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it`),`dropped-container-gone`;let c=r6(t,r);try{return await qU(W(c,`..`),{recursive:!0}),a&&await Jgt(c,a,r),await fS(`${c}.lock`,async()=>{for(let n=0;n<3;n++){let n=e.getText(`source`).toString(),i=r.lkgCache.get(t);if(n===i)return`no-op`;let a=Z3(c);if(a.kind===`failed`)return lU(`store`,`held`),e6.warn({documentName:t,err:a.error},`store: the file could not be read for the compare before the write; nothing was written`),G3(`unreadable`);let o=r.getReconciledBase(t)??i;if(a.kind===`read`&&a.text!==i&&a.text!==o&&a.text!==n){sQe();let n=await Xgt(e,t,a,c,r,`store`);if(n===`retry`)continue;return n}let s=await o6(c,t,n,a.kind===`read`?a.observation:null);if(s!==`moved`)return s===`unreadable`?(lU(`store`,`held`),G3(`unreadable`)):(a6(t,n,r),`persisted`)}return lU(`store`,`held`),e6.warn({documentName:t,rounds:3},`store: the file kept changing outside while it was being saved; nothing more was written`),G3(`keeps-changing`)})}catch(e){return e instanceof dS?(e6.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(e6.warn({documentName:t,err:e},`store: write failed`),`write-failed`)}}async function Qgt(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);if(i!==void 0&&i===n)return`no-op`;if(e.getText(`source`).toString()===n)return a6(t,n,r),`no-op`;let a=r6(t,r);try{return await fS(`${a}.lock`,async()=>{let i=Z3(a);if(i.kind!==`read`||i.text!==n)return`no-op`;let o=await Xgt(e,t,i,a,r,`intake`);return o===`retry`?`no-op`:typeof o==`object`?`held`:o})}catch(e){if(!(e instanceof dS))throw e;return lU(`intake`,`held`),e6.warn({documentName:t,err:e},`intake: the file lock timed out, so the outside change was not taken in; the next save compares it`),`held`}}function $gt(e){return e<=0?`0`:e===1?`1`:e<=5?`2-5`:e<=20?`6-20`:e<=50?`21-50`:`50+`}function e_t(e){return e<=0?`0`:e<=50?`1-50`:e<=200?`51-200`:e<=500?`201-500`:`500+`}let t_t=null,n_t=null;function r_t(){return t_t||=PU().createHistogram(`ok.timeline.query_duration_ms`,{description:`Wall-clock duration of one history query. Bounded labels: width_bucket (ref fan-out), commits_bucket (commits gathered), capped (depth bound hit), error (the walk threw — e.g. the PRD-6972 git timeout). The error label is what separates a timeout storm from a burst of legitimately-empty docs, both of which otherwise record width/commits 0.`,unit:`ms`}),t_t}function i_t(){return n_t||=PU().createCounter(`ok.timeline.coalesced_total`,{description:`History requests served by an in-flight single-flight walk instead of a fresh git walk. Bounded label: mode ∈ {doc, folder}. A high value is the poll-storm / fan-out signal.`}),n_t}function a_t(e){r_t().record(Math.max(0,e.durationMs),{width_bucket:$gt(e.width),commits_bucket:e_t(e.commits),capped:e.capped,error:e.error??!1})}function o_t(e){i_t().add(1,{mode:e})}const s6=q(`timeline`);function s_t(e,t){return Math.min(500,3*(Math.max(0,e)+Math.max(1,t)))}const c6=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,l6={entries:[],total:0,hasMore:!1},c_t=/^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;function l_t(e){return c_t.test(e)}function u_t(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function u6(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=u_t(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:Zx(s),checkpoint:c===`checkpoint`?Ee(s):null,rawBody:s}}).filter(e=>e!==null&&e.sha.length===40):[]}function d6(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let d_t=null;function f_t(){return d_t||=PU().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),d_t}let p_t=null;function m_t(){return p_t||=PU().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),p_t}function f6(e,t){return t.length===0||t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function h_t(e,t,n){return e.length===0||t.length===0?e:e.filter(e=>{let r=Xx(e.rawBody);if(r.length===0)return!0;let i=new Set;for(let e of r){for(let t of e.docs)i.add(t);if(e.previous_paths)for(let t of e.previous_paths)i.add(t.from),i.add(t.to)}if(i.size===0)return!0;for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!(o!==null&&!o.has(e.sha))&&i.has(a.path))return!0}return!1})}async function g_t(e,t,n,r,i,a,o){if(t.length===0||n.length===0)return t;let s=await Promise.all(n.map(async t=>{if(t.renameCommit===null)return null;let n=await I$(e,t.renameCommit,r,o,t.anchors);return n.length===0?new Set:R$(e,n,r,a)})),c=[];for(let e=0;e<t.length;e++){let r=t[e];for(let t=0;t<n.length;t++){let a=n[t],o=s[t];if(!(o!==null&&!o.has(r.sha)))for(let t of i(a.path))c.push({entryIdx:e,sha:r.sha,path:t})}}if(c.length===0)return[];let l=await Jat(e,c.map(e=>({sha:e.sha,path:e.path}))),u=new Set;for(let e=0;e<c.length;e++)l[e]&&u.add(c[e].entryIdx);return t.filter((e,t)=>u.has(t))}async function __t(e,t,n,r,i){if(t.length<2||n.length===0)return t;let a=new Set(n.map(e=>e.renameCommit).filter(e=>e!==null)),o=e=>e.type===`checkpoint`||a.has(e.sha),s=[];for(let e=0;e<t.length;e++)if(!o(t[e]))for(let a=0;a<n.length;a++){let o=r[a];o!==null&&!o.has(t[e].sha)||s.push({entryIdx:e,sha:t[e].sha,path:i(n[a].path)})}if(s.length===0)return t;let c=await Yat(e,s.map(e=>({sha:e.sha,path:e.path}))),l=t.map(()=>null);for(let e=0;e<s.length;e++){let t=s[e].entryIdx;l[t]===null&&c[e]!==null&&(l[t]=c[e])}let u=new Set,d=null,f=-1;for(let e=t.length-1;e>=0;e--){if(o(t[e]))continue;let n=l[e];if(n!==null){if(d!==null&&n===d){t[e].type!==`upstream`&&t[f].type===`upstream`?(u.add(f),f=e):u.add(e);continue}d=n,f=e}}return u.size===0?t:t.filter((e,t)=>!u.has(t))}async function v_t(e,t,n=`.`,r){if(!G(e.workTree)||!G(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return l6;let i=t.branch??`main`,a=Math.max(1,t.limit??50),o=Math.max(0,t.offset??0),s=s_t(o,a),c=performance.now(),l=!1,u=(e,t,n=!1)=>a_t({durationMs:performance.now()-c,width:e,commits:t,capped:l,error:n}),d=d6(t.type),f=d6(t.author),p=d6(t.excludeAuthor),m=t.includeAutoCheckpoints??!1,h=n===`.`?``:n.replace(/^\.\//,``),g=e=>h?`${h}/${e}${qH(e)}`:`${e}${qH(e)}`,_=e=>{let t=g(e),n=UXe(t,e);return n?[t,n]:[t]},v=t.docName?n6(t.docName):{managed:!1},y=v.managed&&v.versioned?v.filePath:void 0,b=v.managed&&v.versioned?v.docKey:t.docName,x=t.docName?y?h?`${h}/${y}`:y:g(t.docName):void 0;try{let n=r?.renameLogIndex??N$(e.gitDir),{chain:c,skipped:h}=await FU(`rename.expandPredecessors`,void 0,async()=>t.docName?Vat(b,i,n):{chain:[],skipped:0}),v=c.length>1;t.docName&&f_t().record(c.length),h>0&&m_t().add(h);let y=Hat(),S=F$(),C=OJ(e);if(d.length===1&&d[0]===`checkpoint`){let t=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${i}/`)).trim().split(`
|
|
1132
1132
|
`).filter(e=>e.length===40),n=[];if(i!==`main`)try{n=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
|
|
@@ -2095,11 +2095,11 @@ tags: [lore, history]
|
|
|
2095
2095
|
`))if(r.startsWith(`p`)){let e=Number.parseInt(r.slice(1),10);n=Number.isNaN(e)?null:e}else r.startsWith(`n`)&&r.length>1&&n!==null&&!t.has(n)&&t.set(n,r.slice(1));return t}function qTt(e){let t=Bs(`lsof`,[`-p`,e.join(`,`),`-a`,`-d`,`cwd`,`-Fn`],cW({encoding:`utf-8`,timeout:v5}));return t.error==null?{cwds:KTt(t.stdout??``),queryFailed:!1}:{cwds:new Map,queryFailed:!0}}function x5(e){if(e.length===0)return new Map;let t=qTt(e);if(!t.queryFailed||e.length===1)return t.cwds;let n=new Map;for(let t of e){let e=qTt([t]).cwds.get(t);e!==void 0&&n.set(t,e)}return n}async function JTt(e=!1){let t=new Set,n=!0,r=await NTt(`lsof`,DTt,e=>{if(n){n=!1;return}let r=e.trim().split(/\s+/),i=Number.parseInt(r[1]??``,10);Number.isNaN(i)||t.add(i)}),i=r.code===1&&!r.hasStdout&&!r.hasStderr;if(r.signal||r.code===null||e&&r.code!==0&&!i)throw Error(PTt(r));return[...t]}function YTt(e){return G(H(e,`server.lock`))}function S5(e,t){for(let n of[H(t,`.ok`,`local`),H(t,`.ok`)])G(n)&&YTt(n)&&e.add(n)}function XTt(e,t){let n=0,r=(t,i)=>{if(n>=ETt||(n++,S5(e,t),i>=3))return;let a;try{a=mc(t)}catch{return}for(let e of a){if(n>=ETt)return;if(e===`node_modules`||e===`.git`||e===`Library`||e.startsWith(`.`)&&e!==`.ok`)continue;let a=H(t,e),o=!1;try{o=cc(a).isDirectory()}catch{continue}o&&r(a,i+1)}};r(t,0)}async function ZTt(){let e=new Set,t=await LTt(),n=x5(t.map(e=>e.pid)),r=t.map(e=>n.get(e.pid)??null);for(let n of t){let t=ATt(n.command);t!=null&&G(t)&&e.add(t);let r=jTt(n.command);r!=null&&S5(e,r)}for(let t of r)t!=null&&S5(e,t);let i=await JTt().catch(()=>null);if(i!==null){let n=new Set(t.map(e=>e.pid)),r=i.filter(e=>!n.has(e)),a=x5(r),o=r.map(e=>a.get(e)??null);for(let t of o)t!=null&&S5(e,t)}(e.size===0||r.some(e=>e===`/`))&&XTt(e,process.cwd());let a=new Map;for(let t of e)try{let e=await Nc(t);a.set(e,e)}catch{a.set(t,t)}return[...a.values()]}function QTt(){let e=new Set;return t=>({onProbeFailure:n=>{e.has(t)||(e.add(t),process.stderr.write(VTt(n)))}})}async function $Tt(e=QTt()){let t={candidates:[],unavailable:[]},n;try{n=await LTt(!0)}catch(e){return t.unavailable.push(e instanceof Error?e.message:String(e)),t}let r=async(e,n,r)=>{let i=await Nc(e).catch(()=>W(e));t.candidates.push({lockDir:i,pid:n,source:r})},i=async(e,t,n)=>{await r(H(e,`.ok`,`local`),t,n),await r(H(e,`.ok`),t,n)},a=[];for(let e of n){if(!nJ(e.pid))continue;let t=ATt(e.command),n=jTt(e.command);t?await r(t,e.pid,`lock-dir-argument`):n?await i(n,e.pid,`project-argument`):a.push({pid:e.pid,source:`process-cwd`})}let o=[],s=``;try{o=await JTt(!0)}catch(e){s=`Could not enumerate TCP listeners: lsof (${DTt.join(` `)}): ${y5(e)}`}let c=new Set(n.map(e=>e.pid));for(let e of o)nJ(e)&&!c.has(e)&&a.push({pid:e,source:`listener-cwd`});let l=x5(a.map(({pid:e})=>e));for(let{pid:n,source:r}of a){let a=l.get(n);a?await i(a,n,r):GTt(n,e(n))&&t.unavailable.push(`Could not read the working directory of process ${n}`)}s&&t.unavailable.push(s);let u=new Set;for(let n of new Set(t.candidates.map(e=>e.pid)))UTt(n,e(n))&&u.add(n);return t.candidates=t.candidates.filter(e=>!u.has(e.pid)),t}function eEt(e,t){if(e===t)return!0;let n=t.endsWith(Ys)?t:t+Ys;return e.startsWith(n)}function tEt(e,t){return U(e,t).split(Ys).join(`/`).replace(/\.(md|mdx)$/i,``)}async function C5(e,t){let n=await t.realpath(W(e)).catch(()=>W(e)),r=await t.discover(),i=await Promise.all(r.map(e=>t.inspect(e).catch(()=>null))),a=null;for(let e of i)e===null||!e.alive||eEt(n,e.contentDir)&&(a===null||e.contentDir.length>a.contentDir.length)&&(a=e);return a===null?null:{baseUrl:a.baseUrl,docName:tEt(a.contentDir,n)}}function nEt(e){return V(V(e))}function rEt(){return{discover:()=>ZTt(),realpath:e=>Nc(e).catch(()=>e),inspect:async e=>{let t=nEt(e),n;try{let e=oS({absPath:pS(`project`,t),sideline:!1,warn:()=>{}}).value.content?.dir??`.`,r=W(t,e);n=await Nc(r).catch(()=>r)}catch(t){return process.stderr.write(`[off-cwd-resolver] skipping ${e} (config unreadable): ${t instanceof Error?t.message:String(t)}\n`),null}let r=N4(e),i=r!=null&&P4(r)?D4(r):null,a=i??`http://localhost:${r?.port??0}`,o=r!=null&&r.draining!==!0&&i!==null&&tJ(r.pid);return{lockDir:e,contentDir:n,baseUrl:a,alive:o}}}}const iEt={detached:!0,stdio:`ignore`},w5=new Map;function aEt(e,t){let n=t.sleep??Ri,r=t.now??(()=>Date.now()),i=t.pollIntervalMs??500,a=t.timeoutMs??15e3;return(async()=>{let o=await t.realpath(W(e)).catch(()=>W(e)),s=w5.get(o);if(s)return s;let c=(async()=>{let e=()=>t.isServing(o).catch(()=>!1);if(await e())return!0;t.spawnSession(o);let s=r()+a;for(;r()<s;)if(await n(i),await e())return!0;return!1})().finally(()=>{w5.delete(o)});return w5.set(o,c),c})()}function oEt(){let e={spawnSession:e=>{if(!BH(e)||!G(e))return;let t=process.argv[1];if(!t){process.stderr.write(`[ensure-single-file-session] process.argv[1] is empty — cannot spawn a single-file session
|
|
2096
2096
|
`);return}let n={...process.env,OK_SINGLE_FILE_NO_OPEN:`1`,ELECTRON_RUN_AS_NODE:`1`};zs(process.execPath,[t,e],cW({...iEt,env:n})).unref()},isServing:async e=>await C5(e,rEt())!==null,realpath:e=>Nc(e).catch(()=>e)};return t=>aEt(t,e)}const sEt=new Nae;function cEt(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e}var lEt=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??zc().slice(0,12),this.corrId=zc().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t===void 0?n:{error:t,...n};this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={};for(let[e,t]of Object.entries(n))r[e]=cEt(t);let i={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...r},a=`${JSON.stringify(i)}\n`;process.stderr.write(a);let o=process.env.OK_LOG_FILE;if(o)try{tc(o,a)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function uEt(e,t){return sEt.run(e,t)}function T5(){return sEt.getStore()}let E5=null,D5=null;jU(()=>{E5=null,D5=null});function dEt(){return E5??=PU().createHistogram(`ok.mcp.tool.duration`,{description:`MCP tool invocation duration. Bounded label: tool (static registry names).`,unit:`ms`}),E5}function fEt(){return D5??=PU().createCounter(`ok.mcp.tool.errors`,{description:`MCP tool invocation failures. Bounded labels: tool (static registry names), kind ∈ {exception, error_result}.`,unit:`{errors}`}),D5}function pEt(e){return typeof e==`object`&&!!e&&e.isError===!0}function mEt(e,t){return(...n)=>FU(`mcp.tool.${e}`,{attributes:{"mcp.tool.name":e}},async r=>{let i=performance.now();try{let i=await t(...n);return pEt(i)&&(r.setStatus({code:No.ERROR,message:`tool returned isError result`}),fEt().add(1,{tool:e,kind:`error_result`})),i}catch(t){throw fEt().add(1,{tool:e,kind:`exception`}),t}finally{dEt().record(performance.now()-i,{tool:e})}})}const hEt=new Set([`find`,`markdown`,`replace`]),gEt=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],_Et=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function O5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vEt(e){return O5(e)&&`requestId`in e}function yEt(e,t){if(hEt.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
2097
2097
|
`).length};let n=e===`command`?240:120;return t.length<=n?t:{type:`string`,length:t.length,preview:`${t.slice(0,n)}...`}}function bEt(e,t){if(t===null)return null;if(typeof t==`string`)return yEt(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(O5(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function xEt(e,t){return O5(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,bEt(e,t)])):bEt(e,t)}function SEt(e){let t={structuredKeys:Object.keys(e).sort()};for(let n of _Et)n in e&&(t[n]=e[n]);for(let n of gEt){let r=e[n];Array.isArray(r)&&(t[`${n}Count`]=r.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),O5(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function CEt(e){if(!O5(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>O5(t)&&typeof t.text==`string`?e+t.text.length:e,0)),O5(e.structuredContent)&&Object.assign(t,SEt(e.structuredContent)),t}function wEt(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function TEt(e){let t=e.at(-1);return vEt(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function EEt(e,t,n){let r=n.logger;return r?async(...i)=>{let a=r.child(),o=Date.now(),{toolArgs:s,extra:c}=TEt(i);a.info(`tool start`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},...c?.sessionId?{transportSessionId:c.sessionId}:{},...n.identityRef?.current?{agent:wEt(n.identityRef.current)}:{},...s===void 0?{}:{args:xEt(e,s)}});try{let n=await uEt(a,async()=>await t(...i));return a.info(`tool finish`,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o,result:CEt(n)}),n}catch(t){throw a.error(`tool error`,t,{tool:e,...c?.requestId===void 0?{}:{requestId:c.requestId},durationMs:Date.now()-o}),t}}:t}function DEt(e,t){let n=(e,n)=>mEt(e,EEt(e,n,t)),r=e.tool.bind(e),i=e.registerTool,a=typeof i==`function`?i.bind(e):void 0,o=Object.create(e);return o.tool=((...e)=>{let t=String(e[0]),i=e.at(-1);if(typeof i!=`function`)return r(...e);let a=[...e];return a[a.length-1]=n(t,i),r(...a)}),a&&(o.registerTool=((e,t,r)=>{if(typeof r!=`function`)return a(e,t,r);let i=n(e,r);return a(e,t,i)})),o}function k5(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{let t=Qa.safeParse(e);return t.success?[t.data]:[]});return t.length>0?t:void 0}function A5(e){return Array.isArray(e)?e.flatMap(e=>{let t=_re.safeParse(e);return t.success?[t.data]:[]}):[]}function j5(e){let t=Aa.safeParse(e);return t.success?t.data:void 0}function OEt(e){return e.length===0?[]:[`⚠ ${e.length} broken outbound link${e.length===1?``:`s`} — fix or remove (the write still landed):`,...e.map(e=>` • ${AEt(e)}`)]}function kEt(e){return e.length===0?null:`⚠ ${e.length} broken outbound link${e.length===1?``:`s`} (see brokenLinks).`}function AEt(e){let t=e.localTarget?.role===`image`?`image `:``,n=e.resolvedTo?`${t}${e.href} → ${e.resolvedTo} (${e.reason})`:`${t}${e.href} (${e.reason})`,r=e.localTarget?.definition;return r?`${n} — fix the [${r.label}] definition (line ${r.line+1})`:n}function jEt(e){return e.filter(e=>xie(e.kind))}function MEt(e){return e.filter(e=>e.kind===`mermaid-parse-error`)}function NEt(e){return e.filter(e=>e.kind===`lint-violation`)}function PEt(e){return e.filter(e=>e.kind===`link-check-deferred`)}const FEt=new Set([...Fee,`mermaid-parse-error`,`lint-violation`,`link-check-deferred`]);function IEt(e){return e.filter(e=>!FEt.has(e.kind))}function LEt(e){return`⚠ Advisory "${e.kind}" — see structuredContent.document.warnings for details.`}function REt(e){return`⚠ Advisory "${e.kind}" (see warnings).`}function zEt(e){let t=e.severity===`error`?`error`:`warning`;return`⚠ Content rule ${e.source}/${e.code} (${t}, line ${e.line}): ${e.message}`}function BEt(e){return`⚠ ${e.source}/${e.code} (line ${e.line}): ${e.message}`}function M5(e){let t=jEt(e).map(HEt),n=MEt(e);return n.length>0&&t.push(KEt(n)),t.push(...NEt(e).map(zEt)),t.push(...PEt(e).map(e=>`⚠ ${e.message}`)),t.push(...IEt(e).map(LEt)),t}function VEt(e){let t=jEt(e).map(GEt),n=MEt(e);return n.length>0&&t.push(qEt(n)),t.push(...NEt(e).map(BEt)),PEt(e).length>0&&t.push(`⚠ Links not checked yet: the link index is still building or busy (see warnings).`),t.push(...IEt(e).map(REt)),t}function HEt(e){switch(e.kind){case`content-divergence`:return`⚠ Content divergence: ${e.actualBytes} actual bytes vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}). ${e.hint??`The stored text differs from what you sent; re-read the document before the next edit.`}`;case`disk-edit-reconciled`:return`⚠ ${e.hint??`An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.`}`;default:return xo(e)}}function UEt(e){let t=e.restoredDeletedHere??0,n=e.restoredDeletedOutside??0,r=e.duplicatedBlocks??(t+n>0?0:1),i=[...r>0?[`an out-of-band edit to the same block was kept beside the version here`]:[],...t>0?[`a deletion here was undone and the out-of-band version restored`]:[],...n>0?[`an out-of-band deletion was undone and the version here kept`]:[]].join(`; `),a=[...r>0?[`remove the duplicate`]:[],...t>0?[`delete the restored block again`]:[]],o=a.length>0?`Re-read and ${a.join(` or `)} if needed.`:`Re-read before continuing.`;return`⚠ ${i.charAt(0).toUpperCase()}${i.slice(1)}; the write landed. ${o}`}function WEt(e){let t=tte(e.mergeOutcome)?e.mergeOutcome:void 0;switch(t){case`both-kept`:return UEt(e);case`kept-live`:return`⚠ An out-of-band edit could not be merged and was saved to history; the write landed. Re-read before continuing.`;case`clean`:case`merged`:case void 0:return`⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.`;default:return`⚠ Out-of-band disk edit reconciled before this write (${String(t)}) — re-read for the combined result.`}}function GEt(e){switch(e.kind){case`content-divergence`:return`⚠ Content divergence: ${e.actualBytes} actual vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}).`;case`disk-edit-reconciled`:return WEt(e);default:return xo(e)}}function KEt(e){let t=e[0];if(e.length===1&&t){let e=t.line===void 0?``:` (line ${t.line})`,n=t.fenceFirstLine===``?`(empty fence)`:`("${t.fenceFirstLine}")`;return`⚠ Mermaid fence ${t.fenceIndex} ${n} will not render${e}: ${JEt(t.message)} Fix the fence and re-edit.`}return`⚠ ${e.length>=10?`10+`:String(e.length)} mermaid fences will not render — see structuredContent.document.warnings (kind "mermaid-parse-error") for per-fence errors. Fix the fences and re-edit.`}function qEt(e){return`⚠ ${e.length>=10?`10+`:String(e.length)} mermaid fence${e.length===1?``:`s`} will not render (see warnings).`}function JEt(e){let t=e.split(`
|
|
2098
|
-
`,1)[0]?.trim()??``;return t.endsWith(`.`)||t.endsWith(`:`)?t:`${t}.`}const YEt=["Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.","ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.",`Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.`,`Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped
|
|
2099
|
-
`);function XEt(e,t){e.registerTool(`audit`,{description:YEt,inputSchema:{path:R().optional().describe(`Audit scope: a folder or single doc file (content-dir-relative). Default: the whole project.`),cwd:R().optional().describe(X4)},outputSchema:i3({files:t3.optional().describe(`Per-file diagnostics — only files with at least one problem.`),fileCount:Ia().optional().describe(`Total in-scope documents scanned.`),errorCount:Ia().describe(`Total error-severity findings across validators.`),warningCount:Ia().describe(`Total warning-severity findings across validators.`),warnings:To(R()).optional().describe("Anything that made this run less than a full answer: unreadable files/dirs, config problems, a validator that could not run, or a family that ran only partially (`… validation degraded: …`). A source family named here is still listed in `ran` — it was selected, and a degraded family may still have contributed findings."),ran:To(R()).optional().describe("Validation source families selected for this run. A family absent from `ran` was not checked."),brokenLinkSuppression:Aa.optional().describe("Present when the reserved-log policy withheld broken-link findings. Carries only the reason and count, never paths or hrefs. Absent both when nothing was withheld and when a withholding arrived in a shape this build cannot validate. In that second case `warnings` carries the disclosure, so an empty `brokenLinkSuppression` beside a non-empty `warnings` is not an all-clear."),omittedWarningCount:Ia().optional().describe("Warnings omitted from `warnings` by the output cap."),omittedFileCount:Ia().optional().describe("Files with problems omitted from `files` by the output cap."),cwd:R().describe(`Absolute directory the audit ran against.`)}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async
|
|
2100
|
-
`),
|
|
2101
|
-
`)}),
|
|
2102
|
-
`),
|
|
2098
|
+
`,1)[0]?.trim()??``;return t.endsWith(`.`)||t.endsWith(`:`)?t:`${t}.`}const YEt=["Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.","ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.",`Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.`,`Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.`,"Large project scans can exceed host or transport timeouts. If a scan times out, narrow `path` to a file or folder and retry.",`Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.`].join(`
|
|
2099
|
+
`);function XEt(e,t){e.registerTool(`audit`,{description:YEt,inputSchema:{path:R().optional().describe(`Audit scope: a folder or single doc file (content-dir-relative). Default: the whole project.`),cwd:R().optional().describe(X4)},outputSchema:i3({files:t3.optional().describe(`Per-file diagnostics — only files with at least one problem.`),fileCount:Ia().optional().describe(`Total in-scope documents scanned.`),errorCount:Ia().describe(`Total error-severity findings across validators.`),warningCount:Ia().describe(`Total warning-severity findings across validators.`),warnings:To(R()).optional().describe("Anything that made this run less than a full answer: unreadable files/dirs, config problems, a validator that could not run, or a family that ran only partially (`… validation degraded: …`). A source family named here is still listed in `ran` — it was selected, and a degraded family may still have contributed findings."),ran:To(R()).optional().describe("Validation source families selected for this run. A family absent from `ran` was not checked."),brokenLinkSuppression:Aa.optional().describe("Present when the reserved-log policy withheld broken-link findings. Carries only the reason and count, never paths or hrefs. Absent both when nothing was withheld and when a withholding arrived in a shape this build cannot validate. In that second case `warnings` carries the disclosure, so an empty `brokenLinkSuppression` beside a non-empty `warnings` is not an all-clear."),omittedWarningCount:Ia().optional().describe("Warnings omitted from `warnings` by the output cap."),omittedFileCount:Ia().optional().describe("Files with problems omitted from `files` by the output cap."),cwd:R().describe(`Absolute directory the audit ran against.`)}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async(e,{signal:n})=>{let r=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!r.ok)return $(`Error: ${r.error}`,!0);let{cwd:i,url:a}=r;return a?ZEt(e.path,a,i,n):$(o3(),!0)})}async function ZEt(e,t,n,r){let i=await g3(t,`/api/audit${e?`?path=${encodeURIComponent(e)}`:``}`,r);if(!i.ok)return $(`Error: ${String(i.error)}`,!0);let{ok:a,...o}=i,s=o,c=s.files??[],l=s.fileCount??0,u=s.errorCount??0,d=s.warningCount??0,f=Rt(s.ran,l),p=s.brokenLinkSuppression,m=p!=null,h=j5(p),g=m&&h===void 0,_=h?fut(h,{surface:`mcp`}):void 0,v=c.slice(0,10).map(e=>{let t=e.diagnostics??[],n=t.slice(0,10),r=t.length-n.length;return{...e,diagnostics:n,...r>0?{omittedDiagnosticCount:r}:{}}}),y=c.length-v.length,b=[...g?[put({surface:`mcp`})]:[],...s.warnings??[]],{shownWarnings:x,omittedWarningCount:S}=tht(b),C={files:v,fileCount:l,errorCount:u,warningCount:d,...s.ran===void 0?{}:{ran:s.ran},...h===void 0?{}:{brokenLinkSuppression:h},...x.length>0?{warnings:x}:{},...S>0?{omittedWarningCount:S}:{},...y>0?{omittedFileCount:y}:{},cwd:n},w=E3(`Audit`,x,S),T=e?` in ${e}`:``;if(c.length===0)return a3([nht(`Audit`,l,b,T),..._===void 0?[]:[_],...f,...w].join(`
|
|
2100
|
+
`),C);let E=`${c.length} of ${l} document${l===1?``:`s`}${T} with problems — ${O3(u,d)}:`,D=v.map(e=>{let t=e.diagnostics.map(D3);return e.omittedDiagnosticCount!==void 0&&t.push(` … and ${e.omittedDiagnosticCount} more problem${e.omittedDiagnosticCount===1?``:`s`}. For lint findings, use lint({ document: ${JSON.stringify(e.file)} }); for broken links, use links({ kind: "dead", sourceDocuments: [${JSON.stringify(e.file)}] }). Project-tree OKF findings remain capped.`),[`${e.file??`(unknown)`}:`,...t].join(`
|
|
2101
|
+
`)}),O=y>0?[`… and ${y} more file${y===1?``:`s`} with problems. Narrow path to reduce competing files; per-file caps still apply.`]:[];return a3([E,...D,...O,...w,..._===void 0?[]:[_],"Auto-fix fixable lint findings with `lint({ document, fix: true })`; broken links need content edits via `edit`/`write`.",...f].join(`
|
|
2102
|
+
`),C)}const QEt=[`Save a project-wide checkpoint of every document. Requires the Hocuspocus server. Optional summary ≤80 chars defaults to "Checkpoint version"; avoid secrets or PII because it persists in git history. Returns version (40-char SHA). Find it with history and restore one doc with restore_version({document,version}).`].join(`
|
|
2103
2103
|
`);function $Et(e,t){e.registerTool(`checkpoint`,{description:QEt,inputSchema:{summary:Z4.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:R().optional().describe(X4)},outputSchema:i3({version:R().describe(Lmt),previewUrl:Q4.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let n=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{url:r}=n;if(!r)return $(o3(),!0);let i=t.identityRef?.current,a=await y3(p3(r,t.localApi),`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...i?{writers:[{id:`agent-${i.connectionId}`,name:i.displayName,email:`agent-${i.connectionId}@openknowledge.local`}]}:{}});if(!a.ok)return $(`Error: ${a.error}`,!0);let o=typeof a.checkpointRef==`string`?a.checkpointRef:``,s=o.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(s)?a3(`Checkpoint saved. Version: ${s}`,{version:s,previewUrl:null}):$(`Error: checkpoint committed but the server returned no usable version ref ("${o}"). Find the latest checkpoint via \`history\`.`,!0)})}const eDt=[`Read effective config merged defaults → user → project; no running OK server needed. Optional key is a dotted path (content, appearance.theme); omit for the full config. All fields are readable. Re-read after disk changes or before relying on an old value.`,"Removed server.*, mcp.*, github.*, preview.baseUrl and preview.scriptSrc return exists:false; appearance.preview.autoOpen remains live. This is a pure read. Use `install` skillFolders for folder topology."].join(`
|
|
2104
2104
|
`),tDt={key:R().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:R().optional().describe(X4)},nDt=i3({value:B().describe(`Resolved config value at the requested path (or full config).`),exists:A().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:R().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function rDt(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function iDt(e,t){e.registerTool(`config`,{description:eDt,inputSchema:tDt,outputSchema:nDt,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let n=await s3(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let r=e.key?e.key.split(`.`).filter(e=>e.length>0):[],i=r.length>0?rDt(n.config,r):n.config;return r.length>0&&i===void 0?a3(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):a3(JSON.stringify(i,null,2),{value:i,exists:!0,...e.key?{key:e.key}:{}})})}const aDt=[`lock`];function N5(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function oDt(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${N5(t)}/`:``}function P5(e,t){return`__skill__/${e}/${N5(t)}`}function F5(){return`No UI is running for this project. Start one to see the preview: \`${$e()} start\` (terminal), or open the project in OK Electron.`}function sDt(){return`No browser is attached to the preview. Open it in your host's surface: \`preview_url\`, then drive your in-app browser (Claude Code Desktop: \`preview_start({url})\` to open the pane, then \`navigate({url})\` to move; Cursor: \`Navigate\`; Codex desktop: \`@Browser\`); on a stdio CLI with no browser, \`${$e()} open <doc>\`.`}function I5(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:sDt(),autoOpen:t}:{action:`start-ui`,previewUrl:null,message:F5(),autoOpen:t}}async function L5(e,t,n){return B5(e,{lockDir:JJ(n??await t.resolveCwd())})}function R5(e){try{let t=N4(e.lockDir);if(t&&t.draining!==!0&&P4(t)){let e=D4(t);if(e!==null)return{baseUrl:e}}}catch(t){process.stderr.write(`[preview-url] readServerLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function cDt(e,t){let n=Date.now()+t.timeoutMs;for(;;){let{baseUrl:r}=R5(e);if(r!==null)return r;if(Date.now()>=n)return null;await new Promise(e=>setTimeout(e,t.pollIntervalMs))}}async function z5(e,t){let n={lockDir:JJ(t??await e.resolveCwd())};return{resolve:e=>B5(e,n)}}function lDt(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function B5(e,t){return dDt(`/#/${N5(e)}`,t)}function uDt(e,t,n){return dDt(`/#/${P5(e,t)}`,n)}function dDt(e,t){let{baseUrl:n}=R5(t);return n===null?null:{url:e,source:`lock`}}const fDt=ea([Fte,an()]),pDt=ea([R(),Ia(),A(),To(B()),z(R(),B()),an()]),V5=kee(pDt).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))fDt.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),mDt=Ct([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),hDt=Ct(ae).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`.");function gDt(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n===-1?{folder:``,name:t}:{folder:t.slice(0,n),name:t.slice(n+1)}}const _Dt=`Template path = \`<folder>/<name>\` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name, which must use ${sn}. Stored at \`<folder>/.ok/templates/<name>.md\`.`;function H5(e){let{folder:t,name:n}=gDt(e);return wt.test(n)?{ok:!0,folder:t,name:n}:{ok:!1,error:`the final segment of a template path is its name — "${n}" must use ${sn}. e.g. { template: { path: "fishing-log/trip-log" } }.`}}const U5='Skill name — the skill\'s identity AND its bundle-dir name, wherever the skill lives (e.g. `.agents/skills/<name>/`). Lowercase letters, digits, hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase). Example: "trip-log".',vDt="One-line description (≤1024 chars) — the PRIMARY triggering surface telling an agent WHEN to use this skill. No XML tags (`<...>`), which break the skill loader.",W5=Ct(Zn).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`);function G5(e){return typeof e!=`string`||e.length===0||e.length>64||!Ce.test(e)?{ok:!1,error:`a skill name must be lowercase letters, digits, and hyphens (≤64 chars, no slashes/dots/spaces/uppercase) — ${JSON.stringify(e)} is invalid. e.g. { skill: { name: "trip-log" } }.`}:{ok:!0,name:e}}function K5(e){if(typeof e!=`string`||e.length===0)return{ok:!1,error:'a skill file `path` is required (e.g. "references/tiers.md").'};if(e.includes(`\0`))return{ok:!1,error:"a skill file `path` may not contain a NUL byte."};if(e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e))return{ok:!1,error:`a skill file \`path\` must be skill-relative, not absolute — "${e}" is rejected. e.g. { path: "references/tiers.md" }.`};let t=ma(e);return t.some(e=>e===`..`)?{ok:!1,error:`a skill file \`path\` may not contain ".." — "${e}" could escape the skill dir.`}:t.length===0?{ok:!1,error:'a skill file `path` is required (e.g. "references/tiers.md").'}:t.length===1&&(t[0]===`references`||t[0]===`scripts`)?{ok:!1,error:`a skill file \`path\` needs a file under \`${t[0]}/\` (e.g. "${t[0]}/notes.md") — "${e}" names only the directory.`}:t.length===1&&t[0]?.toLowerCase()===`skill.md`?{ok:!1,error:"SKILL.md is authored via `body`, not as a bundle file."}:{ok:!0,path:t.join(`/`),kind:t[0]===`scripts`?`script`:`reference`}}function q5(e,t){let n=t.filter(t=>e[t]!==void 0);if(n.length===1)return null;let r=t.map(e=>`\`${e}\``).join(`, `);return n.length===0?`Name exactly one of ${r} — the one thing you are addressing. Nest that target's fields under its key (e.g. \`{ document: { path, … } }\`); see this tool's parameter docs for which fields each target takes.`:`You named ${n.map(e=>`\`${e}\``).join(` and `)} — name exactly ONE target.`}function yDt(e){return Object.entries(e).map(([e,t])=>`\`${e}\`: ${t}`).join(`; `)}const J5={outcome:Ct(f).optional().describe(`What happened to this write, present on every write result the server answered, success or not. ${yDt(Tte)}. A value this tool version does not know is reported as merged-first when saved, else refused, with nextStep re-read.`),saved:A().optional().describe("Whether the write's bytes were in the document's file when the server answered. Not the same as the move result's `committed` (git history)."),nextStep:Ct(Cee).optional().describe(`What to do next about this write. ${yDt(pr)}. Never retry a write whose outcome is merged-first, both-kept or projection-held: it landed.`)};function Y5(e){return Ir({outcome:e.outcome,saved:e.saved,nextStep:e.nextStep})}function X5(e){return e===void 0?{}:{outcome:e.outcome,...e.saved===void 0?{}:{saved:e.saved},...e.nextStep===void 0?{}:{nextStep:e.nextStep}}}function Z5(e){return e?.outcome===`both-kept`||e?.outcome===`projection-held`}function Q5(e){return e?.outcome===`refused`||e?.outcome===`both-kept`||e?.outcome===`projection-held`}function $5(e){if(e===void 0)return null;let t=e.unknownOutcome===void 0?e.unknownNextStep===void 0?``:` The server reported next step "${e.unknownNextStep}", which this tool version does not know; treated as re-read.`:` The server reported outcome "${e.unknownOutcome}", which this tool version does not know; treated as ${e.outcome}.`;return`${[`Outcome: ${e.outcome}`,...e.saved===void 0?[]:[`saved: ${e.saved?`yes`:`no`}`],...e.nextStep===void 0?[]:[`next step: ${e.nextStep}`]].join(`; `)}.${t}`}function e7(e,t){return e.outcome===`both-kept`?`${t}: both versions of a block changed here and outside were kept. The write landed and is saved; do not retry it. Re-read the document and remove the duplicate with an ordinary edit if your task calls for it.`:`${t}: the edit is in the document, but its save to the file is not confirmed yet; OpenKnowledge saves it on its own. Do not retry it. Re-read the document before the next edit.`}function t7(e,t,n){return e!==void 0&&Z5(e)?e7(e,t):n}const bDt={applied:0,"merged-first":1,"both-kept":2,"projection-held":3,refused:4};function xDt(e,t){return e===void 0?t:t===void 0?e:bDt[t.outcome]>bDt[e.outcome]?t:e}function SDt(e){return{outcome:e.outcome,...e.saved===void 0?{}:{saved:e.saved},nextStep:`re-read`,...e.unknownOutcome===void 0?{}:{unknownOutcome:e.unknownOutcome}}}function n7(e){return e?.outcome===`refused`}function r7(e,t){return i7(`Error: ${e} was not saved. The server answered without an error status but reported the write as refused.`,t)}function i7(e,t){let n=$5(t),r=n===null?e:`${e}\n${n}`;return t===void 0?$(r,!0):a3(r,X5(t),!0)}const CDt=new Set(lo);function wDt(e,t){for(let[n,r]of Object.entries(Y4(t)))typeof r==`string`&&r.length>0&&e.set(n,r)}async function TDt(e,t){let n=G5(t.name);if(!n.ok)return $(`Error: ${n.error}`,!0);if(!e)return $(o3(),!0);let r=await b3(e,`/api/skill`,{...t.scope===void 0?{}:{scope:t.scope},name:t.name,body:t.body??``,frontmatter:{name:t.name,description:t.description},...t.summary===void 0?{}:{summary:t.summary},...Y4(t.identity)}),i=Y5(r);if(!r.ok)return i7(r3(r,t.resubmitted?t.resubmitted===`metadata-edit`?`Any body offset refers to the full stored skill body resubmitted by this edit. Remove stored controls through a clean full replacement using write({ skill: ... }).`:`Any body offset refers to the full stored skill body resubmitted by this edit, including any supplied replace. Clean controls in replace, or, if stored controls remain, use a clean full replacement through write({ skill: ... }).`:`Any body offset refers to the full submitted skill body.`),i);if(n7(i))return r7(`The write of skill "${t.name}"`,i);let a=r.created===!0,o=typeof r.path==`string`?r.path:void 0,s=S3(r.warnings,r.warningCodes,CDt),c=i?.outcome===`applied`?null:$5(i),l=[t7(i,`${a?`Created`:`Updated`} skill "${t.name}"`,`${a?`Created`:`Updated`} skill "${t.name}"${o?` (${o})`:``} — live for that folder's agent. Use \`install\` with \`add\` to put it in your other editors.`),...s.warnings,...c?[c]:[]],u=t.lockDir?uDt(t.scope??`project`,t.name,{lockDir:t.lockDir}):null;return a3(l.join(`
|
|
2105
2105
|
`),{skill:{ok:!0,path:o,created:a,...s},...u?{previewUrl:u.url,previewUrlSource:u.source}:{},...X5(i)},Q5(i))}async function EDt(e,t,n){let r=await g3(e,`/api/skill?${new URLSearchParams({name:n,scope:t}).toString()}`);if(!r.ok)return{ok:!1,error:String(r.error),notFound:r.httpStatus===404};let i=r.skill,a=Array.isArray(i?.files)?i.files.map(e=>typeof e?.path==`string`?{path:e.path}:null).filter(e=>e!==null):[];return{ok:!0,description:typeof i?.frontmatter?.description==`string`?i.frontmatter.description:``,body:typeof i?.body==`string`?i.body:``,files:a}}async function DDt(e,t){let n=G5(t.name);if(!n.ok)return $(`Error: ${n.error}`,!0);if(!e)return $(o3(),!0);let r=await b3(e,`/api/skill-file`,{...t.scope===void 0?{}:{scope:t.scope},name:t.name,path:t.path,content:t.content,...t.summary===void 0?{}:{summary:t.summary},...Y4(t.identity)}),i=Y5(r);if(!r.ok)return i7(r3(r,qre(t.path)?t.resubmitted?`Any content offset refers to the full stored file content resubmitted by this edit, including frontmatter and any supplied replace. Clean controls in replace, or, if stored controls remain, use a clean full replacement through write({ skill: { files: ... } }).`:`Any content offset refers to the whole submitted file content, including frontmatter.`:void 0),i);if(n7(i))return r7(`The write of "${t.path}" in skill "${t.name}"`,i);let a=r.created===!0,o=typeof r.path==`string`?r.path:t.path,s=r.kind===`script`?`script`:`reference`,c=i?.outcome===`applied`?null:$5(i);return a3([t7(i,`${a?`Created`:`Updated`} skill ${s} "${t.path}" in "${t.name}"`,`${a?`Created`:`Updated`} skill ${s} "${t.path}" in "${t.name}".`),...c?[c]:[]].join(`
|
|
@@ -2128,13 +2128,13 @@ tags: [lore, history]
|
|
|
2128
2128
|
`),{name:i,path:typeof r.path==`string`?r.path:void 0,alreadyImported:o,...s?{collisionRenamedFrom:s}:{},warnings:u,...c.warningCodes&&l.warningCodes?{warningCodes:[...c.warningCodes,...l.warningCodes]}:{}})})}const Bkt=new Set(Jr),Vkt=["Manage where a SKILL is available: `{name, add?, remove?, convert?, mode?, source?, scope?}` or `{skillFolders: {...}}` alone. Requires the Hocuspocus server. One real source folder plus managed copies/symlinks; the source still loads with no extra locations. Use delete to remove the skill everywhere.",`name is the bundle identity: lowercase letters/digits/hyphens, ≤64 chars. Locations: claude/cursor/codex/copilot/opencode/pi, agents (.agents/skills), or custom root containing '/' such as .team/skills. Custom roots are project-relative, home-relative at global scope. scope: project (default, shared via git) or global (user-wide).`,`add/remove change membership; omitting both installs to configured editors. remove cannot remove the source; folder aliases unfollow minus this skill and keep others. Differing copies are preserved; editor removal may succeed and leave them in place.`,`mode: link = live symlink for source updates (copy where the OS refuses symlinks); copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.`,`source moves the real folder; its old location becomes a symlink. Run alone, not with add/remove. Source SKILL.md with conflict markers, invalid/missing frontmatter, XML in name/description or reserved open-knowledge* names is refused before projection.`,`skillFolders runs alone without name. link: {action:'link', scope, root, target}; target required, merge then symlink root; equal entries deduplicate, differing skills abort, interrupted merges can rerun. unlink: {action:'unlink', scope, root, exclude?}; makes a real directory of per-skill symlinks, excluding named skills and retaining others. add-root: {action:'add-root', scope, root}; declares a custom root for install/link.`].join(`
|
|
2129
2129
|
`);async function Hkt(e,t,n){let r=await c3(e.resolveCwd,e.config,e.serverUrl,n);if(!r.ok)return r.result;let i=await b3(r.url,`/api/skill-targets`,{folderAction:t});if(!i.ok)return $(`Error: ${i.error}`,!0);let a=i.folder??{moved:[],dropped:[],linked:[]};return a3(t.action===`link`?`Linked ${t.root} → ${t.target}: moved ${a.moved?.length??0} skill(s), dropped ${a.dropped?.length??0} duplicate(s). Its agent now reads everything placed in ${t.target}.`:t.action===`unlink`?`Unlinked ${t.root} — it is a real directory again with per-skill symlinks (nothing stopped working).`:`Declared ${t.root} as a custom skills root — it is now an install and link target.`,{folder:{moved:a.moved??[],dropped:a.dropped??[],linked:a.linked??[]}})}function Ukt(e,t){e.registerTool(`install`,{description:Vkt,inputSchema:{name:R().optional().describe(`${U5} Required unless \`skillFolders\` is given.`),skillFolders:Ure.optional().describe("Folder-level skill-topology verb (link / unlink / add-root). Lives here rather than on `config` so that `config` stays a pure read and hosts can auto-approve it. Run alone, without `name`."),add:To(Ki).optional().describe('Locations to ADD the skill to — everything else untouched. Editor ids (`claude`…`pi`), `agents` (the hub), or a custom root path (".team/skills").'),remove:To(Ki).optional().describe("Locations to REMOVE the skill from; differing copies are preserved and may remain after success. An editor reading via a folder alias is unfollowed from the shared root minus this skill (it keeps the rest). The SOURCE cannot be removed — its folder IS the skill; use `source` to move it or `delete` to remove the skill."),convert:To(Ki).optional().describe("Existing locations to change the FORM of, leaving their membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a differing copy is refused rather than overwritten."),mode:Ct([`copy`,`link`]).optional().describe('Form for locations in `add` or `convert`. "link": live pointer to the source. "copy": independent folder, refreshed on watcher/startup sync while unedited; a hand edit forks it. Omit on `add` to inherit the existing form. Other locations stay unchanged; no skill-wide default. Requires `add` or `convert`; `mode` alone is refused.'),source:Ki.optional().describe(`Move the skill's REAL folder to this location (the old source becomes a symlink — never a removal). Run alone, not combined with add/remove.`),scope:W5.optional(),summary:Z4,cwd:R().optional().describe(X4)},outputSchema:i3({name:R().optional().describe(`Managed skill name installed or uninstalled.`),hosts:To(R()).optional().describe("Every location holding the skill after the operation, SOURCE first (editor ids, `agents`, custom root paths). Never empty — the source folder is the skill."),sourceMovedTo:R().optional().describe("Set when `source` relocated the real folder — its new bundle dir."),converted:To(R()).optional().describe("Locations whose form `convert` changed. Membership is unchanged."),warningCodes:To(Ct(Jr)).optional().describe(`${C3} ${$mt}`),scripts:A().optional().describe("true when the skill ships executable `scripts/` (projected, never auto-run)."),warnings:To(R()).optional().describe(`Non-fatal install/uninstall warnings from target projection. ${w3}`),folder:L({moved:To(R()).describe(`Skill bundles moved into the target root.`),dropped:To(R()).describe(`Same-content duplicates dropped during the merge.`),linked:To(R()).describe(`Folders now linked (or unlinked/declared).`)}).optional().describe("Present after a `skillFolders` verb: what the folder operation did.")})},async e=>{if(e.skillFolders!==void 0)return e.name===void 0?await Hkt(t,e.skillFolders,e.cwd):$("Error: `skillFolders` operates on folders, not one skill — do not combine with `name`.",!0);if(e.name===void 0)return $("Error: `name` is required (or pass `skillFolders`).",!0);let n=G5(e.name);if(!n.ok)return $(`Error: ${n.error}`,!0);if(e.convert!==void 0&&e.mode===void 0)return $("Error: `convert` needs `mode` — the form to convert those locations to.",!0);if(e.mode!==void 0&&(e.add?.length??0)===0&&(e.convert?.length??0)===0)return $("Error: `mode` needs `add` or `convert` — name the locations whose form should change.",!0);let r=await c3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!r.ok)return r.result;for(let n of e.convert??[]){let i=await y3(p3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,convert:{target:n,mode:e.mode},...e.summary===void 0?{}:{summary:e.summary},...Y4(t.identityRef?.current)});if(!i.ok)return $(r3(i),!0)}if(e.convert!==void 0&&e.add===void 0&&e.remove===void 0&&e.source===void 0){let t=e.mode===`link`?`symlinks to the source`:`independent copies`;return a3(`Converted ${e.convert.length} location(s) of skill "${e.name}" to ${t}.`,{name:e.name,converted:[...e.convert]})}let i=await y3(p3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,...e.add===void 0?{}:{add:e.add},...e.remove===void 0?{}:{remove:e.remove},...e.source===void 0?{}:{source:e.source},...e.summary===void 0?{}:{summary:e.summary},...Y4(t.identityRef?.current)});if(!i.ok)return $(r3(i),!0);for(let n of e.mode===void 0?[]:e.add??[]){let i=await y3(p3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,convert:{target:n,mode:e.mode},...Y4(t.identityRef?.current)});if(!i.ok)return $(`Added ${e.add?.join(`, `)} to "${e.name}", but setting ${n} to ${e.mode} failed. ${r3(i)}`,!0)}let a=Array.isArray(i.hosts)?i.hosts:[],o=i.scripts===!0,s=S3(i.warnings,i.warningCodes,Bkt),c=typeof i.sourceMovedTo==`string`?i.sourceMovedTo:void 0;return a3([c===void 0?`Skill "${e.name}" now lives at: ${a.join(`, `)||`(its source folder)`}.`:`Moved skill "${e.name}"'s source folder to ${c}; other locations now link to it.`,...s.warnings].join(`
|
|
2130
2130
|
`),{name:e.name,hosts:a,scripts:o,warnings:s.warnings,...s.warningCodes?{warningCodes:s.warningCodes}:{},...c===void 0?{}:{sourceMovedTo:c}})})}const Wkt=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],Gkt=[`Read the wiki-link graph. Requires the Hocuspocus server. kind is one value or an array; results merge, failures go in errors. Use audit for validation.`,"`backlinks`/`forward`/`suggest` require document. suggest finds unlinked prose mentions; excerpt is normalized context, NOT edit-ready text. Re-read with exec, locate the real text using offset, then edit into a wiki-link.","`dead` lists raw unresolved internal targets; sourceDocuments optionally filters with OR semantics. Includes skill docs and lowercase log.md/log.mdx: inspect deliberately, never use as a repair queue or rewrite existing log entries to clear findings.","`orphans` finds disconnected pages; mode incoming/outgoing/both. `hubs` lists most-linked pages; limit defaults 20."].join(`
|
|
2131
|
-
`);function Kkt(e,t){e.registerTool(`links`,{description:Gkt,inputSchema:{kind:ea([Ct(Wkt),To(Ct(Wkt)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:R().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:To(R()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:Ct(nl).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:Ia().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:R().optional().describe(X4)},outputSchema:i3({backlinks:t3.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:t3.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:t3.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:t3.optional().describe(`kind=orphans: disconnected pages.`),hubs:t3.optional().describe(`kind=hubs: the most-linked pages.`),suggest:z(R(),B()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:z(R(),R()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:R().describe(`Absolute directory the read ran against.`)})},async e=>{let n=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return $(o3(),!0);let a=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:o}=await z5(t,r),s=await Promise.all(a.map(n=>qkt(n,e,p3(i,t.localApi),r,t,o))),c={},l={};if(a.forEach((e,t)=>{let n=s[t];n.ok?Object.assign(c,n.data):l[e]=n.error}),Object.keys(c).length===0){let e=a.length===1?l[a[0]]:`All requested link kinds failed: ${JSON.stringify(l)}`;return $(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let u={...c,...Object.keys(l).length>0?{errors:l}:{},cwd:r};return a3(JSON.stringify(u,null,2),u)})}function qkt(e,t,n,r,i,a){switch(e){case`backlinks`:return Jkt(t,n,a);case`forward`:return Ykt(t,n,a);case`dead`:return Xkt(t,n,a);case`orphans`:return Zkt(t,n,a);case`hubs`:return Qkt(t,n,a);case`suggest`:return $kt(t,n,r,i)}}async function Jkt(e,t,n){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let r=d3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await g3(t,`/api/backlinks?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{backlinks:(o.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Ykt(e,t,n){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let r=d3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await g3(t,`/api/forward-links?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{forwardLinks:(o.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Xkt(e,t,n){let r=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=d3(t);if(!e.ok)return{ok:!1,error:e.error};r.append(`sourceDocName`,e.docName)}let i=r.toString(),a=await g3(t,`/api/dead-links${i?`?${i}`:``}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a;return{ok:!0,data:{deadLinks:(s.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,r=t?n(t):null,i=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}});return{...e,sources:i,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Zkt(e,t,n){let r=await g3(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{orphans:(a.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Qkt(e,t,n){let r=await g3(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{hubs:(a.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function $kt(e,t,n,r){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let i=d3(e.document);if(!i.ok)return{ok:!1,error:i.error};let a=await g3(t,`/api/suggest-links?docName=${encodeURIComponent(i.docName)}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a,c=await L5(i.docName,{config:r.config,resolveCwd:r.resolveCwd},n);return{ok:!0,data:{suggest:{...s,previewUrl:c?.url??null,...c?{previewUrlSource:c.source}:{}}}}}const eAt=["Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; the OpenKnowledge CLI's lint --fix is the unattributed headless/CI path.","ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.",`Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.`,`Configure lint in Settings → Plugins and native .markdownlint.* rules
|
|
2132
|
-
`);function tAt(e,t){if(e===0)return"None are auto-fixable — these need content edits via `edit`/`write`.";let n=t-e;return`${e} of ${t} are auto-fixable — pass \`fix: true\` to apply in place (attributed, live preview).${n>0?` The other ${n} need content edits via \`edit\`/\`write\`.`:``}`}function nAt(e,t){e.registerTool(`lint`,{description:eAt,inputSchema:{document:R().optional().describe(`Doc to lint (path, extension-less). Omit to audit the whole project.`),path:R().optional().describe("Audit scope when `document` is omitted: a folder or single file (content-dir-relative). Default: the whole project."),fix:A().optional().describe("Auto-fix fixable rules in `document` IN PLACE (attributed, live preview), then report what remains. Requires `document`."),cwd:R().optional().describe(X4)},outputSchema:i3({...J5,files:t3.optional().describe("Per-file diagnostics. For a single-doc lint, the one file (even if clean). Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),fileCount:Ia().optional().describe(`Audit only: total in-scope documents scanned.`),errorCount:Ia().optional().describe("Total error-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warningCount:Ia().optional().describe("Total warning-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warnings:To(R()).optional().describe("Anything that made this run less than a full answer: unreadable files/dirs (audit), lint-config problems such as a broken frontmatter schema file, and selected lint plugins that threw. A source family named here is still listed in `ran`: it was selected, it just could not finish. In fix mode this array carries the plugin failures from BOTH lint passes, so a post-write re-lint failure can appear here as the failing plugin, but never as the `Re-lint after fix failed: ` entry an older server sends, which is filtered out. The prose explanation is in `reLintFailure.message`, its machine-readable discriminant in `reLintFailure.reason`, and `diagnosticsArePreFix` is the flag to branch on."),diagnosticsArePreFix:A().optional().describe("Fix mode only. Present and true when the server flags pre-fix diagnostics, supplies `reLintFailure`, or reports a legacy re-lint-failure warning; absent when none of those signals is present. The reported `files[].diagnostics` and their `errorCount`/`warningCount` describe the pre-fix set and may overstate what remains. Treat the fix as applied and re-run `lint` to confirm. A non-empty explanation, when available, is in `reLintFailure.message`, and `reLintFailure.reason` says which of the two failure shapes it was."),reLintFailure:Die.optional().describe("Fix mode only: why the post-write re-lint could not report. `reason` is the machine-readable discriminant — `re-lint-threw` when the re-lint pass itself threw, `source-went-blind` when a lint source that read the pre-fix text failed on the post-fix text — and `message` is the trimmed, non-empty prose, normalized from the server’s typed failure or a legacy prefixed warning. When present, `diagnosticsArePreFix` is true; that flag can also be present without a failure."),ran:To(R()).optional().describe("Lint source families selected for this run. A family absent from `ran` was not checked."),omittedWarningCount:Ia().optional().describe("Audit only: warnings omitted from `warnings` by the output cap."),omittedFileCount:Ia().optional().describe("Audit only: files with problems omitted from `files` by the output cap."),fixedCount:Ia().optional().describe("Fix mode only: the server-reported number of problems resolved by auto-fix, or 0 if omitted. When `diagnosticsArePreFix` is true, the post-fix result is unavailable; do not treat 0 as evidence that nothing was fixed."),cwd:R().optional().describe(`Absolute directory the lint ran against; absent when a fix did not land.`)}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0}},async
|
|
2131
|
+
`);function Kkt(e,t){e.registerTool(`links`,{description:Gkt,inputSchema:{kind:ea([Ct(Wkt),To(Ct(Wkt)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:R().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:To(R()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:Ct(nl).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:Ia().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:R().optional().describe(X4)},outputSchema:i3({backlinks:t3.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:t3.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:t3.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:t3.optional().describe(`kind=orphans: disconnected pages.`),hubs:t3.optional().describe(`kind=hubs: the most-linked pages.`),suggest:z(R(),B()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:z(R(),R()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:R().describe(`Absolute directory the read ran against.`)})},async e=>{let n=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return $(o3(),!0);let a=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:o}=await z5(t,r),s=await Promise.all(a.map(n=>qkt(n,e,p3(i,t.localApi),r,t,o))),c={},l={};if(a.forEach((e,t)=>{let n=s[t];n.ok?Object.assign(c,n.data):l[e]=n.error}),Object.keys(c).length===0){let e=a.length===1?l[a[0]]:`All requested link kinds failed: ${JSON.stringify(l)}`;return $(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let u={...c,...Object.keys(l).length>0?{errors:l}:{},cwd:r};return a3(JSON.stringify(u,null,2),u)})}function qkt(e,t,n,r,i,a){switch(e){case`backlinks`:return Jkt(t,n,a);case`forward`:return Ykt(t,n,a);case`dead`:return Xkt(t,n,a);case`orphans`:return Zkt(t,n,a);case`hubs`:return Qkt(t,n,a);case`suggest`:return $kt(t,n,r,i)}}async function Jkt(e,t,n){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let r=d3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await g3(t,`/api/backlinks?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{backlinks:(o.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Ykt(e,t,n){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let r=d3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await g3(t,`/api/forward-links?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{forwardLinks:(o.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Xkt(e,t,n){let r=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=d3(t);if(!e.ok)return{ok:!1,error:e.error};r.append(`sourceDocName`,e.docName)}let i=r.toString(),a=await g3(t,`/api/dead-links${i?`?${i}`:``}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a;return{ok:!0,data:{deadLinks:(s.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,r=t?n(t):null,i=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}});return{...e,sources:i,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Zkt(e,t,n){let r=await g3(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{orphans:(a.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function Qkt(e,t,n){let r=await g3(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{hubs:(a.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function $kt(e,t,n,r){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let i=d3(e.document);if(!i.ok)return{ok:!1,error:i.error};let a=await g3(t,`/api/suggest-links?docName=${encodeURIComponent(i.docName)}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a,c=await L5(i.docName,{config:r.config,resolveCwd:r.resolveCwd},n);return{ok:!0,data:{suggest:{...s,previewUrl:c?.url??null,...c?{previewUrlSource:c.source}:{}}}}}const eAt=["Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; the OpenKnowledge CLI's lint --fix is the unattributed headless/CI path.","ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.",`Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.`,`Configure lint in Settings → Plugins and native .markdownlint.* rules.`,"If a project-wide scan times out, narrow `path` to a file or folder and retry."].join(`
|
|
2132
|
+
`);function tAt(e,t){if(e===0)return"None are auto-fixable — these need content edits via `edit`/`write`.";let n=t-e;return`${e} of ${t} are auto-fixable — pass \`fix: true\` to apply in place (attributed, live preview).${n>0?` The other ${n} need content edits via \`edit\`/\`write\`.`:``}`}function nAt(e,t){e.registerTool(`lint`,{description:eAt,inputSchema:{document:R().optional().describe(`Doc to lint (path, extension-less). Omit to audit the whole project.`),path:R().optional().describe("Audit scope when `document` is omitted: a folder or single file (content-dir-relative). Default: the whole project."),fix:A().optional().describe("Auto-fix fixable rules in `document` IN PLACE (attributed, live preview), then report what remains. Requires `document`."),cwd:R().optional().describe(X4)},outputSchema:i3({...J5,files:t3.optional().describe("Per-file diagnostics. For a single-doc lint, the one file (even if clean). Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),fileCount:Ia().optional().describe(`Audit only: total in-scope documents scanned.`),errorCount:Ia().optional().describe("Total error-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warningCount:Ia().optional().describe("Total warning-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warnings:To(R()).optional().describe("Anything that made this run less than a full answer: unreadable files/dirs (audit), lint-config problems such as a broken frontmatter schema file, and selected lint plugins that threw. A source family named here is still listed in `ran`: it was selected, it just could not finish. In fix mode this array carries the plugin failures from BOTH lint passes, so a post-write re-lint failure can appear here as the failing plugin, but never as the `Re-lint after fix failed: ` entry an older server sends, which is filtered out. The prose explanation is in `reLintFailure.message`, its machine-readable discriminant in `reLintFailure.reason`, and `diagnosticsArePreFix` is the flag to branch on."),diagnosticsArePreFix:A().optional().describe("Fix mode only. Present and true when the server flags pre-fix diagnostics, supplies `reLintFailure`, or reports a legacy re-lint-failure warning; absent when none of those signals is present. The reported `files[].diagnostics` and their `errorCount`/`warningCount` describe the pre-fix set and may overstate what remains. Treat the fix as applied and re-run `lint` to confirm. A non-empty explanation, when available, is in `reLintFailure.message`, and `reLintFailure.reason` says which of the two failure shapes it was."),reLintFailure:Die.optional().describe("Fix mode only: why the post-write re-lint could not report. `reason` is the machine-readable discriminant — `re-lint-threw` when the re-lint pass itself threw, `source-went-blind` when a lint source that read the pre-fix text failed on the post-fix text — and `message` is the trimmed, non-empty prose, normalized from the server’s typed failure or a legacy prefixed warning. When present, `diagnosticsArePreFix` is true; that flag can also be present without a failure."),ran:To(R()).optional().describe("Lint source families selected for this run. A family absent from `ran` was not checked."),omittedWarningCount:Ia().optional().describe("Audit only: warnings omitted from `warnings` by the output cap."),omittedFileCount:Ia().optional().describe("Audit only: files with problems omitted from `files` by the output cap."),fixedCount:Ia().optional().describe("Fix mode only: the server-reported number of problems resolved by auto-fix, or 0 if omitted. When `diagnosticsArePreFix` is true, the post-fix result is unavailable; do not treat 0 as evidence that nothing was fixed."),cwd:R().optional().describe(`Absolute directory the lint ran against; absent when a fix did not land.`)}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0}},async(e,{signal:n})=>{let r=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!r.ok)return $(`Error: ${r.error}`,!0);let{cwd:i,url:a}=r;return a?e.fix===!0?e.document===void 0?$("Error: `fix: true` requires `document` (fix one doc at a time). Omit `fix` to audit the whole project.",!0):rAt(e.document,a,i,t.identityRef?.current):e.document===void 0?aAt(e.path,a,i,n):iAt(e.document,a,i):$(o3(),!0)})}async function rAt(e,t,n,r){let i=d3(e);if(!i.ok)return $(i.error,!0);let a=await y3(t,`/api/lint/fix`,{docName:i.docName,...Y4(r)}),o=Y5(a);if(!a.ok)return i7(r3(a),o);if(n7(o))return r7(`The auto-fix of ${i.docName}`,o);let{ok:s,...c}=a,l=c,u=l.file??i.docName,d=l.diagnostics??[],f=l.fixedCount??0,p=d.filter(e=>e.severity===`error`).length,m=d.length-p,h=typeof c.warning==`string`&&Dt(c.warning)?c.warning:void 0,g=[...l.warnings??[],...h===void 0?[]:[h]],_=g.find(Dt),v=g.filter(e=>!Dt(e)),y=l.diagnosticsArePreFix===!0||l.reLintFailure!==void 0||_!==void 0,b=typeof l.reLintFailure?.message==`string`?l.reLintFailure.message.trim():``,x=b?{reason:un(l.reLintFailure?.reason)?l.reLintFailure.reason:`re-lint-threw`,message:b}:void 0,S=_?.slice(sie.length).trim(),C=x??(S?{reason:`re-lint-threw`,message:S}:void 0),w=C?` (${C.message})`:``,T=Rt(l.ran),E={files:[{file:u,diagnostics:d}],fixedCount:f,errorCount:p,warningCount:m,...v.length>0?{warnings:v}:{},...y?{diagnosticsArePreFix:!0}:{},...C?{reLintFailure:C}:{},...l.ran===void 0?{}:{ran:l.ran},cwd:n,...X5(o)},D=y?`Applied auto-fixes to ${u}, but re-lint failed${w}; the fix landed — problems below are the pre-fix set, re-run \`lint\` to confirm.`:f>0?`Fixed ${f} problem${f===1?``:`s`} in ${u}.`:v.length>0?`No auto-fixable problems in ${u}, but the lint could not fully complete.`:`No auto-fixable problems in ${u}.`,O=d.map(D3),k=E3(`Lint`,v),A=d.length>0&&!y?[`${d.length} problem${d.length===1?``:`s`} remain (${O3(p,m)}) — need content edits via \`edit\`/\`write\`.`]:[],j=o===void 0||o.outcome===`applied`?[]:[$5(o)??``],M=o!==void 0&&Z5(o)?[e7(o,`Applied auto-fixes to ${u}`)]:[];return a3((d.length===0?[...M,D,...j,...T,...k]:[...M,D,...j,...O,...k,...A,...T]).join(`
|
|
2133
2133
|
`),E,Q5(o))}async function iAt(e,t,n){let r=d3(e);if(!r.ok)return $(r.error,!0);let i=await g3(t,`/api/lint?doc=${encodeURIComponent(r.docName)}`);if(!i.ok)return $(`Error: ${String(i.error)}`,!0);let{ok:a,...o}=i,s=o,c=s.diagnostics??[],l=s.warnings??[],u=c.filter(e=>e.severity===`error`).length,d=c.length-u,f=Rt(s.ran),p={file:s.file??r.docName,diagnostics:c},m={files:[p],errorCount:u,warningCount:d,...l.length>0?{warnings:l}:{},...s.ran===void 0?{}:{ran:s.ran},cwd:n},h=c.length>0?`${p.file}: ${O3(u,d)}`:l.length>0?`No problems found in ${p.file}, but the lint could not fully complete.`:`No problems in ${p.file}.`,g=c.map(D3),_=E3(`Lint`,l),v=c.filter(e=>(e.fixes?.length??0)>0).length,y=c.length>0?[tAt(v,c.length)]:[];return a3((c.length===0?[h,...f,..._]:[h,...g,..._,...y,...f]).join(`
|
|
2134
|
-
`),m)}async function aAt(e,t,n){let
|
|
2135
|
-
`),
|
|
2136
|
-
`)}),
|
|
2137
|
-
`),
|
|
2134
|
+
`),m)}async function aAt(e,t,n,r){let i=await g3(t,`/api/lint/audit${e?`?path=${encodeURIComponent(e)}`:``}`,r);if(!i.ok)return $(`Error: ${String(i.error)}`,!0);let{ok:a,...o}=i,s=o,c=s.files??[],l=s.fileCount??0,u=s.errorCount??0,d=s.warningCount??0,f=Rt(s.ran,l),p=c.slice(0,10).map(e=>{let t=e.diagnostics??[],n=t.slice(0,10),r=t.length-n.length;return{...e,diagnostics:n,...r>0?{omittedDiagnosticCount:r}:{}}}),m=c.length-p.length,h=s.warnings??[],{shownWarnings:g,omittedWarningCount:_}=tht(h),v={files:p,fileCount:l,errorCount:u,warningCount:d,...g.length>0?{warnings:g}:{},..._>0?{omittedWarningCount:_}:{},...s.ran===void 0?{}:{ran:s.ran},...m>0?{omittedFileCount:m}:{},cwd:n},y=e?` in ${e}`:``,b=E3(`Lint`,g,_);if(c.length===0)return a3([nht(`Lint`,l,h,y),...f,...b].join(`
|
|
2135
|
+
`),v);let x=`${c.length} of ${l} document${l===1?``:`s`}${y} with problems — ${O3(u,d)}:`,S=p.map(e=>{let t=e.diagnostics.map(D3);return e.omittedDiagnosticCount!==void 0&&t.push(` … and ${e.omittedDiagnosticCount} more problem${e.omittedDiagnosticCount===1?``:`s`}; use lint({ document: ${JSON.stringify(e.file)} }) for all document lint findings.`),[`${e.file??`(unknown)`}:`,...t].join(`
|
|
2136
|
+
`)}),C=m>0?[`… and ${m} more file${m===1?``:`s`} with problems. Narrow path to reduce competing files; per-file caps still apply.`]:[];return a3([x,...S,...C,...b,"Auto-fix a single file with `lint({ document, fix: true })` (attributed, live preview). Violations that resist auto-fix need content edits.",...f].join(`
|
|
2137
|
+
`),v)}const S7="history does not transfer; the editor locations the destination level can host are re-projected there, while everything else — the `agents` hub, custom roots, and any editor with no skills root at that level — is removed at the source and not re-created at the destination. Re-add the ones the destination level can place with `install` (every removed location comes back as `droppedLocations`) — but only on a success: on a reported failure `droppedLocations` instead lists what this call had already removed at the source, so installing those at the destination spreads a retained copy rather than restoring anything (see `droppedLocations` for the per-`moveState` split).",oAt=[`For .md/.mdx inspection before or after a move in a project with .ok/, use exec; native Read/Grep/Glob omit wiki context.`,"Move/rename a document, folder or asset with `{from, to}`, a template with `{template: {from, to}}`, or a skill with `{skill: {from, to, scope?, toScope?}}`. Choose one form. Requires the Hocuspocus server. Document/folder/asset kind is auto-detected.",`Paths: docs accept optional .md/.mdx; folders are relative with no leading/trailing slash; assets include the extension. Templates use '<folder>/<name>'; inherited templates cannot move (move their local copy or owning folder). Template moves rewrite no inbound links.`,`Links to the moved document keep pointing to it. The old path stops existing; do not leave a redirect or stub.`,`Managed moves preserve wiki-link targets and rewrite supported inline Markdown links; renamed assets are reported.`,`Skills: scope defaults project; global means your home. Within one scope, rename keeps SKILL.md name in sync. A differing toScope moves between project/global: history does not transfer; supported editor locations are re-projected. Other locations are dropped; on SUCCESS only, use droppedLocations and the response to reinstall at the destination.`,`Cross-scope failures can leave partial state. Before retrying or reinstalling, read moveState and recovery text regardless of status. Never remove either copy without comparing source/destination when the outcome is missing or inconsistent.`,`Optional summary: one-line outcome ≤80 chars. If omitted, defaults to "Renamed X → Y". Avoid secrets or PII; persisted to git history. Invalid/excluded paths, missing sources and existing destinations are refused; collisions report colliding[].`].join(`
|
|
2138
2138
|
`);function sAt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function cAt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function lAt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromPath:t,toPath:n}]:[]}):[]}function uAt(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function dAt(e,t,n=`${t}s`){return e===1?t:n}function fAt(e,t){let n=J4(e,t);if(!n.ok)return null;let r=n.abs;if(G(r))try{let e=yc(r);if(e.isDirectory())return`folder`;if(e.isFile())return r.endsWith(`.md`)||r.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of ae)if(G(`${r}${e}`))return`file`;return null}function pAt(e,t){e.registerTool(`move`,{description:oAt,inputSchema:{from:R().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:R().optional().describe(`New path. Links keep their intended targets; supported inline links are rewritten.`),template:L({from:R(),to:R()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),skill:L({from:R(),to:R(),scope:Ct(Zn).optional().describe(`Source level (default "project"). "project" = this KB; "global" = your user home.`),toScope:Ct(Zn).optional().describe(`Destination level. Omit (or set equal to \`scope\`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global): ${S7}`)}).optional().describe(`Move/rename a SKILL: \`{ from: "<name>", to: "<name>", scope?, toScope? }\`. Within one level: renames the skill folder and keeps SKILL.md \`name\` in sync. Across levels (\`toScope\` differs from \`scope\`): moves between Project and Global; ${S7} Mutually exclusive with flat \`from\`/\`to\`.`),summary:Z4.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:R().optional().describe(X4)},outputSchema:i3({ok:A().describe(`Whether the move succeeded.`),kind:Ct([`file`,`folder`,`asset`,`template`,`skill`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template`/`skill` when that nested target was used)."),committed:A().optional().describe("Template move, or a skill move WITHIN one level: `true` = tracked `git mv` (history preserved), `false` = plain disk rename. Always `false` on a cross-level skill move — history does not transfer."),renamed:To(L({fromDocName:R(),toDocName:R()})).optional().describe(`docName remappings performed.`),rewrittenDocs:t3.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:t3.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:z(R(),R()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:$4,previousPreviewUrl:zmt,summary:e3.optional(),error:R().optional().describe("Present when `ok` is false."),colliding:t3.optional().describe(`On a 409 collision: the conflicting from→to pairs.`),crossScope:A().optional().describe(`Skill cross-level move only: \`true\` when the skill was moved between the Project and Global levels. ${S7}`),droppedLocations:To(R()).optional().describe("Skill cross-level move only: locations the skill occupied at the source that the move did not automatically re-project at the destination — the `agents` hub, custom roots, and any editor with no skills root at that level — as `install` location ids. On a SUCCESS they were removed at the source and not re-created at the destination, and the ones the destination level can place (the `agents` hub and custom roots) go back with `install` as `add`, together with `scope` set to the DESTINATION level; an editor with no skills root there cannot be placed at all — `install` accepts its id and projects nothing, so the move's own success text names the equivalent (an editor that reads the `agents` hub at that level takes `add: [\"agents\"]` instead) or states that no destination-level placement exists. Custom roots resolve against that level's base — your home directory at the Global level, the project directory at the Project level — not wherever the root lived before the move. On a FAILURE this is instead the set of source-side placements this call had already removed, and whether the skill moved is what `moveState` says: on `nothing-written`, `destination-removed`, `destination-stray` and the two retained states the source is still there, so do not pass these to `install` at the DESTINATION level — re-add them at the SOURCE level, and retry the move only once that state is resolved. On `destination-unreadable` and `partially-applied` the source removal may already have run, so inspect both locations before re-adding anywhere."),moveState:Ct(Ie).optional().describe('Skill cross-level move failures only: what is on disk, so you can decide whether to retry. Present on every cross-level skill-move failure this handler reports whose triple this build recognises as consistent, at whatever status it reports it. Do not read it as a 500-only concern: `destination-retained-blocking`, and the `nothing-written` collision that carries a `retentionLedger`, both arrive as 409, while `destination-retained` is the 500. Withheld here, together with `sourceState` and `retentionLedger`, when the three do not form a triple this build recognises as consistent; that case reports "The server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination." in the text instead, and is to be treated as unknown state, not as an ordinary collision. A request rejected before it runs — wrong method, an oversized or unreadable body, a timeout, or a body that fails schema validation against a differently-versioned server — carries none, as does a transport failure that never reached the server. Treat an absent `moveState` on a failure as unknown state, not as a state that cannot occur. `nothing-written` = THIS call wrote nothing, so it changed neither location; it says nothing about damage an earlier call left behind. Safe to retry once the refusal is addressed. `destination-removed` = the destination copy failed and was cleaned up; the source is intact; safe to retry. `destination-stray` = the destination copy failed and cleanup also failed; the source is intact but a stray copy remains; remove it before retrying. `destination-retained` = source removal failed and the complete destination copy was deliberately kept; a retry will collide with it, so read `sourceState` first. `destination-retained-blocking` = this call refused because the destination is a copy an EARLIER failed move retained; read `sourceState` before touching it — on `intact` it is a redundant duplicate and removing it unblocks the retry, otherwise do not delete it before reconciling it against the source, since it may hold the only copy of files that failed removal already deleted. `destination-unreadable` = the source was removed and the destination is not readable; do not retry, recover from history or a backup. `partially-applied` = an unexpected failure after the copy began left an indeterminate state; inspect both locations before doing anything.'),sourceState:Ct(Sne).optional().describe("Skill cross-level move failures only: accompanies both states that report a retained destination — `moveState: destination-retained` (this call kept it) and `moveState: destination-retained-blocking` (an earlier call did, and this retry was refused) — and reports what the SOURCE looked like when its removal failed. Every value is an as-of-then observation: on `destination-retained` this call took it, and on `destination-retained-blocking` it is replayed out of the record the earlier call wrote, so nothing has re-read the source since. `intact` = the source matched the content hash recorded before the move, so the retained destination copy is a redundant duplicate; it is safe to remove before retrying, and removing it is what unblocks the retry. `lossy` = the source no longer matched that hash, so it is partially removed; do not remove either location before recovering the missing source files from the retained copy. `unknown` = the source could not be verified against a known content hash, so whether files were lost is undetermined; do not remove either location before comparing them."),retentionLedger:Ct(Gn).optional().describe("Skill cross-level move failures only: present when this call could not determine whether the occupant at the destination is a copy an earlier failed move retained. `unreadable` = the retained-destination ledger itself could not be read. `occupant-unverifiable` = the directory at the destination could not be verified against the copy this server recorded — either it could not be read at all, or it carries no SKILL.md to compare — so this server could not confirm whether it is the copy an earlier failed move retained. It accompanies `moveState: nothing-written` — that code is still true of this call, which wrote nothing — but do NOT read it as an ordinary collision: treat the occupant the way you would a `sourceState` other than `intact` and compare it against the source before deleting it. A triple this MCP process cannot recognise as consistent is withheld whole — `moveState`, `sourceState` and `retentionLedger` together — so once any server on this connection can emit this field, treat an absent `retentionLedger` on a `nothing-written` refusal that reports a destination collision (`urn:ok:error:doc-already-exists`) as unverified rather than as an unconditionally safe retry. The other `nothing-written` refusals — invalid arguments, no project root, no usable skill home — never reached a destination occupant to verify, so they stay safe to retry once the refusal is addressed.")})},async e=>{let n=await l3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return $(o3(),!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return $("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let n=H5(e.template.from);if(!n.ok)return $(`Error: ${n.error}`,!0);let r=H5(e.template.to);if(!r.ok)return $(`Error: ${r.error}`,!0);let i=await y3(a,`/api/template`,{fromFolder:n.folder,fromName:n.name,toFolder:r.folder,toName:r.name,...e.summary===void 0?{}:{summary:e.summary},...Y4(t.identityRef?.current)});if(!i.ok){let e=typeof i.error==`string`?i.error:`Template move failed`;return a3(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let o=i.committed===!0,s=typeof i.from==`string`?i.from:e.template.from,c=typeof i.to==`string`?i.to:e.template.to;return a3(`${o?`Renamed`:`Moved`} template ${s} → ${c}.${o?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:o})}if(e.skill!==void 0){if(e.from!==void 0||e.to!==void 0)return $("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `skill: { from, to }` — not both.",!0);let n=e.skill.scope??`project`;return e.skill.toScope!==void 0&&e.skill.toScope!==n?IDt(a,{fromScope:n,toScope:e.skill.toScope,fromName:e.skill.from,toName:e.skill.to,summary:e.summary,identity:t.identityRef?.current}):jDt(a,{fromName:e.skill.from,toName:e.skill.to,scope:e.skill.scope,summary:e.summary,identity:t.identityRef?.current})}if(e.from===void 0||e.to===void 0)return $("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template, or `skill: { from, to }` to move/rename a skill).",!0);let o=H(r,i.content.dir),s=fAt(o,e.from);if(s===null){let t=H5(e.from);return t.ok&&G(H(o,t.folder,`.ok`,`templates`,`${t.name}.md`))?$(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):$(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let c=e.from,l=e.to;if(s===`file`){let t=d3(e.from);if(!t.ok)return $(t.error,!0);let n=d3(e.to);if(!n.ok)return $(n.error,!0);c=t.docName,l=n.docName}else if(s===`folder`&&(!uAt(e.from)||!uAt(e.to)))return $("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let u=await y3(a,`/api/rename-path`,{kind:s,fromPath:c,toPath:l,...e.summary===void 0?{}:{summary:e.summary},...Y4(t.identityRef?.current)});if(!u.ok){let e=u.error,t=Xmt(u.colliding),n={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return a3(`Error: ${e}`,n,!0)}let d=sAt(u.renamed),f=cAt(u.rewrittenDocs),p=lAt(u.renamedAssets),m={config:t.config,resolveCwd:t.resolveCwd},h={},g,_;if(s===`file`){let e=await L5(l,m,r),t=await L5(c,m,r);e&&(h[l]=e.url,g=e.source),t&&(_=t.url)}else if(s===`folder`)for(let{toDocName:e}of d){let t=await L5(e,m,r);t&&(h[e]=t.url,g??=t.source)}let v=u.summary&&typeof u.summary==`object`?u.summary:void 0,y=typeof v?.hint==`string`?v.hint:void 0,b=[];if(s===`asset`)b.push(`Moved asset ${c} → ${l}.`);else if(s===`folder`)b.push(d.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${d.length} doc${d.length===1?``:`s`}, ${f.length} rewrite${f.length===1?``:`s`}).`);else{let e=d.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${c} -> ${l}`,t=f.length===0?`No inbound links required updates.`:`Rewrote ${f.length} ${dAt(f.length,`document`)}.`;b.push(`Renamed ${e}. ${t}`)}return p.length>0&&b.push(`Moved ${p.length} referenced ${dAt(p.length,`asset`)}.`),y&&b.push(y),a3(b.join(`
|
|
2139
2139
|
`),{ok:!0,kind:s,renamed:d,rewrittenDocs:f,...p.length>0?{renamedAssets:p}:{},...Object.keys(h).length>0?{previewUrls:h}:{},...g?{previewUrlSource:g}:{},..._?{previousPreviewUrl:_}:{},...v?{summary:v}:{}})})}const mAt=[`Read the authoring palette: markdown-native components/examples/guidance, themed html preview embedPatterns (charts, stat cards, SVG, interactive controls), and CSS tokens. No running OK server needed. Optional components:[ids] adds full JSX props in componentDetails plus notFound; ids are case-sensitive, max 32. cwd selects project.`,`Prefer native forms: > [!NOTE], <details>, mermaid fences, $math$. For interactive HTML/JS/CSS use html preview starters and var(--chart-1)/var(--foreground) tokens for light/dark themes. Inside SVG use style="fill: var(--chart-1)", not a fill presentation attribute.`,`Delimiters are live even in ordinary prose: ==highlight==, $inline math$/$$block math$$, %%comment%% and <!-- comment --> (HIDES text), ~~strikethrough~~. Keep literal pairs in an inline code span or backslash-escape either delimiter. For ~~ escape BOTH tildes on both sides; one-sided escaping is rewritten on save.`,`Preview iframes have open network access for external HTTPS resources/fetch/fonts/maps. They are sandboxed null-origin frames and cannot access the knowledge base, cookies or auth.`].join(`
|
|
2140
2140
|
`),hAt={components:To(R().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),cwd:R().optional().describe(X4)},gAt=i3({version:I(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:To(L({id:R(),displayName:R(),description:R(),authoring:Ct([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:R().describe(`Copy-ready source for the authoring form.`),guidance:R().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:To(L({id:R(),title:R(),description:R(),snippet:R().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:To(L({name:R().describe("CSS custom-property name, e.g. `--chart-1`."),light:R(),dark:R()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:To(z(R(),B())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:To(R()).optional().describe("Requested `components` ids that did not match any canonical.")}),_At=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
|