@inkeep/open-knowledge 0.53.2 → 0.53.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-harness-probe-BnGJfP5G.mjs → acp-harness-probe-3JkYEtle.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/constants-DqlH1WMe.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/{init-BbAtilzZ.mjs → init-BphshJ0S.mjs} +3 -3
- package/dist/init-DRrJo2ZC.mjs +1 -0
- package/dist/{launch-json-removal-DfpCmQT9.mjs → launch-json-removal-DFARSS9F.mjs} +2 -2
- package/dist/loader-CMrPyRH1.mjs +1 -0
- package/dist/{loader-BOUyv05v.mjs → loader-D2I7_Rs6.mjs} +2 -2
- package/dist/{open-browser-BA50pLLQ.mjs → open-browser-BfbWvPXH.mjs} +2 -2
- package/dist/{preview-DoBitDZ-.mjs → preview-Bnzh6BEb.mjs} +2 -2
- package/dist/preview-CInjvD39.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-BmQRzJZw.js → ActivityModeContent-BMqdsZEQ.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-DCXp5E1P.js → AgentDiffPane-D_ubtipg.js} +1 -1
- package/dist/public/assets/{ChangedOutsideBadge-J6l1plFR.js → ChangedOutsideBadge-4TgQdQOf.js} +1 -1
- package/dist/public/assets/CodeMirrorPropInput-CjgqNZXo.js +3 -0
- package/dist/public/assets/DocumentContext-tOm4SkOp.js +38 -0
- package/dist/public/assets/{EditorModeToggle-BsFjeEn4.js → EditorModeToggle-CFFhQhHA.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-DNDI39lu.js → EnableSyncConfirmDialog-BiThAkoH.js} +1 -1
- package/dist/public/assets/FeedbackForm-tTwFtkKO.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-DNZi7-O6.js → ImportSkillDialog-DcZoBHf-.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-nq2Ekm-O.js → LintConfigEditor--yFdaWpg.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-Bb9ghWb1.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-CeSsPfJA.js → ManagedArtifactProperties-CIVfnd15.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-DceTAjtX.js → MermaidDocEditor-civq6mkL.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-D23bGRYq.js → SchemaConfigEditor-NxaI-Jdd.js} +1 -1
- package/dist/public/assets/{SessionsHost-BD8Io20F.js → SessionsHost-PjSsebux.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-D_2SfOcL.js → SettingsDialogBody-BNYz-D4X.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-BDYU64bD.js → ShareReceiveMissDialog-R20sy2ia.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BP8iught.js → SkillToolbarControls-B_RJpm5V.js} +1 -1
- package/dist/public/assets/{SourceEditor-8vj7fGo1.js → SourceEditor-BW7yuIvG.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-Bzu1XJoP.js → TerminalWindowApp-DRbYHuvS.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Kaj3NBL9.js → TextDocEditor-Bwwrrcn5.js} +1 -1
- package/dist/public/assets/{ThreadView-C0oxDyxf.js → ThreadView-BA7gxPI6.js} +2 -2
- package/dist/public/assets/{TimelineDiffPane-CG6Z1uma.js → TimelineDiffPane-CTJnk9me.js} +1 -1
- package/dist/public/assets/{agent-diff-store-DxMs0J9Y.js → agent-diff-store-BvxTke2d.js} +1 -1
- package/dist/public/assets/{auth-state-cache-CGY7eNch.js → auth-state-cache-DrAhOPTB.js} +1 -1
- package/dist/public/assets/{client-version-BenFW72U.js → client-version-DFQNNQh_.js} +1 -1
- package/dist/public/assets/comment-chips-W2ozPSpm.js +5 -0
- package/dist/public/assets/{config-provider-B6fsarOv.js → config-provider-DamFbxl8.js} +3 -3
- package/dist/public/assets/follow-file-D0HdtSlc.js +4 -0
- package/dist/public/assets/globals-CZFxK0Rt.css +1 -0
- package/dist/public/assets/i18n-CUKvPzxt.js +1 -0
- package/dist/public/assets/{index-Du6HTehY.js → index-qtxLhYJO.js} +9 -9
- package/dist/public/assets/messages-BD6xU0hl.js +1 -0
- package/dist/public/assets/messages-BrOihCC2.js +1 -0
- package/dist/public/assets/messages-CeGZ3qGI.js +1 -0
- package/dist/public/assets/messages-DLAxD4Ea.js +1 -0
- package/dist/public/assets/messages-DiRAd1Pa.js +1 -0
- package/dist/public/assets/messages-DoSs73jK.js +1 -0
- package/dist/public/assets/messages-FGGtYX0Z.js +1 -0
- package/dist/public/assets/messages-QNJusJtV.js +1 -0
- package/dist/public/assets/messages-T7J7xjCi.js +1 -0
- package/dist/public/assets/messages-rE7VifgH.js +1 -0
- package/dist/public/assets/messages-zscDryNK.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-BZigj_ik.js → pending-receive-nav-store-CpVItLnx.js} +1 -1
- package/dist/public/assets/{selection-context-PgPm0oHr.js → selection-context-nm7zlSXJ.js} +1 -1
- package/dist/public/assets/{skill-actions-Btw-8DsB.js → skill-actions-e3PRoOA3.js} +1 -1
- package/dist/public/assets/{src-DoCu_Oe2.js → src-BKQkpwCc.js} +1 -1
- package/dist/public/assets/{telemetry-impl-Bvv5kEhb.js → telemetry-impl-Byic_ID0.js} +1 -1
- package/dist/public/assets/{telemetry-startup-htUA83Zn.js → telemetry-startup-D_ttbNLC.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-XmZhxL72.js → typing-burst-detector-B6UhFT8T.js} +3 -3
- package/dist/public/assets/{uninstall-CDJGY7Qx.js → uninstall-BE8yLKij.js} +1 -1
- package/dist/public/assets/{use-activity-panel-DeQ1S88x.js → use-activity-panel-CF6Guvjl.js} +1 -1
- package/dist/public/assets/{use-open-skill-CgnR7yXa.js → use-open-skill-CtzMj-sg.js} +1 -1
- package/dist/public/assets/{use-popular-skills-BefXxEcp.js → use-popular-skills-BY0ulPzk.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-DPQRp9bB.js → use-terminal-enabled-CIQB6jgW.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-Bw_6uLLl.js → use-timeline-entry-diff-CDFU16yg.js} +2 -2
- package/dist/public/index.html +23 -23
- package/dist/public/uninstall.html +5 -5
- package/dist/{repair-launch-json-r4ZvDSZL.mjs → repair-launch-json-BEYvmnMN.mjs} +2 -2
- package/dist/{repair-mcp-configs-8YO27I4W.mjs → repair-mcp-configs-BNg_uIZk.mjs} +2 -2
- package/dist/{repair-skills-Dk0Hee-r.mjs → repair-skills-BVCJQr-D.mjs} +2 -2
- package/dist/repair-skills-BmAntgZP.mjs +1 -0
- package/dist/{skill-teardown-DtXC2fAI.mjs → skill-teardown-CybJJo-5.mjs} +2 -2
- package/dist/{src-DvuwJKkU.mjs → src--OhnhRml.mjs} +4 -4
- package/dist/{src--XQg-7vm.mjs → src-3gxGmFyn.mjs} +1 -1
- package/dist/src-CnKeKhYe.mjs +1 -0
- package/dist/{src-BwjoUUIl.mjs → src-D-aeKj3b.mjs} +2 -2
- package/dist/{start-D_Gfcl0_.mjs → start-BG9Kwkdp.mjs} +4 -4
- package/dist/start-BQLnfOio.mjs +1 -0
- package/dist/{ui-7z12LoCq.mjs → ui-DXs7IMUP.mjs} +3 -3
- package/dist/{write-project-skill-DUj7e5tZ.mjs → write-project-skill-B4M4CzQe.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-CibuukV7.mjs +0 -2
- package/dist/init-OoQjBgC9.mjs +0 -1
- package/dist/loader-P0nrGvJv.mjs +0 -1
- package/dist/preview-D2AT6aBO.mjs +0 -1
- package/dist/public/assets/CodeMirrorPropInput-DiDkBTg6.js +0 -3
- package/dist/public/assets/DocumentContext-J495RUh0.js +0 -38
- package/dist/public/assets/FeedbackForm-BwQovorQ.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-D5Q8gGkr.js +0 -1
- package/dist/public/assets/comment-chips-Q0_SZK9C.js +0 -5
- package/dist/public/assets/follow-file-D4LD9UAw.js +0 -4
- package/dist/public/assets/globals-tIUZlcbW.css +0 -1
- package/dist/public/assets/i18n-C3d0M4ue.js +0 -1
- package/dist/public/assets/messages-B6wDP6_L.js +0 -1
- package/dist/public/assets/messages-BS6hWxWK.js +0 -1
- package/dist/public/assets/messages-Bg44_w_B.js +0 -1
- package/dist/public/assets/messages-D9hQcSkC.js +0 -1
- package/dist/public/assets/messages-DAPhT0w6.js +0 -1
- package/dist/public/assets/messages-DaVac3jo.js +0 -1
- package/dist/public/assets/messages-Dbqu7ts9.js +0 -1
- package/dist/public/assets/messages-DdoJCt_r.js +0 -1
- package/dist/public/assets/messages-Djc_MIS0.js +0 -1
- package/dist/public/assets/messages-DmHqd1yQ.js +0 -1
- package/dist/public/assets/messages-xKq8BSm6.js +0 -1
- package/dist/repair-skills-BWNXcIRv.mjs +0 -1
- package/dist/src-DK8qZiyv.mjs +0 -1
- package/dist/start-ZpOYP9oW.mjs +0 -1
- /package/dist/public/assets/{globals-CLY_4Hw9.js → globals-CfOSCw3_.js} +0 -0
|
@@ -20,11 +20,11 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt
|
|
|
20
20
|
`:``)+r)}function yw(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function bw(e,t,n){let r=nw(e);r&&Cw(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function xw(e,t,n,r,i,a){if(mS(e))throw new gS({file:gw(e.name)});return Go(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let o=ww(e,t,n,r,i,a);return o!==void 0&&Wo({"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 Sw(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function Cw(e,t,n){let{frontmatter:r,body:i}=jt(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?ch(t):jt(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:Fn(s,c)}}function ww(e,t,n,r,i,a){try{let o=e.getText(`source`).toString(),s=Cw(o,t,n);if(s===void 0)return;let{existingFm:c,finalFm:l,newContent:u}=s,d=a&&Rx(hw.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:o}:void 0;if(l!==c){let t=En(Xt(l));if(t.map===null)throw new xS({file:gw(e.name),parseError:t.parseError??`unknown YAML parse error`});ES(`mcp-write`)}else if(l===``&&jt(u).frontmatter!==``)throw new xS({file:gw(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`?Ib(e,u,r,i,d):Fb(e,u,`agent`,r,i,d);let f=yS(e.getText(`source`).toString(),u,n);return mw.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 xS||mw.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function Tw(e,t,n,r){let i=e.dc.document;if(mS(i))throw new gS({file:gw(i.name)});return Go(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=Ew(e,t,n,r);return Wo({"agent.undo_effective":i}),i})}function Ew(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&&nw(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&Rx(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&&Kae(s,n,d)},o),mw.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function Dw(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 Ow(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 Tce=256,Ece=5e3;var kw=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let Aw=null;function Dce(){return Aw||=xs().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}`}),Aw}var jw=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(Zx(e)||Qx(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 mw.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 mw.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new kw(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=Dw(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=Ow(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);mw.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new Mie([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),mw.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++,poe(),Dce().add(1),mw.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){mw.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){mw.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){mw.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}),mw.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));mw.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));mw.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()];mw.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 Mw=`x-ok-connection-id`,Nw=`x-ok-hosted-agent`;function Pw(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 Fw=16e3;function Iw(e){return e.length<=Fw?e:`${e.slice(0,Fw)}\n… [truncated ${e.length-Fw} chars]`}function Oce(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`?Iw(t.oldText):t.oldText,i=typeof t.newText==`string`?Iw(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=Iw(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 kce=new Set([`agent_message_chunk`,`agent_thought_chunk`,`user_message_chunk`]),Lw=16e3;function Rw(e){if(typeof e!=`object`||!e)return null;let t=e;return t.type===`text`&&typeof t.text==`string`?t.text:null}function zw(e){return typeof e.messageId==`string`?e.messageId:`default`}function Ace(e,t){if(e.kind===`terminal_output`&&t.kind===`terminal_output`)return e.terminalId!==t.terminalId||e.chunk.length>=Lw?!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||!kce.has(r.sessionUpdate)||zw(n)!==zw(r))return!1;let i=Rw(n.content),a=Rw(r.content);return i===null||a===null||i.length>=Lw?!1:(n.content={type:`text`,text:i+a},!0)}function Bw(e,t){let n=Rl(e)+Vl;return`${Rl(t)}${Vl}`.startsWith(n)}function Vw(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,`_`);return t===``||t===`.`||t===`..`?`_`:t}function Hw(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=jl(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 Uw(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=Cu(`sha256`),s=0,c=Jl(t),l=xu.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 jce(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 Mce(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 Ww=`__OK_PATH_BEGIN__`,Gw=`__OK_PATH_END__`,Kw=`printf %s ${Ww}; printenv PATH; printf %s ${Gw}`;function Nce(){return[`-l`,`-i`,`-c`,Kw]}function Pce(){return[`-i`,`-c`,Kw]}const Fce=new Set([`bash`,`sh`]);function Ice(e){let t=e.lastIndexOf(Ww);if(t===-1)return null;let n=t+17,r=e.indexOf(Gw,n);if(r===-1)return null;let i=e.slice(n,r).trim();return i===``?null:i}function qw(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 Lce=new Set([`false`,`nologin`,`sync`]),Rce=(e,t,n)=>new Promise(r=>{let i;try{i=jl(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 Jw(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=Ice(o);return c===null?(e.log.debug({shell:t,args:n,elapsed:s},`[login-shell-path] probe output carried no PATH`),null):c}function zce(e){let t=e.platform??process.platform,n=e.shell??process.env.SHELL,r=e.timeoutMs??5e3,i=e.runProbe??Rce,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(Lce.has(a))return e.log.debug({shell:n},`[login-shell-path] login-refusing shell; skipping probe`),null;let o=await Jw(e,n,Nce(),r,i);if(!Fce.has(a))return o;let s=await Jw(e,n,Pce(),r,i);return o===null?s:s===null?o:qw(o,s,Fl)};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 Yw=null;function Xw(e){return Yw??=zce({log:e}),Yw}function Bce(){Yw=null}var Zw=class extends Error{code;constructor(e,t){super(t),this.name=`AgentLaunchError`,this.code=e}};function Vce(){return L(uu(),`.ok`,`acp-agents`)}function Hce(e){try{return ou(e).isDirectory()}catch{return!1}}function Qw(e){let t={};for(let[e,n]of Object.entries(process.env))n!==void 0&&(t[e]=n);return t[rT(t)]=Ye(aT(t),{platform:process.platform,homeDir:uu(),isDir:Hce,delimiter:Fl}),{...t,...e}}function $w(e){return e!==void 0&&Object.keys(e).some(e=>e.toLowerCase()===`path`)}function eT(e){return{...e,[Ti]:`1`}}async function Uce(e,t,n,r=Vce()){let i=e.distribution;if(i.npx!==void 0)return{cmd:`npx`,args:[`-y`,i.npx.package,...i.npx.args??[]],env:Qw(i.npx.env),kind:`npx`,pathFromOverlay:$w(i.npx.env)};if(i.uvx!==void 0)return{cmd:`uvx`,args:[i.uvx.package,...i.uvx.args??[]],env:Qw(i.uvx.env),kind:`uvx`,pathFromOverlay:$w(i.uvx.env)};if(i.binary!==void 0){if(t===null||i.binary[t]===void 0)throw new Zw(`unsupported-platform`,`${e.name} has no build for this platform`);let a=i.binary[t],o=await qce(e.id,e.version,a,r,n),s=z(o,a.cmd.replace(/\\/g,`/`));if(!Bw(o,s))throw new Zw(`install-failed`,`${e.name} manifest cmd escapes its archive`);return{cmd:s,args:[...a.args??[]],env:Qw(a.env),kind:`binary`,pathFromOverlay:$w(a.env)}}throw new Zw(`no-distribution`,`${e.name} has no supported distribution`)}function Wce(e){return{cmd:e.command,args:[...e.args??[]],env:Qw(e.env),kind:`custom`,pathFromOverlay:$w(e.env)}}function Gce(e,t){let n={...e.env};n[rT(n)]=Kce(t.binDir,aT(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 tT(e,t){return{...e,env:nT(e.env,t)}}function nT(e,t){let n={...e};return n[rT(n)]=qw(aT(n),t,Fl),n}function rT(e){for(let t of Object.keys(e))if(t.toLowerCase()===`path`)return t;return`PATH`}function Kce(e,t){return t!==void 0&&t!==``?`${e}${Fl}${t}`:e}async function qce(e,t,n,r,i){let a=L(r,Vw(e),Vw(t));try{if((await bu(a)).isDirectory())return a}catch{}i.info({id:e,version:t,archive:n.archive},`[acp-launch] downloading agent binary`);let o=L(pu(),`ok-acp-install-${process.pid}-${Date.now()}`);await ts(o,{recursive:!0});let s=/\.zip$/i.test(new URL(n.archive).pathname),c=L(o,s?`archive.zip`:`archive.tar.gz`);try{let l=await Uw(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=L(o,`extracted`);await ts(u,{recursive:!0}),await Hw(c,u,s);let d=z(u,n.cmd.replace(/\\/g,`/`));if(!Bw(u,d))throw Error(`manifest cmd escapes the extracted archive`);return await qte(d,493).catch(()=>{}),await ts(L(r,Vw(e)),{recursive:!0}),await rs(a,{recursive:!0,force:!0}),await _s(u,a),i.info({id:e,version:t,versionDir:a},`[acp-launch] agent binary installed`),a}catch(n){throw new Zw(`install-failed`,`installing ${e}@${t} failed: ${n instanceof Error?n.message:String(n)}`)}finally{await rs(o,{recursive:!0,force:!0}).catch(()=>{})}}async function iT(e){if(!await sT(e.cmd,aT(e.env)))throw new Zw(`command-not-found`,Jce(e))}function Jce(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 aT(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()===`path`)return n;return process.env.PATH}function oT(e){let t=process.platform===`win32`;return Ll(e)||e.includes(`/`)||t&&e.includes(`\\`)}async function sT(e,t){let n=process.platform===`win32`;if(oT(e))return cT(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(Fl))if(n!==``){for(let t of r)if(await cT(L(n,e+t)))return!0}return!1}async function cT(e){try{return(await bu(e)).isFile()?(process.platform===`win32`||await mu(e,Kl.X_OK),!0):!1}catch{return!1}}function lT(e,t){if(Ll(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(Fl))if(r!==``)for(let t of n){let n=L(r,e+t);try{if(ou(n).isFile())return n}catch{}}return e}function uT(e){return e===``?`""`:/[\s"&()<>^|%]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function dT(e,t){let n=[`"${e}"`,...t.map(uT)].join(` `);return{cmd:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,`"${n}"`]}}function fT(e,t){if(!Ll(t))throw Error(`spawnAcpAgent requires an absolute cwd, got: ${t}`);let n=process.platform===`win32`,r=n?lT(e.cmd,aT(e.env)):e.cmd,i=n&&/\.(cmd|bat)$/i.test(r),{cmd:a,args:o}=i?dT(r,e.args):{cmd:r,args:e.args};return jl(a,o,{cwd:t,env:eT(e.env),stdio:[`pipe`,`pipe`,`pipe`],shell:!1,detached:!n,windowsHide:!0,windowsVerbatimArguments:i})}function pT(e){return e.exitCode!==null||e.signalCode!==null}function mT(e,t){return pT(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 hT(e,t){let n=e.pid;if(!(n===void 0||pT(e))){try{process.kill(-n,t);return}catch{}try{e.kill(t)}catch{}}}async function gT(e,t){let n=t.forceWaitMs??2e3;if(pT(e))return!0;if(process.platform===`win32`){if(e.pid!==void 0)try{jl(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`,shell:!1,windowsHide:!0}).unref()}catch{try{e.kill(`SIGKILL`)}catch{}}return mT(e,Math.max(t.graceMs,n))}return hT(e,`SIGTERM`),await mT(e,t.graceMs)?!0:(hT(e,`SIGKILL`),mT(e,n))}const _T=`v24.18.0`,vT=`0.11.28`,yT=`https://nodejs.org/dist`,bT=`https://github.com/astral-sh/uv/releases/download`,xT={node:45,uv:20};function ST(e){return e===`npx`?`node`:`uv`}function CT(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:_T,approxSizeMB:xT.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:vT,approxSizeMB:xT.uv,sourceHost:`github.com/astral-sh`}}function wT(){return L(uu(),`.ok`)}function TT(){return L(wT(),`runtimes`)}function ET(e){return e===`node`?_T:vT}function DT(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function OT(){let e=fu(),t=lu(),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-${_T}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${yT}/${_T}/${a}`,checksumUrl:`${yT}/${_T}/SHASUMS256.txt`,archiveName:a,isZip:i}}function kT(){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`}[`${fu()}-${lu()}`];if(e===void 0)return null;let t=fu()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${bT}/${vT}/${n}`,checksumUrl:`${bT}/${vT}/${n}.sha256`,archiveName:n,isZip:t}}function AT(e){return e===`node`?OT():kT()}function jT(e){return AT(e)!==null}async function MT(e){try{let t=await bu(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await mu(e,hu.X_OK),!0)}catch{return!1}}async function NT(e,t,n){let r;try{r=await vu(e,{withFileTypes:!0})}catch{return null}for(let n of r)if((n.isFile()||n.isSymbolicLink())&&t.includes(n.name))return L(e,n.name);if(n<=0)return null;for(let i of r)if(i.isDirectory()){let r=await NT(L(e,i.name),t,n-1);if(r!==null)return r}return null}function PT(e,t,n){let r=I(t),i=L(n,`cache`,e);return e===`node`?{kind:`node`,binDir:r,npxBin:t,cacheDir:i}:{kind:`uv`,binDir:r,uvxBin:t,cacheDir:i}}async function FT(e,t=TT()){let n=L(t,e,Vw(ET(e)));try{if(!(await bu(n)).isDirectory())return null}catch{return null}let r=await NT(n,DT(e),3);return r===null||!await MT(r)?null:PT(e,r,t)}var IT=class extends Error{constructor(e){super(e),this.name=`RuntimeInstallError`}};async function LT(e,t){let n;try{n=await vu(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=L(e,i.name);try{if((await bu(n)).mtimeMs>=r)continue;await rs(n,{recursive:!0,force:!0})}catch(e){if(e.code===`ENOENT`)continue;t.warn({err:e},`[managed-runtime] stale staging cleanup failed`)}}}async function RT(e,t,n=TT()){await LT(L(n,e),t)}async function zT(e,t,n={}){let r=n.root??TT(),i=L(r,e,Vw(ET(e))),a=I(i),o=await FT(e,r);if(o!==null)return await LT(a,t),o;let s=AT(e);if(s===null)throw new IT(`no ${e} build for ${fu()}-${lu()}`);await ts(a,{recursive:!0}),await LT(a,t);let c=L(a,`.install-${Vw(ET(e))}-${process.pid}-${wu()}`);await ts(c,{recursive:!0});let l=L(c,s.archiveName);t.info({kind:e,version:ET(e),url:s.archiveUrl},`[managed-runtime] downloading runtime`);try{let[a,o]=await Promise.all([Uw(s.archiveUrl,l,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),jce(s.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),u=Mce(o,s.archiveName);if(u===null)throw new IT(`no published checksum for ${s.archiveName}`);if(a!==u)throw new IT(`checksum mismatch for ${s.archiveName}: got ${a}, expected ${u}`);let d=L(c,`extracted`);await ts(d,{recursive:!0}),await Hw(l,d,s.isZip);let f=await NT(d,DT(e),3);if(f===null||!Bw(d,f))throw new IT(`extracted ${e} archive has no usable launcher`);let p=await FT(e,r);if(p!==null)return p;await n.beforeCommit?.();try{return await qo(`${i}.install.lock`,async()=>{let n=await FT(e,r);if(n!==null)return n;await rs(i,{recursive:!0,force:!0}),await _s(d,i),t.info({kind:e,version:ET(e),versionDir:i},`[managed-runtime] runtime installed`);let a=await FT(e,r);if(a===null)throw new IT(`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 ss){let i=await FT(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 IT?t:new IT(`installing ${e} ${ET(e)} failed: ${t instanceof Error?t.message:String(t)}`)}finally{await rs(c,{recursive:!0,force:!0}).catch(()=>{})}}const BT=`acp-runtime-consent.json`;async function VT(e=wT()){let t;try{let{readFile:n}=await import(`node:fs/promises`);t=await n(L(e,BT),`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 HT(e,t,n,r=wT()){try{let n={version:1,...await VT(r),[e]:t,updatedAt:Date.now()};await ts(r,{recursive:!0}),await Qo(L(r,BT),`${JSON.stringify(n,null,2)}\n`)}catch(t){n.warn({err:t,kind:e},`[managed-runtime] consent persist failed`)}}const UT=2e3;function WT(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function GT(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:WT(n.subarray(n.length-t)).toString(`utf8`)}function KT(e){if(e.outputBytes<=e.byteLimit)return;let t=WT(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var qT=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=eT(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:Ll(e.cwd)?e.cwd:z(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?lT(e.command,aT(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?dT(o,e.args??[]):{cmd:o,args:e.args??[]},u=jl(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 KT(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 gT(t.child,{graceMs:UT})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await gT(t.child,{graceMs:UT}),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=Qw(e);return this.loginShellPath===null||$w(e)?t:nT(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?KT(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=GT(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,KT(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 JT=`threads`;var YT=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=L(e.primaryDir,JT),this.legacyThreadsDir=e.legacyDir==null?null:L(e.legacyDir,JT),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 ts(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 ts(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 L(this.threadsDirFor(e),`${e}.ndjson`)}metaPath(e){return L(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 ms(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 Qo(r,n),await _s(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await rs(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 QT(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 vu(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=L(e,a),o;try{o=JSON.parse(await _u(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 QT(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(!B(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||!B(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(ZT(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=>rs(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=ql(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=tne({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 XT(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function XT(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 ZT(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function QT(e){try{return await yu(e)}catch{return z(e)}}const $T=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`),eE=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/;function tE(e){return(e.trim().split(`
|
|
23
|
-
`)[0]??``).trim()}function nE(e){let t=tE(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 rE(e){let t=tE(e),n=t.replace(eE,``);for(let e=0;e<6;e++){let e=n.replace($T,``);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?nE(t):nE(n.charAt(0).toUpperCase()+n.slice(1))}const iE=8,aE=5e3,oE=5e3,sE=2e3;var cE=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},lE=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}};function uE(){return new cE(`not-ready`,`the thread was restarted during the sign-in`)}function dE(e,t){let[n=`open-knowledge`,...r]=e&&e.length>0?e:[`open-knowledge`];return{command:n,args:[...r,`mcp`,`--port`,String(t)]}}var fE=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??(()=>Xw(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 YT({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,mE(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 cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`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 Ed(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new cE(`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 cE(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new cE(`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=Wce(t);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new cE(`unknown-agent`,`agent vanished`);n=await Uce(t,bd(),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 qT({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:i});this.emitStatus(e,`spawning`);let o=fT(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 nE(e){let t=tE(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 rE(e){let t=tE(e),n=t.replace(eE,``);for(let e=0;e<6;e++){let e=n.replace($T,``);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?nE(t):nE(n.charAt(0).toUpperCase()+n.slice(1))}const iE=8,aE=5e3,oE=5e3,sE=2e3;var cE=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},lE=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}};function uE(){return new cE(`not-ready`,`the thread was restarted during the sign-in`)}function dE(e,t){let[n=`open-knowledge`,...r]=e&&e.length>0?e:[`open-knowledge`];return{command:n,args:[...r,`mcp`,`--port`,String(t)]}}var fE=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??(()=>Xw(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 YT({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,mE(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 cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`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,availableCommands: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,envNotePending:!1};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 Ed(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new cE(`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 cE(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new cE(`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=Wce(t);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new cE(`unknown-agent`,`agent vanished`);n=await Uce(t,bd(),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 qT({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:i});this.emitStatus(e,`spawning`);let o=fT(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 cE(`spawn-failed`,`agent process has no stdio`);let s=tie(Xte.toWeb(o.stdin),xu.toWeb(o.stdout)),c=Cie({name:`open-knowledge`}).onRequest(Rm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Rm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Rm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Rm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Rm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Rm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Rm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Rm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Rm.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(Rm.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 cE(`spawn-failed`,`initialize failed: ${vE(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 iT(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof Zw)||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=ST(t.kind);if(!jT(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=Gce(t,a);return await iT(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(aT(t.env)===aT(e.env))return null;try{await iT(t)}catch(t){if(!(t instanceof Zw))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||oT(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:tT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await RT(t,this.opts.log,n);let r=await FT(t,n).catch(()=>null);if(r!==null)return r;let i=(await VT(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new Zw(`command-not-found`,gE(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=CT(t).displayName;throw new Zw(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=CT(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&&HT(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 zT(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:Nw,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Ti,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=Tne[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 Zw||t instanceof cE?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:xE(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(Rm.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=SE(yE(t),xE(e));return _E(t)?this.emitStatus(e,`auth_required`,`sign in required: ${vE(t)}`,{reason:`auth-required`,agentMessage:vE(t),machineDetail:r,authMethods:CE(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${vE(t)}`,{reason:`session-setup`,agentMessage:vE(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 cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new cE(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new cE(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`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 cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`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 cE(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new cE(`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(Rm.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(Rm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new cE(`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 cE?t:t instanceof Zw?new cE(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 cE(`resume-unsupported`,`couldn't resume the previous session: ${vE(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new cE(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new cE(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new cE(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{Bce();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 cE(`spawn-failed`,n)}if(t.closed)throw new cE(`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 cE(`spawn-failed`,bE(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new cE(`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 cE(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new cE(`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 uE();let t=e instanceof lE?`the sign-in didn't complete in time — try again`:vE(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:SE(yE(e),xE(n)),authMethods:CE(i.authMethods)}),new cE(`not-ready`,t)}if(n.closed)throw new cE(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw uE();if(!await this.openSession(n,r,i,n.launchSettings))throw new cE(`not-ready`,bE(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 lE),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Rm.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 gT(t,{graceMs:sE}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(ih(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 cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new cE(`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 cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`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=rE(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 cE(`not-ready`,`the thread is closing`);let r=nE(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 cE(`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(Rm.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: ${vE(t)}`,{reason:`prompt`,agentMessage:vE(t),machineDetail:SE(yE(t),xE(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(Rm.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 cE(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Rm.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 cE(`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(Rm.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||!hE(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(Rm.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(Rm.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`&&hE(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Rm.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 gT(r,{graceMs:t?.killGraceMs??oE})||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(ih(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 cE(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new cE(`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:sE})))}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:Oce(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await _u(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await _u(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 cE(`spawn-failed`,`agent process has no stdio`);let s=tie(Xte.toWeb(o.stdin),xu.toWeb(o.stdout)),c=Cie({name:`open-knowledge`}).onRequest(Rm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Rm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Rm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Rm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Rm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Rm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Rm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Rm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Rm.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(Rm.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 cE(`spawn-failed`,`initialize failed: ${vE(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 iT(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof Zw)||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=ST(t.kind);if(!jT(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=Gce(t,a);return await iT(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(aT(t.env)===aT(e.env))return null;try{await iT(t)}catch(t){if(!(t instanceof Zw))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||oT(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:tT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await RT(t,this.opts.log,n);let r=await FT(t,n).catch(()=>null);if(r!==null)return r;let i=(await VT(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new Zw(`command-not-found`,gE(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=CT(t).displayName;throw new Zw(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=CT(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&&HT(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 zT(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:Nw,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Ti,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=Tne[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 Zw||t instanceof cE?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:xE(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){e.info.availableCommands=null;let i=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Rm.agent.session.new,{cwd:e.cwd,mcpServers:i});e.sessionId=n.sessionId,e.envNotePending=!0,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=SE(yE(t),xE(e));return _E(t)?this.emitStatus(e,`auth_required`,`sign in required: ${vE(t)}`,{reason:`auth-required`,agentMessage:vE(t),machineDetail:r,authMethods:CE(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${vE(t)}`,{reason:`session-setup`,agentMessage:vE(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 cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new cE(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new cE(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`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 cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.info.availableCommands=null,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 cE(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new cE(`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(Rm.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(Rm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new cE(`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 cE?t:t instanceof Zw?new cE(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 cE(`resume-unsupported`,`couldn't resume the previous session: ${vE(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new cE(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new cE(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new cE(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{Bce();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 cE(`spawn-failed`,n)}if(t.closed)throw new cE(`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 cE(`spawn-failed`,bE(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new cE(`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 cE(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new cE(`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 uE();let t=e instanceof lE?`the sign-in didn't complete in time — try again`:vE(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:SE(yE(e),xE(n)),authMethods:CE(i.authMethods)}),new cE(`not-ready`,t)}if(n.closed)throw new cE(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw uE();if(!await this.openSession(n,r,i,n.launchSettings))throw new cE(`not-ready`,bE(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 lE),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Rm.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 gT(t,{graceMs:sE}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(ih(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 cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new cE(`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 cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`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=rE(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 cE(`not-ready`,`the thread is closing`);let r=nE(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 cE(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t);let r=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,r=`Note on your environment: you are running inside the OpenKnowledge app, connected over ACP (Agent Client Protocol) — not inside your own terminal app. Your host CLI's terminal UI is not present, so its built-in slash commands (such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not exist here; never recommend them. The only slash commands available to the user are the ones you advertise over ACP.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let i=e.sessionId;e.conn.agent.request(Rm.agent.session.prompt,{sessionId:i,prompt:[{type:`text`,text:r}]}).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: ${vE(t)}`,{reason:`prompt`,agentMessage:vE(t),machineDetail:SE(yE(t),xE(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(Rm.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 cE(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Rm.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 cE(`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(Rm.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||!hE(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(Rm.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(Rm.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`&&hE(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Rm.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 gT(r,{graceMs:t?.killGraceMs??oE})||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(ih(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 cE(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new cE(`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:sE})))}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)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:Oce(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await _u(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await _u(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
|
-
`)}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=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=it(r,Sw(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-DtlsFK7O.mjs`);await e(I(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return pE(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new cE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&Ace(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>aE){let t=e.events.length-aE;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 gT(t,{graceMs:oE})}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=qr(e.info.agent.id),i=xa[r]??Ui(e.agentSessionId);n.setPresence(ih(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 pE(e,t,n){let r=await yu(e),i=Rl(Ll(t)?t:z(r,t)),a=i,o=``;for(;;)try{let e=await yu(a),i=o===``?e:L(e,o),s=R(r,i);if(s===``||s.startsWith(`..`)||Ll(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(Vl).join(`/`),t=s.split(Vl).join(`/`);!Zx(e)&&!Qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Vl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=I(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):L(a.slice(t.length+1),o),a=t}}function mE(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 hE(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 gE(e){let t=CT(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 _E(e){return typeof e==`object`&&!!e&&e.code===-32e3}function vE(e){return e instanceof Error?e.message:String(e)}function yE(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 bE(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 xE(e){let t=e.stderrTail.join(`
|
|
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=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=it(r,Sw(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-DtlsFK7O.mjs`);await e(I(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return pE(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new cE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&Ace(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>aE){let t=e.events.length-aE;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 gT(t,{graceMs:oE})}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=qr(e.info.agent.id),i=xa[r]??Ui(e.agentSessionId);n.setPresence(ih(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 pE(e,t,n){let r=await yu(e),i=Rl(Ll(t)?t:z(r,t)),a=i,o=``;for(;;)try{let e=await yu(a),i=o===``?e:L(e,o),s=R(r,i);if(s===``||s.startsWith(`..`)||Ll(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(Vl).join(`/`),t=s.split(Vl).join(`/`);!Zx(e)&&!Qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Vl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=I(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):L(a.slice(t.length+1),o),a=t}}function mE(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,envNotePending:!1}}function hE(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 gE(e){let t=CT(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 _E(e){return typeof e==`object`&&!!e&&e.code===-32e3}function vE(e){return e instanceof Error?e.message:String(e)}function yE(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 bE(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 xE(e){let t=e.stderrTail.join(`
|
|
28
28
|
`);return t===``?void 0:t}function SE(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
|
|
29
29
|
`);return t===``?void 0:t}function CE(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}const wE=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`steer`,`queue_edit`,`queue_hold`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`retry`,`authenticate`,`delete`,`list`]);function Yce(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!wE.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`steer`:return!r(`threadId`)||!r(`reqId`)||!r(`content`)?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)||n.reqId!==void 0&&!r(`reqId`)?null:n;case`queue_hold`:return!r(`threadId`)||!r(`id`)||typeof n.held!=`boolean`?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`retry`:return!r(`threadId`)||!r(`reqId`)?null:n;case`authenticate`:return!r(`threadId`)||!r(`reqId`)||!r(`methodId`)?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function TE(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Xce(e,t,n));e.on(`message`,e=>{let s=Yce(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`steer`:t.steerPrompt(s.threadId,s.content);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof cE?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof cE)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Xce(e,t,n){return{op:`error`,code:e,message:t,...n}}var EE=class{hocuspocus;log=F(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){ah(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){ah(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(ga);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Zce(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Zce(e){return e?.awareness??null}var DE=class{hocuspocus;log=F(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!ah(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!ah(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!ah(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!ah(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return mse(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(ga);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Qce(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Qce(e){return e?.awareness??null}var OE=class extends Error{};const $ce=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],kE=1024*1024;async function AE(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new OE(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new OE(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new OE(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new OE(`Website skill fetch exceeded 5 redirects: ${t}`)}function jE(e){let t;try{t=new URL(e)}catch{throw new OE(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new OE(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new OE(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function ME(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function ele(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!ME(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&ME(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function tle(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function NE(e,t,n){let r=[];for(let i of $ce){let a=new URL(i,e).href;try{let o=await AE(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>kE){r.push(`${i}: index exceeds ${kE} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=ele(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new OE(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function nle(e,t={}){let{skills:n}=t.index??await PE(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function PE(e,t={}){let n=jE(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new OE(`No fetch implementation available.`);return NE(n,r,t.timeoutMs??15e3)}async function rle(e,t={}){if(!ME(e.skill)||e.skill.includes(`/`))throw new OE(`Invalid website skill name: ${e.skill}`);let n=jE(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new OE(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await NE(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new OE(`Website skill index does not contain ${e.skill}`);let c=Zl(L(pu(),`ok-skill-site-`)),l=L(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await AE(r,tle(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new OE(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new OE(`Website skill file exceeds ${qt} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new OE(`Website skill file exceeds ${qt} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new OE(`Website skill bundle exceeds ${dn} bytes.`);let d=L(l,...e.split(`/`));Xl(I(d),{recursive:!0}),cu(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>iu(c,{recursive:!0,force:!0})}}catch(t){throw iu(c,{recursive:!0,force:!0}),t instanceof OE?t:new OE(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const ile=Au(Al),ale=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,FE=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function IE(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return FE.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=ale.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function LE(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function RE(e,t={}){if(e.kind===`well-known`)return rle(e,t);if(e.kind===`local`){let t=z(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!B(t))throw new OE(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!FE.some(t=>t.test(e.url)))throw new OE(`Unsupported git transport: ${e.url}`);let n=Zl(L(pu(),`ok-skill-import-`));try{await ile(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){iu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new OE(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Rte(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?z(n,e.subpath):n,a=R(n,i);if(a.startsWith(`..`)||Ll(a))throw iu(n,{recursive:!0,force:!0}),new OE(`subpath escapes the clone: ${e.subpath}`);if(!B(i))throw iu(n,{recursive:!0,force:!0}),new OE(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>iu(n,{recursive:!0,force:!0})}}const zE=[`.ok`,`skills-lock.json`],ole=ve({source:u(),pluginProvider:u().optional(),skill:u().optional(),ref:u().optional(),contentHash:u(),files:P(u()).optional(),localHash:u().optional(),baselineRef:u().optional(),publisher:u().optional(),importedAt:a(),autoUpdate:D().optional()}),sle=ve({schema:x(1),skills:C(u(),ole).default({})});function BE(){return{schema:1,skills:{}}}function VE(e){let t;try{t=JSON.parse(e)}catch{return null}let n=sle.safeParse(t);return n.success?n.data:null}function HE(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const cle=new Set(Object.values(xr));function lle(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?UE(e,t,n):!cle.has(e)||r?.selfIdentifiesAsPack!==!0?null:UE(e,t,n)}function UE(e,t,n){return{source:Wt,skill:e,contentHash:t,importedAt:n}}function ule(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function WE(e,t){let n=t,r=``,{frontmatter:i}=jt(e);if(i!==``){let{map:e}=En(Xt(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const GE=new Set([`.git`,`node_modules`]),dle=new Set([...GE,`scripts`,`references`]);function fle(e){let t=[],n=r=>{for(let i of tu(r,{withFileTypes:!0})){let a=L(r,i.name);if(i.isDirectory()){GE.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=R(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=V(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function KE(e){let t=L(e,`SKILL.md`);return B(t)?WE(V(t,`utf-8`),Pl(e)):null}function qE(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=B(L(e,`SKILL.md`))?ou(L(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${qt}.`;if(n>67108864)return`Skill exceeds ${dn} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=tu(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=L(o,c.name);if(c.isDirectory()){GE.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=R(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=ou(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${qt}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${dn} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function JE(e){let t=L(e,`SKILL.md`);if(!B(t))return null;let n=V(t,`utf-8`),{name:r,description:i}=WE(n,Pl(e)),a=fle(e),o=Cu(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
|
|
30
30
|
`);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function YE(e){if(B(L(e,`SKILL.md`)))return[{name:Pl(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(B(L(e,`SKILL.md`))){t.push({name:Pl(e),dir:e});return}let a;try{a=tu(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!dle.has(t.name)&&r(L(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function XE(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;if(!i||!r)continue;let a=typeof t.name==`string`&&t.name?t.name:bt(i);za(a,r)||n.push({id:i,name:a,source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:at(r)})}return n}const ple={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`,"'":`'`,"'":`'`};function mle(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>ple[e]??e)}function hle(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=mle(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function gle(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:bt(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:at(r)})}return n}function ZE(e){return e.trim().toLowerCase()}function _le(e){return e.split(`/`).filter(Boolean).pop()??e}function QE(e){let t=po(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=LE(e);if(!n)return null;let r=po(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function $E(e,t,n={}){let r=QE(e);if(r){let e=t??r.skill;if(!e)throw new OE(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=LE(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new OE(`No fetch implementation available.`);let o=t??i.skill,s=ZE(o),c=ZE(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new OE(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof OE?e:new OE(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=XE(l).find(e=>{if((e.publisher?ZE(e.publisher):``)!==c)return!1;let t=ZE(e.name),n=ZE(_le(e.id));return t===s||n===s});if(!u)throw new OE(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=po(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:IE(u.source);if(!f||f.kind===`local`)throw new OE(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const eD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function tD(e){let t=eD.indexOf(e);return t===-1?eD.length:t}function nD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=tD(e.editor)-tD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function rD(e){if(!B(e))return[];try{return tu(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>L(e.parentPath,e.name)).sort()}catch{return[]}}function iD(e,t,n,r){let i=L(e,`SKILL.md`);if(!B(i))return null;let a=Pl(e),o=a,s=``;try{({name:o,description:s}=WE(V(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:rD(L(e,`scripts`)),references:rD(L(e,`references`)),provenance:n,inert:r}}function aD(e){if(!B(e))return[];try{return tu(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function vle(e){let t=e=>{try{return ou(e).isDirectory()}catch{return!1}};return{commands:t(L(e,`commands`)),hooks:t(L(e,`hooks`)),mcp:B(L(e,`.mcp.json`))}}const yle={commands:!1,hooks:!1,mcp:!1};function oD(e,t){let n=[];for(let r of aD(e)){let i=iD(L(e,r),t,{},yle);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function sD(e){try{return tu(e).length>0}catch{return!1}}function ble(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=tu(e,{withFileTypes:!0})}catch{return}if(B(L(e,`SKILL.md`))||B(L(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(L(e,t.name),r+1)};return n(L(e,`skills`),0),[...t].sort()}function xle(e){return{commands:sD(L(e,`commands`)),hooks:sD(L(e,`hooks`))||B(L(e,`hooks.json`)),mcp:B(L(e,`.mcp.json`)),agents:sD(L(e,`agents`))}}function Sle(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function Cle(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!B(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function wle(e){let t=L(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(V(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function Tle(e,t){let n=L(e,`installed_plugins.json`);if(!B(n))return[];let r;try{r=JSON.parse(V(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=Sle(e);for(let e of Cle(n)){let n=e.installPath,o=vle(n),s=wle(n),c=L(n,`skills`),l=[];for(let n of aD(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=iD(L(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const cD=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,Ele=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,Dle=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function lD(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function Ole(e){let t=Ele.exec(lD(e));if(!t)return null;try{let e=V(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function uD(e,t){let n=z(e);try{ou(n).isDirectory()||(n=I(n))}catch{return null}let r=z(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(V(L(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=I(n)}return null}function kle(e){let t=lD(e),n=cD.exec(t);if(n){let t=uD(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=Dle.exec(t);if(!r)return null;let i=uD(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function Ale(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function jle(e){let t=lD(e),n=cD.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=tu(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=Ale(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return B(c)?c:e}function dD(e,t){for(let n of t)try{let t=JSON.parse(V(L(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function Mle(e){let t=dD(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(V(L(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const Nle={id:`claude`,homes:e=>[{harness:`claude`,dir:L(e,`.claude`,`plugins`)}],enumerate:Tle,inspectSource:kle,repositoryUrl:Ole,resolveUpdateSource:jle,detectDir:Mle};function fD(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=dD(e,t);return n?{...n,setupSupported:!1}:null}}}function Ple(e,t){try{return JSON.parse(V(L(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const pD=[Nle,fD(`codex`,[`.codex-plugin/plugin.json`]),fD(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=dD(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!Ple(e,`plugin.json`))return null;let n=dD(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function mD(e){return pD.find(t=>t.id===e)}function hD(e){if(e===void 0)return pD;let t=mD(e);return t?[t]:[]}function Fle(e){return pD.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function Ile(e,t,n=e){let r=mD(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function gD(e,t){for(let n of hD(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function Lle(e){for(let t of pD){let n=t.detectDir(e);if(!n)continue;let r=ble(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:xle(e),setupSupported:n.setupSupported}}return null}function Rle(e,t){for(let n of hD(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function zle(e,t){for(let n of hD(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function Ble(e=uu()){let t=Za.flatMap(t=>{let n=_i[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:L(e,...n.split(`/`))}]});return[...Fle(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:L(e,`.agents`,`skills`)}]}function Vle(e){return Za.flatMap(t=>{let n=io[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:L(e,...n.split(`/`))}]})}function _D(e){return Object.keys(e.provenance).length>0}function vD(e){return e.provenance.plugin!==void 0}function Hle(e,t){if(vD(e)!==vD(t))return vD(e)?e:t;if(_D(e)!==_D(t))return _D(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function Ule(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function Wle(e){try{return JE(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function Gle(e){let t=new Map;for(let n of e){let e=pt(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${Wle(n)}`,i=t.get(r);i?(i.winner=Hle(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>Ule(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||pt(e.provenance.scope).localeCompare(pt(t.provenance.scope))||e.home.localeCompare(t.home))}function Kle(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function yD(e={}){let t=[];for(let n of Ble(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...Ile(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...oD(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...qle(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>Dn(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:Gle(n.flatMap(e=>e.skills)),packs:Kle(n)}}function qle(e){let t=bD(z(e,`.ok`,`skills`)),n=[];for(let r of Vle(e))try{for(let i of oD(r.dir,r.harness)){let r=i.skills.filter(e=>!Yle(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>Jle(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function Jle(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function Yle(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=bD(e.home);return n===t||n.startsWith(t+Vl)}function bD(e){try{return H(e)}catch{return z(e)}}function Xle(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const Zle=[`skillId`,`source`,`installs`];function Qle(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*$le(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!Zle.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield Qle(r)}}}}function eue(e){let t=Xle(e),n=[];for(let e of $le(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function tue(e){let t=new Map;for(let n of eue(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||za(n.skillId,n.source)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:at(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}const xD=/href="\/([^"/]+)\/([^"/]+)\/([^"/?#]+)"([\s\S]*?)<\/a>/g,nue=/<span[^>]*font-mono[^>]*>\s*([\d,]+)\s*<\/span>/;function rue(e,t){let n=new Map;xD.lastIndex=0;for(let r=xD.exec(e);r!==null;r=xD.exec(e)){let[,e,i,a,o]=r;if(!e||!i||!a||!o||`${e}/${i}`!==t||za(a,t))continue;let s=Number.parseInt(nue.exec(o)?.[1]?.replaceAll(`,`,``)??``,10);if(!Number.isInteger(s)||s<0)continue;let c=`${t}/${a}`;n.has(c)||n.set(c,{id:c,name:a,source:t,description:``,installs:s,publisher:at(t)})}return[...n.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function iue(e,t){return`${e}/${t}`}function aue(e){if(e.preferredSource===!0)return-1;let t=eD.indexOf(e.editor);return t===-1?eD.length:t}function oue(e){let t=nD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=iue(e.scope,e.name),o=aue(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var SD=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),sue=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),cue=n(((t,n)=>{let{Readable:r,Writable:i}=e(`stream`),a=sue(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=SD(),d=Buffer.from(`\r
|
|
@@ -2037,4 +2037,4 @@ native-divergence-injected
|
|
|
2037
2037
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await ve.flushDeferredStores(`discard-stale`),t=!0,De?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),t||(ee(!1),await ve.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&M.current&&t>0){let t=p??`.`;try{let n=await kx(M.current,t,e.oldHead,e.newHead,i);qb(),b.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){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),St.push(`head-watcher`)}function l(e){for(let t of e)try{let e=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Vx(e),a=Se.documents.get(i);if(!a)continue;let o=it(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Se.documents.get(Vx(e));i&&ot(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=AAe(h),m=O();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{vt=new EAe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=M.current;n&&await jx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=M.current;n&&await jx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Uo({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:be(t.error),configPath:cs(`project-local`,r)},`[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 vt.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),vt=null}Ge(`files`),_e.announceReadyViews();let g=LL();g!==void 0&&RL(`readyMs`,g),ae()}return Ct().then(ze,e=>{_e.close(),He(),Be(e)}),{hocuspocus:Se,durabilityState:x,sessionManager:Ce,nativeApi:we,localApi:Te,cc1Broadcaster:De,agentFocusBroadcaster:ke,agentPresenceBroadcaster:Ae,maintenanceCoordinator:N,contentFilter:ge,basenameIndex:de,serverInstanceId:j,destroy:xt,ready:Ve,degraded:St,lockDir:ce,get syncEngine(){return vt},getLinkPreviewsEnabled:re,resolveEmbed:fe,acpRegistry:le,acpPermissions:ue}}function f9(e){return e/1048576}function MAe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;Xo(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function NAe(){if(p9)return;let e=xs().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}=MAe();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`})}),p9=e}function PAe(){if(!m9){let e=xs().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(!_9){_9=ene({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=xs().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=v9;if(v9={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`}))}),h9=e}}const y9=F(`skill-migrate`);function b9(e){return[{host:`agents`,root:vr},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=eD.indexOf(e.host),r=eD.indexOf(t.host);return(n===-1?eD.length:n)-(r===-1?eD.length:r)||e.host.localeCompare(t.host)})}const FAe=b9(io),IAe=b9(_i);function LAe(e,t){ls(I(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function RAe(e,t,n){let r=LI(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 x9(e,t){let n;try{n=H(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!H(z(e,t.dir)).startsWith(n+Vl)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??FAe,a={migrated:[],skipped:[]};if(!B(n))return a;let o;try{o=tu(n)}catch{return a}let s=R(t,n).split(Vl).join(`/`),c=new Set;for(let[e,n]of Object.entries(qX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Wa.test(e)||iI.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=z(n,e);if(!B(L(o,`SKILL.md`)))continue;let s=JE(o)?.contentHash;if(s===void 0)continue;let l=H(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:GI(t,i),state:RAe(L(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`&&B(z(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`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ps(d.path,{recursive:!0,force:!0}),LAe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await VN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=F(`skill-reconcile`),zAe=iI;function w9(){let e=[];for(let t of Pa){let n=io[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:vr,editor:null}),e}function BAe(e,t){let n=R(e,z(t));return Ll(n)?z(t):n}function T9(e){let{frontmatter:t,body:n}=jt(e),r={};if(t!==``)try{let e=(0,CD.parse)(Xt(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function VAe(e,t){let n=T9(e),r=T9(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 E9(e,t){let n=D9(e),r=D9(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=L(e,o),c=L(t,o);if(i+=ou(s).size+ou(c).size,i>1048576)return!1;let l=V(s),u=V(c);if(!l.equals(u)&&(o!==`SKILL.md`||!VAe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of tu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(BAe(e,n),t,`dir`)}function k9(e,t){try{let n=nu(e);return z(Ll(n)?n:z(I(e),n))===z(t)}catch{return!1}}function HAe(e,t){try{let n=nu(e),r=Ll(n)?z(n):z(I(e),n);if(!B(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||Ll(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const UAe=[...Pa,`agents`];function WAe(e){for(let t of UAe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function GAe(e){let{projectDir:t,skillsRoot:n}=e;if(!B(n))return;let r;try{r=tu(n)}catch{return}let i=w9();for(let e of r){let r=WAe(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(B(o))try{let n=Yl(a);if(n.isSymbolicLink()||!n.isDirectory()||!B(L(a,`SKILL.md`))||!B(L(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(GI(t,r))continue;let i=L(r,e);k9(i,a)&&O9(r,i,o)}ps(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function KAe(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 w9()){let o=z(t,e);if(!B(o)||GI(t,o))continue;let s;try{s=tu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(zAe.has(e))continue;let t=L(o,e),s=z(n,e),c=B(s);try{let l=Yl(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(HAe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Wa.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=RN(t);for(let[r,a]of i){let i=z(n,r);if(!B(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await BN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??BI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{GAe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=dO(e);A9=new As({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ao(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){ao(null),await A9?.drain(),A9=null,j9=!1}zo();const qAe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],JAe=[`cache`,`tmp`];function YAe(e){let t=z(e,ge);if(!(()=>{if(!B(t))return!0;try{return tu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of qAe)B(z(e,t))&&n.push(t);for(let t of JAe){let r=z(e,t);try{B(r)&&ou(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function XAe(e){let t=Gu(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 F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function ZAe(e){IL();let t=e.projectDir??e.contentDir,n=Rge({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}`)}Es.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),N9(t),NAe(),PAe();let{kind:r,gitdir:i}=XAe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=Ige(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Zo(`ok.boot`,{attributes:a},async()=>QAe(e)),l=()=>{if(s)try{let e=Lo.extract(Bo.active(),{traceparent:s});return Bo.with(e,c)}catch(e){F(`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 QAe(e){let t=e.skipAutoInit??!1,n=e.log??F(`boot`),r=e.serverRuntime??{...Sr(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((fr(r)||!Gt(i))&&!r.allowExternal)throw new UB(`refusing to start: the server would bind a non-loopback address (${(Gt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=KB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.publicUrlSource!==`server`&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.publicUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.publicUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.publicUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.publicUrl to admit a hostname.`));let 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-CDm0H6LS.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new J8(B(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);B(h)||F(`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 g=e.gitPreflight??yK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof gK||e instanceof _K){let t=e instanceof _K?e.detected:``,r=e instanceof _K?`too_old`:`not_available`;RK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ys(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=YAe(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);let v=d9({contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,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:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,k=()=>r.publicUrlSource===`server`&&r.publicUrl!==void 0?r.publicUrl.replace(/\/+$/,``):`http://${D}:${O}`,A=e.ephemeral?void 0:V8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:v.localApi,log:n}),ne=c();ne.headersTimeout=3e4,ne.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:_Q({contentFilter:v.contentFilter,contentSirv:ic(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_e,assetExtensions:w,blocklistExtensions:ke,ingressPolicy:a}),ie=!1;if(e.reactShellDistDir)try{xZ(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof bZ)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let ae=e.reactShellDistDir?ic(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new fE({contentDir:e.contentDir,localDir:C,globalDir:z(uu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>k(),getMcpStdioCommand:()=>dE(e.localOpCliArgs,O),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let j=K8({httpServer:ne,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:A,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},le=null;e.idleShutdownMs!==null&&(le=jQ({httpServer:ne,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ce()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let ue=[...new Set(i)],de=ue[0],fe=async()=>{if(ie)try{wZ(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await pe(ne,e.port??0,de??`127.0.0.1`)}catch(e){throw await fe(),e}let me=ne.address(),he=typeof me==`object`&&me?me.port:e.port??0,M=[];for(let e of ue.slice(1)){let t=c();t.headersTimeout=ne.headersTimeout,t.requestTimeout=ne.requestTimeout;for(let e of ne.listeners(`request`))t.on(`request`,e);for(let e of ne.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:M.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...M,ne])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await fe(),t}M.push(t)}let N=LL();N!==void 0&&RL(`httpListenMs`,N);let ve=ne.address(),ye=typeof ve==`object`&&ve?ve.port:e.port??0;O=ye;let be=`http://${D}:${ye}`;d(C,ye,be),ie&&SZ(C,ye,be);let xe=!1,Se=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ce=async()=>{if(xe)return;xe=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await Se(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ie&&sge(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{le?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of M)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>j.shutdown()),A!==void 0&&await t(`mcpHttpHandler.close`,()=>A.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{j.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ne.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ne.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ie&&await t(`releaseUiLock`,async()=>wZ(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>Es.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,yL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=uu(),t=await S9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:IAe,inPlaceNames:x9(e,bL(e))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await KAe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ne,destroy:ce,lockDir:C,contentDir:e.contentDir,port:ye,ready:x,degraded:S,didAutoInit:f,serverInstance:v,runtime:KDe(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new OQ(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=Ku(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(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=Fs({baseDir:n,timeout:{block:5e3}});s=new Set(await Wb(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=Vx(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 $Ae=Me;function eje(e={}){let t=e.home??uu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?B(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?B(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(ks(),1);const R9=L(uu(),`.ok`,`logs`),tje=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function nje(){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 rje(e){Xl(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function ije(e){try{if(ou(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{ru(n,r)}catch{}}try{su(`${e}.3`)}catch{}}function aje(e){try{let t=Date.now(),n=10080*60*1e3,r=tu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ou(L(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{su(L(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{su(L(e,t.name)),a-=t.size}catch{}}}catch{}}function oje(e){rje(R9);let t=z9(),n=e.filePath??L(R9,`${e.name}.${t}.log`);ije(n),(e._setTimeout??setTimeout)(()=>aje(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:nje(),name:e.name,redact:{paths:tje,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function sje(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.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 cje(e){return L(R9,`${e}.${z9()}.log`)}function lje(){return R9}function uje(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=B(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const B9=Au(Al),V9=F(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function dje(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],fN({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function fje(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],fN({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function pje(e){let t=z(e,`packed-refs`);if(B(t))try{if(V(t,`utf-8`).split(`
|
|
2038
2038
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return tu(z(e,`refs/heads`)).length>0}catch{return!1}}function U9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function W9(e,t){if(await fje(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await dje(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,fN({cwd:t,encoding:`utf-8`})),r||V9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){V9.warn({path:t,stderr:U9(e)},`could not create initial commit`)}}async function mje(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],fN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function hje(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1,a=!1;if(B(n)){if(!ou(n).isDirectory())return{didInit:!1};if(B(r)){if(pje(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=yK()}catch(e){throw e instanceof gK||e instanceof _K?(RK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof _K?`too_old`:`not_available`,detectedVersion:e instanceof _K?e.detected:``},e instanceof _K?`git binary too old`:`git binary not found`)):V9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await W9(s,t),{didInit:!1};if(!i&&await mje(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],fN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new H9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new H9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await W9(s,t),i?(V9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(V9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,gje=Sa.map(e=>e.replace(/\/$/,``));async function _je(e){let t=Ku(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(xje(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Is(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ps(async()=>{let t=await vje(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await yje(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=Is(e,{gitIndexFile:L(pu(),`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 bje(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await NB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Rs(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 \`${Yi}\` 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 gje){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function vje(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 yje(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function bje(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function xje(e){return B(L(e,`MERGE_HEAD`))||B(L(e,`rebase-merge`))||B(L(e,`rebase-apply`))||B(L(e,`CHERRY_PICK_HEAD`))||B(L(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function Sje(e,t){let n;try{n=kl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=I(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await _u(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=I(t);if(r===t)return;t=r}}const Cje=[{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 Cje)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 wje(e){if(!zx(e))throw new $9(e);let t;try{t=H(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ou(t).isFile())throw new Q9(e);let n=I(t),r=_B(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Vx(R(Tje(e),t).split(Vl).join(`/`)),canonicalFilePath:t}}let i=Pl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Vx(i)}}function Tje(e){return z(e,Ko({absPath:cs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Eje(e){let t=Zl(z(pu(),`ok-ephemeral-`)),n=z(t,`.ok`);return Xl(n,{recursive:!0}),cu(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),cu(z(n,`.gitignore`),`local/
|
|
2039
2039
|
`,`utf-8`),t}export{J2 as $,kx as $i,uz as $n,JM as $r,GJ as $t,J7 as A,hw as Ai,LB as An,qP as Ar,mQ as At,u7 as B,K as Bi,Zz as Bn,Qde as Br,JJ as Bt,d9 as C,Yu as Ca,EE as Ci,UB as Cn,rI as Cr,yQ as Ct,Y7 as D,dE as Di,YB as Dn,aF as Dr,_ge as Dt,K7 as E,Fu as Ea,iE as Ei,VB as En,GF as Er,LZ as Et,Cke as F,xw as Fi,Oz as Fn,zP as Fr,wZ as Ft,G8 as G,$x as Gi,Qz as Gn,wN as Gr,$J as Gt,q8 as H,aS as Hi,Nz as Hn,Lde as Hr,oY as Ht,y7 as I,WC as Ii,eB as In,LP as Ir,SZ as It,R8 as J,Px as Ji,bz as Jn,vN as Jr,nY as Jt,U8 as K,nS as Ki,jz as Kn,SN as Kr,sY as Kt,v7 as L,GC as Li,Fz as Ln,$de as Lr,xY as Lt,I7 as M,jw as Mi,FB as Mn,ife as Mr,bZ as Mt,N7 as N,Tce as Ni,_B as Nn,RP as Nr,xZ as Nt,W7 as O,Mw as Oi,XB as On,GP as Or,vge as Ot,_7 as P,Ece as Pi,gB as Pn,BP as Pr,CZ as Pt,U2 as Q,Sx as Qi,mz as Qn,cN as Qr,WJ as Qt,dke as R,pw as Ri,Pz as Rn,IP as Rr,vY as Rt,P9 as S,Xu as Sa,DE as Si,qW as Sn,sI as Sr,TQ as St,U7 as T,qu as Ta,fE as Ti,eV as Tn,Cpe as Tr,RZ as Tt,J8 as U,Qx as Ui,$z as Un,xN as Ur,lY as Ut,s7 as V,fS as Vi,Kz as Vn,lP as Vr,cY as Vt,K8 as W,rS as Wi,mB as Wn,bN as Wr,QJ as Wt,V2 as X,Ex as Xi,pz as Xn,gN as Xr,iY as Xt,O8 as Y,Tx as Yi,fz as Yn,pN as Yr,tY as Yt,H2 as Z,Dx as Zi,hz as Zn,fN as Zr,eY as Zt,$Ae as _,rh as _a,nj as _i,GW as _n,gI as _r,wQ as _t,wje as a,jx as aa,iM as ai,_K as an,Vpe as ar,ube as at,N9 as b,Ed as ba,fO as bi,KW as bn,pI as br,SQ as bt,_je as c,gx as ca,Nj as ci,IK as cn,DI as cr,G0 as ct,uje as d,ax as da,sj as di,xK as dn,TI as dr,O_e as dt,bx as ea,qM as ei,HK as en,tz as er,Sbe as et,oje as f,Qb as fa,cj as fi,dK as fn,wI as fr,m1 as ft,eje as g,ih as ga,rj as gi,WW as gn,hI as gr,xQ as gt,lje as h,nh as ha,ej as hi,IW as hn,_I as hr,EQ as ht,Eje as i,Nx as ia,sM as ii,gK as in,FI as ir,lbe as it,H7 as j,kw as ji,IB as jn,WP as jr,VZ as jt,q7 as k,Pw as ki,qB as kn,KP as kr,gQ as kt,H9 as l,lx as la,Pj as li,vK as ln,OI as lr,x1 as lt,cje as m,Tie as ma,ij as mi,sK as mn,EI as mr,jQ as mt,Z9 as n,Fx as na,rM as ni,LK as nn,MR as nr,P2 as nt,X9 as o,Mx as oa,oM as oi,mK as on,MI as or,dbe as ot,sje as p,hse as pa,aj as pi,uK as pn,kpe as pr,_1 as pt,V8 as q,Zx as qi,yz as qn,CN as qr,uY as qt,$9 as r,vx as ra,$j as ri,RK as rn,II as rr,k2 as rt,Sje as s,Ix as sa,aM as si,yK as sn,AI as sr,C2 as st,Q9 as t,wx as ta,cM as ti,BK as tn,BR as tr,F2 as tt,hje as u,sx as ua,Kj as ui,TK as un,kI as ur,$$ as ut,ZAe as v,Td as va,dO as vi,BW as vn,mI as vr,bQ as vt,u9 as w,md as wa,TE as wi,KB as wn,cI as wr,_Q as wt,M9 as x,gd as xa,yD as xi,RW as xn,oI as xr,Mge as xt,I9 as y,_d as ya,uO as yi,YW as yn,dI as yr,CQ as yt,d7 as z,pS as zi,tB as zn,FP as zr,pY as zt};
|
|
2040
|
-
//# sourceMappingURL=src
|
|
2040
|
+
//# sourceMappingURL=src--OhnhRml.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$o as e,U as t,_ as n,_s as r,h as i,ks as a,nc as o,ns as s,rs as c,ys as l,z as u}from"./src-Dj6UxpKM.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,Bt as w,C as T,Ca 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,Fr as W,Ft as G,G as K,Gi as q,Gn as J,Gr as Y,Gt as X,H as Z,Hi as Q,Hn as $,Hr as ee,Ht as te,I as ne,Ii as re,In as ie,It as ae,J as oe,Ji as se,Jn as ce,Jr as le,Jt as ue,K as de,Ki as fe,Kn as pe,Kr as me,Kt as he,L as ge,Li as _e,Ln as ve,Lt as ye,M as be,Mi as xe,Mn as Se,Mr as Ce,Mt as we,N as Te,Ni as Ee,Nn as De,Nr as Oe,Nt as ke,O as Ae,Oi as je,On as Me,Or as Ne,Ot as Pe,P as Fe,Pi as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qi as Ve,Qn as He,Qr as Ue,Qt as We,R as Ge,Ri as Ke,Rn as qe,Rt as Je,S as Ye,Sa as Xe,Si as Ze,Sn as Qe,Sr as $e,St as et,T as tt,Ti as nt,Tn as rt,Tr as it,Tt as at,U as ot,Ui as st,Un as ct,Ur as lt,Ut as ut,V as dt,Vi as ft,Vn as pt,Vr as mt,Vt as ht,W as gt,Wi as _t,Wn as vt,Wr as yt,Wt as bt,X as xt,Xi as St,Xn as Ct,Xr as wt,Xt as Tt,Y as Et,Yi as Dt,Yn as Ot,Yr as kt,Yt as At,Z as jt,Zi as Mt,Zn as Nt,Zr as Pt,Zt as Ft,_ as It,_a as Lt,_i as Rt,_n as zt,_r as Bt,_t as Vt,a as Ht,aa as Ut,ai as Wt,an as Gt,ar as Kt,at as qt,b as Jt,ba as Yt,bi as Xt,bn as Zt,br as Qt,bt as $t,c as en,ca as tn,ci as nn,cn as rn,cr as an,d as on,da as sn,di as cn,dn as ln,dr as un,ea as dn,ei as fn,en as pn,er as mn,et as hn,f as gn,fa as _n,fi as vn,fn as yn,fr as bn,g as xn,ga as Sn,gi as Cn,gn as wn,gr as Tn,gt as En,h as Dn,ha as On,hi as kn,hn as An,hr as jn,ht as Mn,i as Nn,ia as Pn,ii as Fn,in as In,ir as Ln,it as Rn,j as zn,ji as Bn,jn as Vn,jr as Hn,jt as Un,k as Wn,ki as Gn,kn as Kn,kr as qn,kt as Jn,l as Yn,la as Xn,li as Zn,ln as Qn,lr as $n,m as er,ma as tr,mi as nr,mn as rr,mr as ir,mt as ar,n as or,na as sr,ni as cr,nn as lr,nr as ur,nt as dr,o as fr,oa as pr,oi as mr,on as hr,or as gr,ot as _r,p as vr,pa as yr,pi as br,pn as xr,pr as Sr,q as Cr,qi as wr,qn as Tr,qr as Er,qt as Dr,r as Or,ra as kr,ri as Ar,rn as jr,rr as Mr,rt as Nr,s as Pr,sa as Fr,si as Ir,sn as Lr,sr as Rr,st as zr,t as Br,ta as Vr,ti as Hr,tn as Ur,tr as Wr,tt as Gr,u as Kr,ua as qr,ui as Jr,un as Yr,ur as Xr,v as Zr,va as Qr,vi as $r,vn as ei,vr as ti,vt as ni,w as ri,wi as ii,wn as ai,wr as oi,wt as si,x as ci,xa as li,xn as ui,xr as di,xt as fi,y as pi,ya as mi,yi as hi,yn as gi,yr as _i,yt as vi,z as yi,zi as bi,zn as xi,zt as Si}from"./src-DvuwJKkU.mjs";import{C as Ci,E as wi,T as Ti,_ as Ei,b as Di,c as Oi,d as ki,g as Ai,i as ji,l as Mi,m as Ni,n as Pi,p as Fi,s as Ii,t as Li,u as Ri,v as zi,w as Bi,x as Vi,y as Hi}from"./fs-traced-DV9uD41t.mjs";import{a as Ui,d as Wi,f as Gi,i as Ki,l as qi,n as Ji,r as Yi,t as Xi,u as Zi}from"./logger-DFxEUjvj.mjs";import{C as Qi,S as $i,_ as ea,a as ta,c as na,d as ra,g as ia,h as aa,i as oa,l as sa,m as ca,n as la,o as ua,p as da,r as fa,s as pa,t as ma,u as ha,v as ga,y as _a}from"./server-lock-CeKMy65H.mjs";export{tr as AGENT_ID_MAX_LEN,On as AGENT_ID_RE,_ as AGENT_WRITE_ORIGIN,li as AcpPermissionStore,Qr as AcpRegistry,nt as AcpThreadManager,D as AgentFocusBroadcaster,Ze as AgentPresenceBroadcaster,Bn as AgentSessionCapacityError,xe as AgentSessionManager,Mn as AutoStartDisabledError,di as BUNDLE_IDS,$e as BUNDLE_SCOPE,k as BUNDLE_SKILL_NAME,Wr as BacklinkIndex,Q as CC1Broadcaster,l as CC1_CONTRACT_VERSION,An as CONFIG_FILENAME,Ot as CONFLICT_MARKER_RE,lt as CURSOR_BUNDLE_PATHS_BY_PLATFORM,It as ConfigSchema,se as DEFAULT_CHECKPOINT_RETENTION,nn as DEFAULT_EMBEDDINGS_DIMENSIONS,w as DEFAULT_PACK_ID,dt as DocumentDurabilityState,Zn as EMBEDDINGS_API_KEY_ENV,O as ExposureConsentError,mi as FEATURED_AGENT_IDS,Dt as FILE_SYSTEM_WRITER,p as FILE_WATCHER_ORIGIN,cr as FileEmbeddingsBackend,lr as GIT_PREFLIGHT_FAIL_SPAN_NAME,St as GIT_UPSTREAM_WRITER,Xe as GitDirAccessError,In as GitNotAvailableError,Gt as GitTooOldError,En as HOCUSPOCUS_AUTH_REJECTION_REASONS,Vt as HocuspocusAuthRejection,ni as HocuspocusAuthTokenSchema,kt as INSTALLED_AGENTS_SCHEMES,r as LINEAGE_EPOCH_KEY,Ge as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ht as LOG_MD_TEMPLATE,at as MANAGED_RENAME_ORIGIN,L as MAX_ACP_THREADS,Ee as MAX_AGENT_SESSIONS,je as MCP_CONNECTION_ID_HEADER,e as MCP_SERVER_NAME,Ie as MIN_EVICTABLE_IDLE_MS,hr as MIN_GIT_VERSION,Z as MISSING_OK_CONFIG_MESSAGE,E as MalformedGitPointerError,hn as McpLogger,ot as MissingOkConfigError,re as OBSERVER_SYNC_ORIGIN,wn as OK_OKIGNORE_TEMPLATE,s as ORPHAN_MODES,o as PROTOCOL_VERSION,Xi as PinoLogger,na as ProcessLockCollisionError,Yn as ProjectGitInitError,B as ROLLBACK_ORIGIN,zt as ROOT_GITIGNORE_TEMPLATE,ea as RUNTIME_VERSION,Mt as SERVICE_WRITER,Tn as SKILL_INSTALL_EVENTS_FILE_REL,u as SKILL_STATE_TARGETS,te as STARTER_FOLDERS,ut as STARTER_FOLDER_FRONTMATTER_FILENAME,bt as STARTER_PACKS,X as STARTER_PACK_IDS,he as STARTER_TEMPLATES,tt as STATE_MANIFEST_FILENAME,ga as STATE_SCHEMA_VERSION,a as SYSTEM_DOC_NAME,We as SeedPrerequisiteError,h as SeedRootDirError,ma as ServerLockCollisionError,Br as SingleFileNotAFileError,or as SingleFileNotFoundError,Or as SingleFileNotMarkdownError,I as StateManifestError,mn as TagIndex,oi as USER_GLOBAL_BUNDLE_IDS,we as UiLockCollisionError,F as __getShowAllWalkStatsForTesting,Pe as __resetShowAllWalkStatsForTesting,sa as acquireProcessLock,la as acquireServerLock,ke as acquireUiLock,H as applyAgentMarkdownWrite,Tr as applyExternalChange,Si as applySeed,j as assertCompatibleStateManifest,Lr as assertGitAvailable,U as assertNeverDiskEvent,ii as attachAcpThreadSocket,ar as attachIdleShutdown,Zr as bootServer,Mr as buildAndOpenSkill,ei as buildConfigYmlContent,Et as buildExecResult,ai as buildIngressPolicy,M as buildOkMcpStdioCommand,ti as buildSkillZip,Dr as buildStarterFolderFrontmatterYaml,Ve as buildWipTree,it as bundleSkillMdPath,Ar as canonicalProjectKey,ie as classifyEvents,Li as classifyFsPath,Fn as clearAllEmbeddingsKeys,cn as clearContributors,ue as coercePackId,i as colorFromSeed,f as commitUpstreamImport,dn as commitWip,Vr as commitWipFromTree,rn as compareSemver,Ne as composeEffectiveLinterConfig,qn as composeFrontmatterSchemasConfig,Ct as containsConflictMarkers,ve as contentHash,vn as contributorCount,Fe as countShadowObjects,V as countStaleAgentWipRefs,ne as countWipRefs,Jn as createApiExtension,si as createAssetServeMiddleware,K as createCollaborationHost,mt as createContentFilter,ee as createContentFilterAsync,Wt as createEmbeddingsSecretStore,Nn as createEphemeralProjectDir,ce as createExternalChangeHandler,gn as createFileLogger,yi as createLiveDerivedIndexExtension,Cr as createMcpHttpHandler,wt as createOsProbe,Te as createPersistenceExtension,T as createServer,zn as createServerObserverExtension,bi as createStreamingErrorWriter,Ji as createTestLogger,mr as describeStoredEmbeddingsKey,xn as detectClaudeDesktopPresence,Qn as detectGit,Ae as detectProjectShape,Ln as detectUserSkillHosts,Nr as discoverLockDirs,Ce as discoverMarkdownlintConfig,jr as emitPreflightFailureSpan,xt as encodeDocName,jt as encodeFolderRoute,Be as encodeSkillRoute,Kr as ensureProjectGit,gi as ensureProjectSkillGitignore,S as errorResponse,qe as evictStaleTrackerEntries,b as extractHeadings,Rn as extractOkBinaryPath,ur as extractWikiLinksFromMarkdown,Yr as fallbackPaths,on as findEnclosingGitRoot,De as findEnclosingProjectRoot,Oe as findNativeMarkdownlintFile,vr as flushFileLogger,vi as formatAuthRejectionWire,br as formatContributors,nr as formatContributorsFrom,ye as formatPackRationale,sr as gcCheckpointRefs,Gr as getCurrentMcpLogger,rt as getIngressContext,$r as getLocalDir,er as getLogFilePath,Yi as getLogger,Dn as getLogsDir,_a as getMachineId,Hi as getMeter,Xn as getMetrics,Di as getTracer,qr as handleCollabSocketError,yt as handleSpawnCursor,R as hasForwardingHeaders,ge as hasGcLogLatch,n as iconFromClientName,sn as incrementCollabSocketFilteredError,_n as incrementServerObserverFire,Zt as initContent,kr as initShadowRepo,Vi as initTelemetry,Jt as initToleranceTelemetryWriter,zr as installPrettyZodErrors,Ki as installTestLoggers,Kt as installUserSkill,Se as isAllowedApiOrigin,v as isAllowedWorkspaceHostHeader,st as isConfigDoc,$t as isHocuspocusAuthRejectionReason,N as isHostAdmitted,At as isKnownPackId,_t as isLinkIndexExcludedDoc,Vn as isLoopbackAddress,q as isManagedArtifactDoc,Me as isOriginAdmitted,c as isOrphanMode,_e as isPairedWriteOrigin,Y as isPathWithinDir,Kn as isPeerAdmitted,$i as isProcessAlive,Le as isProjectRoot,fe as isReservedForUserTree,xi as isSelfWrite,wr as isSystemDoc,ci as isToleranceTelemetryEnabled,Qi as isValidLockPid,C as lastKnownHash,Pn as listRescueCheckpoints,Tt as listStarterPacks,Yt as loadCustomAgents,be as loadPrincipal,ha as lockBaseUrl,ra as lockFilePath,Ui as loggerFactory,qi as logsCurrentPath,Zi as logsPreviousPath,Ir as makeLazyEmbeddingsKeyStore,fa as markServerLockDraining,gt as mountMcpAndApi,Pi as normalizeFsPath,z as originGitHubHost,ui as packageVersionMajorMinor,fi as parseAuthRejectionWire,ln as parseGitVersion,et as parseHocuspocusAuthToken,de as parseKeepaliveConnectionId,pt as pathToDocName,Je as planSeed,Ht as prepareSingleFileOpen,qt as processCommand,_r as processUsage,Rr as readAllTargets,an as readBundleDecision,Re as readOwnNativeRules,da as readProcessLock,ca as readProcessLockDetailed,x as readProjectHeadState,Hr as readProjectLocalSemanticConfig,oa as readServerLock,$n as readServerPackageVersion,Xr as readSkillInstallStateSnapshot,Wn as readStateManifest,un as readTargetRecordedAt,bn as readTargetVersion,ze as readUiLock,Nt as reconcile,kn as recordContributor,Bt as recordSkillInstallEvent,oe as registerAllTools,$ as registerWrite,aa as releaseProcessLock,ta as releaseServerLock,G as releaseUiLock,ct as removeLastKnownHash,gr as reportSkillInstall,yr as resetMetrics,t as resolveBundleEnabled,_i as resolveBundledSkillDir,hi as resolveContentDir,me as resolveCursorBinaryDefault,Er as resolveCursorSpawnInvocation,y as resolveEffectiveLinterConfig,Jr as resolveEmbeddingsCredential,Xt as resolveLockDir,Hn as resolveNativeConfigForDoc,W as resolveNativeMarkdownlintConfig,Ft as resolvePack,Pr as resolvePackageVersion,jn as resolveSkillInstallReportSettings,d as resolveUiInfo,Cn as restoreContributors,pi as restoreLifecycleFromConflictsJson,m as rewriteMarkdownLinksForDocumentRename,fn as rewriteWikiLinksForDocumentRename,yn as runAuthReposSubprocess,xr as runAuthStatusSubprocess,pn as runCloneSubprocess,rr as runDeviceFlowSubprocess,dr as runWithMcpLogger,Ue as safeContentPath,Un as safeSubdir,Ut as safetyCheckpoint,Gn as sanitizeClientName,pr as saveInMemoryCheckpoint,Fr as saveVersion,A as seedBasenameIndex,fr as serializeError,Ci as setActiveSpanAttributes,Ke as setupServerObservers,tn as shadowGit,Bi as shutdownTelemetry,Wi as spansCurrentPath,Gi as spansPreviousPath,le as spawnDetached,He as splitMarkdownBlocks,vt as startWatcher,ft as streamingProblemEvent,Rt as swapContributors,Ye as teardownToleranceTelemetryWriter,Sn as toBroadcasterKey,ji as tracedAppendFileSync,Ii as tracedLinkSync,Oi as tracedMkdir,Mi as tracedMkdirSync,Ri as tracedRename,ki as tracedRenameSync,Fi as tracedRmSync,Ni as tracedRmdirSync,Ai as tracedUnlinkSync,Ei as tracedWriteFile,zi as tracedWriteFileSync,ri as trustSystemCertificates,en as untrackTrackedProjectSkillProjection,J as updateLastKnownHash,ia as updateProcessLockPort,ua as updateServerLockPort,ae as updateUiLockPort,Lt as validateAgentId,Ur as validateCloneInputs,Qt as validateSkillZip,pa as waitForServerLockDrain,Pt as withHiddenWindowsConsole,Ti as withSpan,wi as withSpanSync,Sr as writeBundleDecision,P as writeMarkdownlintRule,Qe as writeRootGitignoreForNewRepo,g as writeStateManifest,ir as writeTargetVersion,pe as writeTracker};
|
|
1
|
+
import{$o as e,U as t,_ as n,_s as r,h as i,ks as a,nc as o,ns as s,rs as c,ys as l,z as u}from"./src-Dj6UxpKM.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,Bt as w,C as T,Ca 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,Fr as W,Ft as G,G as K,Gi as q,Gn as J,Gr as Y,Gt as X,H as Z,Hi as Q,Hn as $,Hr as ee,Ht as te,I as ne,Ii as re,In as ie,It as ae,J as oe,Ji as se,Jn as ce,Jr as le,Jt as ue,K as de,Ki as fe,Kn as pe,Kr as me,Kt as he,L as ge,Li as _e,Ln as ve,Lt as ye,M as be,Mi as xe,Mn as Se,Mr as Ce,Mt as we,N as Te,Ni as Ee,Nn as De,Nr as Oe,Nt as ke,O as Ae,Oi as je,On as Me,Or as Ne,Ot as Pe,P as Fe,Pi as Ie,Pn as Le,Pr as Re,Pt as ze,Q as Be,Qi as Ve,Qn as He,Qr as Ue,Qt as We,R as Ge,Ri as Ke,Rn as qe,Rt as Je,S as Ye,Sa as Xe,Si as Ze,Sn as Qe,Sr as $e,St as et,T as tt,Ti as nt,Tn as rt,Tr as it,Tt as at,U as ot,Ui as st,Un as ct,Ur as lt,Ut as ut,V as dt,Vi as ft,Vn as pt,Vr as mt,Vt as ht,W as gt,Wi as _t,Wn as vt,Wr as yt,Wt as bt,X as xt,Xi as St,Xn as Ct,Xr as wt,Xt as Tt,Y as Et,Yi as Dt,Yn as Ot,Yr as kt,Yt as At,Z as jt,Zi as Mt,Zn as Nt,Zr as Pt,Zt as Ft,_ as It,_a as Lt,_i as Rt,_n as zt,_r as Bt,_t as Vt,a as Ht,aa as Ut,ai as Wt,an as Gt,ar as Kt,at as qt,b as Jt,ba as Yt,bi as Xt,bn as Zt,br as Qt,bt as $t,c as en,ca as tn,ci as nn,cn as rn,cr as an,d as on,da as sn,di as cn,dn as ln,dr as un,ea as dn,ei as fn,en as pn,er as mn,et as hn,f as gn,fa as _n,fi as vn,fn as yn,fr as bn,g as xn,ga as Sn,gi as Cn,gn as wn,gr as Tn,gt as En,h as Dn,ha as On,hi as kn,hn as An,hr as jn,ht as Mn,i as Nn,ia as Pn,ii as Fn,in as In,ir as Ln,it as Rn,j as zn,ji as Bn,jn as Vn,jr as Hn,jt as Un,k as Wn,ki as Gn,kn as Kn,kr as qn,kt as Jn,l as Yn,la as Xn,li as Zn,ln as Qn,lr as $n,m as er,ma as tr,mi as nr,mn as rr,mr as ir,mt as ar,n as or,na as sr,ni as cr,nn as lr,nr as ur,nt as dr,o as fr,oa as pr,oi as mr,on as hr,or as gr,ot as _r,p as vr,pa as yr,pi as br,pn as xr,pr as Sr,q as Cr,qi as wr,qn as Tr,qr as Er,qt as Dr,r as Or,ra as kr,ri as Ar,rn as jr,rr as Mr,rt as Nr,s as Pr,sa as Fr,si as Ir,sn as Lr,sr as Rr,st as zr,t as Br,ta as Vr,ti as Hr,tn as Ur,tr as Wr,tt as Gr,u as Kr,ua as qr,ui as Jr,un as Yr,ur as Xr,v as Zr,va as Qr,vi as $r,vn as ei,vr as ti,vt as ni,w as ri,wi as ii,wn as ai,wr as oi,wt as si,x as ci,xa as li,xn as ui,xr as di,xt as fi,y as pi,ya as mi,yi as hi,yn as gi,yr as _i,yt as vi,z as yi,zi as bi,zn as xi,zt as Si}from"./src--OhnhRml.mjs";import{C as Ci,E as wi,T as Ti,_ as Ei,b as Di,c as Oi,d as ki,g as Ai,i as ji,l as Mi,m as Ni,n as Pi,p as Fi,s as Ii,t as Li,u as Ri,v as zi,w as Bi,x as Vi,y as Hi}from"./fs-traced-DV9uD41t.mjs";import{a as Ui,d as Wi,f as Gi,i as Ki,l as qi,n as Ji,r as Yi,t as Xi,u as Zi}from"./logger-DFxEUjvj.mjs";import{C as Qi,S as $i,_ as ea,a as ta,c as na,d as ra,g as ia,h as aa,i as oa,l as sa,m as ca,n as la,o as ua,p as da,r as fa,s as pa,t as ma,u as ha,v as ga,y as _a}from"./server-lock-CeKMy65H.mjs";export{tr as AGENT_ID_MAX_LEN,On as AGENT_ID_RE,_ as AGENT_WRITE_ORIGIN,li as AcpPermissionStore,Qr as AcpRegistry,nt as AcpThreadManager,D as AgentFocusBroadcaster,Ze as AgentPresenceBroadcaster,Bn as AgentSessionCapacityError,xe as AgentSessionManager,Mn as AutoStartDisabledError,di as BUNDLE_IDS,$e as BUNDLE_SCOPE,k as BUNDLE_SKILL_NAME,Wr as BacklinkIndex,Q as CC1Broadcaster,l as CC1_CONTRACT_VERSION,An as CONFIG_FILENAME,Ot as CONFLICT_MARKER_RE,lt as CURSOR_BUNDLE_PATHS_BY_PLATFORM,It as ConfigSchema,se as DEFAULT_CHECKPOINT_RETENTION,nn as DEFAULT_EMBEDDINGS_DIMENSIONS,w as DEFAULT_PACK_ID,dt as DocumentDurabilityState,Zn as EMBEDDINGS_API_KEY_ENV,O as ExposureConsentError,mi as FEATURED_AGENT_IDS,Dt as FILE_SYSTEM_WRITER,p as FILE_WATCHER_ORIGIN,cr as FileEmbeddingsBackend,lr as GIT_PREFLIGHT_FAIL_SPAN_NAME,St as GIT_UPSTREAM_WRITER,Xe as GitDirAccessError,In as GitNotAvailableError,Gt as GitTooOldError,En as HOCUSPOCUS_AUTH_REJECTION_REASONS,Vt as HocuspocusAuthRejection,ni as HocuspocusAuthTokenSchema,kt as INSTALLED_AGENTS_SCHEMES,r as LINEAGE_EPOCH_KEY,Ge as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ht as LOG_MD_TEMPLATE,at as MANAGED_RENAME_ORIGIN,L as MAX_ACP_THREADS,Ee as MAX_AGENT_SESSIONS,je as MCP_CONNECTION_ID_HEADER,e as MCP_SERVER_NAME,Ie as MIN_EVICTABLE_IDLE_MS,hr as MIN_GIT_VERSION,Z as MISSING_OK_CONFIG_MESSAGE,E as MalformedGitPointerError,hn as McpLogger,ot as MissingOkConfigError,re as OBSERVER_SYNC_ORIGIN,wn as OK_OKIGNORE_TEMPLATE,s as ORPHAN_MODES,o as PROTOCOL_VERSION,Xi as PinoLogger,na as ProcessLockCollisionError,Yn as ProjectGitInitError,B as ROLLBACK_ORIGIN,zt as ROOT_GITIGNORE_TEMPLATE,ea as RUNTIME_VERSION,Mt as SERVICE_WRITER,Tn as SKILL_INSTALL_EVENTS_FILE_REL,u as SKILL_STATE_TARGETS,te as STARTER_FOLDERS,ut as STARTER_FOLDER_FRONTMATTER_FILENAME,bt as STARTER_PACKS,X as STARTER_PACK_IDS,he as STARTER_TEMPLATES,tt as STATE_MANIFEST_FILENAME,ga as STATE_SCHEMA_VERSION,a as SYSTEM_DOC_NAME,We as SeedPrerequisiteError,h as SeedRootDirError,ma as ServerLockCollisionError,Br as SingleFileNotAFileError,or as SingleFileNotFoundError,Or as SingleFileNotMarkdownError,I as StateManifestError,mn as TagIndex,oi as USER_GLOBAL_BUNDLE_IDS,we as UiLockCollisionError,F as __getShowAllWalkStatsForTesting,Pe as __resetShowAllWalkStatsForTesting,sa as acquireProcessLock,la as acquireServerLock,ke as acquireUiLock,H as applyAgentMarkdownWrite,Tr as applyExternalChange,Si as applySeed,j as assertCompatibleStateManifest,Lr as assertGitAvailable,U as assertNeverDiskEvent,ii as attachAcpThreadSocket,ar as attachIdleShutdown,Zr as bootServer,Mr as buildAndOpenSkill,ei as buildConfigYmlContent,Et as buildExecResult,ai as buildIngressPolicy,M as buildOkMcpStdioCommand,ti as buildSkillZip,Dr as buildStarterFolderFrontmatterYaml,Ve as buildWipTree,it as bundleSkillMdPath,Ar as canonicalProjectKey,ie as classifyEvents,Li as classifyFsPath,Fn as clearAllEmbeddingsKeys,cn as clearContributors,ue as coercePackId,i as colorFromSeed,f as commitUpstreamImport,dn as commitWip,Vr as commitWipFromTree,rn as compareSemver,Ne as composeEffectiveLinterConfig,qn as composeFrontmatterSchemasConfig,Ct as containsConflictMarkers,ve as contentHash,vn as contributorCount,Fe as countShadowObjects,V as countStaleAgentWipRefs,ne as countWipRefs,Jn as createApiExtension,si as createAssetServeMiddleware,K as createCollaborationHost,mt as createContentFilter,ee as createContentFilterAsync,Wt as createEmbeddingsSecretStore,Nn as createEphemeralProjectDir,ce as createExternalChangeHandler,gn as createFileLogger,yi as createLiveDerivedIndexExtension,Cr as createMcpHttpHandler,wt as createOsProbe,Te as createPersistenceExtension,T as createServer,zn as createServerObserverExtension,bi as createStreamingErrorWriter,Ji as createTestLogger,mr as describeStoredEmbeddingsKey,xn as detectClaudeDesktopPresence,Qn as detectGit,Ae as detectProjectShape,Ln as detectUserSkillHosts,Nr as discoverLockDirs,Ce as discoverMarkdownlintConfig,jr as emitPreflightFailureSpan,xt as encodeDocName,jt as encodeFolderRoute,Be as encodeSkillRoute,Kr as ensureProjectGit,gi as ensureProjectSkillGitignore,S as errorResponse,qe as evictStaleTrackerEntries,b as extractHeadings,Rn as extractOkBinaryPath,ur as extractWikiLinksFromMarkdown,Yr as fallbackPaths,on as findEnclosingGitRoot,De as findEnclosingProjectRoot,Oe as findNativeMarkdownlintFile,vr as flushFileLogger,vi as formatAuthRejectionWire,br as formatContributors,nr as formatContributorsFrom,ye as formatPackRationale,sr as gcCheckpointRefs,Gr as getCurrentMcpLogger,rt as getIngressContext,$r as getLocalDir,er as getLogFilePath,Yi as getLogger,Dn as getLogsDir,_a as getMachineId,Hi as getMeter,Xn as getMetrics,Di as getTracer,qr as handleCollabSocketError,yt as handleSpawnCursor,R as hasForwardingHeaders,ge as hasGcLogLatch,n as iconFromClientName,sn as incrementCollabSocketFilteredError,_n as incrementServerObserverFire,Zt as initContent,kr as initShadowRepo,Vi as initTelemetry,Jt as initToleranceTelemetryWriter,zr as installPrettyZodErrors,Ki as installTestLoggers,Kt as installUserSkill,Se as isAllowedApiOrigin,v as isAllowedWorkspaceHostHeader,st as isConfigDoc,$t as isHocuspocusAuthRejectionReason,N as isHostAdmitted,At as isKnownPackId,_t as isLinkIndexExcludedDoc,Vn as isLoopbackAddress,q as isManagedArtifactDoc,Me as isOriginAdmitted,c as isOrphanMode,_e as isPairedWriteOrigin,Y as isPathWithinDir,Kn as isPeerAdmitted,$i as isProcessAlive,Le as isProjectRoot,fe as isReservedForUserTree,xi as isSelfWrite,wr as isSystemDoc,ci as isToleranceTelemetryEnabled,Qi as isValidLockPid,C as lastKnownHash,Pn as listRescueCheckpoints,Tt as listStarterPacks,Yt as loadCustomAgents,be as loadPrincipal,ha as lockBaseUrl,ra as lockFilePath,Ui as loggerFactory,qi as logsCurrentPath,Zi as logsPreviousPath,Ir as makeLazyEmbeddingsKeyStore,fa as markServerLockDraining,gt as mountMcpAndApi,Pi as normalizeFsPath,z as originGitHubHost,ui as packageVersionMajorMinor,fi as parseAuthRejectionWire,ln as parseGitVersion,et as parseHocuspocusAuthToken,de as parseKeepaliveConnectionId,pt as pathToDocName,Je as planSeed,Ht as prepareSingleFileOpen,qt as processCommand,_r as processUsage,Rr as readAllTargets,an as readBundleDecision,Re as readOwnNativeRules,da as readProcessLock,ca as readProcessLockDetailed,x as readProjectHeadState,Hr as readProjectLocalSemanticConfig,oa as readServerLock,$n as readServerPackageVersion,Xr as readSkillInstallStateSnapshot,Wn as readStateManifest,un as readTargetRecordedAt,bn as readTargetVersion,ze as readUiLock,Nt as reconcile,kn as recordContributor,Bt as recordSkillInstallEvent,oe as registerAllTools,$ as registerWrite,aa as releaseProcessLock,ta as releaseServerLock,G as releaseUiLock,ct as removeLastKnownHash,gr as reportSkillInstall,yr as resetMetrics,t as resolveBundleEnabled,_i as resolveBundledSkillDir,hi as resolveContentDir,me as resolveCursorBinaryDefault,Er as resolveCursorSpawnInvocation,y as resolveEffectiveLinterConfig,Jr as resolveEmbeddingsCredential,Xt as resolveLockDir,Hn as resolveNativeConfigForDoc,W as resolveNativeMarkdownlintConfig,Ft as resolvePack,Pr as resolvePackageVersion,jn as resolveSkillInstallReportSettings,d as resolveUiInfo,Cn as restoreContributors,pi as restoreLifecycleFromConflictsJson,m as rewriteMarkdownLinksForDocumentRename,fn as rewriteWikiLinksForDocumentRename,yn as runAuthReposSubprocess,xr as runAuthStatusSubprocess,pn as runCloneSubprocess,rr as runDeviceFlowSubprocess,dr as runWithMcpLogger,Ue as safeContentPath,Un as safeSubdir,Ut as safetyCheckpoint,Gn as sanitizeClientName,pr as saveInMemoryCheckpoint,Fr as saveVersion,A as seedBasenameIndex,fr as serializeError,Ci as setActiveSpanAttributes,Ke as setupServerObservers,tn as shadowGit,Bi as shutdownTelemetry,Wi as spansCurrentPath,Gi as spansPreviousPath,le as spawnDetached,He as splitMarkdownBlocks,vt as startWatcher,ft as streamingProblemEvent,Rt as swapContributors,Ye as teardownToleranceTelemetryWriter,Sn as toBroadcasterKey,ji as tracedAppendFileSync,Ii as tracedLinkSync,Oi as tracedMkdir,Mi as tracedMkdirSync,Ri as tracedRename,ki as tracedRenameSync,Fi as tracedRmSync,Ni as tracedRmdirSync,Ai as tracedUnlinkSync,Ei as tracedWriteFile,zi as tracedWriteFileSync,ri as trustSystemCertificates,en as untrackTrackedProjectSkillProjection,J as updateLastKnownHash,ia as updateProcessLockPort,ua as updateServerLockPort,ae as updateUiLockPort,Lt as validateAgentId,Ur as validateCloneInputs,Qt as validateSkillZip,pa as waitForServerLockDrain,Pt as withHiddenWindowsConsole,Ti as withSpan,wi as withSpanSync,Sr as writeBundleDecision,P as writeMarkdownlintRule,Qe as writeRootGitignoreForNewRepo,g as writeStateManifest,ir as writeTargetVersion,pe as writeTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./src-Dj6UxpKM.mjs";import"./write-project-skill-B4M4CzQe.mjs";import"./src-D-aeKj3b.mjs";import"./acp-harness-probe-3JkYEtle.mjs";import"./init-BphshJ0S.mjs";import{n as e}from"./loader-D2I7_Rs6.mjs";import"./skill-teardown-CybJJo-5.mjs";import"./preview-Bnzh6BEb.mjs";import"./mcp-migrate-event-B1gJf6bG.mjs";export{e as loadConfig};
|