@inkeep/open-knowledge 0.50.0-beta.8 → 0.50.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/{acp-harness-probe-CcFQmgX3.mjs → acp-harness-probe-Bl1wO1jG.mjs} +2 -2
  2. package/dist/cli.mjs +7 -7
  3. package/dist/constants-WesqvVEb.mjs +2 -0
  4. package/dist/index.d.mts +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-B17jtLEt.mjs +1 -0
  7. package/dist/{init-BBQ5oZSu.mjs → init-Cs060ZhU.mjs} +3 -3
  8. package/dist/{launch-json-removal-2TjcexXj.mjs → launch-json-removal-D0Z9HiC6.mjs} +2 -2
  9. package/dist/loader-C2IzfV23.mjs +1 -0
  10. package/dist/{loader-BIpUYYKt.mjs → loader-C_U6y8K2.mjs} +2 -2
  11. package/dist/{open-browser-BE__nPRv.mjs → open-browser-BVRsx4UD.mjs} +2 -2
  12. package/dist/{preview-DmCOiYiE.mjs → preview-1BHwOzN5.mjs} +2 -2
  13. package/dist/preview-BOmw4Npa.mjs +1 -0
  14. package/dist/public/assets/{ActivityModeContent-Do0P5PkB.js → ActivityModeContent-DFgZy7oE.js} +1 -1
  15. package/dist/public/assets/{AgentDiffPane-DFRVwXr-.js → AgentDiffPane-CWxNDLJy.js} +1 -1
  16. package/dist/public/assets/{ChangedOutsideBadge-do2_817w.js → ChangedOutsideBadge-B4qPknqp.js} +1 -1
  17. package/dist/public/assets/{CodeMirrorPropInput-BTBqLMWS.js → CodeMirrorPropInput-CQzidEcb.js} +1 -1
  18. package/dist/public/assets/{DocumentContext-B1UtgXw5.js → DocumentContext-CNSuvcIw.js} +16 -16
  19. package/dist/public/assets/{EditorModeToggle-DsMo0oeU.js → EditorModeToggle-DkQghTpa.js} +1 -1
  20. package/dist/public/assets/{EnableSyncConfirmDialog-BrRBeEzr.js → EnableSyncConfirmDialog-Btif19hJ.js} +1 -1
  21. package/dist/public/assets/FeedbackForm-sQ4Muu3U.js +1 -0
  22. package/dist/public/assets/{ImportSkillDialog-ChNKMjwJ.js → ImportSkillDialog-CiRpJ3T5.js} +1 -1
  23. package/dist/public/assets/{LintConfigEditor-Cg_osArr.js → LintConfigEditor-5XRvqcql.js} +1 -1
  24. package/dist/public/assets/{ManagedArtifactProperties-DmLlKjD9.js → ManagedArtifactProperties-CIqNGD9N.js} +1 -1
  25. package/dist/public/assets/ManagedArtifactProperties-D1vyOCad.js +1 -0
  26. package/dist/public/assets/{MermaidDocEditor-BmIEBgEV.js → MermaidDocEditor-D2cBfG9r.js} +1 -1
  27. package/dist/public/assets/{SchemaConfigEditor-BBqKhENz.js → SchemaConfigEditor-B7a503PZ.js} +1 -1
  28. package/dist/public/assets/{SessionsHost-BQqsJZay.js → SessionsHost-CpLvCqvs.js} +2 -2
  29. package/dist/public/assets/{SettingsDialogBody-okmHTajR.js → SettingsDialogBody-C7DVY6B-.js} +2 -2
  30. package/dist/public/assets/{ShareReceiveMissDialog-BRiPsQxv.js → ShareReceiveMissDialog-MPUr0dv1.js} +1 -1
  31. package/dist/public/assets/{SkillToolbarControls-CIzXYpP0.js → SkillToolbarControls-CaHitAH1.js} +1 -1
  32. package/dist/public/assets/{SourceEditor-D-ZojZ1R.js → SourceEditor-DKEUL0BH.js} +1 -1
  33. package/dist/public/assets/{TerminalWindowApp--SieYOj2.js → TerminalWindowApp-DLh-TT_A.js} +1 -1
  34. package/dist/public/assets/{TextDocEditor-CR8RlbZz.js → TextDocEditor-0dFDtMs6.js} +1 -1
  35. package/dist/public/assets/ThreadView-CHmtUGoi.js +10 -0
  36. package/dist/public/assets/{TimelineDiffPane-CBnAmGxS.js → TimelineDiffPane-Ba7SXNWn.js} +1 -1
  37. package/dist/public/assets/{agent-diff-store-CGbJo0xm.js → agent-diff-store-DbDYdvOw.js} +1 -1
  38. package/dist/public/assets/{auth-state-cache-BrIjR7Qf.js → auth-state-cache-BF6Z4GtZ.js} +3 -3
  39. package/dist/public/assets/{comment-chips-uegP4pH6.js → comment-chips-pQK8zh5P.js} +1 -1
  40. package/dist/public/assets/{config-provider-7a2bYG1Y.js → config-provider-Dz54I9YH.js} +3 -3
  41. package/dist/public/assets/{follow-file-BcVK10qo.js → follow-file-CjlmJwxJ.js} +1 -1
  42. package/dist/public/assets/i18n-DWCqmgsa.js +1 -0
  43. package/dist/public/assets/index-gC7cHSmk.js +2097 -0
  44. package/dist/public/assets/messages-B12ABuMo.js +1 -0
  45. package/dist/public/assets/messages-BUufFcK8.js +1 -0
  46. package/dist/public/assets/messages-BV-Jgai1.js +1 -0
  47. package/dist/public/assets/messages-B_u6thtp.js +1 -0
  48. package/dist/public/assets/messages-CS-CWF8r.js +1 -0
  49. package/dist/public/assets/messages-CwQGRPEE.js +1 -0
  50. package/dist/public/assets/messages-Cwceyxby.js +1 -0
  51. package/dist/public/assets/messages-DGpodehZ.js +1 -0
  52. package/dist/public/assets/messages-DHl_AYzv.js +1 -0
  53. package/dist/public/assets/messages-DbRvxOAn.js +1 -0
  54. package/dist/public/assets/messages-DdKkPWw3.js +1 -0
  55. package/dist/public/assets/{pending-receive-nav-store-Bgy0uGX1.js → pending-receive-nav-store-B4qUnaqd.js} +1 -1
  56. package/dist/public/assets/{selection-context-BzSHpc5K.js → selection-context-BPfggRPr.js} +1 -1
  57. package/dist/public/assets/{skill-actions-CcWeYGSe.js → skill-actions-BIlEExO7.js} +2 -2
  58. package/dist/public/assets/{src-CuYJwSNo.js → src-DFsYGwxw.js} +1 -1
  59. package/dist/public/assets/{terminal-cli-display-C7F4bitQ.js → terminal-cli-display-DOg7CEcR.js} +1 -1
  60. package/dist/public/assets/{terminal-launch-events-9H84Qwtv.js → terminal-launch-events-BIj1IHuR.js} +1 -1
  61. package/dist/public/assets/{terminal-telemetry-CedWu1hq.js → terminal-telemetry-DRwNgR5W.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-BBlqPp_d.js → typing-burst-detector-CWZPjxCH.js} +1 -1
  63. package/dist/public/assets/{uninstall-BmrDQXtu.js → uninstall-DhJ_Rklh.js} +1 -1
  64. package/dist/public/assets/{use-activity-panel-aHDXnP43.js → use-activity-panel-BkEUKYpF.js} +1 -1
  65. package/dist/public/assets/{use-open-skill-IVQ8LRcM.js → use-open-skill-DqKBpu6s.js} +1 -1
  66. package/dist/public/assets/{use-popular-skills-BAuUERAB.js → use-popular-skills-DUCqHl15.js} +1 -1
  67. package/dist/public/assets/{use-terminal-enabled-BXKMhE7B.js → use-terminal-enabled-B3TJxcey.js} +1 -1
  68. package/dist/public/assets/{use-timeline-entry-diff-DBpBbxuy.js → use-timeline-entry-diff-BNIl-plH.js} +1 -1
  69. package/dist/public/index.html +23 -23
  70. package/dist/public/uninstall.html +3 -3
  71. package/dist/{repair-launch-json-Ccf7daSp.mjs → repair-launch-json-Cd_Vv1Ki.mjs} +2 -2
  72. package/dist/{repair-mcp-configs-CoNwCRjc.mjs → repair-mcp-configs-wnLWp4-Q.mjs} +2 -2
  73. package/dist/repair-skills-6sP48q4r.mjs +1 -0
  74. package/dist/{repair-skills-BrOFbDSH.mjs → repair-skills-B3DXhSuF.mjs} +2 -2
  75. package/dist/{skill-teardown-D31Ah_77.mjs → skill-teardown-DpitP3Vs.mjs} +2 -2
  76. package/dist/{src-D6v6esDL.mjs → src-3pZWeowR.mjs} +3 -3
  77. package/dist/{src-5W71opsG.mjs → src-Bcg8O-xQ.mjs} +1 -1
  78. package/dist/src-CO4cFiT1.mjs +1 -0
  79. package/dist/{src-BvzFYC4G.mjs → src-s5E_Y9Xd.mjs} +2 -2
  80. package/dist/{start-CCD3K5PY.mjs → start-C5ud_ElN.mjs} +3 -3
  81. package/dist/start-gNbMBnlE.mjs +1 -0
  82. package/dist/{write-project-skill-Dpr3DYpv.mjs → write-project-skill-BIyatqdb.mjs} +2 -2
  83. package/package.json +4 -4
  84. package/dist/constants-B51mAM4l.mjs +0 -2
  85. package/dist/init-DnZMOBvW.mjs +0 -1
  86. package/dist/loader-CyB-T8UJ.mjs +0 -1
  87. package/dist/preview-D3Txy4Ba.mjs +0 -1
  88. package/dist/public/assets/FeedbackForm-BXQKPBhM.js +0 -1
  89. package/dist/public/assets/ManagedArtifactProperties-CBhFU95H.js +0 -1
  90. package/dist/public/assets/ThreadView-BZQgz_OT.js +0 -10
  91. package/dist/public/assets/i18n-CDj8TaBr.js +0 -1
  92. package/dist/public/assets/index--rSjedb-.js +0 -2097
  93. package/dist/public/assets/messages-7Y8pfBz0.js +0 -1
  94. package/dist/public/assets/messages-B4sBf5fy.js +0 -1
  95. package/dist/public/assets/messages-BIEb40JZ.js +0 -1
  96. package/dist/public/assets/messages-BfLJys0I.js +0 -1
  97. package/dist/public/assets/messages-Cf6YBtq4.js +0 -1
  98. package/dist/public/assets/messages-CtiGbVvK.js +0 -1
  99. package/dist/public/assets/messages-D1QObPqW.js +0 -1
  100. package/dist/public/assets/messages-D1nlMujt.js +0 -1
  101. package/dist/public/assets/messages-Dg4RPh9k.js +0 -1
  102. package/dist/public/assets/messages-gxmuaITL.js +0 -1
  103. package/dist/public/assets/messages-mE27tR2H.js +0 -1
  104. package/dist/repair-skills-SUdBvS9h.mjs +0 -1
  105. package/dist/src-DqxPJWfl.mjs +0 -1
  106. package/dist/start-Bjkfv8bC.mjs +0 -1
