@inkeep/open-knowledge 0.89.4-beta.0 → 0.89.5-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cli-DAKo1Dp3.mjs → cli-BJHt5k5U.mjs} +6 -6
- package/dist/cli.mjs +1 -1
- package/dist/constants-CBlHBrLD.mjs +1 -0
- package/dist/{dist-k81QnN99.mjs → dist-CfKMRf03.mjs} +1 -1
- package/dist/{dist-CIYAWEYF.mjs → dist-CtwIv2ht.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-Ck7IdPUt.mjs → init-C7aWQIng.mjs} +2 -2
- package/dist/init-DKCPSGUy.mjs +1 -0
- package/dist/{launch-json-removal-U2KFm9Sc.mjs → launch-json-removal-DuZvM_QQ.mjs} +1 -1
- package/dist/{loader-Dnyz7fM9.mjs → loader-B9rADE46.mjs} +1 -1
- package/dist/loader-g-ztpgSj.mjs +1 -0
- package/dist/{open-browser-CozXyn3C.mjs → open-browser-BXYOobWo.mjs} +1 -1
- package/dist/preview-BO3kMuMd.mjs +1 -0
- package/dist/{preview-DIbjm9qq.mjs → preview-DVCjmHQa.mjs} +1 -1
- package/dist/public/assets/{AccountSection-O_yo52Dy.js → AccountSection-DnvSwNjb.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-cPL1LX-b.js → ActivityModeContent-X6Ift1uN.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-CG9_LIkJ.js → AddPropertiesButton-Be8m4PP5.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CADFHRsv.js → AgentDiffPane-BjMlrhGB.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-pECr6aIV.js → AttachmentsSection-e21S24ER.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-C4TY1f7B.js → CodeMirrorPropInput-BNo8oP9K.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-sxmESH2w.js → ContentRulesSection-C-wjtjKV.js} +1 -1
- package/dist/public/assets/{DocumentContext-BvOjiWsQ.js → DocumentContext-7-bcCjyC.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-C6xwRU0E.js → EditorModeToggle-BRMOEIli.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-Bn6D3KS6.js → ExcalidrawDocEditor-BIYYFBYb.js} +1 -1
- package/dist/public/assets/FeedbackForm-DtNueGGg.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-U1diThTm.js → ImportSkillDialog-BJbN8kfl.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-BbwR_Xhc.js → LinkPreviewsSection-DCJnkUOe.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-By8IWEC2.js → LintConfigEditor-BByZMbFx.js} +1 -1
- package/dist/public/assets/{LintingSection-EkiEd6XH.js → LintingSection-DOatBpog.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CFbF1QRE.js → ManagedArtifactProperties-CeDKYJOB.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-TDFaJYya.js +1 -0
- package/dist/public/assets/{Mermaid-B8e_9k_P.js → Mermaid-D0e9Tm5x.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-CjUeUynW.js → MermaidDocEditor-C2m6bXQl.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-BTq7VLG5.js → NetworkAccessSection-BJE3Ap5M.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DoRxhXZY.js → PropertyDisplayRow-7ZBuIDx0.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-DRKtn3mD.js → PublishToGitHubDialog-DfSETA5B.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-DZ2bS2r5.js → SchemaConfigEditor-BCWNZc1I.js} +1 -1
- package/dist/public/assets/{SearchSection-BocBPH7s.js → SearchSection-BvocdXd7.js} +1 -1
- package/dist/public/assets/{SessionsHost-Qg62Qwqh.js → SessionsHost-Cqcuh851.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-D5hV_-H4.js → SettingsDialogBody-3CQy2TPR.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-DITSL55U.js → ShareReceiveMissDialog-LwzyXRj8.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-LOhvM0Vh.js → SkillToolbarControls-DmeWPCaf.js} +1 -1
- package/dist/public/assets/{SourceEditor-BM7alMKz.js → SourceEditor-Bn_zPfy5.js} +1 -1
- package/dist/public/assets/{SyncSection-D6SWg41E.js → SyncSection-aAPqIx7v.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-DwT-TrQS.js → SyncStatusBadge-BOipzN-4.js} +1 -1
- package/dist/public/assets/{TerminalSection-CMJ2IWFq.js → TerminalSection-D1_0LTb2.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-llj2SU1r.js → TerminalWindowApp-CsohmnIv.js} +1 -1
- package/dist/public/assets/{TextDocEditor-C-XNuWo_.js → TextDocEditor-BIAguiv5.js} +1 -1
- package/dist/public/assets/{ThreadView-BSQ0MMDw.js → ThreadView-DRj6Zvtr.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-1Ja5O3Q5.js → TimelineDiffPane-CKOQnQrd.js} +1 -1
- package/dist/public/assets/{client-version-DQw-TZ5F.js → client-version-BhwKksa9.js} +1 -1
- package/dist/public/assets/{comment-chips-CqCNIMjK.js → comment-chips-DXW5W5jE.js} +1 -1
- package/dist/public/assets/{config-provider-BGDDkwi7.js → config-provider-BgNLp1Er.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-D320rwaw.js → doc-undo-manager-CclDJnI5.js} +1 -1
- package/dist/public/assets/{index-DSP8p9bh.js → index-DaU5bLfl.js} +7 -7
- package/dist/public/assets/{lint-plugins-Cg1aq0h8.js → lint-plugins-B77U8rg8.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-CjsYVdhG.js → pending-receive-nav-store-BUrIh1Pu.js} +1 -1
- package/dist/public/assets/{preferred-session-events-DFdQa1Ey.js → preferred-session-events-BSH7WP6z.js} +1 -1
- package/dist/public/assets/{progress-Daj1dWiJ.js → progress-DWKgBsNU.js} +1 -1
- package/dist/public/assets/{selection-context-Cuwfdopq.js → selection-context-DJeMv6Cb.js} +1 -1
- package/dist/public/assets/{src-CAA1FVoz.js → src-xiqls-1H.js} +1 -1
- package/dist/public/assets/{telemetry-impl-LA-vQlId.js → telemetry-impl-QvMh0c1r.js} +1 -1
- package/dist/public/assets/{telemetry-startup-WUeATH0W.js → telemetry-startup-Cwg3dafZ.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Wolqh09v.js → typing-burst-detector-BlG0DVbX.js} +1 -1
- package/dist/public/assets/{use-activity-panel-a8YARhmb.js → use-activity-panel-BiuJa4cj.js} +1 -1
- package/dist/public/assets/{use-open-skill-D9PDpWe0.js → use-open-skill-BN8Q7ks6.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-Dc8lWV60.js → use-terminal-enabled-BlDEOd4m.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-7xIXFItS.js → use-timeline-entry-diff-Bz9i7WsC.js} +1 -1
- package/dist/public/index.html +20 -20
- package/dist/{registry-probes-BBpzaE65.mjs → registry-probes-DmgGl3IH.mjs} +1 -1
- package/dist/{removal-file-path-CuS8lv9y.mjs → removal-file-path-CdKGHPS1.mjs} +1 -1
- package/dist/{repair-launch-json-Cd7MGZwo.mjs → repair-launch-json-qSUvUxa6.mjs} +1 -1
- package/dist/{repair-mcp-configs-D50j0NhQ.mjs → repair-mcp-configs-CVornOTQ.mjs} +1 -1
- package/dist/src-BGEkGg-X.mjs +1 -0
- package/dist/{src-CeaYzyFh.mjs → src-hsW7d3xx.mjs} +1 -1
- package/dist/start-Ct8L_vAu.mjs +1 -0
- package/dist/{start-D6IfSsxL.mjs → start-KK_40BBB.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-BFHqrsor.mjs +0 -1
- package/dist/init-Cbj53Eeg.mjs +0 -1
- package/dist/loader-CQUqdd74.mjs +0 -1
- package/dist/preview-Dp4YDD7T.mjs +0 -1
- package/dist/public/assets/FeedbackForm-WurwG1D6.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-sONecdUw.js +0 -1
- package/dist/src-3IaANAHe.mjs +0 -1
- package/dist/start-CZxUk5Zk.mjs +0 -1
|
@@ -1153,7 +1153,7 @@ ${uet(e).join(`
|
|
|
1153
1153
|
`).length)}),before:o,after:s,properties:ie(i,a)}}function xat(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function Sat(e,t){let n=t.doc,r=new Set,i=new Set;n&&n.transact(t=>{vat(t,e.insertions,r),vat(t,e.deletions,i)});let a=0,o=0;for(let e of GZ(t)){if(!(e.content instanceof gE))continue;let t=e.content.str.length;!e.deleted&&r.has(e)&&(a+=t),i.has(e)&&(o+=t)}return{additions:a,deletions:o}}function Cat(e,t){let n=[],r=null,i=!1;for(let a of e.sessionsForConnection(t)){if(i=!0,!r){let e=a.origin.context,n=typeof e?.agent_type==`string`?e.agent_type:void 0,i=typeof e?.color_seed==`string`?e.color_seed:t,o=ar(n),s=uo[o]??rt(i);r={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:s,icon:o,connectionId:t}}let e=a.docName,o=a.um,s=a.dc.document.getText(`source`),c=[];for(let e=0;e<o.undoStack.length;e++){let t=o.undoStack[e],n=xat(t),{additions:r,deletions:i}=Sat(t,s);c.push({stackIndex:e,ts:n,additions:r,deletions:i})}if(c.length===0)continue;c.sort((e,t)=>t.stackIndex-e.stackIndex);let l=c.reduce((e,t)=>e+t.additions,0),u=c.reduce((e,t)=>e+t.deletions,0),d=Math.max(...c.map(e=>e.ts));n.push({docName:e,additionsTotal:l,deletionsTotal:u,lastTs:d,bursts:c})}return i?(n.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:r,files:n}):{sessionAlive:!1,agent:null,files:[]}}function wat(e,t,n){if(e===null)return{preDrain:!1,reason:`checkpoint-null-splice`};if(t===null)return{preDrain:!1,reason:`checkpoint-no-target`};if(t.start===t.end){let n=t.start;return e.start<n&&n<e.end?{preDrain:!1,reason:`checkpoint-substantive-overlap`}:{preDrain:!0,reason:`pre-drain-disjoint`}}let r=Math.max(e.start,t.start),i=Math.min(e.end,t.end);return r>=i?{preDrain:!0,reason:`pre-drain-disjoint`}:n.slice(r,i).trim()===``?{preDrain:!0,reason:`pre-drain-whitespace-graze`}:{preDrain:!1,reason:`checkpoint-substantive-overlap`}}function Tat(e,t,n,r){let i=r.clients.get(e);if(i===void 0)return!1;let a=t+n;for(let e of i)if(t<e.clock+e.len&&e.clock<a)return!0;return!1}function*Eat(e,t,n,r,i){let a=i.clients.get(e);if(a===void 0)return;let o=t+n;for(let e of a){let n=Math.max(t,e.clock),i=Math.min(o,e.clock+e.len);n<i&&(yield[r+(n-t),r+(i-t)])}}function Dat(e,t,n){let r=0,i=1/0,a=-1/0;for(let n of GZ(e)){if(!(n.content instanceof gE))continue;let{client:e,clock:o}=n.id,s=n.content.str.length;if(n.deleted)Tat(e,o,s,t.deletions)&&(i=Math.min(i,r),a=Math.max(a,r));else{for(let[n,c]of Eat(e,o,s,r,t.insertions))i=Math.min(i,n),a=Math.max(a,c);r+=s}}return i===1/0?null:{start:Math.max(0,i-n),end:Math.max(0,a-n)}}const Oat=new Set([`replace`,`patch`]);function kat(e,t){return t===`append`?{start:e.replace(/\s+$/,``).length,end:e.length}:null}function Aat(e){let t=e=>({preDrain:!1,verdict:{preDrain:!1,reason:e},splice:null});if(!e.pendingDirty)return t(`skip-no-pending`);if(!e.witnessMatched)return t(`checkpoint-witness-mismatch`);if(e.op.kind===`agent-write`&&Oat.has(e.op.writeKind))return t(`checkpoint-full-overwrite`);let n=e.op.kind===`agent-undo`?Dat(e.op.ytext,e.op.stackItem,e.fmPrefixLen):kat(e.body,e.op.writeKind);if(n===null)return t(`checkpoint-no-target`);let r=lat(e.body,e.fragmentPmJson,e.mdManager,{lineEnding:e.lineEnding});if(r===null)return t(`checkpoint-null-splice`);if(r.newSlice===e.body.slice(r.spliceStart,r.spliceEnd))return t(`skip-already-converged`);let i=wat({start:r.spliceStart,end:r.spliceEnd},n,e.body);return i.preDrain?{preDrain:!0,verdict:i,splice:r}:{preDrain:!1,verdict:i,splice:null}}const KZ=new Set,qZ=new Set,JZ=new Set,YZ=new Set,XZ=new Set;let ZZ=null,QZ=null,$Z=null,eQ=null,tQ=null,nQ=null;pU(()=>{ZZ=null,QZ=null,$Z=null,eQ=null,tQ=null,nQ=null});function jat(e){return KZ.add(e),()=>{KZ.delete(e)}}function Mat(e){return qZ.add(e),()=>{qZ.delete(e)}}function Nat(e){return JZ.add(e),()=>{JZ.delete(e)}}function Pat(e){return YZ.add(e),()=>{YZ.delete(e)}}function Fat(e){return XZ.add(e),()=>{XZ.delete(e)}}function Iat(){if(!(ZZ&&QZ&&$Z&&eQ&&tQ&&nQ)){if(!ZZ){let e=gU().createObservableGauge(`ok.server.docs.loaded`,{description:`Server-side Y.Docs currently resident in memory (includes synthetic system/config docs).`,unit:`{documents}`});e.addCallback(e=>{let t=0;for(let e of KZ)try{t+=e()}catch{}e.observe(t)}),ZZ=e}if(!QZ){let e=gU().createObservableGauge(`ok.persistence.queue.depth`,{description:`Pending persistence stores by queue. Bounded labels: queue ∈ {branch_deferred, quiescence_deferred}.`,unit:`{documents}`});e.addCallback(e=>{let t=0,n=0;for(let e of qZ)try{let r=e();t+=r.branchDeferred,n+=r.quiescenceDeferred}catch{}e.observe(t,{queue:`branch_deferred`}),e.observe(n,{queue:`quiescence_deferred`})}),QZ=e}if(!$Z){let e=gU().createObservableGauge(`ok.bridge.drain_backlog`,{description:`Docs whose bridge observers hold an un-settled dirty flag at sample time (settlement is synchronous per drain, so a sustained non-zero value indicates a stuck drain).`,unit:`{documents}`});e.addCallback(e=>{let t=0;for(let e of JZ)try{e()&&t++}catch{}e.observe(t)}),$Z=e}if(!eQ){let e=gU().createObservableGauge(`ok.ws.connections.active`,{description:`Live collab connections. Bounded labels: kind ∈ {websocket, direct}. websocket = deduplicated client sockets; direct = in-process DirectConnections (agent sessions + server-held system/config docs).`,unit:`{connections}`});e.addCallback(e=>{let t=0,n=0;for(let e of YZ)try{let r=e();t+=r.websocket,n+=r.direct}catch{}e.observe(t,{kind:`websocket`}),e.observe(n,{kind:`direct`})}),eQ=e}if(!tQ||!nQ){let e=gU().createObservableGauge(`ok.sessions.active`,{description:`Live (docName, agentId) agent sessions. Pinned at ok.sessions.limit means new sessions are being refused with 503s.`,unit:`{sessions}`}),t=gU().createObservableGauge(`ok.sessions.limit`,{description:`Hard cap on live agent sessions (summed across server instances in this process).`,unit:`{sessions}`});e.addCallback(e=>{let t=0;for(let e of XZ)try{t+=e().active}catch{}e.observe(t)}),t.addCallback(e=>{let t=0;for(let e of XZ)try{t+=e().limit}catch{}e.observe(t)}),tQ=e,nQ=t}}}const rQ=J(`server-observers`),iQ=J(`server-observers`),aQ={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},oQ=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0,Lat=e=>typeof e==`object`&&!!e&&e.source===`connection`;function Rat(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}var zat=class extends Error{info;constructor(e){super(`Observer-A producer guard: serialize output failed structural legality (${e.reason}: ${e.detail})`),this.name=`ProducerGuardViolationError`,this.info=e}};const Bat=new Set([`jsxComponent`,`table`,`tableCell`,`tableHeader`]),sQ=`merge-boundary`;function Vat(e){if(e.type&&Bat.has(e.type))return!0;if(e.content){for(let t of e.content)if(Vat(t))return!0}return!1}function Hat(e){let t=new Set,n=e=>{if(e.type&&Bat.has(e.type)&&t.add(e.type),e.content)for(let t of e.content)n(t)};return n(e),[...t].sort().join(`,`)}let Uat=!1;function Wat(e,t){Uat||(Uat=!0,rQ.warn({docName:e??`unknown`,err:t instanceof Error?t:Error(String(t))},`[Server Observer A] Map-driven splice parse/serialize threw (doc: ${e??`unknown`}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only)`))}let Gat=!1;function Kat(e,t){Gat||(Gat=!0,rQ.warn({docName:e??`unknown`,err:t instanceof Error?t:Error(String(t))},`[Server Observer A] Spliced-body memo composition threw (doc: ${e??`unknown`}); the splice is unaffected and the next drain re-parses (warned once; further failures count in mapDrivenSpliceMemoSkips only)`))}function qat(e){let{currentText:t,lastSyncedXmlMd:n,mdManager:r,docName:i,mdastMemo:a,serializedNewPm:o,onResidualFallback:s}=e,c=s===void 0,l=e=>{s?s(e):z$e(e)},u=o.json;if(t!==n)return l(`text-mismatch`),null;if(i!==void 0&&($H(i)||eU(i)))return l(`synthetic-doc`),null;let{body:d}=an(t),f=t.length-d.length,p=lat(d,u,r,{onFallback:(e,t)=>{l(e),e===`parse-error`&&Wat(i,t)},onMemoHit:()=>{c&&B$e()},onMemoSkip:(e,t)=>{c&&V$e(e),e===`compose-failed`&&Kat(i,t)},memo:a,serializedNewPm:o,lineEnding:ho(t)});return p?{spliceStart:f+p.spliceStart,spliceEnd:f+p.spliceEnd,newSlice:p.newSlice}:null}function Jat(e,t){let n=t.spliceEnd-t.spliceStart;n>0&&e.delete(t.spliceStart,n),t.newSlice.length>0&&e.insert(t.spliceStart,t.newSlice)}const cQ=new WeakMap;function Yat(e){return cQ.get(e)}const lQ=new WeakMap;function Xat(e){return lQ.get(e)?.()}const uQ=new WeakMap;function Zat(e){return uQ.get(e)?.()}function Qat(e,t,n,r){return e!==t&&(r??ga(e))!==(n??ga(t))}function $at(e){return e instanceof aE?e.nodeName:e instanceof oE?`#text`:`#hook`}function eot(e){return e._item?.id?.client}const tot=e=>e.replace(/\s+/g,` `).trim(),not=e=>e.replace(/[*_~`]+/g,``);function rot(e){return tot(not(e.replace(/<[^>]*>/g,``).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/&/g,`&`)))}function iot(e){return tot(not(e.replace(/!?\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\\([\\`*_{}[\]()#+\-.!><])/g,`$1`)))}function aot(e,t,n){if(n.length===0)return!1;let r=e.toArray(),i=r.map(e=>rot(e.toString()));for(let e of n){let n=iot(e);if(n.length<8)continue;let a=new Set,o=new Set;for(let e=0;e<r.length;e++){let s=r[e];if(s===void 0||!i[e]?.includes(n))continue;let c=eot(s);c!==void 0&&(c===t?a.add($at(s)):o.add($at(s)))}for(let e of a)for(let t of o)if(e!==t)return!0}return!1}function oot(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),t.info.which===`growth`?y$e():v$e();let i=t.info.which,a=t.info.lostSubstrings.reduce((e,t)=>e+t.length,0),o=e.shadow?.();if(!o||!e.docName){e.lossRing?.record({event:Mq,docName:e.docName??``,writerId:null,direction:`a`,site:sQ,lostLen:a,which:i});return}let s=e.getBranch?.()??`main`,c=e.contentRoot??``;queueMicrotask(()=>{NJ(o,c,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:s,metadata:{lostSubstrings:t.info.lostSubstrings,which:t.info.which}}).then(t=>{C$e(),e.lossRing?.record({event:Mq,docName:e.docName,writerId:null,direction:`a`,site:sQ,lostLen:a,which:i,checkpointSha:t}),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));rQ.warn({err:n},`[Server Observer A] Silent checkpoint write failed`),iQ.warn({err:n,"doc.name":e.docName??null,branch:s,kind:`bridge-merge-loss`},`checkpoint write failed`),e.lossRing?.record({event:Mq,docName:e.docName,writerId:null,direction:`a`,site:sQ,lostLen:a,which:i})})})},s=t=>{M=!0,E=!0;try{tat(t,e.docName)&&(w1e(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){rQ.warn({err:e},`[Server Observer A] Split-brain telemetry failed`)}},c=t=>{e.lossRing?.record({event:`guard-defer`,docName:e.docName??``,writerId:null,direction:`b`,lostLen:t.reduce((e,t)=>e+t.length,0)})},l=(t,n)=>{let r=e.shadow?.();if(!r||!e.docName)return;let i=e.getBranch?.()??`main`,a=e.contentRoot??``,o=e.docName;queueMicrotask(()=>{NJ(r,a,{kind:`observer-a-duplication`,docName:o,contents:t,label:`Before duplication re-derive @ ${new Date().toISOString()}`,branch:i,metadata:{duplicatedLineCount:n}}).then(e=>{q$e(),console.warn(JSON.stringify({event:`observer-a-duplication-checkpoint-created`,docName:o,sha:e,kind:`observer-a-duplication`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));rQ.warn({docName:o,err:t},`[Server Observer A] Duplication checkpoint write failed`),iQ.warn({err:t,"doc.name":o,branch:i,kind:`observer-a-duplication`},`checkpoint write failed`)})})},u=(t,n,r,i)=>{if(e.lossDetectorEnabled===!1)return;let a=zet(t,n,r,i);if(a.length===0)return;J$e();let o=a.reduce((e,t)=>e+t.length,0),s=Ee(a.join(`
|
|
1154
1154
|
`)),c=e.shadow?.();if(!c||!e.docName){e.lossRing?.record({event:Mq,docName:e.docName??``,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s});return}let l=e.getBranch?.()??`main`,u=e.contentRoot??``,d=e.docName;queueMicrotask(()=>{NJ(c,u,{kind:`observer-a-apply-loss`,docName:d,contents:t,label:`Before Observer-A apply content-loss @ ${new Date().toISOString()}`,branch:l,metadata:{lostSubstrings:a}}).then(t=>{Y$e(),e.lossRing?.record({event:Mq,docName:d,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s,checkpointSha:t}),console.warn(JSON.stringify({event:`observer-a-apply-loss-checkpoint-created`,docName:d,sha:t,kind:`observer-a-apply-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));rQ.warn({docName:d,err:n},`[Server Observer A] Apply-loss checkpoint write failed`),iQ.warn({err:n,"doc.name":d,branch:l,kind:`observer-a-apply-loss`},`checkpoint write failed`),e.lossRing?.record({event:Mq,docName:d,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s})})})},d=(t,n,r)=>{X$e();let i=r.reduce((e,t)=>e+t.length,0),a=e.shadow?.(),o=e.docName;if(!a||!o){e.lossRing?.record({event:Pq,docName:o??``,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i});return}let s=e.getBranch?.()??`main`,c=e.contentRoot??``;queueMicrotask(()=>{NJ(a,c,{kind:`defer-exhaustion-loss`,docName:o,contents:t,label:`Before derive-defer force-resolve @ ${new Date().toISOString()}`,branch:s,metadata:{deferCount:n}}).then(t=>{e.lossRing?.record({event:Pq,docName:o,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i,checkpointSha:t}),console.warn(JSON.stringify({event:`derive-defer-exhaustion-checkpoint-created`,docName:o,sha:t,kind:`defer-exhaustion-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));rQ.warn({docName:o,err:n},`[Server Observer B] Derive-defer exhaustion checkpoint write failed`),iQ.warn({err:n,"doc.name":o,branch:s,kind:`defer-exhaustion-loss`},`checkpoint write failed`),e.lossRing?.record({event:Pq,docName:o,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i})})})},f=t=>{j=!0,C1e(),e.onReDeriveBackstop?.(t);let n=r.toString(),i=e.shadow?.(),a=e.docName;if(!i||!a){e.lossRing?.record({event:Nq,docName:a??``,writerId:null,direction:`b`,site:`rederive-backstop`});return}let o=e.getBranch?.()??`main`,s=e.contentRoot??``;queueMicrotask(()=>{NJ(i,s,{kind:`bridge-backstop-trip`,docName:a,contents:n,label:`Before re-derive backstop freeze @ ${new Date().toISOString()}`,branch:o,metadata:{rounds:t}}).then(t=>{e.lossRing?.record({event:Nq,docName:a,writerId:null,direction:`b`,site:`rederive-backstop`,checkpointSha:t}),console.warn(JSON.stringify({event:`bridge-rederive-backstop-checkpoint-created`,docName:a,sha:t,kind:`bridge-backstop-trip`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));rQ.warn({docName:a,err:n},`[Server Observer B] Re-derive backstop checkpoint write failed`),iQ.warn({err:n,"doc.name":a,branch:o,kind:`bridge-backstop-trip`},`checkpoint write failed`),e.lossRing?.record({event:Nq,docName:a,writerId:null,direction:`b`,site:`rederive-backstop`})})})},p=``,m=``,h=sat(),g=!1,_=!1,v=!1,y=0,b=0,x=e.deferGuardEnabled!==!1,S=``,C=!1,w=0,T=!1,E=!1,D=e.fixedPointBackstopEnabled!==!1,O=e.preDrainEnabled!==!1,k=[],A=0,j=!1,M=!1,N=!1,P=!1,ee=()=>{m=r.toString(),g=!1},te=e=>{p=e,ee(),g=e!==``,D&&e!==``&&m===e&&(N=!0)},F=e=>{p=e,m=e,g=!1},I=e=>{p=e,g=!1},ne=e=>{p=e,m=r.toString(),g=!0},re=()=>an(r.toString()).frontmatter,ie=(e,t)=>{let{slot:n}=ht(e,an(r.toString()).body);return sa(e,n+t)},ae=(e,t)=>e.frontmatter+vr(e.body,ho(t)),oe=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,se=rat(i,{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,docName:e.docName}),ce=``,le=``,ue=!1,de=(e,t)=>{if(ue&&e===ce&&t===le)return!0;let n=it(e,t,se);return n&&(ce=e,le=t,ue=!0),n},fe=(e,t,n,r)=>Qat(e,t,n,r)&&!de(e,t);try{let e=YN(n,a).toJSON(),t=i.serialize(e),o=ie(re(),t).md;de(r.toString(),o)?te(o):F(o),S=o}catch(e){BH(`a`),rQ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer A] Baseline init failed — starting from empty snapshot`),te(``)}let pe,he=new Map,ge=new Map,_e=(t,n)=>{let i=e.docName??`__nodoc__`,a=Date.now(),o=he.get(i);if(o!==void 0&&a-o.lastMs<5e3)o.suppressed+=1,E$e();else{let r=o?.suppressed??0;he.set(i,{lastMs:a,suppressed:0}),T$e(),console.warn(JSON.stringify({event:`producer-guard-violation`,docName:e.docName??null,reason:t.reason,construct:n,appliedDegrades:t.appliedDegrades,suppressedSincePrevious:r,timestamp:new Date().toISOString()}))}let s=e.shadow?.();if(!s||!e.docName)return;let c=r.toString();if(ge.get(i)===c)return;ge.set(i,c);let l=e.getBranch?.()??`main`,u=e.contentRoot??``,d=e.docName;queueMicrotask(()=>{NJ(s,u,{kind:`producer-guard-loss`,docName:d,contents:c,label:`Before producer-guard content-loss @ ${new Date().toISOString()}`,branch:l,metadata:{construct:n}}).then(e=>{w$e(),console.warn(JSON.stringify({event:`producer-guard-checkpoint-created`,docName:d,sha:e,kind:`producer-guard-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{ge.get(i)===c&&ge.delete(i);let t=e instanceof Error?e:Error(String(e));rQ.warn({err:t},`[Server Observer A] Producer-guard checkpoint write failed`),iQ.warn({err:t,"doc.name":d,branch:l,kind:`producer-guard-loss`},`checkpoint write failed`)})})},ve=(t,n)=>{if(n===pe||(pe=n,!Vat(t)))return;let r=i.parseWithFallback(n,oe),a=Br(t,r,{rawSourceSide:`expected`});if(!(a.equivalent||a.reason!==`content-loss`)){if(Rat())throw new zat({docName:e.docName,reason:a.reason,detail:a.detail});_e(a,Hat(t))}},ye=()=>{try{let c=YN(n,a).toJSON(),d=r.toString()===m,f=Date.now()-y>=2e3,_=d&&f,b=aat(i,c,{skipFreshnessDerive:!_}),x=b.body;_&&ve(c,x);let E=re(),D=ie(E,x),O=D.md,k=r.toString(),A=me(O,k,8);if(A.length>0&&aot(n,t.clientID,A)){F(O),v=!0,T=!0,s(`duplication-guard`),K$e(),l(O,A.length),yU({"observer.a.path":`gated-duplication-rederive`});return}if(_&&(S=O,C=!1,w=0),g&&p===O){fe(r.toString(),O)?(F(O),v=!0,s(`identity-gate`),yU({"observer.a.path":`gated-fragment-unchanged-rederive`})):yU({"observer.a.path":`gated-fragment-unchanged`});return}let j=ga(k),M=ga(O);if(j===M&&!ia(k,O)&&!Ki(k,O)){yU({"observer.a.path":`gated-in-sync`,"observer.a.gate_reason":k===O?`bytes-identical`:`tolerance-equivalent`}),te(O);return}let N=m,P=k===m,ee=P&&g&&m!==p&&j!==ga(p);yU({"observer.a.path":P?ee?`residual-merge`:`path-a`:`path-b`});let I={mergedText:null},ne=t=>D.adjusted===`none`?Ki(k,O)?(t?.(`doc-edge-runs`),null):qat({currentText:k,lastSyncedXmlMd:m,mdManager:i,docName:e.docName,mdastMemo:h,serializedNewPm:b,onResidualFallback:t}):(t?.(`composition-adjusted`),null),oe=e=>{if(!ee||!fe(e,O,M))return e;let t=`not-settled`,n=ne(e=>{t=e});if(n!==null){let t=k.slice(0,n.spliceStart)+n.newSlice+k.slice(n.spliceEnd);if(!fe(t,O,M))return fie(p,k,{start:n.spliceStart,end:n.spliceEnd},n.newSlice).length>0?(W$e(),yU({"observer.a.residual_merge_fallback":`splice-blocked-lossy`}),e):(U$e(),yU({"observer.a.residual_merge_fallback":`map-driven-splice`}),t)}return G$e(t),yU({"observer.a.residual_merge_fallback":`splice-unavailable`,"observer.a.residual_merge_fallback_reason":t}),e},se=performance.now(),ce=ee?null:ne();ce&&yU({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-se)}),t.transact(()=>{if(ce)Jat(r,ce);else if(P&&!ee)Kne(r,k,ae(D,k));else{let t=P?p:N,n=Hee(x),i=e=>n.unproject(e,k),a=e.mergeThreeWay??or;try{let e=oe(i(a(n.project(t),n.project(O),n.project(k))));Aa(r,k,e),I.mergedText=e}catch(e){if(!(e instanceof $a)||(o(e,N),Rat()))throw e;let t=i(e.info.result);Aa(r,k,t),I.mergedText=t}}e.__testApplyLossInjector?.(r)},aQ),ce&&R$e();let le=r.toString(),ue=ga(le);(ce||P&&!ee)&&u(O,M,le,ue),I.mergedText!==null&&!P&&$it(e.docName)&&(I$e(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!P,mergeBytesChanged:Math.abs(I.mergedText.length-k.length)}))),I.mergedText!==null&&P&&H$e(),zH(`a`),te(O),fe(le,O,M,ue)&&(le===N&&F(O),v=!0,s(`post-merge`))}catch(t){if(t instanceof $a||t instanceof zat)throw t;BH(`a`),rQ.error({err:t},`[Server Observer A] Failed to sync tree→text`);try{let e=YN(n,a).toJSON(),t=i.serialize(e),o=ie(re(),t).md;fe(r.toString(),o)?(ne(o),v=!0,s(`error-recovery`)):te(o)}catch(n){rQ.warn({docName:e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:n instanceof Error?n.message:String(n)},`[Server Observer A] Baseline recovery also failed`),p=``,m=``,g=!1}}},be=()=>{vU(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},ye)},xe=(e,t)=>{if(t.origin!==aQ){if(oQ(t.origin)){try{let e=re();ee(),S=m,C=!1,w=0,Se=e}catch(e){BH(`a`),rQ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement`),_=!0}return}Lat(t.origin)&&(b=Date.now()),_=!0,C=!0}};if(n.length>0&&r.length===0)try{let e=YN(n,a).toJSON(),o=i.serialize(e),s=ie(re(),o).md;t.transact(()=>{r.insert(0,s)},aQ),te(s)}catch(e){BH(`a`),rQ.error({err:e},`[Server Observer A] Failed initial sync`),te(``)}let Se=re(),Ce=()=>{try{let o=r.toString(),{frontmatter:s,body:l}=an(o),{slot:u,body:f}=ht(s,l);if(!E&&ga(m)===ga(o)&&!Ki(m,o)){Se!==s&&(_Z(`source-mode`),Se=s),D&&g&&p===o&&(N=!0);return}if(j){yU({"observer.b.path":`backstop-frozen`});return}if(T)T=!1;else if(x&&C){let t=i.serialize(YN(n,a).toJSON()),r=ie(s,t).md;if(ci(r,o,S)){if(w>=8)d(r,w,pa(r,o,S)),w=0,yU({"observer.b.path":`derive-timing-force-resolve`});else{w+=1,_=!0,v=!0,c(pa(r,o,S)),e.onDeriveTimingDefer?.({canonicalWitness:p,rawWitness:m}),P=!0,yU({"observer.b.path":`derive-timing-defer`});return}}}let h=i.parseWithFallback(f,oe),y=e.schema.nodeFromJSON(h);t.transact(()=>{qN(t,n,y,{mapping:new Map,isOMark:new Map})},aQ),E=!1,D&&(M=!0),Se!==s&&(_Z(`source-mode`),Se=s),zH(`b`);try{let t=i.serialize(h),n=Fa(s,u+t);iat(r.toString(),n,{site:`observer-b`,docName:e.docName,canonicalizeBody:e=>e===l?u+t:se(e)}),te(n),S=n,C=!1,w=0}catch(e){if(e instanceof ya)throw e;rQ.warn({err:e},`[Server Observer B] Post-sync re-serialization failed — using input body as baseline`),te(Fa(s,l))}}catch(e){if(e instanceof ya)throw e;BH(`b`),rQ.error({err:e},`[Server Observer B] Failed to sync text→tree`);try{let e=YN(n,a).toJSON(),t=i.serialize(e),r=re();I(ie(r,t).md)}catch(e){if(e instanceof ya)throw e;rQ.warn({err:e},`[Server Observer B] Baseline recovery also failed`)}}},we=()=>{vU(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},Ce)},Te=(e,t)=>{if(t.origin!==aQ){if(oQ(t.origin)){try{let e=re();ee(),Se=e}catch(e){BH(`b`),rQ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement`),v=!0}return}Lat(t.origin)&&(b=Date.now()),y=Date.now(),v=!0}},De=(t,n)=>{vU(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!_&&!v){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===aQ)){_=!1,v=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}M=!1,N=!1,P=!1;let i=_;_&&(_=!1,e.onDispatch?.(`a`),be());let a=v;if(v&&(v=!1,e.onDispatch?.(`b`),we()),D&&!P){if(N)A=0,k.length=0,j=!1;else if(M){let e=Ee(r.toString());k.includes(e)?(A+=1,A>=8&&!j&&f(A)):A=0,k.push(e),k.length>8&&k.shift()}}t.setAttribute(`observer.dispatch`,i&&a?`a-then-b`:i?`a`:a?`b`:`none`)})};n.observeDeep(xe),r.observe(Te),t.on(`afterAllTransactions`,De);let Oe=Nat(()=>_||v),ke=Wit(t);return cQ.set(t,{preDrain(o){if(!O)return{preDrain:!1,reason:`skip-disabled`};if(!C)return{preDrain:!1,reason:`skip-no-pending`};try{let e=YN(n,a).toJSON(),s=r.toString(),{body:c}=an(s),l=s.length-c.length,{preDrain:u,verdict:d,splice:f}=Aat({pendingDirty:!0,body:c,fragmentPmJson:e,witnessMatched:s===m,fmPrefixLen:l,lineEnding:ho(s),op:o.kind===`agent-undo`?{kind:`agent-undo`,ytext:r,stackItem:o.stackItem}:{kind:`agent-write`,writeKind:o.writeKind},mdManager:i});if(!u)return d;let p=ie(re(),i.serialize(e));if(p.adjusted!==`none`)return{preDrain:!1,reason:`checkpoint-fm-ambiguous`};let h=s.length-c.length;t.transact(()=>{Jat(r,{spliceStart:h+f.spliceStart,spliceEnd:h+f.spliceEnd,newSlice:f.newSlice})},aQ);let g=p.md;return te(g),S=g,C=!1,w=0,d}catch(t){return BH(`a`),rQ.warn({err:t instanceof Error?t:Error(String(t)),docName:e.docName},`[Server pre-drain] Discrimination threw — routing to the checkpoint floor`),{preDrain:!1,reason:`checkpoint-witness-mismatch`}}}}),lQ.set(t,()=>S),uQ.set(t,()=>b>0?b:void 0),()=>{Oe(),ke(),cQ.delete(t),lQ.delete(t),uQ.delete(t),t.off(`afterAllTransactions`,De),n.unobserveDeep(xe),r.unobserve(Te)}}const dQ=J(`agent-sessions`),sot={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function fQ(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${TH(e)}${kH(e)}`}async function pQ(e,t,n,r){if(fZ(e))return;let i=vQ(e.getText(`source`).toString(),t,n);if(i!==void 0)return AZ(i.newContent,r)}async function cot(e,t){let n=e.getText(`source`).toString(),{fenced:r,body:i}=It(n),a=yi(r,t);if(!a.ok||a.nextFenced===r)return;let o=r===``&&i!==``&&!i.startsWith(`
|
|
1155
1155
|
`);return AZ(a.nextFenced+(o?`
|
|
1156
|
-
`:``)+i)}const lot=2e3,uot=new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)dot(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function dot(e,t){return e!==void 0&&Math.abs(t-e)<lot}function fot(e,t,n,r){if(t!==`replace`)return;let i=uot.hasRecentPeer(e,n,r),a=dot(Zat(e),r);if(!(!i&&!a))throw new JK(fQ(e.name))}function mQ(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function hQ(e,t,n){let r=Yat(e);r&&vQ(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function gQ(e,t,n,r,i,a,o){if(fZ(e))throw new WJ({file:fQ(e.name)});return vU(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let s=pot(e,t,n,r,i,a,o);return s!==void 0&&yU({"agent.content_divergent":!0,"agent.intended_bytes":s.intendedBytes,"agent.actual_bytes":s.actualBytes,"agent.byte_delta":s.byteDelta,"agent.divergence_type":s.divergenceType}),s})}function _Q(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function vQ(e,t,n){let{frontmatter:r,body:i}=an(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?Dq(t):an(t);if((n===`append`||n===`prepend`)&&o===``)return;let s,c;switch(n){case`replace`:s=a||r,c=o;break;case`patch`:s=a||r,c=o;break;case`prepend`:s=r,c=i.length>0?`${o.replace(/\n+$/,``)}\n\n${i.replace(/^\n+/,``)}`:o;break;case`append`:s=r,c=i.length>0?`${i.replace(/\n+$/,``)}\n\n${o.replace(/^\n+/,``)}`:o}return{existingFm:r,finalFm:s,newContent:Fa(s,c)}}function pot(e,t,n,r,i,a,o){try{let s=e.getText(`source`).toString(),c=vQ(s,t,n);if(c===void 0)return;let{existingFm:l,finalFm:u,newContent:d}=c,f=a&&LJ(sot.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:s}:void 0,p=!1;if(u!==l){let t=Ci(Ni(u));if(t.map===null)throw new hZ({file:fQ(e.name),parseError:t.parseError??`unknown YAML parse error`});p=!0}else if(u===``&&an(d).frontmatter!==``)throw new hZ({file:fQ(e.name),parseError:"the payload's leading `---` fence pair would land at byte 0, where the composed document re-reads it as the frontmatter region instead of body",refusalClass:`byte-0-promotion`,hint:"Start the payload with a blank line so the fence pair cannot open the document, or use `***` / `___` for the thematic break."});fot(e,n,o,Date.now()),p&&_Z(`mcp-write`),n===`replace`?jq(e,d,r,i,f):Aq(e,d,`agent`,r,i,f);let m=e.getText(`source`).toString();o!==void 0&&m!==s&&uot.record(e,o,Date.now());let h=bit(m,d,n);return dQ.debug({docName:e.name,position:n,markdownBytes:t.length,divergent:h!==void 0},`[agent-write] applied agent markdown write`),h}catch(r){throw!(r instanceof hZ)&&!(r instanceof JK)&&dQ.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function mot(e,t,n,r){let i=e.dc.document;if(fZ(i))throw new WJ({file:fQ(i.name)});return vU(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=hot(e,t,n,r);return yU({"agent.undo_effective":i}),i})}function hot(e,t,n,r){let{dc:i,um:a,undoOrigin:o}=e,s=i.document,c=t===`last`?1:t===`count`?Math.min(Math.max(0,r??0),a.undoStack.length):a.undoStack.length;c===1&&a.undoStack.length>0&&Yat(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&LJ(o.context.origin)?{report:t=>u(e.docName,t,e.agentId),baselineFullMd:s.getText(`source`).toString()}:void 0;return s.transact(()=>{for(let e=0;e<c&&a.undoStack.length>0;e++)a.undo(),l=!0;l&&q7e(s,n,d)},o),dQ.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function got(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function _ot(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}const vot=256,yot=5e3;var yQ=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let bot=null;function xot(){return bot||=gU().createCounter(`ok.sessions.evictions_total`,{description:`Agent sessions evicted (LRU-idle) under capacity pressure to admit a new session. Sustained growth alongside ok.sessions.active pinned at ok.sessions.limit means the working set exceeds the cap.`,unit:`{sessions}`}),bot}var Sot=class{sessions=new Map;pendingSessions=new Map;activeOperations=new Map;hocuspocus;maxSessions;minEvictableIdleMs;bridgeLossReporter;assertDocumentScope;awaitWriteAdmission;evictions=0;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256,this.minEvictableIdleMs=t.minEvictableIdleMs??5e3,this.bridgeLossReporter=t.bridgeLossReporter,this.assertDocumentScope=t.assertDocumentScope,this.awaitWriteAdmission=t.awaitWriteAdmission}attachBridgeLossReporter(e){this.bridgeLossReporter=e}get liveSessionCount(){return this.sessions.size}get sessionLimit(){return this.maxSessions}get evictionCount(){return this.evictions}touchSession(e,t){t.lastUsedAt=Date.now(),this.sessions.delete(e),this.sessions.set(e,t)}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){this.assertDocumentScope?.(e);let n=this.sessionKey(e,t),r=this.sessions.get(n);return r&&this.touchSession(n,r),r}async withSessions(e){let t=[],n=async(e,n=pH,r)=>{let i=this.sessionKey(e,n),a=this.activeOperations.get(i)??{count:0};a.count+=1,this.activeOperations.set(i,a);let o=()=>{--a.count,a.count===0&&this.activeOperations.delete(i)};try{let i=await this.getSession(e,n,r);return t.push(o),i}catch(e){throw o(),e}};try{return await e(n)}finally{for(let e of t)e()}}async getSession(e,t=pH,n){if($H(e)||eU(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);if(this.assertDocumentScope?.(e),this.awaitWriteAdmission){let t=Date.now();await this.awaitWriteAdmission()||dQ.warn({docName:e,waitedMs:Date.now()-t},`[agent-session] git batch still in progress after the admission wait; admitting the write`)}let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return this.touchSession(r,i),i;let a=this.pendingSessions.get(r);if(a)return dQ.debug({docName:e,agentId:t},`[agent-session] joining in-flight session creation`),a;for(;this.sessions.size+this.pendingSessions.size>=this.maxSessions;)if(await this.evictLruIdleSession()===null)throw dQ.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new yQ(this.maxSessions);let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=got(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=_ot(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s);dQ.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new $ke([c.document.getText(`source`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),dQ.info({docName:e,agentId:t,sessionId:i},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e,lastUsedAt:Date.now(),bridgeLossReporter:this.bridgeLossReporter}}async evictLruIdleSession(){for(let[e,t]of this.sessions){if(this.activeOperations.has(e))continue;let n=Date.now()-t.lastUsedAt;return n<this.minEvictableIdleMs?null:(this.sessions.delete(e),await this.cleanupSession(e,t,{docName:t.docName,agentId:t.agentId,evicted:!0}),this.evictions++,b$e(),xot().add(1),dQ.info({docName:t.docName,agentId:t.agentId,idleMs:n},`[agent-session] Evicted LRU idle session under capacity pressure`),e)}return null}hasSession(e,t=pH){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,n){dQ.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){dQ.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){dQ.error({err:e,...n},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=pH){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(await this.cleanupSession(n,r,{docName:e,agentId:t}),dQ.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));dQ.debug({agentId:e,pendingSettled:n.length,closing:r.length},`[agent-session] closing all sessions for agent`);for(let t of r){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));dQ.debug({docName:e,closing:n.length},`[agent-session] closing all sessions for doc`);for(let t of n){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];dQ.debug({closing:t.length},`[agent-session] closing all sessions`);for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const Cot=Hc(Dae);function bQ(e){return U(Rs(e),Iee)}async function xQ(e,t){let n=bQ(e);await AU(H(n),{recursive:!0});try{return await yl(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const wot={warn:(e,t)=>J(`skills`).warn(e,t)};async function SQ(e,t=wot){let n=bQ(e),r;try{r=await Cot(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,rl.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=Ui.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function CQ(e,t){let n=Ui.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=bQ(e);await AU(H(r),{recursive:!0});let i=(0,rl.parseDocument)(``);i.contents=i.createNode(n.data);let a=i.toString();await Is(r,a,{fs:UU})}async function wQ(e,t,n){let r=await SQ(e,n);return r===null?null:r.targets[t]?.version??null}async function Tot(e,t,n){let r=await SQ(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function TQ(e,t,n,r,i){if(!xie.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await xQ(e,async()=>{let a=await SQ(e,i)??da(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await CQ(e,{...a,targets:{...a.targets,[t]:l}})})}async function Eot(e,t,n){let r=(await SQ(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function Dot(e,t,n,r){await xQ(e,async()=>{let i=await SQ(e,r)??da();await CQ(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function Oot(e,t){let n=await SQ(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function kot(e,t,n){t.length!==0&&await xQ(e,async()=>{let r=await SQ(e,n)??da(),i=new Set([...r.installsReported??[],...t]);await CQ(e,{...r,installsReported:[...i].sort()})})}async function Aot(e,t,n){t.length!==0&&await xQ(e,async()=>{let r=await SQ(e,n);if(!r?.installsReported?.length)return;let i=new Set(t),a=r.installsReported.filter(e=>!i.has(e));a.length!==r.installsReported.length&&await CQ(e,{...r,installsReported:a})})}async function EQ(){let e=new URL(`../package.json`,import.meta.url),t=await Cot(Bs(e),`utf-8`),n=JSON.parse(t);if(typeof n.version!=`string`||n.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return n.version}async function jot(e,t){let[n,r]=await Promise.all([EQ(),Mot(e,t)]);return{currentVersion:n,targets:r}}async function Mot(e,t=wot){let n=null;try{n=await SQ(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:bQ(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=eie.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const Not=J(`agent-registry-apply`);function Pot(e){return{probes:Ore(e),detection:ne}}const Fot=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function Iot(e,t){try{return await e()}catch(e){return Not.warn({err:e},`host snapshot failed; claiming nothing`),Pot(t)}}async function Lot(e,t){let n=await Iot(t.snapshot,t.env),r=Bre({probes:n.probes,detection:n.detection}),i=Kee(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await sne(i,t.execute??Fot),{decisionHome:o}=t,s=Rot(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await Dot(o,hH.discovery,c).catch(e=>{Not.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await Iot(t.snapshot,t.env)}}function Rot(e){let t=e.actions.filter(e=>e.piece===`skill`&&e.scope===`user`);return t.some(e=>e.action===`written`||e.action===`overwritten`)?`installed`:t.some(e=>e.action===`removed`)?`removed`:null}const zot=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function DQ(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(zot,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function OQ(e,t){let n=DQ(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=kQe(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.suppliedWriterId!==void 0?{kind:`agent`,writerId:r.suppliedWriterId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:fH(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}const Bot=new Set([`GET`,`HEAD`,`OPTIONS`]);function Vot(e){return Bot.has(e??`GET`)}function Hot(e){return e===`null`||e.toLowerCase().startsWith(`file:`)}function Uot(e){if(e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function kQ(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function Wot(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function AQ(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function Got(e,t){return e!==void 0&&AQ(e)===t}const Kot=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function jQ(e){return Kot.some(t=>e.headers[t]!==void 0)}const MQ=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var qot=class extends Error{};const Jot=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function Yot(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function NQ(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(Yot).filter(e=>!Jot.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:AQ(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function PQ(e,t){return kQ(e)?!0:t.allowExternal&&e!==void 0}function Xot(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function FQ(e,t){if(Wot(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=Xot(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&Got(e,t.externalOrigin.host)}function IQ(e,t){if(Uot(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&AQ(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=Yot(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function Zot(e,t,n){if(e===void 0)return{admitted:!0,corsGrant:!0};let r=Hot(e);return!IQ(e,n)||r&&!Vot(t)?{admitted:!1,detail:r?`Requests from a null origin, and writes from a file: origin, are refused. Send the request from a loopback page, the OpenKnowledge app, or a client that sends no Origin header.`:void 0}:{admitted:!0,corsGrant:!r}}function LQ(e,t){return!t.tolerateForwardedHeaders&&jQ(e)}let Qot=!1;function RQ(e,t){Qot||(Qot=!0,e.warn({handler:t},`[ingress] refused a request carrying a forwarding header (X-Forwarded-For etc.) — without external-exposure consent, every surface except the /healthz + /readyz probes refuses proxied requests (APIs 403, /collab upgrades dropped). To front this server with a proxy, set server.externalUrl to the public origin in .ok/config.yml (or OK_EXTERNAL_URL) AND consent with server.allowExternal: true in .ok/local/config.yml (or OK_ALLOW_EXTERNAL=1) — the keys live in different files because consent is per-machine and never travels. allowExternal consents to exposure on a server with NO authentication — restrict access at the edge. Removing server.externalUrl does not lift this refusal (it fires on the header, not the URL) and would un-admit that Host/Origin everywhere else. Warned once per process; every refusal is still logged at warn level (HTTP refusals additionally as api.error, counted in ok.api.error.count).`))}const $ot=new WeakMap;function est(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:kQ(n)?`loopback`:`external`,clientSurface:t.clientSurface,actor:void 0};return $ot.set(e,r),r}function tst(e){return $ot.get(e)}const zQ=J(`local-op-security`),nst=GD,rst=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function BQ(e){return!e||typeof e!=`string`||rst.some(t=>t.test(e))?!1:nst.some(t=>t.test(e))}function VQ(e){return e===`~`?vc():e.startsWith(`~/`)?U(vc(),e.slice(2)):e}function ist(e,t){let n=H(e);for(;n!==t&&n!==H(n);){let e;try{e=rc(n)}catch(e){let t=JW(e);return zQ.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return zQ.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=H(n)}return!1}function ast(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=lc(t)}catch(e){let n=JW(e);return zQ.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=G(VQ(e)),i=[],a=r;for(;;){let e=null;try{e=rc(a)}catch(e){let t=JW(e);if(t!==`ENOENT`)return zQ.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=lc(a)}catch(n){let i=JW(n);if(e.isSymbolicLink())return zQ.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(ist(a,t))return zQ.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;zQ.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return zQ.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:U(r,...i),s=W(n,o);return s===``||!s.startsWith(`..`)&&!Ks(s)}let r=H(a);if(r===a)return!1;i.unshift(Us(a)),a=r}}function HQ(e){return ast(e,vc())}function ost(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function sst(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&cst(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function cst(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function lst(e,t,n){let r=n.policy??NQ({});return!ost(e)&&!PQ(e.socket.remoteAddress,r)?(Z(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):sst(e,r)?!0:(Z(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function ust(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const dst=new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256);function fst(e){dst.push(e)}const pst=$c.cursor,mst=$c.codex,hst=$c[`claude-desktop`],gst={app:null,signals_fired:[]};function _st(e){if(!e)return{...gst};let t=[],n=e.ua,r=e.referer,i=!!n&&pst.test(n),a=!!r&&r.includes(`?strategy=C_iframe`);if(i&&t.push(`cursor_ua_regex`),a&&t.push(`cursor_referer_strategy_iframe`),i||a)return{app:`cursor`,signals_fired:t};let o=!!n&&mst.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&hst.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...gst}}const vst=new Set([`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/agent-write-batch`,`/api/comments`,`/api/comment`,`/api/client-logs`,`/api/frontmatter-patch`,`/api/save-version`,`/api/rollback`,`/api/lint/fix`,`/api/folder-config`,`/api/template`,`/api/agent-integrations/apply`]);function UQ(e,t={}){let{dynamic:n}=t,r=new Set(t.mutating??[]),i=t.mutatingPrefixes??[],a=Object.keys(e);if(n!==void 0&&!n.prefix.endsWith(`/`))throw Error(`dynamic.prefix '${n.prefix}' must end in '/' — a bare prefix mounts a wildcard that also swallows unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);for(let e of i){if(!e.endsWith(`/`))throw Error(`mutatingPrefixes entry '${e}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);if(e!==n?.prefix&&!a.some(t=>t.startsWith(e)))throw Error(`mutatingPrefixes entry '${e}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`)}let o=new Map(Object.entries(e)),s={resolve(e){let t=o.get(e);return t?{template:e,dispatch:(e,n)=>t(e,n)}:n!==void 0&&e.startsWith(n.prefix)?{template:n.template,dispatch:n.dispatch(e.slice(n.prefix.length))}:null},isMutating:e=>r.has(e)||i.some(t=>e.startsWith(t))};return{paths:n===void 0?a:[...a.filter(e=>!e.startsWith(n.prefix)),`${n.prefix}*`],table:s}}let WQ=null;pU(()=>{WQ=null});function yst(){return WQ||=gU().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),WQ}function bst(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??NQ({}),a=e=>FQ(e,i);return async(o,s)=>{let c=o.url?.split(`?`)[0];if(!c)return!1;let l=r.resolve(c);if(!l)return!1;let u=e=>{let t=o.headers[e];if(t!==void 0)return Array.isArray(t)?t.join(`, `):t};fst({ts:Date.now(),url:c,method:o.method??``,ua:u(`user-agent`),origin:u(`origin`),referer:u(`referer`),host:u(`host`),remote:o.socket?.remoteAddress,secChUa:u(`sec-ch-ua`),secChUaMobile:u(`sec-ch-ua-mobile`),secChUaPlatform:u(`sec-ch-ua-platform`),secFetchSite:u(`sec-fetch-site`),secFetchDest:u(`sec-fetch-dest`),secFetchMode:u(`sec-fetch-mode`),secFetchUser:u(`sec-fetch-user`)});let d=o.method??`GET`,f=l.template,p=xoe(u(Kc.kind)),m=c.startsWith(`/api/`)?U8e(o):void 0;if(est(o,{requestId:m,clientSurface:p}),m!==void 0&&(G8e(o,m),typeof s.setHeader==`function`&&s.setHeader(HK,m),typeof s.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:m,method:d,route:f,status:s.statusCode,durationMs:Date.now()-e,...p===void 0?{}:{clientSurface:p},...s.writableFinished?{}:{aborted:!0}},`${d} ${f} ${s.statusCode}`))};s.once(`finish`,r),s.once(`close`,r)}if(c.startsWith(`/api/`)){typeof s.setHeader==`function`&&s.setHeader(`Cache-Control`,`no-store`);let e=o.headers.origin,t=Zot(e,d,i);if(!t.admitted)return Z(s,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`,detail:t.detail}),!0;if(typeof s.setHeader==`function`&&(e!==void 0&&s.setHeader(`Vary`,`Origin`),t.corsGrant&&(e!==void 0&&s.setHeader(`Access-Control-Allow-Origin`,e),s.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${HK}, ${Kc.protocol}, ${Kc.runtime}, ${Kc.kind}`),s.setHeader(`Access-Control-Expose-Headers`,HK))),o.method===`OPTIONS`)return s.writeHead(204),s.end(),!0}if(r.isMutating(c)){if(n&&l.dispatch!==void 0&&(d===`POST`||d===`PUT`||d===`DELETE`)&&!vst.has(c))return Z(s,403,`urn:ok:error:single-file-mode`,`Single-file previews cannot manage project files.`,{handler:`api-preview-content-scope`}),!0;let e=o.socket?.remoteAddress;if(e!==void 0&&!PQ(e,i))return Z(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(o.headers.host))return Z(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:MQ}),!0}if(c.startsWith(`/api/`)){let e=n?`api-ephemeral-gate`:`api-read-gate`,t=o.socket?.remoteAddress;if(t!==void 0&&!PQ(t,i))return Z(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:e}),!0;if(!a(o.headers.host))return Z(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:e,detail:MQ}),!0}if(!c.startsWith(`/api/`))return!1;let h=ko.extract(To.active(),o.headers),g=hU(),_=Date.now();return await To.with(h,()=>g.startActiveSpan(`HTTP ${d} ${f}`,{kind:Hie.SERVER,attributes:{[Cb]:d,[Tb]:f,[Ob]:c,[kb]:`http`,[Ab]:o.headers[`user-agent`]??``,"ok.request.id":m,"ok.client.surface":p}},async t=>{try{let n=l.dispatch;n===void 0?Z(s,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${d} ${c}`}):r.isMutating(c)&&e.dispatchMutation!==void 0?await e.dispatchMutation(()=>n(o,s),c):await n(o,s);let i=s.statusCode;t.setAttribute(wb,i),i>=500&&t.setStatus({code:Ao.ERROR,message:`status ${i}`})}catch(e){throw t.recordException(e),t.setStatus({code:Ao.ERROR,message:e instanceof Error?e.message:String(e)}),!s.headersSent&&!s.writableEnded&&!s.destroyed&&Z(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:f,cause:e}),t.setAttribute(wb,s.statusCode),e}finally{t.end();let e=(Date.now()-_)/1e3;yst().record(e,{[Cb]:d,[Tb]:f,[wb]:s.statusCode})}})),!0}}function GQ(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof $a||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;Z(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function xst(e,t){return KQ(e,{maxBytes:t,timeoutMs:3e4})}function Sst(e){let t=e?.split(`;`,1)[0]?.trim().toLowerCase();return t===void 0?!1:t===`application/json`||/^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(t)}function Cst(e){return e.headers[`transfer-encoding`]!==void 0||Number(e.headers[`content-length`]??0)>0}async function KQ(e,t){if(Cst(e)&&!Sst(e.headers[`content-type`]))throw new qQ;let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new XQ(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new YQ(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var qQ=class extends Error{constructor(){super(`Request body is not labeled as JSON`),this.name=`UnsupportedMediaTypeError`}};function JQ(e,t){Z(e,415,`urn:ok:error:unsupported-media-type`,`Request body must be JSON.`,{handler:t,detail:`Send the request body as JSON with the header Content-Type: application/json.`})}var YQ=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${wst(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},XQ=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function wst(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function ZQ(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.some(e=>e.code===`custom`&&e.params?.contentControlAdmission===!0),o=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `),s=a?`${o} Offsets count the full submitted field after caller composition, including any frontmatter.`:o;return Z(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:s,...a?{extensions:{contentControlAdmission:!0}}:{}}),{ok:!1}}function QQ(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){Z(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&Z(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=ZQ(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await xst(r,n.maxBodyBytes??1048576)}catch(e){if(e instanceof qQ){JQ(i,n.handler);return}if(e instanceof YQ){Z(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof XQ){Z(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}Z(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){Z(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=ZQ(e,o,i,n);s.ok&&await t(r,i,s.value)}}const $Q=()=>J(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){$Q().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){$Q().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),Z(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){$Q().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),Z(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function Tst(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return UQ({"/api/agent-integrations/apply":QQ(Qne,GQ(async(e,n,s)=>{let c=OQ(s,r);if(c.kind===`invalid-summary`){Z(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`agent-integrations-apply`});return}let l=ost(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await Lot(s.intents,{execute:o?.execute,env:l,snapshot:()=>Eq({env:l,resolve:o?.probe}),decisionHome:i??vc(),...o?.userSkillPresentAnywhere===void 0?{}:{userSkillPresentAnywhere:o.userSkillPresentAnywhere},projectDir:a});t.info({actor:c.kind,applied:u.actions.length,failed:u.actions.filter(e=>e.errorId!==void 0).length,conflicts:u.conflicts.map(e=>e.kind)},`[agent-integrations] batch applied`),Q(n,200,Are,{...u,snapshot:d},{handler:`agent-integrations-apply`})},{handler:`agent-integrations-apply`,title:`Failed to apply AI tool connections.`}),{handler:`agent-integrations-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`agent-integrations-apply`})})},{mutating:[`/api/agent-integrations/apply`]})}let Est=0;const Dst=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function e$(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++Est,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},Dst)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),l0e(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}let t$=new Map;function n$(e,t,n,r,i,a,o,s){let c=t$.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},t$.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function Ost(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of t$){for(let e of t)n.docs.delete(e);n.docs.size===0&&t$.delete(e)}}function kst(){let e=t$;return t$=new Map,e}function Ast(e){for(let[t,n]of e){let e=t$.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},t$.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function jst(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1156
|
+
`:``)+i)}const lot=2e3,uot=new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)dot(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function dot(e,t){return e!==void 0&&Math.abs(t-e)<lot}function fot(e,t,n,r){if(t!==`replace`)return;let i=uot.hasRecentPeer(e,n,r),a=dot(Zat(e),r);if(!(!i&&!a))throw new JK(fQ(e.name))}function mQ(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function hQ(e,t,n){let r=Yat(e);r&&vQ(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function gQ(e,t,n,r,i,a,o){if(fZ(e))throw new WJ({file:fQ(e.name)});return vU(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let s=pot(e,t,n,r,i,a,o);return s!==void 0&&yU({"agent.content_divergent":!0,"agent.intended_bytes":s.intendedBytes,"agent.actual_bytes":s.actualBytes,"agent.byte_delta":s.byteDelta,"agent.divergence_type":s.divergenceType}),s})}function _Q(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function vQ(e,t,n){let{frontmatter:r,body:i}=an(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?Dq(t):an(t);if((n===`append`||n===`prepend`)&&o===``)return;let s,c;switch(n){case`replace`:s=a||r,c=o;break;case`patch`:s=a||r,c=o;break;case`prepend`:s=r,c=i.length>0?`${o.replace(/\n+$/,``)}\n\n${i.replace(/^\n+/,``)}`:o;break;case`append`:s=r,c=i.length>0?`${i.replace(/\n+$/,``)}\n\n${o.replace(/^\n+/,``)}`:o}return{existingFm:r,finalFm:s,newContent:Fa(s,c)}}function pot(e,t,n,r,i,a,o){try{let s=e.getText(`source`).toString(),c=vQ(s,t,n);if(c===void 0)return;let{existingFm:l,finalFm:u,newContent:d}=c,f=a&&LJ(sot.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:s}:void 0,p=!1;if(u!==l){let t=Ci(Ni(u));if(t.map===null)throw new hZ({file:fQ(e.name),parseError:t.parseError??`unknown YAML parse error`});p=!0}else if(u===``&&an(d).frontmatter!==``)throw new hZ({file:fQ(e.name),parseError:"the payload's leading `---` fence pair would land at byte 0, where the composed document re-reads it as the frontmatter region instead of body",refusalClass:`byte-0-promotion`,hint:"Start the payload with a blank line so the fence pair cannot open the document, or use `***` / `___` for the thematic break."});fot(e,n,o,Date.now()),p&&_Z(`mcp-write`),n===`replace`?jq(e,d,r,i,f):Aq(e,d,`agent`,r,i,f);let m=e.getText(`source`).toString();o!==void 0&&m!==s&&uot.record(e,o,Date.now());let h=bit(m,d,n);return dQ.debug({docName:e.name,position:n,markdownBytes:t.length,divergent:h!==void 0},`[agent-write] applied agent markdown write`),h}catch(r){throw!(r instanceof hZ)&&!(r instanceof JK)&&dQ.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function mot(e,t,n,r){let i=e.dc.document;if(fZ(i))throw new WJ({file:fQ(i.name)});return vU(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=hot(e,t,n,r);return yU({"agent.undo_effective":i}),i})}function hot(e,t,n,r){let{dc:i,um:a,undoOrigin:o}=e,s=i.document,c=t===`last`?1:t===`count`?Math.min(Math.max(0,r??0),a.undoStack.length):a.undoStack.length;c===1&&a.undoStack.length>0&&Yat(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&LJ(o.context.origin)?{report:t=>u(e.docName,t,e.agentId),baselineFullMd:s.getText(`source`).toString()}:void 0;return s.transact(()=>{for(let e=0;e<c&&a.undoStack.length>0;e++)a.undo(),l=!0;l&&q7e(s,n,d)},o),dQ.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function got(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function _ot(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}const vot=256,yot=5e3;var yQ=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let bot=null;function xot(){return bot||=gU().createCounter(`ok.sessions.evictions_total`,{description:`Agent sessions evicted (LRU-idle) under capacity pressure to admit a new session. Sustained growth alongside ok.sessions.active pinned at ok.sessions.limit means the working set exceeds the cap.`,unit:`{sessions}`}),bot}var Sot=class{sessions=new Map;pendingSessions=new Map;activeOperations=new Map;hocuspocus;maxSessions;minEvictableIdleMs;bridgeLossReporter;assertDocumentScope;awaitWriteAdmission;evictions=0;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256,this.minEvictableIdleMs=t.minEvictableIdleMs??5e3,this.bridgeLossReporter=t.bridgeLossReporter,this.assertDocumentScope=t.assertDocumentScope,this.awaitWriteAdmission=t.awaitWriteAdmission}attachBridgeLossReporter(e){this.bridgeLossReporter=e}get liveSessionCount(){return this.sessions.size}get sessionLimit(){return this.maxSessions}get evictionCount(){return this.evictions}touchSession(e,t){t.lastUsedAt=Date.now(),this.sessions.delete(e),this.sessions.set(e,t)}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){this.assertDocumentScope?.(e);let n=this.sessionKey(e,t),r=this.sessions.get(n);return r&&this.touchSession(n,r),r}async withSessions(e){let t=[],n=async(e,n=pH,r)=>{let i=this.sessionKey(e,n),a=this.activeOperations.get(i)??{count:0};a.count+=1,this.activeOperations.set(i,a);let o=()=>{--a.count,a.count===0&&this.activeOperations.delete(i)};try{let i=await this.getSession(e,n,r);return t.push(o),i}catch(e){throw o(),e}};try{return await e(n)}finally{for(let e of t)e()}}async getSession(e,t=pH,n){if($H(e)||eU(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);if(this.assertDocumentScope?.(e),this.awaitWriteAdmission){let t=Date.now();await this.awaitWriteAdmission()||dQ.warn({docName:e,waitedMs:Date.now()-t},`[agent-session] git batch still in progress after the admission wait; admitting the write`)}let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return this.touchSession(r,i),i;let a=this.pendingSessions.get(r);if(a)return dQ.debug({docName:e,agentId:t},`[agent-session] joining in-flight session creation`),a;for(;this.sessions.size+this.pendingSessions.size>=this.maxSessions;)if(await this.evictLruIdleSession()===null)throw dQ.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new yQ(this.maxSessions);let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=got(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=_ot(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s);dQ.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new $ke([c.document.getText(`source`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),dQ.info({docName:e,agentId:t,sessionId:i},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e,lastUsedAt:Date.now(),bridgeLossReporter:this.bridgeLossReporter}}async evictLruIdleSession(){for(let[e,t]of this.sessions){if(this.activeOperations.has(e))continue;let n=Date.now()-t.lastUsedAt;return n<this.minEvictableIdleMs?null:(this.sessions.delete(e),await this.cleanupSession(e,t,{docName:t.docName,agentId:t.agentId,evicted:!0}),this.evictions++,b$e(),xot().add(1),dQ.info({docName:t.docName,agentId:t.agentId,idleMs:n},`[agent-session] Evicted LRU idle session under capacity pressure`),e)}return null}hasSession(e,t=pH){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,n){dQ.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){dQ.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){dQ.error({err:e,...n},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=pH){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(await this.cleanupSession(n,r,{docName:e,agentId:t}),dQ.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));dQ.debug({agentId:e,pendingSettled:n.length,closing:r.length},`[agent-session] closing all sessions for agent`);for(let t of r){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));dQ.debug({docName:e,closing:n.length},`[agent-session] closing all sessions for doc`);for(let t of n){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];dQ.debug({closing:t.length},`[agent-session] closing all sessions`);for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const Cot=Hc(Dae);function bQ(e){return U(Rs(e),Iee)}async function xQ(e,t){let n=bQ(e);await AU(H(n),{recursive:!0});try{return await yl(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const wot={warn:(e,t)=>J(`skills`).warn(e,t)};async function SQ(e,t=wot){let n=bQ(e),r;try{r=await Cot(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,rl.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=Ui.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function CQ(e,t){let n=Ui.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=bQ(e);await AU(H(r),{recursive:!0});let i=(0,rl.parseDocument)(``);i.contents=i.createNode(n.data);let a=i.toString();await Is(r,a,{fs:UU})}async function wQ(e,t,n){let r=await SQ(e,n);return r===null?null:r.targets[t]?.version??null}async function Tot(e,t,n){let r=await SQ(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function TQ(e,t,n,r,i){if(!xie.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await xQ(e,async()=>{let a=await SQ(e,i)??da(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await CQ(e,{...a,targets:{...a.targets,[t]:l}})})}async function Eot(e,t,n){let r=(await SQ(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function Dot(e,t,n,r){await xQ(e,async()=>{let i=await SQ(e,r)??da();await CQ(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function Oot(e,t){let n=await SQ(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function kot(e,t,n){t.length!==0&&await xQ(e,async()=>{let r=await SQ(e,n)??da(),i=new Set([...r.installsReported??[],...t]);await CQ(e,{...r,installsReported:[...i].sort()})})}async function Aot(e,t,n){t.length!==0&&await xQ(e,async()=>{let r=await SQ(e,n);if(!r?.installsReported?.length)return;let i=new Set(t),a=r.installsReported.filter(e=>!i.has(e));a.length!==r.installsReported.length&&await CQ(e,{...r,installsReported:a})})}async function EQ(){let e=new URL(`../package.json`,import.meta.url),t=await Cot(Bs(e),`utf-8`),n=JSON.parse(t);if(typeof n.version!=`string`||n.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return n.version}async function jot(e,t){let[n,r]=await Promise.all([EQ(),Mot(e,t)]);return{currentVersion:n,targets:r}}async function Mot(e,t=wot){let n=null;try{n=await SQ(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:bQ(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=eie.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const Not=J(`agent-registry-apply`);function Pot(e){return{probes:Ore(e),detection:ne}}const Fot=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function Iot(e,t){try{return await e()}catch(e){return Not.warn({err:e},`host snapshot failed; claiming nothing`),Pot(t)}}async function Lot(e,t){let n=await Iot(t.snapshot,t.env),r=Bre({probes:n.probes,detection:n.detection}),i=Kee(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await sne(i,t.execute??Fot),{decisionHome:o}=t,s=Rot(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await Dot(o,hH.discovery,c).catch(e=>{Not.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await Iot(t.snapshot,t.env)}}function Rot(e){let t=e.actions.filter(e=>e.piece===`skill`&&e.scope===`user`);return t.some(e=>e.action===`written`||e.action===`overwritten`)?`installed`:t.some(e=>e.action===`removed`)?`removed`:null}const zot=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function DQ(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(zot,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function OQ(e,t){let n=DQ(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=kQe(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.suppliedWriterId!==void 0?{kind:`agent`,writerId:r.suppliedWriterId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:fH(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}const Bot=new Set([`GET`,`HEAD`,`OPTIONS`]);function Vot(e){return Bot.has(e??`GET`)}function Hot(e){return e===`null`||e.toLowerCase().startsWith(`file:`)}function Uot(e){if(e===`file://`)return!0;try{let{hostname:t,protocol:n}=new URL(e);return n!==`http:`&&n!==`https:`&&n!==`file:`?!1:t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function kQ(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function Wot(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function AQ(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function Got(e,t){return e!==void 0&&AQ(e)===t}const Kot=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function jQ(e){return Kot.some(t=>e.headers[t]!==void 0)}const MQ=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var qot=class extends Error{};const Jot=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function Yot(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function NQ(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(Yot).filter(e=>!Jot.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:AQ(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function PQ(e,t){return kQ(e)?!0:t.allowExternal&&e!==void 0}function Xot(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function FQ(e,t){if(Wot(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=Xot(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&Got(e,t.externalOrigin.host)}function IQ(e,t){if(Uot(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&AQ(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=Yot(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function Zot(e,t,n){if(e===void 0)return{admitted:!0,corsGrant:!0};let r=Hot(e);return!IQ(e,n)||r&&!Vot(t)?{admitted:!1,detail:r?`Requests from a null origin, and writes from a file: origin, are refused. Send the request from a loopback page, the OpenKnowledge app, or a client that sends no Origin header.`:void 0}:{admitted:!0,corsGrant:!r}}function LQ(e,t){return!t.tolerateForwardedHeaders&&jQ(e)}let Qot=!1;function RQ(e,t){Qot||(Qot=!0,e.warn({handler:t},`[ingress] refused a request carrying a forwarding header (X-Forwarded-For etc.) — without external-exposure consent, every surface except the /healthz + /readyz probes refuses proxied requests (APIs 403, /collab upgrades dropped). To front this server with a proxy, set server.externalUrl to the public origin in .ok/config.yml (or OK_EXTERNAL_URL) AND consent with server.allowExternal: true in .ok/local/config.yml (or OK_ALLOW_EXTERNAL=1) — the keys live in different files because consent is per-machine and never travels. allowExternal consents to exposure on a server with NO authentication — restrict access at the edge. Removing server.externalUrl does not lift this refusal (it fires on the header, not the URL) and would un-admit that Host/Origin everywhere else. Warned once per process; every refusal is still logged at warn level (HTTP refusals additionally as api.error, counted in ok.api.error.count).`))}const $ot=new WeakMap;function est(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:kQ(n)?`loopback`:`external`,clientSurface:t.clientSurface,actor:void 0};return $ot.set(e,r),r}function tst(e){return $ot.get(e)}const zQ=J(`local-op-security`),nst=GD,rst=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function BQ(e){return!e||typeof e!=`string`||rst.some(t=>t.test(e))?!1:nst.some(t=>t.test(e))}function VQ(e){return e===`~`?vc():e.startsWith(`~/`)?U(vc(),e.slice(2)):e}function ist(e,t){let n=H(e);for(;n!==t&&n!==H(n);){let e;try{e=rc(n)}catch(e){let t=JW(e);return zQ.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return zQ.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=H(n)}return!1}function ast(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=lc(t)}catch(e){let n=JW(e);return zQ.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=G(VQ(e)),i=[],a=r;for(;;){let e=null;try{e=rc(a)}catch(e){let t=JW(e);if(t!==`ENOENT`)return zQ.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=lc(a)}catch(n){let i=JW(n);if(e.isSymbolicLink())return zQ.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(ist(a,t))return zQ.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;zQ.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return zQ.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:U(r,...i),s=W(n,o);return s===``||!s.startsWith(`..`)&&!Ks(s)}let r=H(a);if(r===a)return!1;i.unshift(Us(a)),a=r}}function HQ(e){return ast(e,vc())}function ost(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function sst(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`file:`;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&cst(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function cst(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function lst(e,t,n){let r=n.policy??NQ({});return!ost(e)&&!PQ(e.socket.remoteAddress,r)?(Z(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):sst(e,r)?!0:(Z(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function ust(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const dst=new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256);function fst(e){dst.push(e)}const pst=$c.cursor,mst=$c.codex,hst=$c[`claude-desktop`],gst={app:null,signals_fired:[]};function _st(e){if(!e)return{...gst};let t=[],n=e.ua,r=e.referer,i=!!n&&pst.test(n),a=!!r&&r.includes(`?strategy=C_iframe`);if(i&&t.push(`cursor_ua_regex`),a&&t.push(`cursor_referer_strategy_iframe`),i||a)return{app:`cursor`,signals_fired:t};let o=!!n&&mst.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&hst.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...gst}}const vst=new Set([`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/agent-write-batch`,`/api/comments`,`/api/comment`,`/api/client-logs`,`/api/frontmatter-patch`,`/api/save-version`,`/api/rollback`,`/api/lint/fix`,`/api/folder-config`,`/api/template`,`/api/agent-integrations/apply`]);function UQ(e,t={}){let{dynamic:n}=t,r=new Set(t.mutating??[]),i=t.mutatingPrefixes??[],a=Object.keys(e);if(n!==void 0&&!n.prefix.endsWith(`/`))throw Error(`dynamic.prefix '${n.prefix}' must end in '/' — a bare prefix mounts a wildcard that also swallows unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);for(let e of i){if(!e.endsWith(`/`))throw Error(`mutatingPrefixes entry '${e}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);if(e!==n?.prefix&&!a.some(t=>t.startsWith(e)))throw Error(`mutatingPrefixes entry '${e}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`)}let o=new Map(Object.entries(e)),s={resolve(e){let t=o.get(e);return t?{template:e,dispatch:(e,n)=>t(e,n)}:n!==void 0&&e.startsWith(n.prefix)?{template:n.template,dispatch:n.dispatch(e.slice(n.prefix.length))}:null},isMutating:e=>r.has(e)||i.some(t=>e.startsWith(t))};return{paths:n===void 0?a:[...a.filter(e=>!e.startsWith(n.prefix)),`${n.prefix}*`],table:s}}let WQ=null;pU(()=>{WQ=null});function yst(){return WQ||=gU().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),WQ}function bst(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??NQ({}),a=e=>FQ(e,i);return async(o,s)=>{let c=o.url?.split(`?`)[0];if(!c)return!1;let l=r.resolve(c);if(!l)return!1;let u=e=>{let t=o.headers[e];if(t!==void 0)return Array.isArray(t)?t.join(`, `):t};fst({ts:Date.now(),url:c,method:o.method??``,ua:u(`user-agent`),origin:u(`origin`),referer:u(`referer`),host:u(`host`),remote:o.socket?.remoteAddress,secChUa:u(`sec-ch-ua`),secChUaMobile:u(`sec-ch-ua-mobile`),secChUaPlatform:u(`sec-ch-ua-platform`),secFetchSite:u(`sec-fetch-site`),secFetchDest:u(`sec-fetch-dest`),secFetchMode:u(`sec-fetch-mode`),secFetchUser:u(`sec-fetch-user`)});let d=o.method??`GET`,f=l.template,p=xoe(u(Kc.kind)),m=c.startsWith(`/api/`)?U8e(o):void 0;if(est(o,{requestId:m,clientSurface:p}),m!==void 0&&(G8e(o,m),typeof s.setHeader==`function`&&s.setHeader(HK,m),typeof s.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:m,method:d,route:f,status:s.statusCode,durationMs:Date.now()-e,...p===void 0?{}:{clientSurface:p},...s.writableFinished?{}:{aborted:!0}},`${d} ${f} ${s.statusCode}`))};s.once(`finish`,r),s.once(`close`,r)}if(c.startsWith(`/api/`)){typeof s.setHeader==`function`&&s.setHeader(`Cache-Control`,`no-store`);let e=o.headers.origin,t=Zot(e,d,i);if(!t.admitted)return Z(s,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`,detail:t.detail}),!0;if(typeof s.setHeader==`function`&&(e!==void 0&&s.setHeader(`Vary`,`Origin`),t.corsGrant&&(e!==void 0&&s.setHeader(`Access-Control-Allow-Origin`,e),s.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${HK}, ${Kc.protocol}, ${Kc.runtime}, ${Kc.kind}`),s.setHeader(`Access-Control-Expose-Headers`,HK))),o.method===`OPTIONS`)return s.writeHead(204),s.end(),!0}if(r.isMutating(c)){if(n&&l.dispatch!==void 0&&(d===`POST`||d===`PUT`||d===`DELETE`)&&!vst.has(c))return Z(s,403,`urn:ok:error:single-file-mode`,`Single-file previews cannot manage project files.`,{handler:`api-preview-content-scope`}),!0;let e=o.socket?.remoteAddress;if(e!==void 0&&!PQ(e,i))return Z(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(o.headers.host))return Z(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:MQ}),!0}if(c.startsWith(`/api/`)){let e=n?`api-ephemeral-gate`:`api-read-gate`,t=o.socket?.remoteAddress;if(t!==void 0&&!PQ(t,i))return Z(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:e}),!0;if(!a(o.headers.host))return Z(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:e,detail:MQ}),!0}if(!c.startsWith(`/api/`))return!1;let h=ko.extract(To.active(),o.headers),g=hU(),_=Date.now();return await To.with(h,()=>g.startActiveSpan(`HTTP ${d} ${f}`,{kind:Hie.SERVER,attributes:{[Cb]:d,[Tb]:f,[Ob]:c,[kb]:`http`,[Ab]:o.headers[`user-agent`]??``,"ok.request.id":m,"ok.client.surface":p}},async t=>{try{let n=l.dispatch;n===void 0?Z(s,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${d} ${c}`}):r.isMutating(c)&&e.dispatchMutation!==void 0?await e.dispatchMutation(()=>n(o,s),c):await n(o,s);let i=s.statusCode;t.setAttribute(wb,i),i>=500&&t.setStatus({code:Ao.ERROR,message:`status ${i}`})}catch(e){throw t.recordException(e),t.setStatus({code:Ao.ERROR,message:e instanceof Error?e.message:String(e)}),!s.headersSent&&!s.writableEnded&&!s.destroyed&&Z(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:f,cause:e}),t.setAttribute(wb,s.statusCode),e}finally{t.end();let e=(Date.now()-_)/1e3;yst().record(e,{[Cb]:d,[Tb]:f,[wb]:s.statusCode})}})),!0}}function GQ(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof $a||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;Z(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function xst(e,t){return KQ(e,{maxBytes:t,timeoutMs:3e4})}function Sst(e){let t=e?.split(`;`,1)[0]?.trim().toLowerCase();return t===void 0?!1:t===`application/json`||/^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(t)}function Cst(e){return e.headers[`transfer-encoding`]!==void 0||Number(e.headers[`content-length`]??0)>0}async function KQ(e,t){if(Cst(e)&&!Sst(e.headers[`content-type`]))throw new qQ;let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new XQ(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new YQ(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var qQ=class extends Error{constructor(){super(`Request body is not labeled as JSON`),this.name=`UnsupportedMediaTypeError`}};function JQ(e,t){Z(e,415,`urn:ok:error:unsupported-media-type`,`Request body must be JSON.`,{handler:t,detail:`Send the request body as JSON with the header Content-Type: application/json.`})}var YQ=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${wst(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},XQ=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function wst(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function ZQ(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.some(e=>e.code===`custom`&&e.params?.contentControlAdmission===!0),o=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `),s=a?`${o} Offsets count the full submitted field after caller composition, including any frontmatter.`:o;return Z(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:s,...a?{extensions:{contentControlAdmission:!0}}:{}}),{ok:!1}}function QQ(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){Z(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&Z(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=ZQ(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await xst(r,n.maxBodyBytes??1048576)}catch(e){if(e instanceof qQ){JQ(i,n.handler);return}if(e instanceof YQ){Z(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof XQ){Z(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}Z(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){Z(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=ZQ(e,o,i,n);s.ok&&await t(r,i,s.value)}}const $Q=()=>J(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){$Q().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),GK().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){$Q().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),Z(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){$Q().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),Z(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function Tst(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return UQ({"/api/agent-integrations/apply":QQ(Qne,GQ(async(e,n,s)=>{let c=OQ(s,r);if(c.kind===`invalid-summary`){Z(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`agent-integrations-apply`});return}let l=ost(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await Lot(s.intents,{execute:o?.execute,env:l,snapshot:()=>Eq({env:l,resolve:o?.probe}),decisionHome:i??vc(),...o?.userSkillPresentAnywhere===void 0?{}:{userSkillPresentAnywhere:o.userSkillPresentAnywhere},projectDir:a});t.info({actor:c.kind,applied:u.actions.length,failed:u.actions.filter(e=>e.errorId!==void 0).length,conflicts:u.conflicts.map(e=>e.kind)},`[agent-integrations] batch applied`),Q(n,200,Are,{...u,snapshot:d},{handler:`agent-integrations-apply`})},{handler:`agent-integrations-apply`,title:`Failed to apply AI tool connections.`}),{handler:`agent-integrations-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`agent-integrations-apply`})})},{mutating:[`/api/agent-integrations/apply`]})}let Est=0;const Dst=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function e$(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++Est,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},Dst)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),l0e(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}let t$=new Map;function n$(e,t,n,r,i,a,o,s){let c=t$.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},t$.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function Ost(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of t$){for(let e of t)n.docs.delete(e);n.docs.size===0&&t$.delete(e)}}function kst(){let e=t$;return t$=new Map,e}function Ast(e){for(let[t,n]of e){let e=t$.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},t$.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function jst(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1157
1157
|
`)}function Mst(e,t){let n=t$.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},t$.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries]),t.previousPaths.length>0&&(n.previousPaths=[...t.previousPaths,...n.previousPaths])}function r$(){return t$.size}function Nst(e){return t$.has(e)}const i$={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function a$(e,t,n,r,i,a,o){Aq(e,t,`file-watcher`,n&&r?{resolveEmbed:n,resolveSize:i,sourcePath:r}:void 0,o,a)}const Pst=J(`external-change-attribution`),o$=new Map;function Fst(e){for(let[t,n]of o$)n.expiresAtMs<=e&&o$.delete(t)}function Ist(e,t,n=Date.now(),r=3e4){if(Fst(n),o$.size>=256&&!o$.has(e)){let e=o$.keys().next();e.done||o$.delete(e.value)}o$.set(e,{...t,expiresAtMs:n+r})}function Lst(e,t=Date.now()){let n=o$.get(e);if(!n)return;if(o$.delete(e),n.expiresAtMs<=t){Pst.debug({docName:e},`external-change claim expired before its write arrived`);return}let{expiresAtMs:r,...i}=n;return i}function Rst(e){o$.delete(e)}function s$(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`;return e instanceof $a?e.toLog({verbose:t}):e instanceof ya?Kt(e.violation,{verbose:t}):e instanceof Error?e.message:String(e)}function c$(e,t,n,r,i,a,o,s){if($H(n)||eU(n)||nU(n)||rU(n)||iU(n))return;let c=t.documents.get(n);if(!c)return;let l=c.getText(`source`).toString(),u=l===r,d=an(l).frontmatter,{frontmatter:f}=an(r),p=o&&LJ(i$.context.origin)?{report:e=>o(n,e,EJ.id,`file-watcher-intake`),baselineFullMd:l}:void 0;try{c.transact(()=>{a$(c,r,i,n,a,p,s)},i$)}catch(t){try{e.setReconciledBase(n,c.getText(`source`).toString())}catch(e){J(`reconcile`).error({err:e,originalError:s$(t),docName:n},`Unable to persist the reconciled base after an external-change failure`)}throw t}if(d!==f&&_Z(`file-watcher`),!u){let e=Lst(n)??{writerId:EJ.id,displayName:EJ.name,colorSeed:EJ.id};n$(n,e.writerId,e.displayName,e.colorSeed,Tye(n))}e.setReconciledBase(n,r)}function zst(e,t,n,r,i,a,o){if(sU(n))return`not-frozen`;let s=t.documents.get(n);if(!s)return`not-frozen`;let c=s.getMap(`lifecycle`),l=c.get(`status`);if(!VJ(l))return`not-frozen`;let u=s.getText(`source`).toString()!==r;try{c$(e,t,n,r,i,a,o)}catch(e){return J(`reconcile`).error({err:s$(e),docName:n,status:l},`[reconcile] could not revive ${n}: it stays ${l} and keeps refusing stores until the server reloads it`),`failed`}return c.delete(`status`),c.delete(`newPath`),e.endRenameCarry(n),J(`reconcile`).info({docName:n,status:l,replacedInMemoryContent:u},`[reconcile] revived ${n}: its name is occupied on disk again, so the ${l} freeze no longer applies`),`revived`}function Bst(e,t,n,r,i){return async(a,o)=>{try{c$(e,t,a,o,n,r,i),J(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof ya||e instanceof $a)throw e;D1e(),J(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const l$=`stale-external-write`;function u$(e,t,n,r){let i=e.getStaleExternalWrite(n)?.retainedContent;if(i!==void 0&&i!==e.getReconciledBase(n))return;e.clearStaleExternalWrite(n),r?.dissolveReconcile(n,l$);let a=t?.getMap(`lifecycle`);a?.get(`reason`)===l$&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`))}function d$(e,t,n){t.kind===`refused`&&t.reason===`check-failed`&&(QQe(),J(`reconcile`).warn({docName:e,site:n,failure:t.failure},`[reconcile] ${n} ${e} merge output failed the fidelity check (${t.failure.check})`))}function f$(e,t,n){let r=qJ(t);e$e(r.duplicated),J(`reconcile`).info({docName:e,site:n,...r},`[reconcile] ${n} ${e} kept both versions of ${r.duplicated} block(s), restored ${r.restoredDeletedHere} block(s) deleted here and ${r.restoredDeletedOutside} block(s) deleted outside`)}function p$(e,t,n){t$e(),J(`reconcile`).warn({docName:e,site:n,reason:t},`[reconcile] ${n} ${e} could not be merged (${t}); the live version stays and the other version was saved to history`)}function Vst(e){switch(e){case`conflict-markers`:return`refused-conflict-markers`;case`no-base`:return`refused-no-base`;case`too-large`:case`check-failed`:return`refused-too-large`;default:throw Error(`unhandled reconcile refusal reason: ${String(e)}`)}}function m$(e,t,n,r,i,a){let o=e.getReconciledBase(n),s=e.getStaleExternalWrite(n),c=(r,a)=>{let s=e.recordStaleExternalWrite(n,r,a);i&&i.raise({kind:`reconcile`,file:i.fileOf(n),reason:l$,detectedAt:s.detectedAt,stages:{base:o??r,ours:s.retainedContent??(t===void 0?o??r:v$(t)),theirs:s.diskContent}})};return s?.retainedContent!==void 0&&s.retainedContent!==o?(c(r,a??s.retainedContent),!0):o===r?(u$(e,t,n,i),!1):e.staleExternalWriteMatches(n,r)?(c(r,a??s?.retainedContent),!0):e.isDisplacedVersion(n,r)?(J(`reconcile`).warn({docName:n,diskBytes:r.length},`[reconcile] refused stale external write for ${n}; disk restores a version this server already displaced`),c(r,a),!0):(u$(e,t,n,i),!1)}const Hst='Re-read the document (e.g. `exec("cat <path>")`)';function h$(e){return e===1?`1 block`:`${e} blocks`}function Ust(e){let t=[];e.duplicated>0&&t.push(`An out-of-band edit changed ${h$(e.duplicated)} also edited here, so both versions were kept: the version here first, the out-of-band version directly under it.`),e.restoredDeletedHere>0&&t.push(`The deletion here of ${h$(e.restoredDeletedHere)} was undone because the out-of-band edit changed ${e.restoredDeletedHere===1?`it`:`them`}: the out-of-band version was restored.`),e.restoredDeletedOutside>0&&t.push(`The out-of-band deletion of ${h$(e.restoredDeletedOutside)} edited here was undone: the version here was kept.`),t.push(`Your write landed; do not retry it.`);let n=[...e.duplicated>0?[`remove the duplicate`]:[],...e.restoredDeletedHere>0?[`delete the restored block again`]:[]];return t.push(n.length>0?`${Hst} and, if your task calls for it, ${n.join(` or `)} with an ordinary edit.`:`${Hst} before continuing.`),t.join(` `)}function Wst(e){let t=e.mergeOutcome;switch(t){case`merged`:return'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.';case`both-kept`:return Ust(e.keptBlocks??{duplicated:1,restoredDeletedHere:0,restoredDeletedOutside:0});case`kept-live`:return'An out-of-band edit to this file could not be merged safely, so the version here was kept and the out-of-band version was saved to the history of this document. Your write landed; do not retry it. Re-read the document (e.g. `exec("cat <path>")`) before continuing.';case`clean`:case void 0:return'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.';default:throw Error(`unhandled merge outcome: ${String(t)}`)}}function g$(e){if(!e.reconciled)return;let t=e.mergeOutcome===`both-kept`||e.mergeOutcome===`kept-live`;return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},...e.keptBlocks===void 0?{}:{duplicatedBlocks:e.keptBlocks.duplicated,restoredDeletedHere:e.keptBlocks.restoredDeletedHere,restoredDeletedOutside:e.keptBlocks.restoredDeletedOutside},...t?{nextStep:`re-read`}:{},hint:Wst(e)}}const _$={reconciled:!1,baseBytes:0,diskBytes:0};function v$(e){let t=e.getText(`source`).toString(),{frontmatter:n,body:r}=an(t);return Fa(n,r)}async function y$(e,t,n,r,i,a,o,s){if($H(n)||eU(n)||nU(n)||rU(n)||iU(n))return _$;let c=t.documents.get(n);if(c&&fZ(c)&&c.getMap(`lifecycle`).get(`reason`)!==l$)return _$;let l=e.getReconciledBase(n);if(l===void 0)return _$;let u,d;try{if(u=jG(n,r),!K(u))return _$;d=lc(u)}catch{return _$}if(yK(u,d,r))return J(`reconcile`).warn({docName:n,canonical:d,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),_$;let f;try{f=q(d,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&J(`reconcile`).warn({docName:n,canonical:d,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),_$}let p=ga(f);if(f===l)return u$(e,c,n,o),_$;let m=e.inFlightFlushCount(n);if(m>0){if(e.hasInFlightFlush(n,p))return O1e(),J(`reconcile`).debug({docName:n,diskBytes:f.length,pendingFlushes:m},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),_$;k1e(),J(`reconcile`).warn({docName:n,diskBytes:f.length,pendingFlushes:m},`[reconcile] disk matches none of ${m} in-flight flush snapshot(s) for ${n}; falling through to merge`)}if(!c||m$(e,c,n,f,o)||p===ga(l))return _$;let h=v$(c),g=eY({docName:n,base:l,ours:h,theirs:f});J(`reconcile`).info({docName:n,result:g.kind,baseBytes:l.length,diskBytes:f.length},`[reconcile] before-agent-write ${n} result=${g.kind}`);let _=(e,t)=>({reconciled:!0,baseBytes:Buffer.byteLength(l,`utf8`),diskBytes:Buffer.byteLength(f,`utf8`),mergeOutcome:e,...t===void 0?{}:{keptBlocks:t}});switch(g.kind){case`noop`:return _$;case`refused`:return d$(n,g,`agent-write`),(g.reason===`check-failed`||g.reason===`too-large`)&&await s.keptLive(n,{side:`theirs`,bytes:f},g.reason)?(e.setReconciledBase(n,f),p$(n,g.reason,`agent-write`),_(`kept-live`)):(o.raise({kind:`reconcile`,file:o.fileOf(n),reason:Vst(g.reason),stages:{base:l,ours:h,theirs:f}}),_$);case`clean`:case`merged`:case`both-kept`:{let r=g.kind===`clean`?f:g.newContent;if(g.kind!==`clean`&&g.dedupSkipped&&(ZQe(),J(`reconcile`).warn({docName:n},`[reconcile] ${n} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`)),c$(e,t,n,r,i,void 0,a),g.kind!==`clean`&&e.setReconciledBase(n,f),g.kind!==`both-kept`)return _(g.kind);let o=qJ(g.kept);return s.bothKept(n,{ours:h,theirs:f},g.kept),f$(n,g.kept,`agent-write`),_(`both-kept`,o)}}}const b$=J(`mermaid-validator`);let Gst=null;function Kst(e){let t=[],n=e.split(`
|
|
1158
1158
|
`),r=e=>e.endsWith(`\r`)?e.slice(0,-1):e,i=0;for(;i<n.length;){let e=r(n[i]??``),a=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!a){i++;continue}let o=a[1]??``,s=o[0]??"`";if(s==="`"&&e.slice(e.indexOf(o)+o.length).includes("`")){i++;continue}let c=a[2]??``,l=RegExp(`^ {0,3}\\${s}{${o.length},}[ \t]*$`),u=[],d=i+1;for(;d<n.length&&!l.test(r(n[d]??``));)u.push(n[d]??``),d++;if(c===`mermaid`){let e=u.join(`
|
|
1159
1159
|
`),n=(u.find(e=>e.trim().length>0)?.trim()??``).slice(0,200);t.push({firstLine:n,body:e})}i=d+1}return t}async function qst(){let{Window:e}=await import(`./lib-CMODqczN.mjs`),t=new e({url:`http://localhost/`}),n={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},r=new Map;try{for(let[e,t]of Object.entries(n))r.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-NW5-Y1wO.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
|
package/dist/index.mjs
CHANGED
|
@@ -1637,6 +1637,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1637
1637
|
`);j(e,o)}function A9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=O9(JSON.parse(n),t),i=n.endsWith(`
|
|
1638
1638
|
`)?`
|
|
1639
1639
|
`:``;j(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}function M9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>F(e,t.name))}catch{return[]}}const SVe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function N9(e){return/\.log\.\d+$/.test(e)}function CVe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||N9(e)}const wVe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function P9(e){let t={contentDirSpellings:E9(e.contentDir)};for(let n of wVe)for(let r of M9(F(e.stagingDir,n)))CVe(r)?k9(r,t):r.endsWith(`.json`)?A9(r,t):j9(r,t);for(let n of M9(F(e.stagingDir,`state`))){let e=ne(n);n.endsWith(`.jsonl`)?k9(n,t):SVe.has(e)?A9(n,t):j9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=Bf.spansCurrent,z9=Bf.spansPrevious,B9=Bf.logsCurrent,V9=Bf.logsPrevious,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function TVe(e){return F(e,...L9,H9)}function EVe(e){return F(e,...L9,U9)}const W9=1e3;async function DVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function OVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function kVe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}function AVe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
|
|
1640
|
-
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.
|
|
1640
|
+
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.5-beta.0`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??NVe,m=r.isOtlpPushEnabled??PVe,g=b(F(he(),`ok-bundle-`));try{y(F(g,`telemetry`),{recursive:!0}),y(F(g,`logs`),{recursive:!0}),y(F(g,`state`),{recursive:!0}),Z9(XEe(n),F(n,...F9,R9),g,F(`telemetry`,R9)),Z9(ZEe(n),F(n,...F9,z9),g,F(`telemetry`,z9)),Z9(dY(n),F(n,...I9,B9),g,F(`logs`,B9)),Z9(fY(n),F(n,...I9,V9),g,F(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,F(g,`logs`,ne(t)));for(let t of e.userStateFiles??[])X9(t,F(g,JK,ne(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,F(g,`diagnostic-reports`,ne(t)))&&(v+=1);let b=F(n,`.ok`,`local`),x=F(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,F(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(j(F(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&j(F(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=AVe(n);e!==null&&j(F(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&j(F(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&j(F(g,`state`,`checkpoint-refs.txt`),D),X9(TVe(n),F(g,`state`,H9)),X9(EVe(n),F(g,`state`,U9)),Z9(pEe(n),F(b,zf),g,`state/last-spawn-error.log`),X9(F(b,Hf),F(g,`state`,Hf)),X9(F(b,Uf),F(g,`state`,Uf)),X9(F(b,Vf),F(g,`state`,Vf));let O=p(),A=d(),te=f(),M={ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te}};j(F(g,`state`,`runtime.json`),`${JSON.stringify(M,null,2)}\n`);let N=S===`running`?`running
|
|
1641
1641
|
`:`not-running (${w})\n`;j(F(g,`state`,`server-status.txt`),N);let P=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(j(F(g,`state`,`diagnostic-reports-status.txt`),`${P}\n`),j(F(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=F(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let re=e.redact===!0;re&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:F(g,`legacy`),contentDir:t})),e.note&&j(F(g,`note.txt`),e.note);let ie=null;e.scrubSecrets===!0&&(ie=GVe(g));for(let t of e.extraFiles??[]){let e=t.zipName??ne(t.sourcePath);if(!X9(t.sourcePath,F(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=v7(t,`extra/${e}`);n!==null&&(ie??={redactions:[],redactedLineCount:0},ie.redactions.push(n),ie.redactedLineCount+=n.lineCount)}let I=IVe(n),L=Q9(g),ae=[],oe=0,se=0;for(let e of L){let t=$9(g,e),n=ee(e).size,r=HVe(t)?RVe(e):0;ae.push({path:t,bytes:n,lines:r}),oe+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(se+=BVe(e))}let ce={applied:re};ie!==null&&(ce.secretScrub=ie);let R={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te},contentDir:{pathSha256:LVe(t),absolutePath:re?`<CONTENT_DIR>`:t},telemetry:{localSink:{...I,directory:xt(`logs`,`projects`)},otlpPushEnabled:m()},redaction:ce,serverStatus:S,files:ae};j(F(g,`manifest.json`),`${JSON.stringify(R,null,2)}\n`);let le=E9(t),ue=L.some(e=>{try{let t=C(e,`utf-8`);return le.some(e=>t.includes(e))}catch{return!1}}),de={stagedDiagnosticReports:v,totalBytes:oe,fileCount:ae.length,docNameCount:se,contentDirVisible:ue,redacted:re},fe=!1;return{stagingDir:g,manifest:R,summary:de,cleanup:()=>{fe||(fe=!0,k(g,{recursive:!0,force:!0}))}}}catch(e){throw k(g,{recursive:!0,force:!0}),e}}async function qVe(e){let{collected:t,outputPath:n}=e,r=N(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new zAe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function JVe(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,On.parse)(C(n,`utf-8`)),r=_q(t)?t.content:void 0,i=_q(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ae(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return ae(e)}async function YVe(e,t,n,r,i,a){let o=y7(t,e.logger),s=await KVe({contentDir:JVe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Qze(o,e.userLogsDir??F(St(),`logs`)),...x7(e.cachesDir??F(de(),`Library`,`Caches`))],userStateFiles:S7(e.bugReportsDir??_7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(N(e.outputPath),{recursive:!0}),await qVe({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function XVe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??T9,i=()=>wze(e.diagnosticReportsDir??F(de(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return YVe(e,t,n,r,i(),await h7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await rBe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:x7(e.cachesDir??F(de(),`Library`,`Caches`)),bugReportLedgerFiles:S7(e.bugReportsDir??_7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await h7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Eq as ALL_EDITOR_IDS,Dq as EDITOR_LABELS,sJ as EDITOR_TARGETS,OTe as HOSTS_WITH_USER_SKILL_DIR,fze as LAUNCH_CONFIG_NAME,iVe as PATH_SHIM_BEGIN,oVe as PATH_SHIM_BLOCK_RE,aVe as PATH_SHIM_END,o5 as ProjectPathSafetyError,URe as addOkPathsToGitExclude,s5 as assertProjectPathSafe,Hq as buildManagedServerEntry,BBe as buildMcpConfigDeclineEvent,VBe as buildMcpConfigMigrateEvent,Qq as canonicalEntryFor,H5 as classifyExistingMcpEntry,XVe as collectReportBundle,dVe as createCliProbeResolver,Pn as createTokenStore,Yze as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,gze as detectInstalledEditors,Zq as droppedManagedKeys,YTe as editorConfigPathDisplay,JTe as editorEntryLocator,kBe as ensurePiBridge,Aze as findJetsamKillSync,b5 as formatTrackedRemediation,KRe as getExcludedOkPaths,v5 as getInstalledSkillProjectionPaths,DTe as getNativeTomlMcpEditor,_5 as getOkArtifactPaths,Bq as isEntryUpToDate,Uq as isOwnManagedEntry,tVe as loadConfig,Dee as makeLazyProbeTokenStore,_7 as okBugReportsDir,_9 as parseGitHubBlobUrl,nVe as parseGitHubShareUrl,v9 as parseGitHubTreeUrl,g9 as parseGitUrl,sVe as pathInstallMarkerPath,ORe as previewContent,_ze as probeOwnManagedEditorMcpEntry,DBe as probePiBridgeState,y5 as probeTrackedOkPaths,B5 as readExistingMcpEntry,GRe as readSharingMode,eF as redactContent,sBe as registerWindowsProcessStartReader,WRe as removeOkPathsFromGitExclude,IBe as removeOwnMcpEntry,zRe as removeProjectSkill,pVe as removeUserGlobalSkillBundle,yVe as removeUserSkill,NRe as resolveProjectRoot,YBe as runStop,u9 as truncatePriorEntry,C9 as userGlobalSkillBundleTargets,vVe as userSkillPresentAnywhere,rVe as validateLocalFolderForShare,z5 as writeEditorMcpConfig,gVe as writeProjectAiIntegrations,f5 as writeProjectSkill,hze as writeUserMcpConfigs,_Ve as writeUserSkill};
|
|
1642
1642
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-CtwIv2ht.mjs";import{n as Ve,s as T}from"./fs-find-project-root-pgJRBsWv.mjs";import{i as E,n as D,o as O,r as He,s as k,t as A}from"./colors-r_owlCuY.mjs";import{t as j}from"./is-object-BGze3w87.mjs";import{t as Ue}from"./constants-CBlHBrLD.mjs";import{t as We}from"./preview-DVCjmHQa.mjs";import{createRequire as Ge}from"node:module";import{fileURLToPath as Ke}from"node:url";import qe,{basename as Je,dirname as M,isAbsolute as Ye,join as N,posix as Xe,relative as P,resolve as F,sep as I,win32 as Ze}from"node:path";import L from"node:process";import{copyFileSync as Qe,existsSync as R,lstatSync as $e,mkdirSync as et,readFileSync as z,readdirSync as tt,readlinkSync as nt,realpathSync as rt,rmSync as it,statSync as at,writeFileSync as ot}from"node:fs";import{homedir as B}from"node:os";import{AsyncLocalStorage as st,AsyncResource as ct}from"node:async_hooks";import{execFileSync as lt}from"node:child_process";import{inspect as ut,stripVTControlCharacters as dt,styleText as V}from"node:util";import*as ft from"node:readline";var pt=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),mt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),ht=n((e=>{let{humanReadableArgName:t}=mt();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
2
2
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
3
3
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),gt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&T(e,g,{mode:Ka(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const zo=e=>e!==`project`,Bo=e=>e!==`user`;async function Vo(){let e=await to({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Ho(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Vo)():`both`}async function Uo(e){return oo({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:`OK config stays on this machine only; teammates do not see it. Safe escape hatch via \`${s()} config-sharing share\`.`}]})}async function Wo(e){if(e.sharing!==void 0)return e.sharing;let t=ma(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Uo)(t):t}var Go=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}},Ko=class extends Error{constructor(e){super(`A dev MCP entry is written to project config only, never to user-level editor config, so --scope ${e} is not supported with --dev-mcp or OK_CHANNEL=dev. Re-run with --scope project or without --scope.`),this.name=`DevMcpScopeError`}};const qo=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${c} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;function Jo(e){if(e===void 0||e===!0)return new Set(Ie);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(ye.filter(e=>t.includes(e)))}function Yo(e,t,n){let r=F(n,e),i;try{i=at(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Go(`--content-dir path does not exist: ${r}`):new Go(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Go(`--content-dir must be a directory: ${r}`);let a=Xo(t),o=Xo(r),s=P(a,o);if(s.startsWith(`..`)||Ye(s))throw new Go(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Xo(e){try{return rt(e)}catch{return e}}const Zo=`open-knowledge-ui`;function Qo(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return R(r)}catch{return!1}}function $o(e,t,n){try{let r=F(M(e.configPath(t,n))),i=F(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+I)}catch{return!1}}function es(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!R(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||$o(e,t,r);if(!i&&c&&!Qo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Aa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return ns(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||et(M(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{ve(`${o}.lock`,()=>{let t=yo(o).writePath;if(s||et(M(t),{recursive:!0}),e.format===`toml`){let r=Fo(oi(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=Ro(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=Po(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const ts={pi:uo};function ns(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=ts[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{et(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{ve(`${t}.lock`,()=>{let e=null;try{e=z(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}T(t,c,e===null?void 0:{mode:Ka(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function rs(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!R(n)))return{editorId:e.id,label:e.label,path:n}}async function is(e){let t=sa(e.editors).filter(e=>e.scope===`global`);if(a())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:qo}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>es(t,``,n,e.home))}function as(e,t,n,r){let i=ss(e,t,n,r);return i.kind===`present`?i.entry:null}function os(e,t,n,r){let i=No(e,t,r);if(!j(i))return{kind:`no-entry`};let a=i[n];return j(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function ss(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!R(i))return{kind:`absent`};try{if(at(i).size>Do)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:Ha(e)}}let a;try{a=z(i,`utf-8`)}catch(e){return{kind:`decline`,reason:Ha(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:lo(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=oi().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return os(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,qr.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:os(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=So(a);return s?Co(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:os(we(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function cs(e={}){let t=F(e.cwd??process.cwd()),n=e.projectRootMode===`cwd`?{projectRoot:t,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:mo(t,{homeDir:e.home}),r=n.projectRoot;if(Se(r,e.home??B()))throw new ue(r);if(_e(r))throw new he(r);let i=!R(N(r,`.ok`)),o=n.gitRootPromoted?P(r,t):void 0,c=e.contentDir===void 0?n.defaultContentDir:Yo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&c===`.`&&process.stderr.write(`${k(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${o}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`${s()} init --content-dir .\`, or set content.dir: ${o} in .ok/config.yml.\n`);let l={mode:e.devMcp?`dev`:`published`},u=e.devMcp===!0||a();if(u&&e.mcp!==!1&&e.scope&&e.scope!==`project`)throw new Ko(e.scope);let d=await je(r),f;try{f=ge(r,{contentDir:c})}catch(t){let i=$.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:d.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let p=f.created.includes(Ue),m=!1;if(d.didInit)try{m=Le(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{ze(r)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${r}: ${e instanceof Error?e.message:String(e)}`)}let h=await Ho({scope:u?`project`:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),g=e.editors??ms(r,e.home),v=e.editors??g,y=sa(g),b=sa(v),x=e.mcp===!1||h===null,S=Array.from(new Map([...y,...x?[]:b].map(e=>[e.id,e])).values()),ee=y.filter(t=>Qo(t,r,e.home)),C=[],te=[],ne=new Set;for(let t of S){if(x){let n=``;try{n=t.configPath(r,e.home)}catch{}C.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(zo(h)&&y.includes(t)&&t.scope===`global`&&C.push(es(t,r,l,e.home)),Bo(h)&&b.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=es(t,r,l,e.home,n);C.push(i),(i.action===`written`||i.action===`overwritten`)&&ne.add(n)}}let re=new Set;for(let t of b){let n=t.projectSkillPath?.(r);!n||re.has(n)||(re.add(n),te.push(Ba(t,r,{home:e.home})))}let ie=za(r,b.map(e=>e.id));ie&&te.push(ie);let ae=te.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(ae.length>0){let t=e.home??B();be({source:_,skills:[Ne.project],agents:ae,scope:r},{home:t,enabled:fe(t).enabled})}let oe=!x&&h!==null&&Bo(h)?b.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,se=x?[]:ee.map(e=>rs(e,r)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ce=e.installUserSkill??me,w=e.home??B(),le=Jo(e.skills),pe=typeof e.skills!=`string`,ve=!1,xe=!1,we=!1,Te=!1,De=!1,Oe=!1,ke=!1,Ae=[];for(let t of ye){if(!le.has(t))continue;if(ve=!0,pe){let e=await Ce(w,Ne[t]).then(e=>({ok:!0,value:e}),()=>({ok:!1}));if(!e.ok){Ae.push({bundleId:t,result:`decision-read-failed`}),ke=!0;continue}if(e.value===!1){Ae.push({bundleId:t,result:`opted-out`}),Oe=!0;continue}}await de(w,Ne[t],!0).catch(()=>{});let n=await ce({home:e.home,bundleId:t,force:!0});Ae.push({bundleId:t,result:n}),n===`installed`?xe=!0:n===`failed`?we=!0:n===`no-hosts`?De=!0:Te=!0}let Me=we?`failed`:ke?`decision-read-failed`:xe?`installed`:ve&&Te?`skip-current`:ve&&De?`no-hosts`:Oe?`opted-out`:`declined`,Fe=xe?Pe(w).map(e=>e.editorId):[],Ie=fe(w).enabled&&!Ee(),Re=x?`skipped-flag`:`skipped-missing`,Be=C.find(e=>e.editorId===`claude`)??C[0]??{action:Re,configPath:$.claude.configPath(r,e.home)},Ve=await ls({projectRoot:r,desiredMode:await Wo({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:f.created,contentUpdated:f.updated,contentSkipped:f.skipped,editors:C,projectSkills:te,legacyProjectConfigs:se,skillInstall:Me,skillBundles:Ae,skillsRequested:e.skills,skillHosts:Fe,skillInstallsCounted:Ie,didGitInit:d.didInit,rootGitignoreCreated:m,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDir:p?c:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Be.action,mcpPath:Be.configPath,mcpError:`error`in Be?Be.error:void 0,projectScopeUnsupportedLabels:oe,sharing:Ve}}async function ls(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=ma(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=ua(t);if(n===`local-only`){let e=fa(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:us(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=pa(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:us(t,o,`remove`)}function us(e,t,n){let r=ma(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function ds(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function fs(e,t){let n=[],a=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),o=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),c=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),u=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let d=N(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(A(`Content scaffolded at ${d}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(A(`Content already present at ${d}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(A(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(c)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(u)n.push(A(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(A(`MCP server configuration:`));for(let i of e.editors){let e=i.configPath.startsWith(t)?P(t,i.configPath):i.configPath.replace(/^\/Users\/[^/]+/,`~`),a=i.serverName===r()?``:` (${i.serverName})`,o=i.configScope===`project`?` (project)`:``,s=`${i.label}${o}`,c=` `.repeat(Math.max(1,20-s.length)),l=i.editorId===`claude-desktop`&&(i.action===`written`||i.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(i.action){case`written`:n.push(` ${s}${c}${e} ${O(`registered`)}${a}${l}`);break;case`overwritten`:n.push(` ${s}${c}${e} ${O(`updated`)}${a}${l}`);break;case`skipped-missing`:n.push(` ${s}${c}${e} config root missing; skipped`);break;case`failed`:n.push(` ${s}${c}${e} ${He(`FAILED`)}: ${i.error}`);break;case`declined`:n.push(` ${s}${c}${e} left unchanged (${ds(i.declineReason)})`);break;case`skipped-flag`:break;default:i.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}let a=i.dev.mcpServerName;e.editors.some(e=>e.serverName===a&&(e.action===`written`||e.action===`overwritten`))&&n.push(` The ${a} entry runs this checkout on this machine only; keep it out of commits.`)}if(e.projectSkills.length>0){n.push(``),n.push(A(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?P(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${O(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${O(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${He(`FAILED`)}: ${r.error}`)}}}if(o&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${P(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall===`declined`)n.push(``),n.push(A(`User-global skills:`)),typeof e.skillsRequested==`string`?(n.push(` ${D(`none installed — --skills "${e.skillsRequested}" names no known skill bundle (known: ${ye.join(`, `)})`)}`),n.push(` ${D(`No user-global skill was installed or removed.`)}`)):(n.push(` ${D(`none installed — skipped for this run (--no-skills)`)}`),n.push(` ${D(`No user-global skill was installed or removed; any already on this`)}`),n.push(` ${D(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${D(` ${s()} init`)}`),n.push(` ${D(`--no-skills covers user-global skills only, not project-local skills.`)}`));else if(e.skillInstall){n.push(``),n.push(A(`User-global skills:`));let t=e.skillBundles??[],r=Math.max(0,...t.map(e=>Ne[e.bundleId].length));for(let i of t){let t=Ne[i.bundleId].padEnd(r);switch(i.result){case`installed`:{let r=(e.skillHosts??[]).map(e=>X[e]??e),i=r.length>0?r.join(`, `):`the shared ~/.agents store`;n.push(` ${t} ${O(`installed for ${i}`)}`);break}case`skip-current`:n.push(` ${t} ${O(`already installed at current version`)}`);break;case`no-hosts`:n.push(` ${t} ${D(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${k(`${t} install failed`)}`);break;case`opted-out`:n.push(` ${t} ${D(`not installed — turned off on this machine; reinstall with ${s()} init --skills ${i.bundleId} or Settings → Skills Studio`)}`);break;case`decision-read-failed`:n.push(` ${k(`${t} not installed — could not read whether it is turned off on this machine; rerun ${s()} init once ${l(x)} is readable`)}`);break;default:i.result}}e.skillInstallsCounted&&t.some(e=>e.result===`installed`)&&(n.push(` ${D(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${D(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`)),t.some(e=>e.result===`failed`)&&n.push(` ${k(`Retry with: ${s()} repair-skills`)}`)}e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(k(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(k(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`${s()} init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(` To scope to just that sub-folder, re-run \`${s()} init --content-dir .\` from there, or set`),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(We(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(..._s(e.sharing,t));let f=e=>[`${e}- ${E(`${s()} seed --list-packs`)} — browse the starter packs`,`${e}- ${E(`${s()} seed`)} — scaffold an empty repo`];if(a){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${O(`✓`)} ${A(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`);let i=3;e.contentScaffoldFailed||(n.push(` ${i++}. (Optional) scaffold the starter knowledge-base structure:`),n.push(...f(` `))),n.push(` ${i}. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}else e.contentScaffoldFailed||(n.push(``),n.push(`${A(`Next steps:`)} (optional) scaffold the starter knowledge-base structure:`),n.push(...f(` `)));return n.join(`
|
|
691
691
|
`)}function ps(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function ms(e,t){let n=[];for(let r of ci)r!==`claude-desktop`&&Qo($[r],e,t)&&n.push(r);return n}function hs(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ut(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function gs(){return new Et(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry (node + packages/cli/dist/cli.mjs, debug logging) in project config only, as the dev channel unless OK_CHANNEL is set`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new Ot(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new Ot(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new Ot(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd();e.devMcp&&u(process.env);let n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?hs():null;try{let r;try{r=await cs({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Go||e instanceof Ko||e instanceof ue||e instanceof he){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof Be||e instanceof le||e instanceof xe){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof Me){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-g-ztpgSj.mjs`),{resolveContentDir:s}=await import(`./dist-CfKMRf03.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-BO3kMuMd.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(ps(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${fs(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function _s(e,t){let n=[];switch(e.kind){case`applied`:return n.push(A(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${O(`local-only`)} — appended ${e.appended.length} path(s) to ${A(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${O(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${O(`local-only`)} — already excluded; nothing to do.`):n.push(` ${O(`local-only`)}`):e.action===`removed`?n.push(` ${O(`shared`)} — removed OK paths from ${A(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${O(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(k(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${E(`${s()} config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(k(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${E(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${E(`${s()} config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(k(`Sharing mode unavailable: ${e.reason}.`));return n}}export{Z as $,Ga as A,Da as B,yo as C,Rt as Ct,oo as D,co as E,Ot as Et,Na as F,ua as G,ba as H,Aa as I,pa as J,ga as K,ja as L,Ua as M,Ha as N,to as O,ka as P,li as Q,Va as R,$o as S,U as St,uo as T,wt as Tt,ha as U,fa as V,da as W,X,ci as Y,$ as Z,Wo as _,gr as _t,ls as a,Ei as at,es as b,fn as bt,ms as c,Gi as ct,gs as d,si as dt,Vi as et,Qo as f,oi as ft,Yo as g,Qr as gt,Ho as h,Yr as ht,ts as i,Ci as it,qa as j,Ka as k,fs as l,na as lt,Jo as m,Xr as mt,Ko as n,Hi as nt,ps as o,Wi as ot,as as p,Y as pt,ma as q,Zo as r,Ui as rt,ss as s,Q as st,Go as t,Bi as tt,_s as u,Ai as ut,cs as v,ar as vt,mo as w,Et as wt,is as x,dn as xt,jo as y,hn as yt,Ba as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-CtwIv2ht.mjs";import{v as e}from"./init-C7aWQIng.mjs";export{e as runInit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{as as e,cs as t}from"./dist-
|
|
1
|
+
import{as as e,cs as t}from"./dist-CtwIv2ht.mjs";import{s as n}from"./fs-find-project-root-pgJRBsWv.mjs";import{N as r,j as i,k as a}from"./init-C7aWQIng.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-CdKGHPS1.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:r(e)}}let g=[],_=t(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=i(h,[`configurations`,y]);return x?(n(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-
|
|
1
|
+
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-CtwIv2ht.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-CBlHBrLD.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=e();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(e){let n=e??process.cwd(),u=[],p=[],m=[],h=[],g=s(`user`,n),_=c({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(e,t=!1)=>{let n=v(e);if(n.diagnostic!==void 0&&p.push(n.diagnostic),n.value===null)return{};let o=r({value:n.value,file:n.path,source:n.source,doc:n.doc});p.push(...o),u.push(e);let s=o.length>0?i(n.value):n.value;return t&&h.push(...a({value:s,file:n.path,source:n.source,doc:n.doc})),s},x=f(n,`.ok`,d),S=b(x,!0),C=b(s(`project-local`,n)),w=t(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),t={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(o(t))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-B9rADE46.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ho as e}from"./dist-
|
|
1
|
+
import{Ho as e}from"./dist-CtwIv2ht.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-DVCjmHQa.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{k as e}from"./constants-ok-dir-BmRrWVQT.mjs";import"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Rn as t}from"./dist-
|
|
1
|
+
import{k as e}from"./constants-ok-dir-BmRrWVQT.mjs";import"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Rn as t}from"./dist-CtwIv2ht.mjs";import"./constants-CBlHBrLD.mjs";import{join as n,relative as r}from"node:path";import{existsSync as i,lstatSync as a,readdirSync as o,realpathSync as s,statSync as c}from"node:fs";function l(e){let{projectDir:i,contentDir:l,sampleCap:u=5}=e,d=[],f=[];try{a(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=t({projectDir:i,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=o(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${r(l,e)||`.`}: ${n}`);return}for(let i of t){let t=n(e,i.name);if(i.isSymbolicLink()){let e;try{e=s(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${r(l,t)}`):d.push(`cannot resolve symlink ${r(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=c(e)}catch{continue}if(n.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(i.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function u(t,a){let o=[],s=r(a,t.contentDir),c=s===``?`./`:`./${s}`;if(o.push(`Content:`),o.push(` Found ${t.totalCount} markdown files in ${c}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;o.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)o.push(` Warning: ${e}`);o.push(``);let l=n(a,`.ok`,`config.yml`);return i(l)?(o.push(` To adjust scope, add patterns to .okignore at the project root.`),o.push(` To change the content root, edit .ok/config.yml → content.dir.`)):o.push(` Run \`${e().cliCommandNames[1]} init\` to scaffold config + .okignore.`),o.push(``),o.push(` Re-check anytime: ${e().cliCommandNames[1]} preview`),o.join(`
|
|
2
2
|
`)}export{l as n,u as t};
|