@@ -20,9 +20,9 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{A as r,At as i,Bt
20
20
  `:``)+r)}function Yw(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function Xw(e,t,n){let r=Mw(e);r&&$w(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function Zw(e,t,n,r,i,a){if(vS(e))throw new bS({file:Kw(e.name)});return es(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let o=eT(e,t,n,r,i,a);return o!==void 0&&Qo({"agent.content_divergent":!0,"agent.intended_bytes":o.intendedBytes,"agent.actual_bytes":o.actualBytes,"agent.byte_delta":o.byteDelta,"agent.divergence_type":o.divergenceType}),o})}function Qw(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function $w(e,t,n){let{frontmatter:r,body:i}=vo(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?hh(t):vo(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;break}return{existingFm:r,finalFm:s,newContent:ct(s,c)}}function eT(e,t,n,r,i,a){try{let o=e.getText(`source`).toString(),s=$w(o,t,n);if(s===void 0)return;let{existingFm:c,finalFm:l,newContent:u}=s,d=a&&Hx(Gw.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:o}:void 0;if(l!==c){let t=ia(Zn(l));if(t.map===null)throw new TS({file:Kw(e.name),parseError:t.parseError??`unknown YAML parse error`});jS(`mcp-write`)}else if(l===``&&vo(u).frontmatter!==``)throw new TS({file:Kw(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."});n===`replace`?Bb(e,u,r,i,d):zb(e,u,`agent`,r,i,d);let f=CS(e.getText(`source`).toString(),u,n);return Ww.debug({docName:e.name,position:n,markdownBytes:t.length,divergent:f!==void 0},`[agent-write] applied agent markdown write`),f}catch(r){throw r instanceof TS||Ww.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function tT(e,t,n,r){let i=e.dc.document;if(vS(i))throw new bS({file:Kw(i.name)});return es(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=nT(e,t,n,r);return Qo({"agent.undo_effective":i}),i})}function nT(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&&Mw(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&Hx(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&&Dae(s,n,d)},o),Ww.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function rT(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 iT(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 aT=256,oT=5e3;var sT=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let cT=null;function lT(){return cT||=ks().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}`}),cT}var uT=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;minEvictableIdleMs;bridgeLossReporter;evictions=0;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256,this.minEvictableIdleMs=t.minEvictableIdleMs??5e3,this.bridgeLossReporter=t.bridgeLossReporter}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){let n=this.sessionKey(e,t),r=this.sessions.get(n);return r&&this.touchSession(n,r),r}async getSession(e,t=`claude-1`,n){if(tS(e)||nS(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);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 Ww.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 Ww.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new sT(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=rT(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=iT(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);Ww.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new pie([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),Ww.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(){let e=this.sessions.entries().next();if(e.done)return null;let[t,n]=e.value,r=Date.now()-n.lastUsedAt;return r<this.minEvictableIdleMs?null:(this.sessions.delete(t),await this.cleanupSession(t,n,{docName:n.docName,agentId:n.agentId,evicted:!0}),this.evictions++,Jae(),lT().add(1),Ww.info({docName:n.docName,agentId:n.agentId,idleMs:r},`[agent-session] Evicted LRU idle session under capacity pressure`),t)}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,n){Ww.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){Ww.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){Ww.error({err:e,...n},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(await this.cleanupSession(n,r,{docName:e,agentId:t}),Ww.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));Ww.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));Ww.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()];Ww.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 dT=`x-ok-connection-id`,fT=`x-ok-hosted-agent`;function pT(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}const mT=16e3;function hT(e){return e.length<=mT?e:`${e.slice(0,mT)}\n… [truncated ${e.length-mT} chars]`}function gT(e){let t=e;if(t.sessionUpdate!==`tool_call`&&t.sessionUpdate!==`tool_call_update`||!Array.isArray(t.content))return e;let n=!1,r=t.content.map(e=>{let t=e;if(t.type===`diff`){let r=typeof t.oldText==`string`?hT(t.oldText):t.oldText,i=typeof t.newText==`string`?hT(t.newText):t.newText;return r!==t.oldText||i!==t.newText?(n=!0,{...t,oldText:r,newText:i}):e}if(t.type===`content`){let r=t.content;if(r?.type===`text`&&typeof r.text==`string`){let e=hT(r.text);if(e!==r.text)return n=!0,{...t,content:{...r,text:e}}}return e}return e});return n?{...e,content:r}:e}const _T=new Set([`agent_message_chunk`,`agent_thought_chunk`,`user_message_chunk`]),vT=16e3;function yT(e){if(typeof e!=`object`||!e)return null;let t=e;return t.type===`text`&&typeof t.text==`string`?t.text:null}function bT(e){return typeof e.messageId==`string`?e.messageId:`default`}function xT(e,t){if(e.kind===`terminal_output`&&t.kind===`terminal_output`)return e.terminalId!==t.terminalId||e.chunk.length>=vT?!1:(e.chunk+=t.chunk,!0);if(e.kind!==`session_update`||t.kind!==`session_update`)return!1;let n=e.update,r=t.update;if(n.sessionUpdate!==r.sessionUpdate||!_T.has(r.sessionUpdate)||bT(n)!==bT(r))return!1;let i=yT(n.content),a=yT(r.content);return i===null||a===null||i.length>=vT?!1:(n.content={type:`text`,text:i+a},!0)}function ST(e,t){let n=Ql(e)+tu;return`${Ql(t)}${tu}`.startsWith(n)}function CT(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,`_`);return t===``||t===`.`||t===`..`?`_`:t}function wT(e,t,n,r=12e4){let[i,a]=n?process.platform===`darwin`?[`ditto`,[`-x`,`-k`,e,t]]:process.platform===`win32`?[`tar`,[`-xf`,e,`-C`,t]]:[`unzip`,[`-q`,e,`-d`,t]]:[`tar`,[`-xf`,e,`-C`,t]];return new Promise((t,n)=>{let o=Gl(i,a,{stdio:[`ignore`,`ignore`,`pipe`],shell:!1,windowsHide:!0}),s=setTimeout(()=>{o.kill(`SIGKILL`),n(Error(`${i} timed out after ${r}ms extracting ${e}`))},r);s.unref?.();let c=``;o.stderr?.on(`data`,e=>{c=(c+e.toString()).slice(-2e3)}),o.on(`error`,e=>{clearTimeout(s),n(e)}),o.on(`exit`,e=>{clearTimeout(s),e===0?t():n(Error(`${i} exited ${e}: ${c}`))})})}async function TT(e,t,n={}){let r=await(n.fetchImpl??fetch)(e,{signal:n.signal});if(!r.ok||r.body===null)throw Error(`download failed: HTTP ${r.status} for ${e}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null,o=Lu(`sha256`),s=0,c=cu(t),l=Fu.fromWeb(r.body);return l.on(`data`,e=>{o.update(e),s+=e.length,n.onProgress?.({receivedBytes:s,totalBytes:Number.isFinite(a)?a:null})}),await new Promise((e,t)=>{l.pipe(c).on(`finish`,()=>e()).on(`error`,t),l.on(`error`,t)}),o.digest(`hex`)}async function ET(e,t={}){let n=await(t.fetchImpl??fetch)(e,{signal:t.signal});if(!n.ok)throw Error(`fetch failed: HTTP ${n.status} for ${e}`);return n.text()}function DT(e,t){for(let n of e.split(`
21
21
  `)){let e=n.trim();if(e===``)continue;let r=/^([a-fA-F0-9]{64})\s+\*?(.+)$/.exec(e);if(r===null)continue;let[,i,a]=r;if(a.trim().split(/[\\/]/).pop()===t)return i.toLowerCase()}return null}const OT=`__OK_PATH_BEGIN__`,kT=`__OK_PATH_END__`,AT=`printf %s ${OT}; printenv PATH; printf %s ${kT}`;function jT(){return[`-l`,`-i`,`-c`,AT]}function MT(){return[`-i`,`-c`,AT]}const NT=new Set([`bash`,`sh`]);function PT(e){let t=e.lastIndexOf(OT);if(t===-1)return null;let n=t+17,r=e.indexOf(kT,n);if(r===-1)return null;let i=e.slice(n,r).trim();return i===``?null:i}function FT(e,t,n){let r=(e??``).split(n).filter(e=>e!==``),i=new Set(r);for(let e of t.split(n))e===``||i.has(e)||(i.add(e),r.push(e));return r.join(n)}const IT=new Set([`false`,`nologin`,`sync`]),LT=(e,t,n)=>new Promise(r=>{let i;try{i=Gl(e,[...t],{stdio:[`ignore`,`pipe`,`ignore`],windowsHide:!0})}catch{r(null);return}let a=``,o=!1,s=e=>{o||(o=!0,clearTimeout(c),r(e))},c=setTimeout(()=>{i.kill(`SIGKILL`),s(null)},n);c.unref?.(),i.stdout?.setEncoding(`utf8`),i.stdout?.on(`data`,e=>{a.length>=524288||(a+=e)}),i.on(`error`,()=>s(null)),i.on(`close`,()=>s(a))});async function RT(e,t,n,r,i){let a=Date.now(),o=await i(t,n,r).catch(()=>null),s=Date.now()-a;if(o===null)return e.log.debug({shell:t,args:n,elapsed:s},`[login-shell-path] probe produced no output`),null;let c=PT(o);return c===null?(e.log.debug({shell:t,args:n,elapsed:s},`[login-shell-path] probe output carried no PATH`),null):c}function zT(e){let t=e.platform??process.platform,n=e.shell??process.env.SHELL,r=e.timeoutMs??5e3,i=e.runProbe??LT,a=e.now??Date.now,o=null,s=0,c=async()=>{if(t===`win32`)return null;if(n===void 0||n===``)return e.log.debug({},`[login-shell-path] no $SHELL; skipping probe`),null;let a=n.slice(n.lastIndexOf(`/`)+1);if(IT.has(a))return e.log.debug({shell:n},`[login-shell-path] login-refusing shell; skipping probe`),null;let o=await RT(e,n,jT(),r,i);if(!NT.has(a))return o;let s=await RT(e,n,MT(),r,i);return o===null?s:s===null?o:FT(o,s,Yl)};return()=>{if(o!==null)return o;if(a()<s)return Promise.resolve(null);let e=c().catch(()=>null);return o=e,e.then(e=>{e===null&&(o=null,s=a()+6e4)}),e}}let BT=null;function VT(e){return BT??=zT({log:e}),BT}function HT(){BT=null}var UT=class extends Error{code;constructor(e,t){super(t),this.name=`AgentLaunchError`,this.code=e}};function WT(){return R(wu(),`.ok`,`acp-agents`)}function GT(e){try{return bu(e).isDirectory()}catch{return!1}}function KT(e){let t={};for(let[e,n]of Object.entries(process.env))n!==void 0&&(t[e]=n);return t[eE(t)]=No(aE(t),{platform:process.platform,homeDir:wu(),isDir:GT,delimiter:Yl}),{...t,...e}}function qT(e){return e!==void 0&&Object.keys(e).some(e=>e.toLowerCase()===`path`)}function JT(e){return{...e,[zt]:`1`}}async function YT(e,t,n,r=WT()){let i=e.distribution;if(i.npx!==void 0)return{cmd:`npx`,args:[`-y`,i.npx.package,...i.npx.args??[]],env:KT(i.npx.env),kind:`npx`,pathFromOverlay:qT(i.npx.env)};if(i.uvx!==void 0)return{cmd:`uvx`,args:[i.uvx.package,...i.uvx.args??[]],env:KT(i.uvx.env),kind:`uvx`,pathFromOverlay:qT(i.uvx.env)};if(i.binary!==void 0){if(t===null||i.binary[t]===void 0)throw new UT(`unsupported-platform`,`${e.name} has no build for this platform`);let a=i.binary[t],o=await nE(e.id,e.version,a,r,n),s=B(o,a.cmd.replace(/\\/g,`/`));if(!ST(o,s))throw new UT(`install-failed`,`${e.name} manifest cmd escapes its archive`);return{cmd:s,args:[...a.args??[]],env:KT(a.env),kind:`binary`,pathFromOverlay:qT(a.env)}}throw new UT(`no-distribution`,`${e.name} has no supported distribution`)}function XT(e){return{cmd:e.command,args:[...e.args??[]],env:KT(e.env),kind:`custom`,pathFromOverlay:qT(e.env)}}function ZT(e,t){let n={...e.env};n[eE(n)]=tE(t.binDir,aE(n));let r=e.pathFromOverlay;return t.kind===`node`?(n.npm_config_cache=t.cacheDir,{cmd:t.npxBin,args:[...e.args],env:n,kind:`npx`,pathFromOverlay:r}):(n.UV_CACHE_DIR=t.cacheDir,{cmd:t.uvxBin,args:[...e.args],env:n,kind:`uvx`,pathFromOverlay:r})}function QT(e,t){return{...e,env:$T(e.env,t)}}function $T(e,t){let n={...e};return n[eE(n)]=FT(aE(n),t,Yl),n}function eE(e){for(let t of Object.keys(e))if(t.toLowerCase()===`path`)return t;return`PATH`}function tE(e,t){return t!==void 0&&t!==``?`${e}${Yl}${t}`:e}async function nE(e,t,n,r,i){let a=R(r,CT(e),CT(t));try{if((await Pu(a)).isDirectory())return a}catch{}i.info({id:e,version:t,archive:n.archive},`[acp-launch] downloading agent binary`);let o=R(Du(),`ok-acp-install-${process.pid}-${Date.now()}`);await ls(o,{recursive:!0});let s=/\.zip$/i.test(new URL(n.archive).pathname),c=R(o,s?`archive.zip`:`archive.tar.gz`);try{let l=await TT(n.archive,c,{signal:AbortSignal.timeout(12e4)});if(n.sha256!==void 0){if(l!==n.sha256.toLowerCase())throw Error(`archive checksum mismatch: expected ${n.sha256}, got ${l}`)}else i.warn({id:e,version:t,archive:n.archive},`[acp-launch] manifest carries no sha256 for the binary archive — installing unverified`);let u=R(o,`extracted`);await ls(u,{recursive:!0}),await wT(c,u,s);let d=B(u,n.cmd.replace(/\\/g,`/`));if(!ST(u,d))throw Error(`manifest cmd escapes the extracted archive`);return await _te(d,493).catch(()=>{}),await ls(R(r,CT(e)),{recursive:!0}),await ds(a,{recursive:!0,force:!0}),await Ts(u,a),i.info({id:e,version:t,versionDir:a},`[acp-launch] agent binary installed`),a}catch(n){throw new UT(`install-failed`,`installing ${e}@${t} failed: ${n instanceof Error?n.message:String(n)}`)}finally{await ds(o,{recursive:!0,force:!0}).catch(()=>{})}}async function rE(e){if(!await sE(e.cmd,aE(e.env)))throw new UT(`command-not-found`,iE(e))}function iE(e){switch(e.kind){case`npx`:return`\`${e.cmd}\` was not found. This agent runs through npx, which ships with Node.js — install Node.js (https://nodejs.org) and make sure it is on your PATH.`;case`uvx`:return`\`${e.cmd}\` was not found. This agent runs through uvx, which ships with uv — install uv (https://docs.astral.sh/uv/getting-started/installation/) and make sure it is on your PATH.`;case`binary`:return`the agent binary at ${e.cmd} is missing or not executable.`;case`custom`:return`\`${e.cmd}\` was not found on your PATH. A desktop app launched from the Dock or Finder doesn't inherit your shell's PATH, so an agent installed only in a shell-configured location won't be visible here — use an absolute path to the command, or install it to a standard location.`}}function aE(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()===`path`)return n;return process.env.PATH}function oE(e){let t=process.platform===`win32`;return Zl(e)||e.includes(`/`)||t&&e.includes(`\\`)}async function sE(e,t){let n=process.platform===`win32`;if(oE(e))return cE(e);let r=n?[``,...(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).map(e=>e.trim()).filter(e=>e!==``)]:[``];for(let n of(t??``).split(Yl))if(n!==``){for(let t of r)if(await cE(R(n,e+t)))return!0}return!1}async function cE(e){try{return(await Pu(e)).isFile()?(process.platform===`win32`||await Ou(e,ou.X_OK),!0):!1}catch{return!1}}function lE(e,t){if(Zl(e)||e.includes(`\\`)||e.includes(`/`))return e;let n=(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).map(e=>e.trim()).filter(e=>e!==``);for(let r of(t??``).split(Yl))if(r!==``)for(let t of n){let n=R(r,e+t);try{if(bu(n).isFile())return n}catch{}}return e}function uE(e){return e===``?`""`:/[\s"&()<>^|%]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function dE(e,t){let n=[`"${e}"`,...t.map(uE)].join(` `);return{cmd:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,`"${n}"`]}}function fE(e,t){if(!Zl(t))throw Error(`spawnAcpAgent requires an absolute cwd, got: ${t}`);let n=process.platform===`win32`,r=n?lE(e.cmd,aE(e.env)):e.cmd,i=n&&/\.(cmd|bat)$/i.test(r),{cmd:a,args:o}=i?dE(r,e.args):{cmd:r,args:e.args};return Gl(a,o,{cwd:t,env:JT(e.env),stdio:[`pipe`,`pipe`,`pipe`],shell:!1,detached:!n,windowsHide:!0,windowsVerbatimArguments:i})}function pE(e){return e.exitCode!==null||e.signalCode!==null}function mE(e,t){return pE(e)?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{e.removeListener(`exit`,r),n(!1)},t);i.unref?.(),e.once(`exit`,r)})}function hE(e,t){let n=e.pid;if(!(n===void 0||pE(e))){try{process.kill(-n,t);return}catch{}try{e.kill(t)}catch{}}}async function gE(e,t){let n=t.forceWaitMs??2e3;if(pE(e))return!0;if(process.platform===`win32`){if(e.pid!==void 0)try{Gl(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`,shell:!1,windowsHide:!0}).unref()}catch{try{e.kill(`SIGKILL`)}catch{}}return mE(e,Math.max(t.graceMs,n))}return hE(e,`SIGTERM`),await mE(e,t.graceMs)?!0:(hE(e,`SIGKILL`),mE(e,n))}const _E=`v24.18.0`,vE=`0.11.28`,yE=`https://nodejs.org/dist`,bE=`https://github.com/astral-sh/uv/releases/download`,xE={node:45,uv:20};function SE(e){return e===`npx`?`node`:`uv`}function CE(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:_E,approxSizeMB:xE.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:vE,approxSizeMB:xE.uv,sourceHost:`github.com/astral-sh`}}function wE(){return R(wu(),`.ok`)}function TE(){return R(wE(),`runtimes`)}function EE(e){return e===`node`?_E:vE}function DE(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function OE(){let e=Eu(),t=Cu(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`win`:null,r=t===`arm64`?`arm64`:t===`x64`?`x64`:null;if(n===null||r===null)return null;let i=e===`win32`,a=`node-${_E}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${yE}/${_E}/${a}`,checksumUrl:`${yE}/${_E}/SHASUMS256.txt`,archiveName:a,isZip:i}}function kE(){let e={"darwin-arm64":`aarch64-apple-darwin`,"darwin-x64":`x86_64-apple-darwin`,"linux-arm64":`aarch64-unknown-linux-gnu`,"linux-x64":`x86_64-unknown-linux-gnu`,"win32-x64":`x86_64-pc-windows-msvc`,"win32-arm64":`aarch64-pc-windows-msvc`}[`${Eu()}-${Cu()}`];if(e===void 0)return null;let t=Eu()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${bE}/${vE}/${n}`,checksumUrl:`${bE}/${vE}/${n}.sha256`,archiveName:n,isZip:t}}function AE(e){return e===`node`?OE():kE()}function jE(e){return AE(e)!==null}async function ME(e){try{let t=await Pu(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await Ou(e,ku.X_OK),!0)}catch{return!1}}async function NE(e,t,n){let r;try{r=await Mu(e,{withFileTypes:!0})}catch{return null}for(let n of r)if((n.isFile()||n.isSymbolicLink())&&t.includes(n.name))return R(e,n.name);if(n<=0)return null;for(let i of r)if(i.isDirectory()){let r=await NE(R(e,i.name),t,n-1);if(r!==null)return r}return null}function PE(e,t,n){let r=L(t),i=R(n,`cache`,e);return e===`node`?{kind:`node`,binDir:r,npxBin:t,cacheDir:i}:{kind:`uv`,binDir:r,uvxBin:t,cacheDir:i}}async function FE(e,t=TE()){let n=R(t,e,CT(EE(e)));try{if(!(await Pu(n)).isDirectory())return null}catch{return null}let r=await NE(n,DE(e),3);return r===null||!await ME(r)?null:PE(e,r,t)}var IE=class extends Error{constructor(e){super(e),this.name=`RuntimeInstallError`}};async function LE(e,t){let n;try{n=await Mu(e,{withFileTypes:!0})}catch(e){e.code!==`ENOENT`&&t.warn({err:e},`[managed-runtime] could not read staging dir for cleanup`);return}let r=Date.now()-864e5;for(let i of n){if(!i.isDirectory()||!i.name.startsWith(`.install-`))continue;let n=R(e,i.name);try{if((await Pu(n)).mtimeMs>=r)continue;await ds(n,{recursive:!0,force:!0})}catch(e){if(e.code===`ENOENT`)continue;t.warn({err:e},`[managed-runtime] stale staging cleanup failed`)}}}async function RE(e,t,n=TE()){await LE(R(n,e),t)}async function zE(e,t,n={}){let r=n.root??TE(),i=R(r,e,CT(EE(e))),a=L(i),o=await FE(e,r);if(o!==null)return await LE(a,t),o;let s=AE(e);if(s===null)throw new IE(`no ${e} build for ${Eu()}-${Cu()}`);await ls(a,{recursive:!0}),await LE(a,t);let c=R(a,`.install-${CT(EE(e))}-${process.pid}-${Ru()}`);await ls(c,{recursive:!0});let l=R(c,s.archiveName);t.info({kind:e,version:EE(e),url:s.archiveUrl},`[managed-runtime] downloading runtime`);try{let[a,o]=await Promise.all([TT(s.archiveUrl,l,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),ET(s.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),u=DT(o,s.archiveName);if(u===null)throw new IE(`no published checksum for ${s.archiveName}`);if(a!==u)throw new IE(`checksum mismatch for ${s.archiveName}: got ${a}, expected ${u}`);let d=R(c,`extracted`);await ls(d,{recursive:!0}),await wT(l,d,s.isZip);let f=await NE(d,DE(e),3);if(f===null||!ST(d,f))throw new IE(`extracted ${e} archive has no usable launcher`);let p=await FE(e,r);if(p!==null)return p;await n.beforeCommit?.();try{return await hs(`${i}.install.lock`,async()=>{let n=await FE(e,r);if(n!==null)return n;await ds(i,{recursive:!0,force:!0}),await Ts(d,i),t.info({kind:e,version:EE(e),versionDir:i},`[managed-runtime] runtime installed`);let a=await FE(e,r);if(a===null)throw new IE(`installed ${e} runtime not found after extract`);return a},{timeoutMs:n.commitLockTimeoutMs??6e4,onWarn:(n,r)=>{t.warn({...r,kind:e},`[managed-runtime] ${n}`)}})}catch(n){if(n instanceof Zo){let i=await FE(e,r);if(i!==null)return i;t.warn({kind:e,lockPath:n.lockPath,timeoutMs:n.timeoutMs},`[managed-runtime] commit lock timed out with no winner installed`)}throw n}}catch(t){throw t instanceof IE?t:new IE(`installing ${e} ${EE(e)} failed: ${t instanceof Error?t.message:String(t)}`)}finally{await ds(c,{recursive:!0,force:!0}).catch(()=>{})}}const BE=`acp-runtime-consent.json`;async function VE(e=wE()){let t;try{let{readFile:n}=await import(`node:fs/promises`);t=await n(R(e,BE),`utf8`)}catch{return{}}try{let e=JSON.parse(t),n=e=>e===`granted`||e===`declined`?e:void 0;return{node:n(e.node),uv:n(e.uv)}}catch{return{}}}async function HE(e,t,n,r=wE()){try{let n={version:1,...await VE(r),[e]:t,updatedAt:Date.now()};await ls(r,{recursive:!0}),await os(R(r,BE),`${JSON.stringify(n,null,2)}\n`)}catch(t){n.warn({err:t,kind:e},`[managed-runtime] consent persist failed`)}}const UE=2e3;function WE(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function GE(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:WE(n.subarray(n.length-t)).toString(`utf8`)}function KE(e){if(e.outputBytes<=e.byteLimit)return;let t=WE(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var qE=class{terminals=new Map;emit;defaultCwd;log;loginShellPath;disposed=!1;constructor(e){this.defaultCwd=e.defaultCwd,this.emit=e.emit,this.log=e.log,this.loginShellPath=e.loginShellPath??null}liveCount(){let e=0;for(let t of this.terminals.values())t.exitStatus===null&&e++;return e}create(e){if(this.disposed)throw Error(`thread is closing — no new terminals`);if(this.terminals.size>=64)throw Error(`terminal limit reached (64 per thread) — release finished terminals first`);let t=crypto.randomUUID(),n={};for(let t of e.env??[])n[t.name]=t.value;let r=JT(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:Zl(e.cwd)?e.cwd:B(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?lE(e.command,aE(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?dE(o,e.args??[]):{cmd:o,args:e.args??[]},u=Gl(c,l,{cwd:i,env:r,stdio:[`ignore`,`pipe`,`pipe`],shell:!1,detached:!a,windowsHide:!0,windowsVerbatimArguments:s}),d=e.outputByteLimit,f={child:u,output:``,outputBytes:0,byteLimit:typeof d==`number`&&d>0?Math.floor(d):1048576,truncated:!1,exitStatus:null,exitWaiters:[],transcriptBytes:0,transcriptPaused:!1,pausedTail:``};this.terminals.set(t,f),this.safeEmit({kind:`terminal_created`,terminalId:t,command:e.command,args:e.args??[],ts:Date.now()});let p=e=>this.ingestChunk(t,f,e);u.stdout?.setEncoding(`utf8`),u.stdout?.on(`data`,p),u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,p);let m=!1;return u.on(`spawn`,()=>{m=!0}),u.on(`error`,e=>{if(m){this.log.warn({err:e,terminalId:t},`[acp-terminals] child error after spawn`);return}p(`${e.message}\n`),this.settleExit(t,f,{exitCode:127,signal:null})}),u.on(`close`,(e,n)=>{this.settleExit(t,f,{exitCode:e,signal:n})}),{terminalId:t}}output(e){let t=this.mustGet(e);return KE(t),{output:t.output,truncated:t.truncated,exitStatus:t.exitStatus}}waitForExit(e){let t=this.mustGet(e);return t.exitStatus===null?new Promise(e=>{t.exitWaiters.push(e)}):Promise.resolve(t.exitStatus)}async kill(e){let t=this.mustGet(e);t.exitStatus===null&&await gE(t.child,{graceMs:UE})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await gE(t.child,{graceMs:UE}),this.terminals.delete(e))}async disposeAll(){this.disposed=!0;let e=[...this.terminals.keys()];await Promise.allSettled(e.map(e=>this.release(e)))}spawnEnv(e){let t=KT(e);return this.loginShellPath===null||qT(e)?t:$T(t,this.loginShellPath)}mustGet(e){let t=this.terminals.get(e);if(t===void 0)throw Error(`unknown terminal '${e}'`);return t}safeEmit(e){try{this.emit(e)}catch(t){this.log.warn({err:t,kind:e.kind},`[acp-terminals] transcript emit failed`)}}ingestChunk(e,t,n){if(n!==``){if(t.output+=n,t.outputBytes+=Buffer.byteLength(n,`utf8`),t.outputBytes>t.byteLimit*2?KE(t):t.outputBytes>t.byteLimit&&(t.truncated=!0),!t.transcriptPaused){let r=Buffer.byteLength(n,`utf8`);if(t.transcriptBytes+r<=262144){t.transcriptBytes+=r,this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:n,ts:Date.now()});return}t.transcriptPaused=!0}t.pausedTail=GE(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,KE(t),t.transcriptPaused&&t.pausedTail!==``&&this.safeEmit({kind:`terminal_output`,terminalId:e,chunk:`\n… [output truncated — resuming at the end]\n${t.pausedTail}`,ts:Date.now()}),this.safeEmit({kind:`terminal_exit`,terminalId:e,exitCode:n.exitCode,signal:n.signal,ts:Date.now()});let r=t.exitWaiters;t.exitWaiters=[];for(let t of r)try{t(n)}catch(t){this.log.warn({err:t,terminalId:e},`[acp-terminals] exit waiter threw`)}}};const JE=`threads`;var YE=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=R(e.primaryDir,JE),this.legacyThreadsDir=e.legacyDir==null?null:R(e.legacyDir,JE),this.cwd=e.cwd??null,this.log=e.log,this.writeThreadsDir=this.primaryThreadsDir}threadsDirFor(e){return this.homeByThread.get(e)??this.writeThreadsDir}pinHome(e){this.homeByThread.has(e)||this.homeByThread.set(e,this.writeThreadsDir)}enqueue(e,t){let n=this.writeQueues.get(e)??Promise.resolve();this.writeQueues.set(e,n.then(t))}async init(){try{await ls(this.primaryThreadsDir,{recursive:!0})}catch(e){if(this.log.warn({err:e,dir:this.primaryThreadsDir},`[acp-persist] primary threads dir unavailable`),this.legacyThreadsDir!==null){this.writeThreadsDir=this.legacyThreadsDir;try{await ls(this.legacyThreadsDir,{recursive:!0})}catch(e){this.log.error({err:e,dir:this.legacyThreadsDir},`[acp-persist] legacy threads dir also unavailable; threads are memory-only`)}}}}eventsPath(e){return R(this.threadsDirFor(e),`${e}.ndjson`)}metaPath(e){return R(this.threadsDirFor(e),`${e}.meta.json`)}appendEvents(e,t){if(t.length===0||this.appendBroken.has(e))return;this.pinHome(e);let n=`${t.map(e=>JSON.stringify(e)).join(`
22
22
  `)}\n`;this.enqueue(e,async()=>{if(!this.appendBroken.has(e))try{await Ss(this.eventsPath(e),n)}catch(t){this.appendBroken.add(e),this.log.error({err:t,threadId:e},`[acp-persist] event append failed; thread continues memory-only`)}})}queueMetaWrite(e,t){this.pinHome(e);let n=`${JSON.stringify(t,null,1)}\n`;this.enqueue(e,async()=>{let t=this.metaPath(e),r=`${t}.tmp`;try{await os(r,n),await Ts(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await ds(r,{force:!0})}catch{}}})}whenIdle(e){return this.writeQueues.get(e)??Promise.resolve()}async scan(){let e=[],t=new Set,n=this.cwd===null?null:await QE(this.cwd);return await this.scanDir(this.primaryThreadsDir,n,e,t),this.legacyThreadsDir!==null&&this.legacyThreadsDir!==this.primaryThreadsDir&&await this.scanDir(this.legacyThreadsDir,null,e,t),e}async scanDir(e,t,n,r){let i;try{i=await Mu(e)}catch(t){t.code!==`ENOENT`&&this.log.warn({err:t,dir:e},`[acp-persist] could not read a threads dir`);return}for(let a of i){if(!a.endsWith(`.meta.json`))continue;let i=R(e,a),o;try{o=JSON.parse(await ju(i,`utf8`))}catch(e){this.log.warn({err:e,path:i},`[acp-persist] skipping unreadable thread meta`);continue}if(o.version!==1||typeof o.info!=`object`||o.info===null||typeof o.info.threadId!=`string`||typeof o.cwd!=`string`||typeof o.agentRef!=`object`||o.agentRef===null){this.log.warn({path:i},`[acp-persist] skipping unreadable thread meta`);continue}let s=o,c=s.info.threadId;r.has(c)||t!==null&&await QE(s.cwd)!==t||(r.add(c),this.homeByThread.has(c)||this.homeByThread.set(c,e),n.push(s))}}async resolveEventLog(e){let t=this.eventsPath(e);if(!V(t))return{count:0,midTurn:!1};let n=0,r=!1;return await this.forEachCompleteLine(t,e=>(n+=1,e.startsWith(`{"kind":"turn_started"`)?r=!0:e.startsWith(`{"kind":"turn_ended"`)&&(r=!1),!0)),{count:n,midTurn:r}}async readEvents(e,t,n,r){let i=this.eventsPath(e);if(t>=n||!V(i))return;let a=0,o=[],s=t,c=()=>{o.length!==0&&(r(s,o),s+=o.length,o=[])};await this.forEachCompleteLine(i,e=>a>=n?!1:(a>=t&&(o.push(ZE(e)),o.length>=512&&c()),a+=1,!0)),c()}async delete(e){this.appendBroken.delete(e),this.writeQueues.delete(e);let t=[this.eventsPath(e),this.metaPath(e)],n=await Promise.allSettled(t.map(e=>ds(e,{force:!0})));this.homeByThread.delete(e);for(let[r,i]of n.entries())i.status===`rejected`&&this.log.warn({err:i.reason,threadId:e,path:t[r]},`[acp-persist] thread file removal failed`)}async forEachCompleteLine(e,t){let n=su(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=Tte({input:n,crlfDelay:1/0}),a=!1,o=null,s=!1;try{for await(let e of i){if(o!==null&&!t(o)){s=!0;break}o=e}s||(a=await XE(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function XE(e){let{open:t}=await import(`node:fs/promises`),n=await t(e,`r`);try{let{size:e}=await n.stat();if(e===0)return!1;let t=Buffer.alloc(1);return await n.read(t,0,1,e-1),t[0]===10}finally{await n.close()}}function ZE(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function QE(e){try{return await Nu(e)}catch{return B(e)}}const $E=RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b(?:[\\s,:;!.\\-–—]+|$)`,`i`),eD=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/;function tD(e){return(e.trim().split(`
23
- `)[0]??``).trim()}function nD(e){let t=tD(e);if(t.length<=48)return t;let n=t.slice(0,47),r=n.lastIndexOf(` `);return`${(r>=48/2?n.slice(0,r):n).trimEnd()}…`}function rD(e){let t=tD(e),n=t.replace(eD,``);for(let e=0;e<6;e++){let e=n.replace($E,``);if(e===n)break;n=e}n=n.trim();let r=n.split(/\s+/).filter(e=>e!==``).length;return!(n!==``&&(r>=2||n.length>=12))||n===t?nD(t):nD(n.charAt(0).toUpperCase()+n.slice(1))}const iD=8,aD=5e3,oD=5e3,sD=2e3;var cD=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},lD=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}};function uD(){return new cD(`not-ready`,`the thread was restarted during the sign-in`)}function dD(e,t){let[n=`open-knowledge`,...r]=e&&e.length>0?e:[`open-knowledge`];return{command:n,args:[...r,`mcp`,`--port`,String(t)]}}var fD=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;persistence;resolveLoginShellPath;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>VT(e.log)()),this.maxThreads=e.maxThreads??8,this.idleReapMs=e.idleReapMs??36e5,this.steerStallMs=e.steerStallMs??1e4,this.authenticateTimeoutMs=e.authenticateTimeoutMs??3e5,this.unwatchedTurnCancelMs=e.unwatchedTurnCancelMs??6e5,this.unwatchedTurnKillMs=e.unwatchedTurnKillMs??12e5,this.persistence=new YE({primaryDir:e.globalDir??e.localDir,legacyDir:e.globalDir===null?null:e.localDir,cwd:e.globalDir===null?null:e.contentDir,log:e.log}),this.reapTimer=setInterval(()=>this.reapIdleThreads(),3e5),this.reapTimer.unref?.()}async init(){if(this.initialized)return;this.initialized=!0,this.resolveLoginShellPath().catch(()=>{}),await this.persistence.init();let e=await this.persistence.scan();for(let t of e){let e=t.info.threadId;this.threads.has(e)||this.threads.set(e,mD(t))}e.length>0&&this.opts.log.info({count:e.length},`[acp-threads] rehydrated archived threads`)}listThreads(){return[...this.threads.values()].map(e=>({...e.info}))}liveThreadCount(){let e=0;for(let t of this.threads.values())t.info.archived!==!0&&(e+=1);return e}getInfo(e){let t=this.threads.get(e);return t===void 0?void 0:{...t.info}}async subscribe(e,t,n){let r=this.mustGet(e);await this.ensureLogResolved(r);let i=Math.max(t,0),a=i;for(;a<r.baseSeq;){let t=r.baseSeq;await this.persistence.whenIdle(e),await this.persistence.readEvents(e,a,t,(t,r)=>{n({op:`events`,threadId:e,fromSeq:t,events:r})}),a=t}this.flushBroadcast(r);let o=Math.max(i,r.baseSeq),s=r.baseSeq+r.events.length;for(let t=o;t<s;t+=512){let i=Math.min(t+512,s);n({op:`events`,threadId:e,fromSeq:t,events:r.events.slice(t-r.baseSeq,i-r.baseSeq)})}return r.subscribers.add(n),r.unwatchedSince=null,r.unwatchedCancelSent=!1,{...r.info}}ensureLogResolved(e){return e.logResolved?Promise.resolve():(e.logResolution??=(async()=>{let t=await this.persistence.resolveEventLog(e.info.threadId);e.baseSeq=t.count,e.midTurnOnDisk=t.midTurn,e.info.lastSeq=t.count-1,e.logResolved=!0})(),e.logResolution)}unsubscribe(e,t){let n=this.threads.get(e);n!==void 0&&(n.subscribers.delete(t),n.subscribers.size===0&&n.unwatchedSince===null&&(n.unwatchedSince=Date.now()))}async createThread(e){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let r=crypto.randomUUID(),i=Date.now(),a={info:{threadId:r,agent:t,title:t.name,status:`installing`,createdAt:i,lastActivityAt:i,modes:null,configOptions:null,lastSeq:-1,archived:!1},docName:e.docName,agentRef:{source:e.agent.source,id:e.agent.id},launchSettings:e.settings,cwd:this.opts.contentDir,child:null,conn:null,lastInit:null,sessionId:null,agentSessionId:`acp-${r}`,events:[],baseSeq:0,logResolved:!0,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint};return this.threads.set(r,a),this.emitStatus(a,`installing`),this.startThread(a,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await df(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new cD(`unknown-agent`,`no custom agent '${e.id}'`);return{info:{id:t.id,name:t.name,source:`custom`},custom:t}}let t;try{t=await this.opts.registry.getAgent(e.id)}catch(e){throw new cD(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new cD(`unknown-agent`,`agent '${e.id}' is not in the registry`);return{info:{id:t.id,name:t.name,iconUrl:t.icon,source:`registry`,version:t.version},custom:null}}async connectAgent(e,t){let n;if(t!==null)n=XT(t);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new cD(`unknown-agent`,`agent vanished`);n=await YT(t,af(),this.opts.log)}if(e.closed)return null;let r=await this.ensureLaunchable(e,n);if(r===null||(n=r,e.closed))return null;let i=await this.resolveLoginShellPath().catch(()=>null);if(e.closed)return null;let a=new qE({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:i});this.emitStatus(e,`spawning`);let o=fE(n,e.cwd);if(e.child=o,e.terminals=a,o.stderr?.setEncoding(`utf8`),o.stderr?.on(`data`,t=>{for(let n of t.split(`
23
+ `)[0]??``).trim()}function nD(e){let t=tD(e);if(t.length<=48)return t;let n=t.slice(0,47),r=n.lastIndexOf(` `);return`${(r>=48/2?n.slice(0,r):n).trimEnd()}…`}function rD(e){let t=tD(e),n=t.replace(eD,``);for(let e=0;e<6;e++){let e=n.replace($E,``);if(e===n)break;n=e}n=n.trim();let r=n.split(/\s+/).filter(e=>e!==``).length;return!(n!==``&&(r>=2||n.length>=12))||n===t?nD(t):nD(n.charAt(0).toUpperCase()+n.slice(1))}const iD=8,aD=5e3,oD=5e3,sD=2e3;var cD=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},lD=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}};function uD(){return new cD(`not-ready`,`the thread was restarted during the sign-in`)}function dD(e,t){let[n=`open-knowledge`,...r]=e&&e.length>0?e:[`open-knowledge`];return{command:n,args:[...r,`mcp`,`--port`,String(t)]}}var fD=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;persistence;resolveLoginShellPath;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>VT(e.log)()),this.maxThreads=e.maxThreads??8,this.idleReapMs=e.idleReapMs??36e5,this.steerStallMs=e.steerStallMs??1e4,this.authenticateTimeoutMs=e.authenticateTimeoutMs??3e5,this.unwatchedTurnCancelMs=e.unwatchedTurnCancelMs??6e5,this.unwatchedTurnKillMs=e.unwatchedTurnKillMs??12e5,this.persistence=new YE({primaryDir:e.globalDir??e.localDir,legacyDir:e.globalDir===null?null:e.localDir,cwd:e.globalDir===null?null:e.contentDir,log:e.log}),this.reapTimer=setInterval(()=>this.reapIdleThreads(),3e5),this.reapTimer.unref?.()}async init(){if(this.initialized)return;this.initialized=!0,this.resolveLoginShellPath().catch(()=>{}),await this.persistence.init();let e=await this.persistence.scan();for(let t of e){let e=t.info.threadId;this.threads.has(e)||this.threads.set(e,mD(t))}e.length>0&&this.opts.log.info({count:e.length},`[acp-threads] rehydrated archived threads`)}listThreads(){return[...this.threads.values()].map(e=>({...e.info}))}liveThreadCount(){let e=0;for(let t of this.threads.values())t.info.archived!==!0&&(e+=1);return e}getInfo(e){let t=this.threads.get(e);return t===void 0?void 0:{...t.info}}async subscribe(e,t,n){let r=this.mustGet(e);await this.ensureLogResolved(r);let i=Math.max(t,0),a=i;for(;a<r.baseSeq;){let t=r.baseSeq;await this.persistence.whenIdle(e),await this.persistence.readEvents(e,a,t,(t,r)=>{n({op:`events`,threadId:e,fromSeq:t,events:r})}),a=t}this.flushBroadcast(r);let o=Math.max(i,r.baseSeq),s=r.baseSeq+r.events.length;for(let t=o;t<s;t+=512){let i=Math.min(t+512,s);n({op:`events`,threadId:e,fromSeq:t,events:r.events.slice(t-r.baseSeq,i-r.baseSeq)})}return r.subscribers.add(n),r.unwatchedSince=null,r.unwatchedCancelSent=!1,{...r.info}}ensureLogResolved(e){return e.logResolved?Promise.resolve():(e.logResolution??=(async()=>{let t=await this.persistence.resolveEventLog(e.info.threadId);e.baseSeq=t.count,e.midTurnOnDisk=t.midTurn,e.info.lastSeq=t.count-1,e.logResolved=!0})(),e.logResolution)}unsubscribe(e,t){let n=this.threads.get(e);n!==void 0&&(n.subscribers.delete(t),n.subscribers.size===0&&n.unwatchedSince===null&&(n.unwatchedSince=Date.now()))}async createThread(e){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let r=crypto.randomUUID(),i=Date.now(),a={info:{threadId:r,agent:t,title:t.name,status:`installing`,createdAt:i,lastActivityAt:i,promptCapabilities:null,modes:null,configOptions:null,lastSeq:-1,archived:!1},docName:e.docName,agentRef:{source:e.agent.source,id:e.agent.id},launchSettings:e.settings,cwd:this.opts.contentDir,child:null,conn:null,lastInit:null,sessionId:null,agentSessionId:`acp-${r}`,events:[],baseSeq:0,logResolved:!0,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint};return this.threads.set(r,a),this.emitStatus(a,`installing`),this.startThread(a,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await df(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new cD(`unknown-agent`,`no custom agent '${e.id}'`);return{info:{id:t.id,name:t.name,source:`custom`},custom:t}}let t;try{t=await this.opts.registry.getAgent(e.id)}catch(e){throw new cD(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new cD(`unknown-agent`,`agent '${e.id}' is not in the registry`);return{info:{id:t.id,name:t.name,iconUrl:t.icon,source:`registry`,version:t.version},custom:null}}async connectAgent(e,t){let n;if(t!==null)n=XT(t);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new cD(`unknown-agent`,`agent vanished`);n=await YT(t,af(),this.opts.log)}if(e.closed)return null;let r=await this.ensureLaunchable(e,n);if(r===null||(n=r,e.closed))return null;let i=await this.resolveLoginShellPath().catch(()=>null);if(e.closed)return null;let a=new qE({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:i});this.emitStatus(e,`spawning`);let o=fE(n,e.cwd);if(e.child=o,e.terminals=a,o.stderr?.setEncoding(`utf8`),o.stderr?.on(`data`,t=>{for(let n of t.split(`
24
24
  `))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
25
- `);this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new cD(`spawn-failed`,`agent process has no stdio`);let s=Zre(bte.toWeb(o.stdin),Fu.toWeb(o.stdout)),c=ah({name:`open-knowledge`}).onRequest(Dm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Dm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Dm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Dm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Dm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Dm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Dm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Dm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Dm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(Dm.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new cD(`spawn-failed`,`initialize failed: ${vD(t)}`)}return e.closed?null:(e.lastInit=l,{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){try{return await rE(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof UT)||n.code!==`command-not-found`)throw n;let r=await this.retryWithLoginShellPath(t);if(r!==null)return r;if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=SE(t.kind);if(!jE(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=ZT(t,a);return await rE(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(aE(t.env)===aE(e.env))return null;try{await rE(t)}catch(t){if(!(t instanceof UT))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||oE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:QT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await RE(t,this.opts.log,n);let r=await FE(t,n).catch(()=>null);if(r!==null)return r;let i=(await VE(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new UT(`command-not-found`,gD(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=CE(t).displayName;throw new UT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=CE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:n,runtime:t,displayName:r.displayName,provides:r.provides,version:r.version,approxSizeMB:r.approxSizeMB,sourceHost:r.sourceHost,agentName:e.info.agent.name,ts:Date.now()}),new Promise(r=>{let i=setTimeout(()=>{e.pendingRuntimeConsent.delete(n),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:n,decision:`timeout`,ts:Date.now()}),r(`timeout`)},3e5);i.unref?.(),e.pendingRuntimeConsent.set(n,{runtime:t,resolve:r,timer:i})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;n.remember===!0&&HE(i.runtime,a,this.opts.log,this.opts.runtimeInstall?.consentHome),this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return zE(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[{name:fT,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:zt,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=tf[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof UT||t instanceof cD?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:xD(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),t.prompt!==void 0&&t.prompt!==``&&this.sendPrompt(e.info.threadId,t.prompt))}async openSession(e,t,n,r){let i=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Dm.agent.session.new,{cwd:e.cwd,mcpServers:i});e.sessionId=n.sessionId,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){let r=SD(yD(t),xD(e));return _D(t)?this.emitStatus(e,`auth_required`,`sign in required: ${vD(t)}`,{reason:`auth-required`,agentMessage:vD(t),machineDetail:r,authMethods:CD(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${vD(t)}`,{reason:`session-setup`,agentMessage:vD(t),machineDetail:r}),await this.teardownFailedAgent(e)),!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new cD(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new cD(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.resumeInFlight=!0;let r=Date.now();try{await this.ensureLogResolved(n);let i=n.sessionId,{info:a,custom:o}=await this.resolveAgentInfo(n.agentRef);if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.stderrTail=[],n.midTurnOnDisk&&(n.midTurnOnDisk=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),t!==void 0&&t!==``&&(this.echoUserMessage(n,t),this.flushBroadcast(n)),this.emitStatus(n,`installing`);try{if(i===null)throw new cD(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new cD(`not-ready`,`thread closed during resume`);let{conn:s,init:c}=a,l=await this.buildMcpServers(n,c),u=c.agentCapabilities,d=u?.sessionCapabilities?.resume!=null,f;if(d)f=await s.agent.request(Dm.agent.session.resume,{sessionId:i,cwd:n.cwd,mcpServers:l});else if(u?.loadSession===!0){n.suppressUpdates=!0,n.lastSuppressedAt=Date.now();try{f=await s.agent.request(Dm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new cD(`resume-unsupported`,`${n.info.agent.name} doesn't support resuming previous sessions`);n.sessionId=i;let p=f.modes;p!=null&&(n.info.modes=p);let m=f.configOptions;return m!=null&&(n.info.configOptions=m),this.emitStatus(n,`ready`),this.opts.log.info({threadId:e,agentId:n.info.agent.id,method:d?`session/resume`:`session/load`,msToResumed:Date.now()-r},`[acp-threads] thread resumed`),t!==void 0&&t!==``&&this.dispatchPrompt(n,t,{echo:!1}),{...n.info}}catch(t){throw await this.abortResume(n),t instanceof cD?t:t instanceof UT?new cD(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new cD(`resume-unsupported`,`couldn't resume the previous session: ${vD(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new cD(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new cD(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new cD(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{HT();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new cD(`spawn-failed`,n)}if(t.closed)throw new cD(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new cD(`spawn-failed`,bD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new cD(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new cD(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new cD(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0;try{this.emitStatus(n,`installing`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw uD();let t=e instanceof lD?`the sign-in didn't complete in time — try again`:vD(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:SD(yD(e),xD(n)),authMethods:CD(i.authMethods)}),new cD(`not-ready`,t)}if(n.closed)throw new cD(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw uD();if(!await this.openSession(n,r,i,n.launchSettings))throw new cD(`not-ready`,bD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new lD),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Dm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await gE(t,{graceMs:sD}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(dh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cD(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new cD(`not-ready`,`20 messages are already waiting — let the agent catch up`);n.info.queue=[...e,{id:crypto.randomUUID(),content:t,ts:Date.now()}],n.info.lastActivityAt=Date.now(),this.emitInfo(n);return}this.dispatchPrompt(n,t,{echo:!0})}steerPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cD(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);if(!n.turnActive){this.dispatchPrompt(n,t,{echo:!0});return}this.clearSteer(n),n.info.steer={content:t,ts:Date.now()},n.info.lastActivityAt=Date.now(),this.emitInfo(n);let r=setTimeout(()=>this.demoteStalledSteer(n),this.steerStallMs);r.unref?.(),n.steerStallTimer=r,this.cancelTurn(n,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;t===void 0||e.closed||!e.turnActive||(e.info.steer=void 0,e.info.queue=[{id:crypto.randomUUID(),content:t.content,ts:t.ts},...e.info.queue??[]],this.emitInfo(e))}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=rD(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}this.appendEvent(e,{kind:`user_message`,content:t,ts:Date.now()})}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new cD(`not-ready`,`the thread is closing`);let r=nD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n){if(e.sessionId===null||e.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let r=e.sessionId;e.conn.agent.request(Dm.agent.session.prompt,{sessionId:r,prompt:[{type:`text`,text:t}]}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}this.emitStatus(e,`error`,`prompt failed: ${vD(t)}`,{reason:`prompt`,agentMessage:vD(t),machineDetail:SD(yD(t),xD(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(Dm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new cD(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Dm.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new cD(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(Dm.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!hD(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(Dm.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(Dm.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&hD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Dm.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await gE(r,{graceMs:t?.killGraceMs??oD})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(dh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new cD(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new cD(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:sD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:gT(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await ju(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await ju(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
25
+ `);this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new cD(`spawn-failed`,`agent process has no stdio`);let s=Zre(bte.toWeb(o.stdin),Fu.toWeb(o.stdout)),c=ah({name:`open-knowledge`}).onRequest(Dm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Dm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Dm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Dm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Dm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Dm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Dm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Dm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Dm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(Dm.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new cD(`spawn-failed`,`initialize failed: ${vD(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){try{return await rE(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof UT)||n.code!==`command-not-found`)throw n;let r=await this.retryWithLoginShellPath(t);if(r!==null)return r;if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=SE(t.kind);if(!jE(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=ZT(t,a);return await rE(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(aE(t.env)===aE(e.env))return null;try{await rE(t)}catch(t){if(!(t instanceof UT))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||oE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:QT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await RE(t,this.opts.log,n);let r=await FE(t,n).catch(()=>null);if(r!==null)return r;let i=(await VE(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new UT(`command-not-found`,gD(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=CE(t).displayName;throw new UT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=CE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:n,runtime:t,displayName:r.displayName,provides:r.provides,version:r.version,approxSizeMB:r.approxSizeMB,sourceHost:r.sourceHost,agentName:e.info.agent.name,ts:Date.now()}),new Promise(r=>{let i=setTimeout(()=>{e.pendingRuntimeConsent.delete(n),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:n,decision:`timeout`,ts:Date.now()}),r(`timeout`)},3e5);i.unref?.(),e.pendingRuntimeConsent.set(n,{runtime:t,resolve:r,timer:i})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;n.remember===!0&&HE(i.runtime,a,this.opts.log,this.opts.runtimeInstall?.consentHome),this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return zE(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[{name:fT,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:zt,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=tf[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof UT||t instanceof cD?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:xD(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),t.prompt!==void 0&&t.prompt!==``&&this.sendPrompt(e.info.threadId,t.prompt))}async openSession(e,t,n,r){let i=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Dm.agent.session.new,{cwd:e.cwd,mcpServers:i});e.sessionId=n.sessionId,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){let r=SD(yD(t),xD(e));return _D(t)?this.emitStatus(e,`auth_required`,`sign in required: ${vD(t)}`,{reason:`auth-required`,agentMessage:vD(t),machineDetail:r,authMethods:CD(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${vD(t)}`,{reason:`session-setup`,agentMessage:vD(t),machineDetail:r}),await this.teardownFailedAgent(e)),!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new cD(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new cD(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.resumeInFlight=!0;let r=Date.now();try{await this.ensureLogResolved(n);let i=n.sessionId,{info:a,custom:o}=await this.resolveAgentInfo(n.agentRef);if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.stderrTail=[],n.midTurnOnDisk&&(n.midTurnOnDisk=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),t!==void 0&&t!==``&&(this.echoUserMessage(n,t),this.flushBroadcast(n)),this.emitStatus(n,`installing`);try{if(i===null)throw new cD(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new cD(`not-ready`,`thread closed during resume`);let{conn:s,init:c}=a,l=await this.buildMcpServers(n,c),u=c.agentCapabilities,d=u?.sessionCapabilities?.resume!=null,f;if(d)f=await s.agent.request(Dm.agent.session.resume,{sessionId:i,cwd:n.cwd,mcpServers:l});else if(u?.loadSession===!0){n.suppressUpdates=!0,n.lastSuppressedAt=Date.now();try{f=await s.agent.request(Dm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new cD(`resume-unsupported`,`${n.info.agent.name} doesn't support resuming previous sessions`);n.sessionId=i;let p=f.modes;p!=null&&(n.info.modes=p);let m=f.configOptions;return m!=null&&(n.info.configOptions=m),this.emitStatus(n,`ready`),this.opts.log.info({threadId:e,agentId:n.info.agent.id,method:d?`session/resume`:`session/load`,msToResumed:Date.now()-r},`[acp-threads] thread resumed`),t!==void 0&&t!==``&&this.dispatchPrompt(n,t,{echo:!1}),{...n.info}}catch(t){throw await this.abortResume(n),t instanceof cD?t:t instanceof UT?new cD(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new cD(`resume-unsupported`,`couldn't resume the previous session: ${vD(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new cD(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new cD(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new cD(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{HT();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new cD(`spawn-failed`,n)}if(t.closed)throw new cD(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new cD(`spawn-failed`,bD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new cD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new cD(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new cD(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new cD(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0;try{this.emitStatus(n,`installing`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw uD();let t=e instanceof lD?`the sign-in didn't complete in time — try again`:vD(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:SD(yD(e),xD(n)),authMethods:CD(i.authMethods)}),new cD(`not-ready`,t)}if(n.closed)throw new cD(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw uD();if(!await this.openSession(n,r,i,n.launchSettings))throw new cD(`not-ready`,bD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new lD),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Dm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await gE(t,{graceMs:sD}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(dh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cD(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new cD(`not-ready`,`20 messages are already waiting — let the agent catch up`);n.info.queue=[...e,{id:crypto.randomUUID(),content:t,ts:Date.now()}],n.info.lastActivityAt=Date.now(),this.emitInfo(n);return}this.dispatchPrompt(n,t,{echo:!0})}steerPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cD(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cD(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);if(!n.turnActive){this.dispatchPrompt(n,t,{echo:!0});return}this.clearSteer(n),n.info.steer={content:t,ts:Date.now()},n.info.lastActivityAt=Date.now(),this.emitInfo(n);let r=setTimeout(()=>this.demoteStalledSteer(n),this.steerStallMs);r.unref?.(),n.steerStallTimer=r,this.cancelTurn(n,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;t===void 0||e.closed||!e.turnActive||(e.info.steer=void 0,e.info.queue=[{id:crypto.randomUUID(),content:t.content,ts:t.ts},...e.info.queue??[]],this.emitInfo(e))}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=rD(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}this.appendEvent(e,{kind:`user_message`,content:t,ts:Date.now()})}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new cD(`not-ready`,`the thread is closing`);let r=nD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n){if(e.sessionId===null||e.conn===null)throw new cD(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let r=e.sessionId;e.conn.agent.request(Dm.agent.session.prompt,{sessionId:r,prompt:[{type:`text`,text:t}]}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}this.emitStatus(e,`error`,`prompt failed: ${vD(t)}`,{reason:`prompt`,agentMessage:vD(t),machineDetail:SD(yD(t),xD(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(Dm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new cD(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Dm.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new cD(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(Dm.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!hD(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(Dm.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(Dm.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&hD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Dm.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await gE(r,{graceMs:t?.killGraceMs??oD})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(dh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new cD(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new cD(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:sD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:gT(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await ju(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await ju(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
26
26
  `),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
27
27
  `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=Qw(t.dc.document);Zw(t.dc.document,n,`replace`,i,void 0,Yw(t));let a=wn(r,Qw(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-Bkh7Uqka.mjs`);await e(L(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return pD(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new cD(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&xT(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>aD){let t=e.events.length-aD;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await gE(t,{graceMs:oD})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,steer:n,...r}=e.info;return{version:1,info:r,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=ai(e.info.agent.id),i=ti[r]??aa(e.agentSessionId);n.setPresence(dh(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function pD(e,t,n){let r=await Nu(e),i=Ql(Zl(t)?t:B(r,t)),a=i,o=``;for(;;)try{let e=await Nu(a),i=o===``?e:R(e,o),s=z(r,i);if(s===``||s.startsWith(`..`)||Zl(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(tu).join(`/`),t=s.split(tu).join(`/`);!tS(e)&&!nS(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(tu).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=L(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):R(a.slice(t.length+1),o),a=t}}function mD(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function hD(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function gD(e){let t=CE(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function _D(e){return typeof e==`object`&&!!e&&e.code===-32e3}function vD(e){return e instanceof Error?e.message:String(e)}function yD(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function bD(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function xD(e){let t=e.stderrTail.join(`
28
28
  `);return t===``?void 0:t}function SD(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
@@ -2029,4 +2029,4 @@ native-divergence-injected
2029
2029
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=B(e,r);if(!uN(a,t))continue;let s=mz(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function f9(e){d9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=I(`server`),b=new c7,x=()=>b.getActiveBranch(),S=e=>b.getReconciledBase(e),C=(e,t)=>b.setReconciledBase(e,t),w=e=>b.deleteReconciledBase(e),T=e=>b.switchReconciledBaseScope(e),E=e=>b.setBatchInProgress(e),ee=()=>b.isBatchInProgress();function D(){let e=ts({absPath:rs(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=Te(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function O(){let e=ts({absPath:rs(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=we(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=ts({absPath:rs(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:ce(r.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){let e=ts({absPath:rs(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?xn(e):$i}function te(){return ts({absPath:rs(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ne(){return SM(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function re(){let e=ts({absPath:rs(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ie(){return $o({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function ae(){for(let e of ie().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function oe(e){return`${fM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function se(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=O();t=n.mode,ft?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=ne();Ne.applyConfig({enabled:n.enabled,providerFingerprint:oe(n)}),e===`__config__/project`&&Ee?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}Os();let A=Ru(),le=dA(n),ue=new uf({localDir:le,log:I(`acp-registry`)}),de=new $d(le,I(`acp-permissions`));if(ic(le,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!g)try{X7({lockDir:le,shadowRepoDir:Sd(n)})}catch(e){throw Xs(le),e}let fe=za(),j=(e,t)=>fe.resolveEmbed(e,t),me=(e,n)=>{let r=fe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=B(t,r);if(!cN(i,B(t)))return null;try{let e=bu(i);return e.isFile()?e.size:null}catch{return null}},he,ge,_e,ve,ye,be,M,xe,Se,Ce,N,Ee=null,De=null,Oe=null,ke=null,Ae=null,je=null,Me=ne(),Ne=new oue({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return Kle({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:R(dA(n),`embeddings`),enabled:Me.enabled,providerFingerprint:oe(Me)}),Pe=null,P=new Set,Fe=!1,F=[],Ie,Le,Re,ze=new Promise((e,t)=>{Le=e,Re=t});function Be(e){Ee?.signal(e)}let Ve=null,He=!1,Ue=()=>{try{V7(n,We.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},We=new HDe(void 0,{onEviction:()=>Hoe(),onSizeChange:e=>Uoe(e),onMutate:()=>{!He||Ve!==null||(Ve=setTimeout(()=>{Ve=null,Ue()},2e3))}});for(let[e,r]of GDe(n))oS(e)||gQ(e)&&([`.md`,`.mdx`].some(n=>{let r=B(t,`${e}${n}`);return cN(r,B(t))&&V(r)})||We.restore(e,r));He=!0;let Ge={current:null},Ke=(e,t)=>{oS(e)||We.setRenamed(e,t)},qe=e=>{if(!oS(e)){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e),Ge.current?.deleted(e)}},Je=e=>{oS(e)||We.delete(e)};try{he=uP({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:cL(t),rescanInPlaceSkillDirs:()=>cL(t),onAfterRebuild:()=>{ge.refreshContentScope().catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Lz(ut).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?I(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):I(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ge=new jR({projectDir:n,contentDir:t,contentFilter:he,getGlobalSkillRoots:()=>_K(ye.managedArtifactCtx),signalChannel:Be}),_e={current:d},ve=o?ADe({getShadow:()=>_e.current??null,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:xd(n)??void 0,isWriterLive:e=>{if(!ke&&!xe)return I(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(ke?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of xe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ye=P7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:_e,ephemeral:v,contentRoot:f,derivedDocumentIndex:ge,configHomedirOverride:l,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:j,resolveSize:me,getPrincipal:()=>Pe,onAgentCommit:()=>Ee?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Ee?.emitDiskAck(e,t),!oS(e)&&TB(r,n)&&(Ae?.(),Be(`files`))},onConfigRejected:(e,t)=>Ee?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>We.has(e),mdManager:e.mdManager,getLossRing:()=>be,durabilityState:b}),M=new KEe({quiet:r,debounce:i,maxDebounce:a,extensions:[ye.extension]});let p=M;F.push(fw(()=>p.documents.size),pw(()=>ye.getQueueDepths()),hw(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),_w(),v||(je=BDe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>ye.forceStore(e,t),getBase:e=>b.getReconciledBase(e),isBatchActive:()=>b.isBatchInProgress(),peekInFlight:e=>b.peekInFlightFlush(e),readDiskBytes:e=>{let n=lN(e,t),r,i;try{r=U(n),i=bu(r).size}catch(t){let n=Zs(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new I7(`symlink cycle at content path: ${e}`):t}if(!uN(r,t))throw new I7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new I7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(Zs(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=M.shouldUnloadDocument.bind(M);M.shouldUnloadDocument=e=>{if(P.has(e)||Fe&&g(e))return!0;let t=e.name;return oS(t)||S(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Ie=async e=>{P.add(e);try{await M.unloadDocument(e)}finally{P.delete(e)}},Ee=new lS(M),Oe=new OD(M),ke=new AD(M),xe=new uT(M,e.agentSessionOptions);let C=xe;F.push(gw(()=>({active:C.liveSessionCount,limit:C.sessionLimit})));let w=f7({derivedDocumentIndex:ge,onDocumentSettled:e=>Ge.current?.changed(e)});M.configuration.extensions.push(w),M.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=EQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==A)throw new TQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${A}`);let i=n?.expectedBranch,a=x();if(typeof i==`string`&&i.length>0&&i!==a)throw new TQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Pe&&n.principalId===Pe.id?o.principalId=Pe.id:Pe?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Pe.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),M.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!nS(t.documentName)&&!rS(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!rB(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&lB(a,e.remotePublicHost);if(!iB(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=B(t);function E(e){if(!gQ(e))return null;let t=B(T,Qx(e));return cN(t,T)?t:null}M.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await UDe(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:E,fileExists:V})}}),M.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=EQ(e.token);cDe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>M.documents.get(e)})}}),M.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ur} rejected — server-only channel`)}});let ee=_Q({hocuspocus:M,durabilityState:b,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:Ge,contentDir:t,contentFilter:he,serverInstanceId:A,getFileIndex:()=>ut?ut.getFileIndex():new Map,getAttachmentFolderPath:D,getAllFilesIndex:()=>ut?ut.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ut?.getFileIndexGeneration()??0,mutateFileIndex:e=>ut?.mutateFileIndex(e),getFolderIndex:()=>ut?ut.getFolderIndex():new Map,getAliasMap:()=>ut?ut.getAliasMap():new Map,getFolderAliasIndex:()=>ut?ut.getFolderAliasIndex():new Map,rescanFiles:()=>ut?.rescanFromDisk(),enableTestRoutes:u,shadowRef:_e,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),getCurrentBranch:()=>dt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Ee?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:ge,signalChannel:Be,agentFocusBroadcaster:Oe,agentPresenceBroadcaster:ke,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ft,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:j,getBridgeLossReporter:()=>N,getPrincipal:()=>Pe,acpRegistry:ue,loadAcpCustomAgents:()=>df(le,I(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Ie,ready:ze,recentlyRemovedDocs:We,serializeDoc:$e,evictManagedArtifactLkg:e=>{ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ne,getSemanticSimilarityFloor:()=>ne().similarityFloor,getLinterBaseConfig:()=>k(),getLinksValidationSetting:()=>te(),getLinkPreviewsEnabled:re,getConfigDiagnostics:ie,embeddingsSecretsFile:yM(l),readSemanticProviderConfig:ne,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{Ae=e}});M.configuration.extensions.push(ee),Se=ee.nativeApi,Ce=ee.localApi;let O=ts({absPath:rs(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),ae=O.value.bridge.deferGuard.enabled,oe=O.value.bridge.fixedPoint.enabled,ce=O.value.bridge.preDrain.enabled;be=O.value.lossCapture.enabled?new jae({projectDir:n,maxBytes:O.value.lossCapture.maxBytes}):void 0,O.value.bridge.lossDetector.enabled&&(N=Sse({shadow:()=>_e.current,ring:be,getBranch:()=>dt?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(N)),M.configuration.extensions.push(U7({mdManager:Xo,schema:Yo,shadowRef:_e,contentRoot:f,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:j,resolveSize:me,deferGuardEnabled:ae,lossDetectorEnabled:O.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:oe,preDrainEnabled:ce,lossRing:be})),M.configuration.extensions.push(kOe()),M.configuration.extensions.push(sDe({getSyncEngine:()=>ft,projectDir:n,contentDir:t}))}catch(e){for(let e of F.splice(0))e();throw je?.dispose(),je=null,Xs(le),e}let Ye=null,Xe=new Map,Ze=[];function Qe(e,t){let n=B(e,`rescue`),r=B(n,Qx(t));return cN(r,n)?r:null}function $e(e){let t=M.documents.get(e);return t?WR(t):null}let et=(e,t)=>VR(b,M,e,t,j,me,N);function tt(e){if(!vS(e)||ft?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let nt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of M.documents){if(oS(n))continue;let r=M.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{NR(r,i,j,n)},MR)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rt=null,it=e=>{e&&(rt===null&&(rt=new Set,setImmediate(()=>{let e=rt;if(rt=null,e)try{for(let t of e)nt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rt.add(e))};function at(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return XR(e)}}async function ot(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await ge.recordDiskUpsert(e.docName,e.content),Be(`files`),Je(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=M.documents.get(t);if(!r){await ge.recordDiskUpsert(t,n);return}let i=S(t)??``,a=$e(t)??i,o=LR({docName:t,base:i,ours:a,theirs:n}),s=rz(i).slice(0,6),c=rz(a).slice(0,6),l=rz(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:tt(r),await ge.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{et(t,o.newContent),C(t,o.newContent),Yb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),C(t,n),tt(r)}e&&await ge.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{et(t,o.newContent),C(t,n),Yb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),C(t,n),tt(r)}e&&await ge.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{et(t,o.newContent),C(t,o.newContent),Yb(),Xb(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),C(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await ge.recordDiskUpsert(t,n);break}case`refused`:{Xb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=M.documents.get(t);if(!n){await ge.recordDiskDelete(t),Be(`files`),qe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=S(t)??``,i=$e(t)??``,a=i!==r;if(a&&_e.current){let e=_e.current,n=dt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Ix(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Qb(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),w(t),await ge.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),M.closeConnections(t),await Ie(n),Be(`files`),qe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=M.documents.get(t);if(w(t),C(n,r),await ge.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Be(`files`),Ke(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=M.documents.get(t);if(!n)return;let r=$e(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):C(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:fe.add(e.relativePath),Be(`files`),it(Jl(e.relativePath));break;case`asset-delete`:fe.remove(e.relativePath),Be(`files`),it(Jl(e.relativePath));break;case`folder-create`:case`folder-delete`:Be(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Be(`files`);break;default:XR(e)}}catch(t){let n=at(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let st=[];async function ct(e){if(ee()){st.push(e);return}await ot(e)}async function lt(){let e=st.splice(0,st.length);for(let t of e)await ot(t)}let ut=null,dt=null,ft=null,pt=null;async function mt(e){if(M.documents.size===0)return;let t=!1,n=new Promise(e=>{M.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(M.documents.keys());M.closeConnections(),M.flushPendingStores();for(let e of M.documents.values())e.getConnectionsCount()===0&&M.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(M.documents.keys()),i=[],o=[];if(_e.current){for(let e of n)if(!oS(e))try{let t=$e(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Qe(_e.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}uu(L(n),{recursive:!0}),Su(n,t,`utf-8`),Qb(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ht(){return pt||(pt=(async()=>{let e=Date.now(),t=[];Fe=!0;for(let e of F.splice(0))e();try{await je?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}je=null;try{oc(le)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ve!==null&&(clearTimeout(Ve),Ve=null),He)try{V7(n,We.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([ze.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=M.documents.size;ve?.destroy();try{try{try{De&&=(clearTimeout(De),null),dt&&=(await dt.unsubscribe(),null),ut&&=(await ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ze)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ze.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Ee?.destroy(),ke?.destroy(),Ye&&=(await Ye.disconnect(),null);for(let[e,t]of Xe)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Xe.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await xe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await nC()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await mt(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}ge.close();let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ft&&=(await ft.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){let e;try{await Promise.race([gx(_e.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),p)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await Vs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Su(B(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{rse(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Xs(le,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await Ds()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),pt)}let gt=[];async function _t(){try{Pe=await L7(n),y.info({principalId:Pe.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await Sx(n),y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),gt.push(`shadow-repo`)}if(_e.current){let e=null;try{e=sq(_e.current.gitDir),Aq(_e.current.gitDir,e),fq(_e.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([jq(_e.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ve?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(_e.current)try{await bx(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await Sx(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,gt.includes(`shadow-repo`)||gt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=B(_e.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Vs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Vs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Nx(_e.current,f??``,t,r,e),Zb()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{Su(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=qK(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),gt.push(`managed-rename-recovery`)}try{let e=OL(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),gt.push(`upload-tempfile-sweep`)}try{Ye=await M.openDirectConnection(Ur),Ee?.emitServerInfo(A,x())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),gt.push(`cc1-push`)}let r=v?[]:ri;for(let e of r)try{let t=await M.openDirectConnection(e);Xe.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),gt.push(`config-doc:${e}`)}let i=new Map([[io,rs(`project`,n)],[ci,rs(`project-local`,n)],[bi,rs(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X5(t,t=>{let n=M.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,ye.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Ze.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),gt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=SK(e,ye.managedArtifactCtx);if(!n)return;let r=DK(M.documents.get(n)??null,n,t,ye.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Be(`files`),Do(n)&&ge.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=SK(e,ye.managedArtifactCtx);Be(`files`),t&&Do(t)&&ge.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=_K(ye.managedArtifactCtx),r=await jDe(n,e,t);Ze.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),gt.push(`managed-artifact-watcher:skills`)}try{let e=B(mK(ye.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{Be(`files`)});Ze.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),gt.push(`skill-state-watcher`)}}try{let e=B(t,`.okignore`),r=B(n,`.gitignore`),i=null;try{let e=Kl(`git`,[`rev-parse`,`--git-common-dir`],pN({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=R(B(n,e.stdout.trim()),`info`,`exclude`);V(L(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await QEe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(M.documents.get(`__config__/okignore`)??null,da,r,ye.configPersistenceCtx);o.info({docName:da,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:z(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await he.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:z(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Ee?.signal(`files`);else{let e=z(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Ee?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:z(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ze.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),gt.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;T(a);let o=ge.beginStartup(a),s=!1,c=performance.now();try{await as(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&gt.push(`backlink-index`);let i=0;for(let t of e)oS(t)||We.peek(t)?.kind!==`renamed`&&(We.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=he?cL(t):new Set,d=e=>{e.some(e=>c.test(z(t,e).split(tu).join(`/`)))&&(De&&clearTimeout(De),De=setTimeout(()=>{De=null;try{aZ(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Ee?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=cL(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,he.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Ee?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ut=await as(`ok.boot.seed-walk`,void 0,async()=>Iz(t,ct,he,{onRawBatch:d})),aZ(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??wu();aZ(e,e,oL(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}mR(`seedWalkMs`,Math.round(performance.now()-a));{let e=B(t),n=0;for(let[t]of We.entries()){if(!gQ(t))continue;let r=B(e,`${t}${Xx(t)}`);cN(r,e)&&V(r)&&(We.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await ge.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&gt.push(`tag-index`);let p=0;try{_===void 0?await bQ({contentDir:t,contentFilter:he,basenameIndex:fe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Fme({contentDir:t,basenameIndex:fe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),gt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),gt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),gt.push(`file-watcher`),!s){let e=await ge.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&gt.push(`tag-index`)}}finally{mR(`indexesMs`,Math.round(performance.now()-c)),ut&&hR(`fileCount`,ut.getFileIndex().size)}try{dt=await pDe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),zae(),M.flushPendingStores(),await ye.flushPendingGitCommit(),E(!0),_e.current){let e=x(),t=d7(n).branch??e,r=[];for(let[e,t]of M.documents){if(oS(e))continue;let n=null;if(t.transact(()=>{n=$e(e)},AOe),n===null)continue;let i=S(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await pse(_e.current,e,jx.id,r,t);n&&(Hae(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=st.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(E(!1),await lt(),e.headMoved&&e.newHead){let r=MOe(n,B(t),e.oldHead,e.newHead);if(r.size>0){yle(r.keys());for(let[e,t]of r)Yj(e,vd(t.email),t.name,t.email,Bd(e));await ye.flushContributors()}}if(await ye.flushDeferredStores(`within-branch`),ft!==null)try{await ft.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Vae(),st.splice(0,st.length);let n=!1,r;try{T(i),r=await ge.beginBranchSwitch(i),he.rebuildDirCount();try{let e=0;fe.clear(),await bQ({contentDir:t,contentFilter:he,basenameIndex:fe,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),gt.includes(`basename-index-partial`)||gt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of M.documents)if(!oS(e))try{let r=lN(e,t);if(!V(r)){let t=S(e)??``,r=$e(e)??``;if(r!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{Ix(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Qb(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=H(r,`utf-8`);et(e,a),C(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:M.documents.size},`[branch-switch] loaded branch ${i} (${M.documents.size} docs)`);try{await ge.settleBranchFromDisk(r)}catch(e){ge.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of M.documents)if(!oS(t))try{let n=await hse(_e.current,i,jx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=S(t);if(!r)continue;let a=LR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:et(t,a.newContent),C(t,a.newContent),e++;break;case`conflicts`:et(t,a.newContent),C(t,a.newContent),Xb(),e++;{let e=M.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=bx(_e.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await gx(_e.current).withMutator(async()=>{for(let e of n.split(`
2030
2030
  `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}E(!1),await ye.flushDeferredStores(`discard-stale`),n=!0,Ee?.emitBranchSwitched(i)}finally{ge.abortBranchSwitch(r),n||(E(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&_e.current&&r>0){let t=f??`.`;try{let n=await Nx(_e.current,t,e.oldHead,e.newHead,i);Zb(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=sN(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=Gx(e),a=M.documents.get(i);if(!a)continue;let o=$e(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):C(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=sN(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=M.documents.get(Gx(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=jOe(m),h=O();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new DOe({projectDir:n,contentDir:t,contentFilter:he,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Ee,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{E(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=_e.current;n&&await Fx(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=_e.current;n&&await Fx(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await gs({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:pe(t.error),configPath:rs(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}Be(`files`),ge.announceReadyViews();let g=pR();g!==void 0&&mR(`readyMs`,g),ae()}return _t().then(Le,e=>{ge.close(),Re(e)}),{hocuspocus:M,durabilityState:b,sessionManager:xe,nativeApi:Se,localApi:Ce,cc1Broadcaster:Ee,agentFocusBroadcaster:Oe,agentPresenceBroadcaster:ke,maintenanceCoordinator:ve,contentFilter:he,basenameIndex:fe,serverInstanceId:A,destroy:ht,ready:ze,degraded:gt,lockDir:le,get syncEngine(){return ft},getLinkPreviewsEnabled:re,resolveEmbed:j,acpRegistry:ue,acpPermissions:de}}function p9(e){return e/1048576}function NOe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:p9(e.rss),heapTotalMb:p9(e.heapTotal),heapUsedMb:p9(e.heapUsed),externalMb:p9(e.external),arrayBuffersMb:p9(e.arrayBuffers)}}}let m9=null,h9=null,g9=null;const _9=1e6;let v9=null,y9=null;is(()=>{m9=null,h9=null,g9=null,v9?.disable(),v9=null,y9=null});function POe(){if(m9)return;let e=ks().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=NOe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),m9=e}function FOe(){if(!h9){let e=ks().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!v9){v9=wte({resolution:20}),v9.enable();return}e.observe(v9.percentile(50)/_9,{stat:`p50`}),e.observe(v9.percentile(99)/_9,{stat:`p99`}),v9.reset()}),h9=e}if(!g9){let e=ks().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=y9;if(y9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),g9=e}}const b9=I(`skill-migrate`);function x9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=CO.indexOf(e.host),r=CO.indexOf(t.host);return(n===-1?CO.length:n)-(r===-1?CO.length:r)||e.host.localeCompare(t.host)})}const IOe=x9(In),LOe=x9(Ve);function ROe(e,t){_s(L(t),{recursive:!0});try{us(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;bs(e,t,{recursive:!0}),xs(e,{recursive:!0,force:!0})}}function zOe(e,t,n){let r=CI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function S9(e,t){let n;try{n=U(B(e,`.ok`,`skills`))}catch{n=B(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(B(e,t.dir)).startsWith(n+tu)}catch{return!0}}).map(e=>e.name))}async function C9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??IOe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=hu(n)}catch{return a}let s=z(t,n).split(tu).join(`/`),c=new Set;for(let[e,n]of Object.entries(nZ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ue.test(e)||WF.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=B(n,e);if(!V(R(o,`SKILL.md`)))continue;let s=fO(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=B(t,r);return{host:n,root:r,path:R(i,e),escapes:jI(t,i),state:zOe(R(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&V(B(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?xs(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&xs(d.path,{recursive:!0,force:!0}),ROe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(xs(e.path,{recursive:!0,force:!0}),bs(d.path,e.path,{recursive:!0}));await HN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),b9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),b9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const w9=I(`skill-reconcile`),BOe=WF;function T9(){let e=[];for(let t of Xa){let n=In[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function VOe(e,t){let n=z(e,B(t));return Zl(n)?B(t):n}function E9(e){let{frontmatter:t,body:n}=vo(e),r={};if(t!==``)try{let e=(0,Nk.parse)(Zn(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function HOe(e,t){let n=E9(e),r=E9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function D9(e,t){let n=O9(e),r=O9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=R(e,o),c=R(t,o);if(i+=bu(s).size+bu(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!HOe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function O9(e,t=``){let n=[];for(let r of hu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...O9(R(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function k9(e,t,n){xs(t,{recursive:!0,force:!0}),_s(e,{recursive:!0}),ps(VOe(e,n),t,`dir`)}function A9(e,t){try{let n=gu(e);return B(Zl(n)?n:B(L(e),n))===B(t)}catch{return!1}}function UOe(e,t){try{let n=gu(e),r=Zl(n)?B(n):B(L(e),n);if(!V(r))return!1;let i=z(B(t),r);return i!==``&&(i.startsWith(`..`)||Zl(i))}catch(t){return w9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const WOe=[...Xa,`agents`];function GOe(e){for(let t of WOe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function KOe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=hu(n)}catch{return}let i=T9();for(let e of r){let r=GOe(e);if(r===null)continue;let a=B(n,e),o=B(n,r);if(V(o))try{let n=lu(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(R(a,`SKILL.md`))||!V(R(o,`SKILL.md`))||!D9(o,a))continue;for(let{rel:n}of i){let r=B(t,n);if(jI(t,r))continue;let i=R(r,e);A9(i,a)&&k9(r,i,o)}xs(a,{recursive:!0,force:!0}),w9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){w9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function qOe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of T9()){let o=B(t,e);if(!V(o)||jI(t,o))continue;let s;try{s=hu(o)}catch(e){w9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(BOe.has(e))continue;let t=R(o,e),s=B(n,e),c=V(s);try{let l=lu(t);if(l.isSymbolicLink()){if(A9(t,s)&&c)continue;if(UOe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(k9(o,t,s),r.healed.push({name:e,editor:i})):(xs(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ue.test(e)){w9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&D9(t,s)){k9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){w9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=zN(t);for(let[r,a]of i){let i=B(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await VN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??EI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){w9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{KOe({projectDir:t,skillsRoot:n})}catch(e){w9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let j9=null,M9=!1;function N9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function P9(e){if(!N9())return;let t=dA(e);j9=new Rs({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Da(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};j9?.append(`${JSON.stringify(t)}\n`).catch(e=>{M9||(M9=!0,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function F9(){Da(null),await j9?.drain(),j9=null,M9=!1}qo();const JOe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],YOe=[`cache`,`tmp`];function XOe(e){let t=B(e,Se);if(!(()=>{if(!V(t))return!0;try{return hu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of JOe)V(B(e,t))&&n.push(t);for(let t of YOe){let r=B(e,t);try{V(r)&&bu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function ZOe(e){let t=bd(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const I9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function QOe(e){fR();let t=e.projectDir??e.contentDir,n=Hme({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Ps.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Os({localSink:n?.telemetry}),P9(t),POe(),FOe();let{kind:r,gitdir:i}=ZOe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ys(i));let o=Bme(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>as(`ok.boot`,{attributes:a},async()=>L9(e)),l=()=>{if(s)try{let e=Go.extract(Jo.active(),{traceparent:s});return Jo.with(e,c)}catch(e){I(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function L9(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??I(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?oB(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new aB("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-SvEBQb4s.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=B(p,`.ok`);if(!V(B(m,`config.yml`)))throw new Y8(V(m)?`config`:`okdir`,p);let h=B(m,`.gitignore`);V(h)||I(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??MG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof kG||e instanceof AG){let t=e instanceof AG?e.detected:``,n=e instanceof AG?`too_old`:`not_available`;ZG(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await Ds(),await Promise.race([F9(),new Promise(e=>setTimeout(e,I9))]),e}let v=XOe(m);v.length>0&&I(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Se}/.`);let y=f9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:D}=y,k=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),te=e.port??0,ne=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${k}:${te}`,localApi:y.localApi,log:r}),re=c();re.headersTimeout=3e4,re.requestTimeout=6e4;let ae=e.serveContentAssets===!1?void 0:vQ({contentFilter:y.contentFilter,contentSirv:fc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ie,assetExtensions:O,blocklistExtensions:g}),oe=!1;if(e.reactShellDistDir)try{mL(w,{port:0,worktreeRoot:e.projectDir??e.contentDir}),oe=!0}catch(e){if(e instanceof pL)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:w},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await x().catch(()=>{}),u(w),e}let se=e.reactShellDistDir?fc(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,A=e.ephemeral?null:new fD({contentDir:e.contentDir,localDir:w,globalDir:B(wu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${k}:${te}`,getMcpStdioCommand:()=>dD(e.localOpCliArgs,te),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});A!==null&&await A.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let ce=`pending`;S.then(()=>{ce=`ready`},()=>{ce=`failed`});let le=q8({httpServer:re,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:ne,remoteAccess:i,health:{readiness:()=>ce,degraded:()=>C},log:r,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:D,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ae,reactShellMiddleware:se,ephemeral:e.ephemeral,acpThreadManager:A}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;a!==null&&(de=MQ({httpServer:re,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);re.once(`error`,r),re.listen(e.port,e.host,()=>{re.removeListener(`error`,r),t()})})}catch(e){if(oe)try{_L(w)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await x().catch(()=>{}),u(w),e}let fe=pR();fe!==void 0&&mR(`httpListenMs`,fe);let pe=re.address(),j=typeof pe==`object`&&pe?pe.port:e.port??0;te=j;let me=`http://${k}:${j}`;if(d(w,j,me),oe&&hL(w,j,me),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:w,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let he=!1,ge=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${I9}ms`))},I9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async()=>{if(he)return;he=!0,ce=`draining`;let e=[],t=async(t,n)=>{try{await ge(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(w),oe&&vL(w)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(A!==null&&await t(`acpThreads.destroy`,()=>A.destroy()),await t(`mount.shutdown`,()=>le.shutdown()),ne!==void 0&&await t(`mcpHttpHandler.close`,()=>ne.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{re.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{re.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>x()),oe&&await t(`releaseUiLock`,async()=>_L(w,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Ds()),await t(`teardownToleranceTelemetry`,()=>F9()),await t(`flushLogFileSinks`,()=>Ps.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await C9({projectDir:p,skillsRoot:B(e.contentDir,`.ok`,`skills`),inPlaceNames:S9(e.contentDir,aL(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=wu(),t=await C9({projectDir:e,skillsRoot:B(e,`.ok`,`skills`),hostRoots:LOe,inPlaceNames:S9(e,oL(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await qOe({projectDir:p,skillsRoot:B(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:re,destroy:ue,lockDir:w,contentDir:e.contentDir,port:j,ready:S,degraded:C,didAutoInit:f,serverInstance:y,runtime:YTe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:A}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new kQ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=xd(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Us({baseDir:n,timeout:{block:5e3}});s=new Set(await Jb(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=Gx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const $Oe=le;function eke(e={}){let t=e.home??wu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(Ls(),1);const B9=R(wu(),`.ok`,`logs`),tke=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function nke(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function rke(e){uu(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function ike(e){try{if(bu(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{_u(n,r)}catch{}}try{xu(`${e}.3`)}catch{}}function ake(e){try{let t=Date.now(),n=10080*60*1e3,r=hu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=bu(R(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{xu(R(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{xu(R(e,t.name)),a-=t.size}catch{}}}catch{}}function oke(e){rke(B9);let t=V9(),n=e.filePath??R(B9,`${e.name}.${t}.log`);ike(n),(e._setTimeout??setTimeout)(()=>ake(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:nke(),name:e.name,redact:{paths:tke,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function ske(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function cke(e){return R(B9,`${e}.${V9()}.log`)}function lke(){return B9}function uke(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=L(t);if(r===t)return null;t=r,n+=1}return null}const H9=Gu(Wl),U9=I(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function dke(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],pN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function fke(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!bu(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=MG()}catch(e){throw e instanceof kG||e instanceof AG?(ZG(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof AG?`too_old`:`not_available`,detectedVersion:e instanceof AG?e.detected:``},e instanceof AG?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await dke(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],pN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!V(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,pke=Sa.map(e=>e.replace(/\/$/,``));async function mke(e){let t=xd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(vke(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Ws(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Hs(async()=>{let t=await hke(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await gke(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Ws(e,{gitIndexFile:R(Du(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await _ke(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await tB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ks(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Va}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of pke){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function hke(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function gke(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function _ke(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function vke(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function yke(e,t){let n;try{n=Ul(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=L(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await ju(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=L(t);if(r===t)return;t=r}}const bke=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of bke)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function xke(e){if(!Ux(e))throw new $9(e);let t;try{t=U(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!bu(t).isFile())throw new Q9(e);let n=L(t),r=zz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Gx(z(Ske(e),t).split(tu).join(`/`)),canonicalFilePath:t}}let i=Jl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Gx(i)}}function Ske(e){return B(e,ts({absPath:rs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Cke(e){let t=du(B(Du(),`ok-ephemeral-`)),n=B(t,`.ok`);return uu(n,{recursive:!0}),Su(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Su(B(n,`.gitignore`),`local/
2031
2031
  `,`utf-8`),t}export{Y2 as $,zx as $i,hL as $n,xM as $r,kG as $t,Y7 as A,aT as Ai,nz as An,zP as Ar,hQ as At,d7 as B,nS as Bi,HR as Bn,SN as Br,sJ as Bt,f9 as C,ld as Ca,iD as Ci,iB as Cn,jF as Cr,bQ as Ct,X7 as D,Gw as Di,XR as Dn,JP as Dr,xme as Dt,q7 as E,pT as Ei,Rz as En,qP as Er,zZ as Et,EDe as F,Uw as Fi,xz as Fn,LP as Fr,nJ as Ft,K8 as G,Rx as Gi,MR as Gn,yN as Gr,fJ as Gt,J8 as H,rS as Hi,FR as Hn,TN as Hr,vJ as Ht,b7 as I,_S as Ii,Iz as In,IP as Ir,gJ as It,z8 as J,jx as Ji,tR as Jn,pN as Jr,$q as Jt,W8 as K,kx as Ki,TR as Kn,mN as Kr,cJ as Kt,y7 as L,K as Li,bz as Ln,Tde as Lr,mJ as Lt,L7 as M,Zw as Mi,yz as Mn,BP as Mr,kJ as Mt,P7 as N,bw as Ni,mz as Nn,RP as Nr,EJ as Nt,G7 as O,sT as Oi,Sz as On,GP as Or,Sme as Ot,v7 as P,xw as Pi,tz as Pn,Ede as Pr,xJ as Pt,W2 as Q,Ox as Qi,_L as Qn,SM as Qr,ZG as Qt,mDe as R,gS as Ri,$R as Rn,uP as Rr,_J as Rt,F9 as S,Sd as Sa,fD as Si,oB as Sn,Ffe as Sr,EQ as St,W7 as T,dT as Ti,zz as Tn,KP as Tr,BZ as Tt,Y8 as U,oS as Ui,LR as Un,CN as Ur,uJ as Ut,c7 as V,sS as Vi,PR as Vn,xN as Vr,hJ as Vt,q8 as W,tS as Wi,IR as Wn,wN as Wr,lJ as Wt,H2 as X,Nx as Xi,mL as Xn,YM as Xr,$G as Xt,k8 as Y,Ex as Yi,pL as Yn,lN as Yr,tK as Yt,U2 as Z,wx as Zi,gL as Zn,JM as Zr,XG as Zt,$Oe as _,df as _a,fA as _i,sW as _n,$F as _r,TQ as _t,xke as a,bx as aa,Ble as ai,RG as an,pI as ar,mve as at,P9 as b,Ed as ba,OD as bi,pB as bn,UF as br,CQ as bt,mke as c,lx as ca,Sle as ci,CG as cn,dI as cr,K0 as ct,uke as d,lh as da,Qj as di,iW as dn,fI as dr,Mhe as dt,Sx as ea,vM as ei,AG as en,SI as er,Eve as et,oke as f,ch as fa,Yj as fi,aW as fn,rI as fr,h1 as ft,eke as g,ef as ga,uA as gi,QU as gn,ZF as gr,SQ as gt,lke as h,uf as ha,dA as hi,oW as hn,eI as hr,DQ as ht,Cke as i,Bx as ia,Zle as ii,jG as in,gI as ir,pve as it,U7 as j,oT as ji,Cz as jn,VP as jr,UZ as jt,J7 as k,uT as ki,rz as kn,jde as kr,_Q as kt,W9 as l,nx as la,$j as li,bG as ln,uI as lr,S1 as lt,cke as m,uh as ma,Xj as mi,lW as mn,nI as mr,MQ as mt,Z9 as n,Fx as na,Xle as ni,MG as nn,$fe as nr,F2 as nt,X9 as o,px as oa,sM as oi,PG as on,mI as or,hve as ot,ske as p,dh as pa,Zj as pi,eW as pn,tI as pr,v1 as pt,H8 as q,Ax as qi,lR as qn,_N as qr,Qq as qt,$9 as r,Ix as ra,Qle as ri,YG as rn,vI as rr,A2 as rt,yke as s,dx as sa,mM as si,wG as sn,hI as sr,w2 as st,Q9 as t,Lx as ta,$le as ti,DG as tn,xI as tr,I2 as tt,fke as u,Xoe as ua,ble as ui,XU as un,Vfe as ur,e1 as ut,QOe as v,$d as va,_k as vi,mB as vn,KF as vr,xQ as vt,d9 as w,dD as wi,rB as wn,oF as wr,vQ as wt,N9 as x,Xd as xa,ED as xi,dB as xn,JF as xr,Ime as xt,R9 as y,Dd as ya,AD as yi,aB as yn,qF as yr,wQ as yt,f7 as z,lS as zi,VR as zn,ude as zr,oJ as zt};
2032
- //# sourceMappingURL=src-D6v6esDL.mjs.map
2032
+ //# sourceMappingURL=src-3pZWeowR.mjs.map
@@ -1 +1 @@
1
- import{Go as e,Is as t,P as n,R as r,Vo as i,Wo as a,_s as o,as as s,d as c,l,ss as u}from"./src-DS92rBYx.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Ai as _,An as v,Ar as y,At as b,B as x,Bi as S,Bn as C,Br as w,Bt as T,C as E,Ci as D,Cn as O,Cr as k,Ct as A,D as j,Di as M,Dn as N,Dr as P,Dt as F,E as I,Ei as L,En as R,Er as z,Et as B,F as V,Fi as H,Fn as U,Ft as W,G,Gi as K,Gn as q,Gr as J,Gt as Y,H as X,Hi as Z,Hn as Q,Hr as $,Ht as ee,I as te,Ii as ne,In as re,It as ie,J as ae,Ji as oe,Jn as se,Jr as ce,Jt as le,K as ue,Ki as de,Kn as fe,Kr as pe,Kt as me,L as he,Li as ge,Ln as _e,Lt as ve,M as ye,Mi as be,Mn as xe,Mr as Se,Mt as Ce,N as we,Ni as Te,Nn as Ee,Nt as De,O as Oe,Oi as ke,On as Ae,Or as je,Ot as Me,P as Ne,Pi as Pe,Pn as Fe,Pt as Ie,Q as Le,Qi as Re,Qn as ze,Qr as Be,Qt as Ve,R as He,Ri as Ue,Rn as We,Rr as Ge,Rt as Ke,S as qe,Si as Je,Sn as Ye,Sr as Xe,St as Ze,T as Qe,Ti as $e,Tn as et,Tr as tt,Tt as nt,U as rt,Ui as it,Un as at,Ur as ot,Ut as st,V as ct,Vi as lt,Vn as ut,Vr as dt,Vt as ft,W as pt,Wi as mt,Wn as ht,Wr as gt,Wt as _t,X as vt,Xi as yt,Xn as bt,Xr as xt,Xt as St,Y as Ct,Yi as wt,Yn as Tt,Yr as Et,Yt as Dt,Z as Ot,Zi as kt,Zn as At,Zr as jt,Zt as Mt,_ as Nt,_a as Pt,_i as Ft,_n as It,_r as Lt,_t as Rt,a as zt,aa as Bt,ai as Vt,an as Ht,ar as Ut,at as Wt,b as Gt,ba as Kt,bi as qt,bn as Jt,br as Yt,bt as Xt,c as Zt,ca as Qt,ci as $t,cn as en,cr as tn,d as nn,da as rn,di as an,dn as on,dr as sn,ea as cn,ei as ln,en as un,er as dn,et as fn,f as pn,fa as mn,fi as hn,fn as gn,fr as _n,g as vn,ga as yn,gi as bn,gn as xn,gr as Sn,gt as Cn,h as wn,ha as Tn,hi as En,hn as Dn,hr as On,ht as kn,i as An,ia as jn,ii as Mn,in as Nn,ir as Pn,it as Fn,j as In,ji as Ln,jn as Rn,jr as zn,jt as Bn,k as Vn,ki as Hn,kn as Un,kr as Wn,kt as Gn,l as Kn,la as qn,li as Jn,ln as Yn,lr as Xn,m as Zn,ma as Qn,mi as $n,mn as er,mr as tr,mt as nr,n as rr,na as ir,ni as ar,nn as or,nr as sr,nt as cr,o as lr,oa as ur,oi as dr,on as fr,or as pr,ot as mr,p as hr,pa as gr,pi as _r,pn as vr,pr as yr,q as br,qi as xr,qn as Sr,qr as Cr,qt as wr,r as Tr,ra as Er,ri as Dr,rn as Or,rr as kr,rt as Ar,s as jr,sa as Mr,si as Nr,sn as Pr,sr as Fr,st as Ir,t as Lr,ta as Rr,ti as zr,tn as Br,tr as Vr,tt as Hr,u as Ur,ua as Wr,ui as Gr,un as Kr,ur as qr,v as Jr,va as Yr,vn as Xr,vr as Zr,vt as Qr,w as $r,wi as ei,wn as ti,wr as ni,wt as ri,x as ii,xi as ai,xn as oi,xr as si,xt as ci,y as li,ya as ui,yi as di,yn as fi,yr as pi,yt as mi,z as hi,zi as gi,zn as _i,zr as vi,zt as yi}from"./src-D6v6esDL.mjs";import{C as bi,E as xi,T as Si,_ as Ci,b as wi,c as Ti,d as Ei,g as Di,i as Oi,l as ki,m as Ai,n as ji,p as Mi,s as Ni,t as Pi,u as Fi,v as Ii,w as Li,x as Ri,y as zi}from"./fs-traced-B2GMd7hO.mjs";import{a as Bi,d as Vi,f as Hi,i as Ui,l as Wi,n as Gi,r as Ki,t as qi,u as Ji}from"./logger-DFxEUjvj.mjs";import{C as Yi,S as Xi,_ as Zi,a as Qi,c as $i,d as ea,g as ta,h as na,i as ra,l as ia,m as aa,n as oa,o as sa,p as ca,r as la,s as ua,t as da,u as fa,v as pa,y as ma}from"./server-lock-BOsuOHaz.mjs";export{rn as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,M as AGENT_WRITE_ORIGIN,Yr as AcpPermissionStore,Tn as AcpRegistry,Je as AcpThreadManager,qt as AgentFocusBroadcaster,di as AgentPresenceBroadcaster,ke as AgentSessionCapacityError,Hn as AgentSessionManager,kn as AutoStartDisabledError,Zr as BUNDLE_IDS,pi as BUNDLE_SCOPE,Yt as BUNDLE_SKILL_NAME,Sr as BacklinkIndex,gi as CC1Broadcaster,u as CC1_CONTRACT_VERSION,Kr as CONFIG_FILENAME,ut as CONFLICT_MARKER_RE,w as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Nt as ConfigSchema,K as DEFAULT_CHECKPOINT_RETENTION,Vt as DEFAULT_EMBEDDINGS_DIMENSIONS,W as DEFAULT_PACK_ID,ct as DocumentDurabilityState,dr as EMBEDDINGS_API_KEY_ENV,yn as FEATURED_AGENT_IDS,de as FILE_SYSTEM_WRITER,q as FILE_WATCHER_ORIGIN,m as FileEmbeddingsBackend,Mt as GIT_PREFLIGHT_FAIL_SPAN_NAME,xr as GIT_UPSTREAM_WRITER,ui as GitDirAccessError,h as GitNotAvailableError,un as GitTooOldError,Cn as HOCUSPOCUS_AUTH_REJECTION_REASONS,Rt as HocuspocusAuthRejection,Qr as HocuspocusAuthTokenSchema,pe as INSTALLED_AGENTS_SCHEMES,s as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ie as LOG_MD_TEMPLATE,nt as MANAGED_RENAME_ORIGIN,D as MAX_ACP_THREADS,_ as MAX_AGENT_SESSIONS,$e as MCP_CONNECTION_ID_HEADER,i as MCP_SERVER_NAME,Ln as MIN_EVICTABLE_IDLE_MS,Br as MIN_GIT_VERSION,X as MISSING_OK_CONFIG_MESSAGE,Kt as MalformedGitPointerError,fn as McpLogger,rt as MissingOkConfigError,Te as OBSERVER_SYNC_ORIGIN,on as OK_OKIGNORE_TEMPLATE,a as ORPHAN_MODES,t as PROTOCOL_VERSION,qi as PinoLogger,$i as ProcessLockCollisionError,Kn as ProjectGitInitError,B as ROLLBACK_ORIGIN,gn as ROOT_GITIGNORE_TEMPLATE,Zi as RUNTIME_VERSION,fi as RemoteConfigError,oe as SERVICE_WRITER,yr as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,ve as STARTER_FOLDERS,Ke as STARTER_FOLDER_FRONTMATTER_FILENAME,yi as STARTER_PACKS,T as STARTER_PACK_IDS,ft as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,pa as STATE_SCHEMA_VERSION,o as SYSTEM_DOC_NAME,wr as SeedPrerequisiteError,le as SeedRootDirError,da as ServerLockCollisionError,Lr as SingleFileNotAFileError,rr as SingleFileNotFoundError,Tr as SingleFileNotMarkdownError,I as StateManifestError,fe as TagIndex,si as USER_GLOBAL_BUNDLE_IDS,Tt as UiLockCollisionError,F as __getShowAllWalkStatsForTesting,Me as __resetShowAllWalkStatsForTesting,ia as acquireProcessLock,oa as acquireServerLock,bt as acquireUiLock,be as applyAgentMarkdownWrite,_i as applyExternalChange,Ie as applySeed,j as assertCompatibleStateManifest,or as assertGitAvailable,N as assertNeverDiskEvent,ai as attachAcpThreadSocket,nr as attachIdleShutdown,Jr as bootServer,dn as buildAndOpenSkill,vr as buildConfigYmlContent,Ct as buildExecResult,ei as buildOkMcpStdioCommand,On as buildSkillZip,ee as buildStarterFolderFrontmatterYaml,wt as buildWipTree,Xe as bundleSkillMdPath,ln as canonicalProjectKey,Ae as classifyEvents,Pi as classifyFsPath,zr as clearAllEmbeddingsKeys,$t as clearContributors,st as coercePackId,l as colorFromSeed,yt as commitUpstreamImport,kt as commitWip,Re as commitWipFromTree,Or as compareSemver,tt as composeEffectiveLinterConfig,z as composeFrontmatterSchemasConfig,Q as containsConflictMarkers,Un as contentHash,Jn as contributorCount,Ne as countShadowObjects,V as countStaleAgentWipRefs,te as countWipRefs,Gn as createApiExtension,ri as createAssetServeMiddleware,G as createCollaborationHost,Ge as createContentFilter,vi as createContentFilterAsync,ar as createEmbeddingsSecretStore,An as createEphemeralProjectDir,C as createExternalChangeHandler,pn as createFileLogger,hi as createLiveDerivedIndexExtension,br as createMcpHttpHandler,Cr as createOsProbe,we as createPersistenceExtension,E as createServer,In as createServerObserverExtension,ne as createStreamingErrorWriter,Gi as createTestLogger,Dr as describeStoredEmbeddingsKey,vn as detectClaudeDesktopPresence,Nn as detectGit,Oe as detectProjectShape,Vr as detectUserSkillHosts,Ar as discoverLockDirs,Wn as discoverMarkdownlintConfig,Ve as emitPreflightFailureSpan,vt as encodeDocName,Ot as encodeFolderRoute,Le as encodeSkillRoute,Ur as ensureProjectGit,er as ensureProjectSkillGitignore,ge as errorResponse,v as evictStaleTrackerEntries,b as extractHeadings,Fn as extractOkBinaryPath,se as extractWikiLinksFromMarkdown,Ht as fallbackPaths,nn as findEnclosingGitRoot,et as findEnclosingProjectRoot,y as findNativeMarkdownlintFile,hr as flushFileLogger,mi as formatAuthRejectionWire,Gr as formatContributors,an as formatContributorsFrom,Ce as formatPackRationale,f as gcCheckpointRefs,Hr as getCurrentMcpLogger,En as getLocalDir,Zn as getLogFilePath,Ki as getLogger,wn as getLogsDir,ma as getMachineId,zi as getMeter,ur as getMetrics,wi as getTracer,Mr as handleCollabSocketError,dt as handleSpawnCursor,Jt as hasForwardingHeaders,he as hasGcLogLatch,c as iconFromClientName,Qt as incrementCollabSocketFilteredError,qn as incrementServerObserverFire,Dn as initContent,cn as initShadowRepo,Ri as initTelemetry,Gt as initToleranceTelemetryWriter,Ir as installPrettyZodErrors,Ui as installTestLoggers,sr as installUserSkill,Xr as isAllowedApiOrigin,O as isAllowedWorkspaceHostHeader,S as isConfigDoc,Xt as isHocuspocusAuthRejectionReason,_t as isKnownPackId,lt as isLinkIndexExcludedDoc,ti as isLoopbackAddress,Z as isManagedArtifactDoc,e as isOrphanMode,Pe as isPairedWriteOrigin,$ as isPathWithinDir,Xi as isProcessAlive,R as isProjectRoot,oi as isRemoteAdmitted,it as isReservedForUserTree,Rn as isSelfWrite,mt as isSystemDoc,ii as isToleranceTelemetryEnabled,Yi as isValidLockPid,xe as lastKnownHash,Rr as listRescueCheckpoints,Y as listStarterPacks,Pt as loadCustomAgents,ye as loadPrincipal,fa as lockBaseUrl,ea as lockFilePath,Bi as loggerFactory,Wi as logsCurrentPath,Ji as logsPreviousPath,Mn as makeLazyEmbeddingsKeyStore,la as markServerLockDraining,pt as mountMcpAndApi,ji as normalizeFsPath,k as originGitHubHost,xn as packageVersionMajorMinor,ci as parseAuthRejectionWire,fr as parseGitVersion,Ze as parseHocuspocusAuthToken,ue as parseKeepaliveConnectionId,Ee as pathToDocName,De as planSeed,zt as prepareSingleFileOpen,Wt as processCommand,mr as processUsage,Pn as readAllTargets,Ut as readBundleDecision,zn as readOwnNativeRules,ca as readProcessLock,aa as readProcessLockDetailed,x as readProjectHeadState,Be as readProjectLocalSemanticConfig,ra as readServerLock,pr as readServerPackageVersion,Fr as readSkillInstallStateSnapshot,Vn as readStateManifest,tn as readTargetRecordedAt,Xn as readTargetVersion,At as readUiLock,at as reconcile,hn as recordContributor,tr as recordSkillInstallEvent,ae as registerAllTools,Fe as registerWrite,na as releaseProcessLock,Qi as releaseServerLock,ze as releaseUiLock,U as removeLastKnownHash,kr as reportSkillInstall,Wr as resetMetrics,r as resolveBundleEnabled,Sn as resolveBundledSkillDir,bn as resolveContentDir,ot as resolveCursorBinaryDefault,gt as resolveCursorSpawnInvocation,P as resolveEffectiveLinterConfig,Nr as resolveEmbeddingsCredential,Ft as resolveLockDir,je as resolveNativeConfigForDoc,Se as resolveNativeMarkdownlintConfig,me as resolvePack,jr as resolvePackageVersion,Ye as resolveRemoteAccess,_n as resolveSkillInstallReportSettings,d as resolveUiInfo,_r as restoreContributors,li as restoreLifecycleFromConflictsJson,xt as rewriteMarkdownLinksForDocumentRename,jt as rewriteWikiLinksForDocumentRename,Pr as runAuthReposSubprocess,en as runAuthStatusSubprocess,Dt as runCloneSubprocess,Yn as runDeviceFlowSubprocess,cr as runWithMcpLogger,Et as safeContentPath,Bn as safeSubdir,ir as safetyCheckpoint,L as sanitizeClientName,Er as saveInMemoryCheckpoint,jn as saveVersion,A as seedBasenameIndex,lr as serializeError,bi as setActiveSpanAttributes,H as setupServerObservers,Bt as shadowGit,Li as shutdownTelemetry,Vi as spansCurrentPath,Hi as spansPreviousPath,J as spawnDetached,ht as splitMarkdownBlocks,re as startWatcher,Ue as streamingProblemEvent,$n as swapContributors,qe as teardownToleranceTelemetryWriter,gr as toBroadcasterKey,Oi as tracedAppendFileSync,Ni as tracedLinkSync,Ti as tracedMkdir,ki as tracedMkdirSync,Fi as tracedRename,Ei as tracedRenameSync,Mi as tracedRmSync,Ai as tracedRmdirSync,Di as tracedUnlinkSync,Ci as tracedWriteFile,Ii as tracedWriteFileSync,$r as trustSystemCertificates,Zt as untrackTrackedProjectSkillProjection,_e as updateLastKnownHash,ta as updateProcessLockPort,sa as updateServerLockPort,p as updateUiLockPort,Qn as validateAgentId,St as validateCloneInputs,Lt as validateSkillZip,ua as waitForServerLockDrain,ce as withHiddenWindowsConsole,Si as withSpan,xi as withSpanSync,qr as writeBundleDecision,ni as writeMarkdownlintRule,It as writeRootGitignoreForNewRepo,g as writeStateManifest,sn as writeTargetVersion,We as writeTracker};
1
+ import{Go as e,Is as t,P as n,R as r,Vo as i,Wo as a,_s as o,as as s,d as c,l,ss as u}from"./src-DS92rBYx.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Ai as _,An as v,Ar as y,At as b,B as x,Bi as S,Bn as C,Br as w,Bt as T,C as E,Ci as D,Cn as O,Cr as k,Ct as A,D as j,Di as M,Dn as N,Dr as P,Dt as F,E as I,Ei as L,En as R,Er as z,Et as B,F as V,Fi as H,Fn as U,Ft as W,G,Gi as K,Gn as q,Gr as J,Gt as Y,H as X,Hi as Z,Hn as Q,Hr as $,Ht as ee,I as te,Ii as ne,In as re,It as ie,J as ae,Ji as oe,Jn as se,Jr as ce,Jt as le,K as ue,Ki as de,Kn as fe,Kr as pe,Kt as me,L as he,Li as ge,Ln as _e,Lt as ve,M as ye,Mi as be,Mn as xe,Mr as Se,Mt as Ce,N as we,Ni as Te,Nn as Ee,Nt as De,O as Oe,Oi as ke,On as Ae,Or as je,Ot as Me,P as Ne,Pi as Pe,Pn as Fe,Pt as Ie,Q as Le,Qi as Re,Qn as ze,Qr as Be,Qt as Ve,R as He,Ri as Ue,Rn as We,Rr as Ge,Rt as Ke,S as qe,Si as Je,Sn as Ye,Sr as Xe,St as Ze,T as Qe,Ti as $e,Tn as et,Tr as tt,Tt as nt,U as rt,Ui as it,Un as at,Ur as ot,Ut as st,V as ct,Vi as lt,Vn as ut,Vr as dt,Vt as ft,W as pt,Wi as mt,Wn as ht,Wr as gt,Wt as _t,X as vt,Xi as yt,Xn as bt,Xr as xt,Xt as St,Y as Ct,Yi as wt,Yn as Tt,Yr as Et,Yt as Dt,Z as Ot,Zi as kt,Zn as At,Zr as jt,Zt as Mt,_ as Nt,_a as Pt,_i as Ft,_n as It,_r as Lt,_t as Rt,a as zt,aa as Bt,ai as Vt,an as Ht,ar as Ut,at as Wt,b as Gt,ba as Kt,bi as qt,bn as Jt,br as Yt,bt as Xt,c as Zt,ca as Qt,ci as $t,cn as en,cr as tn,d as nn,da as rn,di as an,dn as on,dr as sn,ea as cn,ei as ln,en as un,er as dn,et as fn,f as pn,fa as mn,fi as hn,fn as gn,fr as _n,g as vn,ga as yn,gi as bn,gn as xn,gr as Sn,gt as Cn,h as wn,ha as Tn,hi as En,hn as Dn,hr as On,ht as kn,i as An,ia as jn,ii as Mn,in as Nn,ir as Pn,it as Fn,j as In,ji as Ln,jn as Rn,jr as zn,jt as Bn,k as Vn,ki as Hn,kn as Un,kr as Wn,kt as Gn,l as Kn,la as qn,li as Jn,ln as Yn,lr as Xn,m as Zn,ma as Qn,mi as $n,mn as er,mr as tr,mt as nr,n as rr,na as ir,ni as ar,nn as or,nr as sr,nt as cr,o as lr,oa as ur,oi as dr,on as fr,or as pr,ot as mr,p as hr,pa as gr,pi as _r,pn as vr,pr as yr,q as br,qi as xr,qn as Sr,qr as Cr,qt as wr,r as Tr,ra as Er,ri as Dr,rn as Or,rr as kr,rt as Ar,s as jr,sa as Mr,si as Nr,sn as Pr,sr as Fr,st as Ir,t as Lr,ta as Rr,ti as zr,tn as Br,tr as Vr,tt as Hr,u as Ur,ua as Wr,ui as Gr,un as Kr,ur as qr,v as Jr,va as Yr,vn as Xr,vr as Zr,vt as Qr,w as $r,wi as ei,wn as ti,wr as ni,wt as ri,x as ii,xi as ai,xn as oi,xr as si,xt as ci,y as li,ya as ui,yi as di,yn as fi,yr as pi,yt as mi,z as hi,zi as gi,zn as _i,zr as vi,zt as yi}from"./src-3pZWeowR.mjs";import{C as bi,E as xi,T as Si,_ as Ci,b as wi,c as Ti,d as Ei,g as Di,i as Oi,l as ki,m as Ai,n as ji,p as Mi,s as Ni,t as Pi,u as Fi,v as Ii,w as Li,x as Ri,y as zi}from"./fs-traced-B2GMd7hO.mjs";import{a as Bi,d as Vi,f as Hi,i as Ui,l as Wi,n as Gi,r as Ki,t as qi,u as Ji}from"./logger-DFxEUjvj.mjs";import{C as Yi,S as Xi,_ as Zi,a as Qi,c as $i,d as ea,g as ta,h as na,i as ra,l as ia,m as aa,n as oa,o as sa,p as ca,r as la,s as ua,t as da,u as fa,v as pa,y as ma}from"./server-lock-BOsuOHaz.mjs";export{rn as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,M as AGENT_WRITE_ORIGIN,Yr as AcpPermissionStore,Tn as AcpRegistry,Je as AcpThreadManager,qt as AgentFocusBroadcaster,di as AgentPresenceBroadcaster,ke as AgentSessionCapacityError,Hn as AgentSessionManager,kn as AutoStartDisabledError,Zr as BUNDLE_IDS,pi as BUNDLE_SCOPE,Yt as BUNDLE_SKILL_NAME,Sr as BacklinkIndex,gi as CC1Broadcaster,u as CC1_CONTRACT_VERSION,Kr as CONFIG_FILENAME,ut as CONFLICT_MARKER_RE,w as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Nt as ConfigSchema,K as DEFAULT_CHECKPOINT_RETENTION,Vt as DEFAULT_EMBEDDINGS_DIMENSIONS,W as DEFAULT_PACK_ID,ct as DocumentDurabilityState,dr as EMBEDDINGS_API_KEY_ENV,yn as FEATURED_AGENT_IDS,de as FILE_SYSTEM_WRITER,q as FILE_WATCHER_ORIGIN,m as FileEmbeddingsBackend,Mt as GIT_PREFLIGHT_FAIL_SPAN_NAME,xr as GIT_UPSTREAM_WRITER,ui as GitDirAccessError,h as GitNotAvailableError,un as GitTooOldError,Cn as HOCUSPOCUS_AUTH_REJECTION_REASONS,Rt as HocuspocusAuthRejection,Qr as HocuspocusAuthTokenSchema,pe as INSTALLED_AGENTS_SCHEMES,s as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ie as LOG_MD_TEMPLATE,nt as MANAGED_RENAME_ORIGIN,D as MAX_ACP_THREADS,_ as MAX_AGENT_SESSIONS,$e as MCP_CONNECTION_ID_HEADER,i as MCP_SERVER_NAME,Ln as MIN_EVICTABLE_IDLE_MS,Br as MIN_GIT_VERSION,X as MISSING_OK_CONFIG_MESSAGE,Kt as MalformedGitPointerError,fn as McpLogger,rt as MissingOkConfigError,Te as OBSERVER_SYNC_ORIGIN,on as OK_OKIGNORE_TEMPLATE,a as ORPHAN_MODES,t as PROTOCOL_VERSION,qi as PinoLogger,$i as ProcessLockCollisionError,Kn as ProjectGitInitError,B as ROLLBACK_ORIGIN,gn as ROOT_GITIGNORE_TEMPLATE,Zi as RUNTIME_VERSION,fi as RemoteConfigError,oe as SERVICE_WRITER,yr as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,ve as STARTER_FOLDERS,Ke as STARTER_FOLDER_FRONTMATTER_FILENAME,yi as STARTER_PACKS,T as STARTER_PACK_IDS,ft as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,pa as STATE_SCHEMA_VERSION,o as SYSTEM_DOC_NAME,wr as SeedPrerequisiteError,le as SeedRootDirError,da as ServerLockCollisionError,Lr as SingleFileNotAFileError,rr as SingleFileNotFoundError,Tr as SingleFileNotMarkdownError,I as StateManifestError,fe as TagIndex,si as USER_GLOBAL_BUNDLE_IDS,Tt as UiLockCollisionError,F as __getShowAllWalkStatsForTesting,Me as __resetShowAllWalkStatsForTesting,ia as acquireProcessLock,oa as acquireServerLock,bt as acquireUiLock,be as applyAgentMarkdownWrite,_i as applyExternalChange,Ie as applySeed,j as assertCompatibleStateManifest,or as assertGitAvailable,N as assertNeverDiskEvent,ai as attachAcpThreadSocket,nr as attachIdleShutdown,Jr as bootServer,dn as buildAndOpenSkill,vr as buildConfigYmlContent,Ct as buildExecResult,ei as buildOkMcpStdioCommand,On as buildSkillZip,ee as buildStarterFolderFrontmatterYaml,wt as buildWipTree,Xe as bundleSkillMdPath,ln as canonicalProjectKey,Ae as classifyEvents,Pi as classifyFsPath,zr as clearAllEmbeddingsKeys,$t as clearContributors,st as coercePackId,l as colorFromSeed,yt as commitUpstreamImport,kt as commitWip,Re as commitWipFromTree,Or as compareSemver,tt as composeEffectiveLinterConfig,z as composeFrontmatterSchemasConfig,Q as containsConflictMarkers,Un as contentHash,Jn as contributorCount,Ne as countShadowObjects,V as countStaleAgentWipRefs,te as countWipRefs,Gn as createApiExtension,ri as createAssetServeMiddleware,G as createCollaborationHost,Ge as createContentFilter,vi as createContentFilterAsync,ar as createEmbeddingsSecretStore,An as createEphemeralProjectDir,C as createExternalChangeHandler,pn as createFileLogger,hi as createLiveDerivedIndexExtension,br as createMcpHttpHandler,Cr as createOsProbe,we as createPersistenceExtension,E as createServer,In as createServerObserverExtension,ne as createStreamingErrorWriter,Gi as createTestLogger,Dr as describeStoredEmbeddingsKey,vn as detectClaudeDesktopPresence,Nn as detectGit,Oe as detectProjectShape,Vr as detectUserSkillHosts,Ar as discoverLockDirs,Wn as discoverMarkdownlintConfig,Ve as emitPreflightFailureSpan,vt as encodeDocName,Ot as encodeFolderRoute,Le as encodeSkillRoute,Ur as ensureProjectGit,er as ensureProjectSkillGitignore,ge as errorResponse,v as evictStaleTrackerEntries,b as extractHeadings,Fn as extractOkBinaryPath,se as extractWikiLinksFromMarkdown,Ht as fallbackPaths,nn as findEnclosingGitRoot,et as findEnclosingProjectRoot,y as findNativeMarkdownlintFile,hr as flushFileLogger,mi as formatAuthRejectionWire,Gr as formatContributors,an as formatContributorsFrom,Ce as formatPackRationale,f as gcCheckpointRefs,Hr as getCurrentMcpLogger,En as getLocalDir,Zn as getLogFilePath,Ki as getLogger,wn as getLogsDir,ma as getMachineId,zi as getMeter,ur as getMetrics,wi as getTracer,Mr as handleCollabSocketError,dt as handleSpawnCursor,Jt as hasForwardingHeaders,he as hasGcLogLatch,c as iconFromClientName,Qt as incrementCollabSocketFilteredError,qn as incrementServerObserverFire,Dn as initContent,cn as initShadowRepo,Ri as initTelemetry,Gt as initToleranceTelemetryWriter,Ir as installPrettyZodErrors,Ui as installTestLoggers,sr as installUserSkill,Xr as isAllowedApiOrigin,O as isAllowedWorkspaceHostHeader,S as isConfigDoc,Xt as isHocuspocusAuthRejectionReason,_t as isKnownPackId,lt as isLinkIndexExcludedDoc,ti as isLoopbackAddress,Z as isManagedArtifactDoc,e as isOrphanMode,Pe as isPairedWriteOrigin,$ as isPathWithinDir,Xi as isProcessAlive,R as isProjectRoot,oi as isRemoteAdmitted,it as isReservedForUserTree,Rn as isSelfWrite,mt as isSystemDoc,ii as isToleranceTelemetryEnabled,Yi as isValidLockPid,xe as lastKnownHash,Rr as listRescueCheckpoints,Y as listStarterPacks,Pt as loadCustomAgents,ye as loadPrincipal,fa as lockBaseUrl,ea as lockFilePath,Bi as loggerFactory,Wi as logsCurrentPath,Ji as logsPreviousPath,Mn as makeLazyEmbeddingsKeyStore,la as markServerLockDraining,pt as mountMcpAndApi,ji as normalizeFsPath,k as originGitHubHost,xn as packageVersionMajorMinor,ci as parseAuthRejectionWire,fr as parseGitVersion,Ze as parseHocuspocusAuthToken,ue as parseKeepaliveConnectionId,Ee as pathToDocName,De as planSeed,zt as prepareSingleFileOpen,Wt as processCommand,mr as processUsage,Pn as readAllTargets,Ut as readBundleDecision,zn as readOwnNativeRules,ca as readProcessLock,aa as readProcessLockDetailed,x as readProjectHeadState,Be as readProjectLocalSemanticConfig,ra as readServerLock,pr as readServerPackageVersion,Fr as readSkillInstallStateSnapshot,Vn as readStateManifest,tn as readTargetRecordedAt,Xn as readTargetVersion,At as readUiLock,at as reconcile,hn as recordContributor,tr as recordSkillInstallEvent,ae as registerAllTools,Fe as registerWrite,na as releaseProcessLock,Qi as releaseServerLock,ze as releaseUiLock,U as removeLastKnownHash,kr as reportSkillInstall,Wr as resetMetrics,r as resolveBundleEnabled,Sn as resolveBundledSkillDir,bn as resolveContentDir,ot as resolveCursorBinaryDefault,gt as resolveCursorSpawnInvocation,P as resolveEffectiveLinterConfig,Nr as resolveEmbeddingsCredential,Ft as resolveLockDir,je as resolveNativeConfigForDoc,Se as resolveNativeMarkdownlintConfig,me as resolvePack,jr as resolvePackageVersion,Ye as resolveRemoteAccess,_n as resolveSkillInstallReportSettings,d as resolveUiInfo,_r as restoreContributors,li as restoreLifecycleFromConflictsJson,xt as rewriteMarkdownLinksForDocumentRename,jt as rewriteWikiLinksForDocumentRename,Pr as runAuthReposSubprocess,en as runAuthStatusSubprocess,Dt as runCloneSubprocess,Yn as runDeviceFlowSubprocess,cr as runWithMcpLogger,Et as safeContentPath,Bn as safeSubdir,ir as safetyCheckpoint,L as sanitizeClientName,Er as saveInMemoryCheckpoint,jn as saveVersion,A as seedBasenameIndex,lr as serializeError,bi as setActiveSpanAttributes,H as setupServerObservers,Bt as shadowGit,Li as shutdownTelemetry,Vi as spansCurrentPath,Hi as spansPreviousPath,J as spawnDetached,ht as splitMarkdownBlocks,re as startWatcher,Ue as streamingProblemEvent,$n as swapContributors,qe as teardownToleranceTelemetryWriter,gr as toBroadcasterKey,Oi as tracedAppendFileSync,Ni as tracedLinkSync,Ti as tracedMkdir,ki as tracedMkdirSync,Fi as tracedRename,Ei as tracedRenameSync,Mi as tracedRmSync,Ai as tracedRmdirSync,Di as tracedUnlinkSync,Ci as tracedWriteFile,Ii as tracedWriteFileSync,$r as trustSystemCertificates,Zt as untrackTrackedProjectSkillProjection,_e as updateLastKnownHash,ta as updateProcessLockPort,sa as updateServerLockPort,p as updateUiLockPort,Qn as validateAgentId,St as validateCloneInputs,Lt as validateSkillZip,ua as waitForServerLockDrain,ce as withHiddenWindowsConsole,Si as withSpan,xi as withSpanSync,qr as writeBundleDecision,ni as writeMarkdownlintRule,It as writeRootGitignoreForNewRepo,g as writeStateManifest,sn as writeTargetVersion,We as writeTracker};
@@ -0,0 +1 @@
1
+ import"./src-DS92rBYx.mjs";import"./write-project-skill-BIyatqdb.mjs";import"./src-s5E_Y9Xd.mjs";import"./acp-harness-probe-Bl1wO1jG.mjs";import"./init-Cs060ZhU.mjs";import{n as e}from"./loader-C_U6y8K2.mjs";import"./skill-teardown-DpitP3Vs.mjs";import"./preview-1BHwOzN5.mjs";import"./mcp-migrate-event-B1gJf6bG.mjs";export{e as loadConfig};
@@ -1,4 +1,4 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{rt as t}from"./sleep-Dj1Ck0gp.mjs";import{Ms as n,Ns as r,X as i,Z as a}from"./src-DS92rBYx.mjs";import{Jr as o,Tn as s,_i as c,at as l,it as u,ot as d,rt as f}from"./src-D6v6esDL.mjs";import{O as p,P as m}from"./fs-traced-B2GMd7hO.mjs";import{C as h,S as g,d as _,y as v}from"./server-lock-BOsuOHaz.mjs";import{t as y}from"./yazl-DZr4PyKA.mjs";import{m as b,p as x,v as S}from"./write-project-skill-Dpr3DYpv.mjs";import{c as C}from"./colors-BsmVIwfM.mjs";import{n as w}from"./acp-harness-probe-CcFQmgX3.mjs";import{E as T,T as E,_ as ee,o as D,w as O,x as te,y as ne}from"./init-BBQ5oZSu.mjs";import{n as k}from"./constants-B51mAM4l.mjs";import{t as A}from"./is-object-ByG7RnjH.mjs";import"./loader-BIpUYYKt.mjs";import"./skill-teardown-D31Ah_77.mjs";import"./preview-DmCOiYiE.mjs";import{execSync as j,spawnSync as M}from"node:child_process";import{basename as N,dirname as P,join as F,relative as re,resolve as I,sep as ie}from"node:path";import{cpSync as ae,createWriteStream as oe,existsSync as L,lstatSync as se,mkdirSync as R,mkdtempSync as ce,readFileSync as z,readdirSync as B,readlinkSync as le,rmSync as V,statSync as ue,writeFileSync as H}from"node:fs";import{arch as de,freemem as fe,homedir as U,hostname as pe,platform as me,release as he,tmpdir as ge,totalmem as _e,type as ve,uptime as ye}from"node:os";import"node:fs/promises";import{createHash as be}from"node:crypto";var W=t();const xe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function Se(e,t,n=s){if(e!==void 0&&!xe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ce=null;function we(e){Ce=e}function Te(){return Ce??process.cwd()}function Ee(){return F(U(),`.ok`,`bug-reports`)}function De(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Ee(),r=`${t}-bugreport`,i=F(n,`${r}.zip`);for(let e=2;L(i);e+=1)i=F(n,`${r}-${e}.zip`);return i}function Oe(e,t){let n=F(e,`.ok`,`config.yml`);if(L(n))try{let e=z(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return L(F(e,`.ok`))?be(`sha256`).update(I(e)).digest(`hex`).slice(0,12):null}function ke(){let e={timestamp:new Date().toISOString(),platform:me(),osType:ve(),osRelease:he(),hostname:`[redacted]`,uptime:ye(),freeMem:fe(),totalMem:_e(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=j(`sw_vers -productVersion 2>/dev/null`,o({encoding:`utf8`})).trim()}catch{}try{let t=F(__dirname,`..`,`..`,`package.json`);L(t)&&(e.okVersion=JSON.parse(z(t,`utf8`)).version)}catch{}return e}const Ae=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function G(e){let t=N(e);return Ae.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function je(e,t){return Pe(e,t).files}const Me=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function Ne(e,t=w){let n=F(e,`${t}.ShipIt`);return L(n)?Me.map(e=>F(n,e)).filter(e=>L(e)):[]}function Pe(e,t){if(!L(t))return{files:[],excludedByProjectSlug:0};let n=B(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>F(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(G),i=[],a=r.filter(t=>{try{return z(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!G(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function Fe(e){let t=F(e,`.ok`,`local`);return L(t)?{files:[`server.lock`,`last-spawn-error.log`,i].map(e=>F(t,e)).filter(e=>L(e))}:{files:[]}}function Ie(e){let t=F(e,`.ok`,`local`,`logs`);return L(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>F(t,e)).filter(e=>L(e))}:{files:[]}}function Le(e){if(e.redact){let{redacted:t,patterns:n,lineCount:i}=r(e.content);e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name),n.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:n})}else e.zipfile.addBuffer(Buffer.from(e.content,`utf8`),e.name),e.bundleFiles.push(e.name)}function Re(e){for(let t of e.files)try{Le({zipfile:e.zipfile,name:`${e.prefix}/${N(t)}`,content:z(t,`utf8`),redact:e.redact,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function ze(t){let{redact:r,outputPath:i,logger:a}=t,o=t.userLogsDir??F(U(),`.ok`,`logs`),s=t.projectDir?Oe(t.projectDir,a):null;R(P(i),{recursive:!0}),a?.info({projectSlug:s},`gathering diagnostic data`);let c=ke();c.desktop=t.desktop??null;let{files:l,excludedByProjectSlug:u}=Pe(s,o),{files:d}=t.projectDir?Fe(t.projectDir):{files:[]},{files:f}=t.projectDir?Ie(t.projectDir):{files:[]},p=t.shipItLogFiles??[];a?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length},`files collected`);let m=[],h=[],{ZipFile:g}=await import(`./yazl-jVENrf5i.mjs`).then(t=>e(t.default,1)),_=new g;Re({zipfile:_,files:[...l,...p],prefix:`logs`,redact:r,bundleFiles:h,redactions:m,logger:a}),Re({zipfile:_,files:d,prefix:`lockdir`,redact:r,bundleFiles:h,redactions:m,logger:a}),Re({zipfile:_,files:f,prefix:`local-logs`,redact:r,bundleFiles:h,redactions:m,logger:a});for(let e of t.extraFiles??[])try{let t=z(e.sourcePath),n=`extra/${e.zipName??N(e.sourcePath)}`;_.addBuffer(t,n),h.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&Le({zipfile:_,name:`note.txt`,content:t.note,redact:r,bundleFiles:h,redactions:m});let v=JSON.stringify(c,null,2);_.addBuffer(Buffer.from(v,`utf8`),`sysinfo.json`),h.push(`sysinfo.json`);let y={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:h,redactions:m,sysinfo:c};_.addBuffer(Buffer.from(JSON.stringify(y,null,2),`utf8`),`MANIFEST.json`);let b=m.reduce((e,t)=>e+t.lineCount,0),x=new Set(p.map(e=>`logs/${N(e)}`)),S=h.filter(e=>x.has(e)),C=s?h.filter(e=>e.startsWith(`logs/`)&&!G(e)&&!x.has(e)):[],w=[`# Bug Report Bundle`,``,`Generated: ${y.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${y.disciplineVersion}`,``,`## Contents`,``,...h.map(e=>`- ${e}`),``,`## Privacy`,``,...C.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...C.map(e=>`- ${e}`),``]:[],...S.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...S.map(e=>`- ${e}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${n.join(`, `)}`,b>0?`${b} line(s) were scrubbed across ${m.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`]:[`Redaction was disabled for this bundle; file contents are unmodified.`]].join(`
1
+ import{o as e}from"./chunk-DTipWd-i.mjs";import{rt as t}from"./sleep-Dj1Ck0gp.mjs";import{Ms as n,Ns as r,X as i,Z as a}from"./src-DS92rBYx.mjs";import{Jr as o,Tn as s,_i as c,at as l,it as u,ot as d,rt as f}from"./src-3pZWeowR.mjs";import{O as p,P as m}from"./fs-traced-B2GMd7hO.mjs";import{C as h,S as g,d as _,y as v}from"./server-lock-BOsuOHaz.mjs";import{t as y}from"./yazl-DZr4PyKA.mjs";import{m as b,p as x,v as S}from"./write-project-skill-BIyatqdb.mjs";import{c as C}from"./colors-BsmVIwfM.mjs";import{n as w}from"./acp-harness-probe-Bl1wO1jG.mjs";import{E as T,T as E,_ as ee,o as D,w as O,x as te,y as ne}from"./init-Cs060ZhU.mjs";import{n as k}from"./constants-WesqvVEb.mjs";import{t as A}from"./is-object-ByG7RnjH.mjs";import"./loader-C_U6y8K2.mjs";import"./skill-teardown-DpitP3Vs.mjs";import"./preview-1BHwOzN5.mjs";import{execSync as j,spawnSync as M}from"node:child_process";import{basename as N,dirname as P,join as F,relative as re,resolve as I,sep as ie}from"node:path";import{cpSync as ae,createWriteStream as oe,existsSync as L,lstatSync as se,mkdirSync as R,mkdtempSync as ce,readFileSync as z,readdirSync as B,readlinkSync as le,rmSync as V,statSync as ue,writeFileSync as H}from"node:fs";import{arch as de,freemem as fe,homedir as U,hostname as pe,platform as me,release as he,tmpdir as ge,totalmem as _e,type as ve,uptime as ye}from"node:os";import"node:fs/promises";import{createHash as be}from"node:crypto";var W=t();const xe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function Se(e,t,n=s){if(e!==void 0&&!xe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ce=null;function we(e){Ce=e}function Te(){return Ce??process.cwd()}function Ee(){return F(U(),`.ok`,`bug-reports`)}function De(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Ee(),r=`${t}-bugreport`,i=F(n,`${r}.zip`);for(let e=2;L(i);e+=1)i=F(n,`${r}-${e}.zip`);return i}function Oe(e,t){let n=F(e,`.ok`,`config.yml`);if(L(n))try{let e=z(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return L(F(e,`.ok`))?be(`sha256`).update(I(e)).digest(`hex`).slice(0,12):null}function ke(){let e={timestamp:new Date().toISOString(),platform:me(),osType:ve(),osRelease:he(),hostname:`[redacted]`,uptime:ye(),freeMem:fe(),totalMem:_e(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=j(`sw_vers -productVersion 2>/dev/null`,o({encoding:`utf8`})).trim()}catch{}try{let t=F(__dirname,`..`,`..`,`package.json`);L(t)&&(e.okVersion=JSON.parse(z(t,`utf8`)).version)}catch{}return e}const Ae=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function G(e){let t=N(e);return Ae.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function je(e,t){return Pe(e,t).files}const Me=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function Ne(e,t=w){let n=F(e,`${t}.ShipIt`);return L(n)?Me.map(e=>F(n,e)).filter(e=>L(e)):[]}function Pe(e,t){if(!L(t))return{files:[],excludedByProjectSlug:0};let n=B(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>F(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(G),i=[],a=r.filter(t=>{try{return z(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!G(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function Fe(e){let t=F(e,`.ok`,`local`);return L(t)?{files:[`server.lock`,`last-spawn-error.log`,i].map(e=>F(t,e)).filter(e=>L(e))}:{files:[]}}function Ie(e){let t=F(e,`.ok`,`local`,`logs`);return L(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>F(t,e)).filter(e=>L(e))}:{files:[]}}function Le(e){if(e.redact){let{redacted:t,patterns:n,lineCount:i}=r(e.content);e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name),n.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:n})}else e.zipfile.addBuffer(Buffer.from(e.content,`utf8`),e.name),e.bundleFiles.push(e.name)}function Re(e){for(let t of e.files)try{Le({zipfile:e.zipfile,name:`${e.prefix}/${N(t)}`,content:z(t,`utf8`),redact:e.redact,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function ze(t){let{redact:r,outputPath:i,logger:a}=t,o=t.userLogsDir??F(U(),`.ok`,`logs`),s=t.projectDir?Oe(t.projectDir,a):null;R(P(i),{recursive:!0}),a?.info({projectSlug:s},`gathering diagnostic data`);let c=ke();c.desktop=t.desktop??null;let{files:l,excludedByProjectSlug:u}=Pe(s,o),{files:d}=t.projectDir?Fe(t.projectDir):{files:[]},{files:f}=t.projectDir?Ie(t.projectDir):{files:[]},p=t.shipItLogFiles??[];a?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length},`files collected`);let m=[],h=[],{ZipFile:g}=await import(`./yazl-jVENrf5i.mjs`).then(t=>e(t.default,1)),_=new g;Re({zipfile:_,files:[...l,...p],prefix:`logs`,redact:r,bundleFiles:h,redactions:m,logger:a}),Re({zipfile:_,files:d,prefix:`lockdir`,redact:r,bundleFiles:h,redactions:m,logger:a}),Re({zipfile:_,files:f,prefix:`local-logs`,redact:r,bundleFiles:h,redactions:m,logger:a});for(let e of t.extraFiles??[])try{let t=z(e.sourcePath),n=`extra/${e.zipName??N(e.sourcePath)}`;_.addBuffer(t,n),h.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&Le({zipfile:_,name:`note.txt`,content:t.note,redact:r,bundleFiles:h,redactions:m});let v=JSON.stringify(c,null,2);_.addBuffer(Buffer.from(v,`utf8`),`sysinfo.json`),h.push(`sysinfo.json`);let y={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:h,redactions:m,sysinfo:c};_.addBuffer(Buffer.from(JSON.stringify(y,null,2),`utf8`),`MANIFEST.json`);let b=m.reduce((e,t)=>e+t.lineCount,0),x=new Set(p.map(e=>`logs/${N(e)}`)),S=h.filter(e=>x.has(e)),C=s?h.filter(e=>e.startsWith(`logs/`)&&!G(e)&&!x.has(e)):[],w=[`# Bug Report Bundle`,``,`Generated: ${y.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${y.disciplineVersion}`,``,`## Contents`,``,...h.map(e=>`- ${e}`),``,`## Privacy`,``,...C.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...C.map(e=>`- ${e}`),``]:[],...S.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...S.map(e=>`- ${e}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${n.join(`, `)}`,b>0?`${b} line(s) were scrubbed across ${m.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`]:[`Redaction was disabled for this bundle; file contents are unmodified.`]].join(`
2
2
  `);_.addBuffer(Buffer.from(w,`utf8`),`README.md`),_.end();let T=oe(i);return _.outputStream.pipe(T),await new Promise((e,t)=>{T.on(`close`,e),T.on(`error`,t)}),a?.info({bundlePath:i,fileCount:h.length,redactionCount:b},`bundle written`),{zipPath:i,summary:{projectSlug:s,files:h,redactions:m,redactedLineCount:b,generatedAt:y.generatedAt}}}var Be=e(y(),1),K=e(C(),1);function Ve(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function He(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e,t){if(typeof e==`string`)return Ve(e,t.contentDir);if(Array.isArray(e))return e.map(e=>q(e,t));if(!He(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=q(i,t);return n}function Ue(e,t){let n=z(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
3
3
  `),i=n.split(`
4
4
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=q(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}H(e,r?`${a.join(`
@@ -17,4 +17,4 @@ import{o as e}from"./chunk-DTipWd-i.mjs";import{rt as t}from"./sleep-Dj1Ck0gp.mj
17
17
  `).replace(/\n/g,`\r
18
18
  `));let u=`${i?``:``}${l}`;return u!==r&&m(e,u,{mode:O(e)}),{kind:`removed`}}function tn(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function nn(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function rn(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:u(r),command:r,isDesktop:tn(r)}}function an(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Q(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&an(e)?`ui-orphan`:`stale`}const on=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function sn(e){switch(e){case`running`:return K.default.green(e);case`desktop`:return K.default.blue(e);case`foreign`:return K.default.cyan(e);case`ui-orphan`:return K.default.magenta(e);case`stale`:return K.default.yellow(e)}}function cn(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ln(e){return`${cn(e.server.usage)} | ${cn(e.ui?.usage??null)}`}function un(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function dn(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Q(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,un(e),ln(e),t,String(n),nn(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=sn(Q(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=K.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
19
19
  `)}async function fn(e={}){let t=e.discover??f,n=e.inspect??Z,r=e.log??(e=>console.log(e)),i=e.resolveCommand??l,a=e.resolveUsage??d,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=rn(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:Q(e)}));r(JSON.stringify(e,null,2));return}r(dn(e.all?s:s.filter(e=>on.has(Q(e)))))}function pn(){return new S(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await fn({all:t.all===!0||e===`all`,json:t.json===!0})})}function mn(e,t,n={}){let r=n.isAlive??g,i=[];for(let[n,a]of[[`server`,e],[`ui`,t]])(a.status===`alive`||a.status===`foreign-host`&&r(a.lock.pid))&&i.push({name:n,pid:a.lock.pid,port:a.lock.port});return{targets:i}}function hn(e){let t=e.inspect??(t=>Z(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=mn(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function $(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function gn(e,t=g){let n=await f(),r=null;for(let i of n){let n=Z(i,`server`),a=Z(i,`ui`);if($(n,t)&&n.lock.port===e||$(a,t)&&a.lock.port===e)return i;r===null&&($(n,t)&&n.lock.pid===e||$(a,t)&&a.lock.pid===e)&&(r=i)}return r}function _n(e){let t=hn({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function vn(e){return new S(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=hn({lockDir:c(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await fn({});return}if(n===`all`){let e=await f();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=Z(n,`server`),r=Z(n,`ui`);!$(e,g)&&!$(r,g)||(_n(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await gn(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}_n(t);return}_n(c(I(Te(),n)))})}export{Te as _,Ut as a,Kt as c,Z as d,Bt as f,Ee as g,De as h,Zt as i,qt as l,Lt as m,vn as n,Jt as o,It as p,pn as r,Wt as s,hn as t,Ht as u,we as v,Se as y};
20
- //# sourceMappingURL=src-BvzFYC4G.mjs.map
20
+ //# sourceMappingURL=src-s5E_Y9Xd.mjs.map