@inkeep/open-knowledge 0.78.0-beta.0 → 0.78.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-CqnSfysY.mjs +1 -0
- package/dist/{dist-DrwvV8ac.mjs → dist-D0NB38wf.mjs} +1 -1
- package/dist/{dist--Fj3tje5.mjs → dist-H727Mac0.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-DI1gfxzX.mjs → init-C0ht_YRB.mjs} +2 -2
- package/dist/init-Dmfw9165.mjs +1 -0
- package/dist/{launch-json-removal-BUU52XaH.mjs → launch-json-removal-BayfH9oD.mjs} +1 -1
- package/dist/loader-BaY7osJS.mjs +1 -0
- package/dist/{loader-Y0pjcUKl.mjs → loader-BwEW4OHx.mjs} +1 -1
- package/dist/{open-browser-Qoh0UyYo.mjs → open-browser-BnVmN9HA.mjs} +1 -1
- package/dist/{preview-kp3tgpeK.mjs → preview-CJ4lC6m4.mjs} +1 -1
- package/dist/preview-rn0piPQ2.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-9eG8YBKX.js → ActivityModeContent-By3_IMI2.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-CygNgwxc.js → AddPropertiesButton-Ds4lHG87.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CFiM8xEM.js → AgentDiffPane-D9SHwzkL.js} +1 -1
- package/dist/public/assets/{AgentIconCluster-HL0VW7ex.js → AgentIconCluster-D4c5FBAw.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-DfpeZqHy.js → AgentThreadClientBinder-B_EgL186.js} +1 -1
- package/dist/public/assets/{ConfigSharingInfoTooltip-DTnyEAkk.js → ConfigSharingInfoTooltip-cmnGMRyM.js} +1 -1
- package/dist/public/assets/{ConsentDialogBody-xByJh_yy.js → ConsentDialogBody-BqIjS2gR.js} +1 -1
- package/dist/public/assets/{DocumentContext-C7SiRLQb.js → DocumentContext-C3MFq3ua.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CjygF6yK.js → EditorModeToggle-BeTnxhxA.js} +1 -1
- package/dist/public/assets/FeedbackForm-CchQrgi0.js +1 -0
- package/dist/public/assets/{GraphPanel-PUtu-HoI.js → GraphPanel-D5xZaXcb.js} +1 -1
- package/dist/public/assets/{ImageAttachments-BY2Tiper.js → ImageAttachments-DJgsccSw.js} +1 -1
- package/dist/public/assets/{ImportSkillDialog-0B5W-rTi.js → ImportSkillDialog-BuL9v-6W.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-2RE7lwuU.js → LintConfigEditor-bFtZkDDa.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-DqjUJDga.js → ManagedArtifactProperties-BogBt9Ik.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DrztV163.js +1 -0
- package/dist/public/assets/{PropertyDisplayRow-CDDGu8nj.js → PropertyDisplayRow-CIz5E76a.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-BVloizGt.js → ReportBugDialogBody-BdLhyQ-4.js} +1 -1
- package/dist/public/assets/{ReportBugMenuTrigger-XGUcCKYj.js → ReportBugMenuTrigger-BTrSdrQf.js} +2 -2
- package/dist/public/assets/{SchemaConfigEditor-HLOCQnGt.js → SchemaConfigEditor-CfZbORWL.js} +1 -1
- package/dist/public/assets/SessionsHost-m1vUsJgF.js +2 -0
- package/dist/public/assets/{SettingsDialogBody-CbiPCUKo.js → SettingsDialogBody-D_GVq8_Z.js} +1 -1
- package/dist/public/assets/{SkillCostValue-VNM6buqE.js → SkillCostValue-BjMa_RzW.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-DTKc6Fb2.js → SkillInstallMenu-cLslx-4M.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-B9szZlfW.js → SkillOriginInline-ghHkXApt.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-CiUk7ClP.js → SkillToolbarControls-S5KMiPEx.js} +1 -1
- package/dist/public/assets/{SlidesToolbarControls-CXtA7p5I.js → SlidesToolbarControls-DgebeZ1o.js} +1 -1
- package/dist/public/assets/{SourceEditor-5m-rKk0W.js → SourceEditor-wsG_saIm.js} +1 -1
- package/dist/public/assets/{TerminalPanel-BKJLHAK8.js → TerminalPanel-B72jSABs.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DG1kmrG5.js → TerminalWindowApp-CqFoMmN8.js} +1 -1
- package/dist/public/assets/ThreadView-DK8pgUsH.js +21 -0
- package/dist/public/assets/{TimelineDiffPane-C2wFbjXz.js → TimelineDiffPane-4ZOOyITN.js} +1 -1
- package/dist/public/assets/{agent-connection-status-DRTKkkhz.js → agent-connection-status-BpmHdteI.js} +1 -1
- package/dist/public/assets/{auth-state-cache-DlDU-uGh.js → auth-state-cache-B3gDmMGR.js} +1 -1
- package/dist/public/assets/{comment-chips-h2R6X8ZK.js → comment-chips-C2qbaCxd.js} +1 -1
- package/dist/public/assets/{index-CcD0riyO.js → index-Dg8USqVa.js} +7 -7
- package/dist/public/assets/launch-agent-thread--2IQ94Jw.js +1 -0
- package/dist/public/assets/{markdownlint-rule-browser-CrVGD-9N.js → markdownlint-rule-browser-Deli4eWi.js} +1 -1
- package/dist/public/assets/{preferred-session-events-aK8uTZkY.js → preferred-session-events-BRTAOH0T.js} +1 -1
- package/dist/public/assets/progress-BUZ09BFV.js +10 -0
- package/dist/public/assets/{project-paths-BTqSbaer.js → project-paths-C72_JOWy.js} +1 -1
- package/dist/public/assets/{select-ByJwKu6h.js → select-D_BhUvh8.js} +1 -1
- package/dist/public/assets/{selection-context-CzFcwgS3.js → selection-context-Bh3Wccul.js} +1 -1
- package/dist/public/assets/{tag-pill-input-MxBCbORt.js → tag-pill-input-Bs1Otf32.js} +1 -1
- package/dist/public/assets/thread-client-Cpl5iQ-N.js +3 -0
- package/dist/public/assets/{tooltip-BnyyQDRs.js → tooltip-DVBVVaAs.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Djy23xa6.js → typing-burst-detector-BsYaC0Hm.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BiJM5Lyy.js → use-activity-panel-C3WeDBAl.js} +1 -1
- package/dist/public/assets/{use-open-skill-CvMMiXmv.js → use-open-skill-MLwbsxuR.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CHwFHTJT.js → use-timeline-entry-diff-CoUYWVFF.js} +1 -1
- package/dist/public/index.html +23 -23
- package/dist/{registry-probes-BEL6kY2a.mjs → registry-probes-Trc22gkn.mjs} +1 -1
- package/dist/{removal-file-path-tAXTvjxX.mjs → removal-file-path-BJLJdU25.mjs} +1 -1
- package/dist/{repair-launch-json-D5502WRP.mjs → repair-launch-json-Dy1MyLSZ.mjs} +1 -1
- package/dist/{repair-mcp-configs-DI9LEPQs.mjs → repair-mcp-configs-xBQEG0AX.mjs} +1 -1
- package/dist/{src-DEL9l4YA.mjs → src-CI2gZlGL.mjs} +1 -1
- package/dist/src-DdAWkvJ7.mjs +1 -0
- package/dist/start-CyNiscGq.mjs +1 -0
- package/dist/{start-BFSCPRdk.mjs → start-DvYJMlYp.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-Dx41km5O.mjs +0 -1
- package/dist/init-nKepqoOu.mjs +0 -1
- package/dist/loader-2RC3eI_T.mjs +0 -1
- package/dist/preview-CxIkF9m4.mjs +0 -1
- package/dist/public/assets/FeedbackForm-CRF733qz.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-D9GiE7xi.js +0 -1
- package/dist/public/assets/SessionsHost-BLdclyM0.js +0 -2
- package/dist/public/assets/ThreadView-Dwdgs8fd.js +0 -21
- package/dist/public/assets/launch-agent-thread-LhwTEmF8.js +0 -1
- package/dist/public/assets/progress-BoD5XUOb.js +0 -9
- package/dist/public/assets/thread-client-shDMogrR.js +0 -3
- package/dist/src-BmFQC4vg.mjs +0 -1
- package/dist/start-itGfoXph.mjs +0 -1
|
@@ -952,7 +952,7 @@ ${uJ.join(`
|
|
|
952
952
|
`)}\n\n`)}const B$=new Map;function BQe(e,t){let n=RQe(e),r=zQe(t),i=(B$.get(n)??Promise.resolve()).then(async()=>{let e=await cc(n).then(e=>e.size,()=>void 0);ve(e)===`w`?await ZK(n,r):await QK(n,r)}),a=i.then(()=>void 0,()=>void 0);return B$.set(n,a),a.then(()=>{B$.get(n)===a&&B$.delete(n)}),i}const V$=`v24.18.0`,H$=`0.11.28`,VQe=`https://nodejs.org/dist`,HQe=`https://github.com/astral-sh/uv/releases/download`,UQe={node:45,uv:20};function WQe(e){return e===`npx`?`node`:`uv`}function U$(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:V$,approxSizeMB:UQe.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:H$,approxSizeMB:UQe.uv,sourceHost:`github.com/astral-sh`}}function GQe(){return H(Xs(),`.ok`)}function W$(){return H(GQe(),`runtimes`)}function G$(e){return e===`node`?V$:H$}function KQe(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function qQe(){let e=Qs(),t=Ys(),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-${V$}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${VQe}/${V$}/${a}`,checksumUrl:`${VQe}/${V$}/SHASUMS256.txt`,archiveName:a,isZip:i}}function JQe(){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`}[`${Qs()}-${Ys()}`];if(e===void 0)return null;let t=Qs()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${HQe}/${H$}/${n}`,checksumUrl:`${HQe}/${H$}/${n}.sha256`,archiveName:n,isZip:t}}function YQe(e){return e===`node`?qQe():JQe()}function XQe(e){return YQe(e)!==null}async function ZQe(e){try{let t=await cc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await ec(e,tc.X_OK),!0)}catch{return!1}}async function K$(e,t,n){let r;try{r=await ac(e,{withFileTypes:!0})}catch{return null}for(let n of r)if((n.isFile()||n.isSymbolicLink())&&t.includes(n.name))return H(e,n.name);if(n<=0)return null;for(let i of r)if(i.isDirectory()){let r=await K$(H(e,i.name),t,n-1);if(r!==null)return r}return null}function QQe(e,t,n){let r=V(t),i=H(n,`cache`,e);return e===`node`?{kind:`node`,binDir:r,npxBin:t,cacheDir:i}:{kind:`uv`,binDir:r,uvxBin:t,cacheDir:i}}async function $Qe(e,t=W$()){let n=H(t,e,u$(G$(e)));try{if(!(await cc(n)).isDirectory())return null}catch{return null}let r=await K$(n,KQe(e),3);return r===null||!await ZQe(r)?null:QQe(e,r,t)}var q$=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function e$e(e,t,n=W$()){await y$(H(n,e),t,`[managed-runtime]`)}async function t$e(e,t,n=W$()){let r=H(n,e,u$(G$(e))),i=H(V(r),`.install-damaged-${u$(G$(e))}-${mc()}`);try{await eq(r,i)}catch(n){return n.code===`ENOENT`||(t.warn({err:n,kind:e,versionDir:r},`[managed-runtime] could not quarantine damaged runtime`),!1)}return t.info({kind:e,versionDir:r},`[managed-runtime] quarantined damaged runtime`),await $K(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function n$e(e,t,n={}){let r=n.root??W$(),i=H(r,e,u$(G$(e)));try{return await b$({versionDir:i,stagingLabel:u$(G$(e)),findInstalled:()=>$Qe(e,r),prepare:async r=>{let i=YQe(e);if(i===null)throw new q$(`no ${e} build for ${Qs()}-${Ys()}`);let a=H(r,i.archiveName);t.info({kind:e,version:G$(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let[o,s]=await Promise.all([dZe(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),fZe(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=pZe(s,i.archiveName);if(c===null)throw new q$(`no published checksum for ${i.archiveName}`);if(o!==c)throw new q$(`checksum mismatch for ${i.archiveName}: got ${o}, expected ${c}`);let l=H(r,`extracted`);await tq(l,{recursive:!0}),await uZe(a,l,i.isZip);let u=await K$(l,KQe(e),3);if(u===null||!l$(l,u))throw new q$(`extracted ${e} archive has no usable launcher`);return l},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:G$(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof q$?t:new q$(`installing ${e} ${G$(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const r$e=`CODEX_CONFIG`;function i$e(e,t){if(!Number.isFinite(e)||e<=0)return 0;let n=t.maxContextWindow??e,r=Math.min(Math.floor(e),n),i=t.effectivePercent??95;return Math.floor(r*i/100)}function a$e(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function o$e(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function s$e(e){if(e===void 0||e.trim()===``)return{};try{return o$e(JSON.parse(e))}catch{return{}}}function c$e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...s$e(e[r$e]),model_context_window:Math.floor(t)};return{...e,[r$e]:JSON.stringify(n)}}function l$e(e){return(e.visibility??`list`)===`list`}const u$e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function J$(e){return u$e[e]??`none`}function d$e(e,t,n){if(n===null||J$(t)!==`codex-config-env`)return e;let r=c$e(e.env,n);return r===e.env?e:{...e,env:r}}function f$e(e){return J$(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function Y$(e,t,n={}){iq(t,{recursive:!0});for(let r of Bs(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);Gs(i).isDirectory()?Y$(i,a,n):nq(a,K(i))}}const p$e=`open-knowledge`,m$e=`SKILL.md`,X$=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function h$e(e){return H(e,`agent-skill`,p$e)}function g$e(e,t){let n;try{n=K(t)}catch(e){let t=e.code;if(t!==void 0&&X$.has(t))return!1;throw e}return K(e).equals(n)}function _$e(e,t){let n=Bs(e),r;try{r=new Set(Bs(t))}catch(e){let t=e.code;if(t!==void 0&&X$.has(t))return!1;throw e}if(n.length!==r.size)return!1;for(let i of n){if(!r.has(i))return!1;let n=H(e,i),a=H(t,i);if(Gs(n).isDirectory()){let e;try{e=Gs(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&X$.has(t))return!1;throw e}if(!e||!_$e(n,a))return!1}else if(!g$e(n,a))return!1}return!0}var v$e=class extends Error{path;constructor(e){super(`refusing to stage the project skill through a symlink at ${e}`),this.name=`ProjectSkillSymlinkError`,this.path=e}};async function y$e(e){let t;try{t=await nc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new v$e(e)}async function b$e(e){let t=h$e(e.localDir),n=V(t),r=async()=>{await y$e(n),await y$e(t)};return b$({versionDir:t,stagingLabel:p$e,findInstalled:async()=>(await r(),_$e(e.sourceDir,t)?t:null),prepare:async t=>(Y$(e.sourceDir,t),t),log:e.log,logPrefix:`[acp-threads]`,logContext:e.logContext??{},installedMessage:`project skill staged`,missingAfterCommitMessage:`project skill missing after the staging commit`})}const x$e=2e3;function S$e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function C$e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:S$e(n.subarray(n.length-t)).toString(`utf8`)}function Z$(e){if(e.outputBytes<=e.byteLimit)return;let t=S$e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var w$e=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=GZe(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:ys(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?P$(e.command,j$(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?F$(o,e.args??[]):{cmd:o,args:e.args??[]},u=ps(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 Z$(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 z$(t.child,{graceMs:x$e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await z$(t.child,{graceMs:x$e}),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=S$(e);return this.loginShellPath===null||C$(e)?t:E$(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?Z$(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=C$e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,Z$(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 T$e=`threads`;var E$e=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=H(e.primaryDir,T$e),this.legacyThreadsDir=e.legacyDir==null?null:H(e.legacyDir,T$e),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 tq(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 tq(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 H(this.threadsDirFor(e),`${e}.ndjson`)}metaPath(e){return H(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(`
|
|
953
953
|
`)}\n`;this.enqueue(e,async()=>{if(!this.appendBroken.has(e))try{await QK(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 ZK(r,n),await eq(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await $K(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 k$e(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 ac(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=H(e,a),o;try{o=JSON.parse(await ic(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}typeof o.sessionId!=`string`&&o.sessionId!==null&&(this.log.warn({path:i,invalidSessionId:o.sessionId},`[acp-persist] thread meta has no usable session id; keeping the transcript as unresumable`),o.sessionId=null);let s=o.contextWindow;s!=null&&(typeof s!=`number`||!Number.isFinite(s)||s<=0)&&(this.log.warn({path:i,invalidContextWindow:s},`[acp-persist] thread meta has an unusable context window; relaunching on the agent default`),o.contextWindow=null);let c=o,l=c.info.threadId;r.has(l)||(t===null||await k$e(c.cwd)===t)&&(r.add(l),this.homeByThread.has(l)||this.homeByThread.set(l,e),n.push(c))}}async resolveEventLog(e){let t=this.eventsPath(e);if(!G(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||!G(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(O$e(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=>$K(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=Ms(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=cae({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 D$e(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function D$e(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 O$e(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function k$e(e){try{return await oc(e)}catch{return W(e)}}const A$e=RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b(?:[\\s,:;!.\\-–—]+|$)`,`i`),j$e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,M$e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function N$e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function P$e(e){return(e.trim().split(`
|
|
954
954
|
`)[0]??``).trim()}function Q$(e){let t=P$e(e);if(t.length<=48)return t;let n=t.slice(0,47),r=n.lastIndexOf(` `);return`${(r>=24?n.slice(0,r):n).trimEnd()}…`}function F$e(e,t){let n=P$e(e),r=n.replace(j$e,``);if(t!==void 0&&t.trim()!==``){let e=N$e(t.trim()),n=String.raw`[,:;!.?\-–—•|]`,i=RegExp(`^(?:@${e}\\b(?:\\s+|${n}+(?:\\s+|$)|$)|${e}\\b\\s*${n}+(?:\\s+|$)|@?${e}\\b$)`,`i`);r=r.replace(i,``)}for(let e=0;e<6;e++){let e=r.replace(A$e,``);if(e===r)break;r=e}r=r.replace(M$e,``).trim();let i=r.split(/\s+/).filter(e=>e!==``).length;return!(r!==``&&(i>=2||r.length>=12))||r===n?Q$(n):Q$(r.charAt(0).toUpperCase()+r.slice(1))}const I$e=8,L$e=5e3,$$=3e5,e1=45e3,R$e=5e3,z$e=2e3,B$e=`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.`;function V$e(e){if(e===null)return B$e;let t=e.inline===!0?"This project uses OpenKnowledge. Its agent skill (SKILL.md) is attached to this message. Follow it before editing any markdown here; it overrides generic markdown habits. If you already have the `open-knowledge` skill loaded, skip it.":`This project uses OpenKnowledge. Its agent skill is at \`${e.skillPath}\`. Read it before editing any markdown here; it overrides generic markdown habits, and you may read its \`references/\` files by path when it points to them. If you already have the \`open-knowledge\` skill loaded, skip the read.`;return`${B$e}\n\n${t}`}const H$e=new Set([`gemini`]);function U$e(e){return e.source===`registry`&&H$e.has(e.id)}function W$e(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:Es(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${m$e} ---\n${t}\n--- End skill ---`}}var t1=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},n1=class extends x${refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},G$e=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},K$e=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function q$e(){return new t1(`not-ready`,`the thread was restarted during the sign-in`)}function J$e(e){return e.source===`registry`&&QG[e.id]===`pi`}function Y$e(e,t,n){let[r=`open-knowledge`,...i]=e&&e.length>0?e:[`open-knowledge`],a=[...i,`mcp`,`--port`,String(t)];if(r.includes(`/`)||r.includes(`\\`))return{command:r,args:a};let o=(n?.resolveCommand??(e=>o$(e,WZe())))(r);return o===null?(n?.log?.warn({command:r},`[acp-threads] OK MCP stdio command did not resolve on PATH — injecting the bare name, which fails for harnesses that spawn MCP children under a minimal PATH`),{command:r,args:a}):{command:o,args:a}}var X$e=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;turnStallMs;persistence;npxCacheClears=new Map;resolveLoginShellPath;healthyInterpreters=new Set;projectSkillStaging=null;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>v$(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.turnStallMs=e.turnStallMs??18e4,this.persistence=new E$e({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,Q$e(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);n({op:`subscribed`,threadId:e,fromSeq:i,info:{...r.info}});let 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()=>{try{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}catch(t){throw e.logResolution=null,this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] durable log resolution failed`),t}})(),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 t1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(await _K({site:`acp-thread`,agentId:n===null?$e(t.id)??t.id:t.id,mode:`acp`,log:this.opts.log,snapshot:this.opts.hostSnapshot}),this.destroyed)throw new t1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`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:`spawning`,createdAt:i,lastActivityAt:i,promptCapabilities:null,modes:null,configOptions:null,availableCommands:null,lastSeq:-1,archived:!1,resumable:!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,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:i,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint,envNotePending:!1,projectSkill:null,chatGrants:new Set};return this.threads.set(r,a),this.emitStatus(a,`spawning`),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 iK(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new t1(`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 t1(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new t1(`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 stageProjectSkillFor(e){let t=this.opts.projectSkillSourceDir;if(t===null)return null;let n={threadId:e.info.threadId,agentId:e.info.agent.id},r;try{this.projectSkillStaging??=b$e({localDir:this.opts.localDir,sourceDir:t??t$(`project`,{checkDesktop:!1}),log:this.opts.log,logContext:{localDir:this.opts.localDir}}).finally(()=>{this.projectSkillStaging=null}),r=await this.projectSkillStaging}catch(e){return this.opts.log.warn({err:e,...n},`[acp-threads] skill staging failed`),null}l$(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,m$e);if(!U$e(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await ic(i,`utf8`)}}catch(e){return this.opts.log.warn({err:e,...n,skillPath:i},`[acp-threads] skill inline read failed; skipping skill delivery`),null}}async connectAgent(e,t,n=`reuse`,r,i=`available`){let a;if(t!==null)a=await this.ensureLaunchable(e,uQe(t),r);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new t1(`unknown-agent`,`agent vanished`);a=await KZe(t,tK(),this.opts.log,void 0,t=>this.ensureLaunchable(e,t,r),{reacquire:n===`reacquire`,onProbeStart:()=>this.emitStatus(e,`installing`),onResolved:({acquired:t,outcome:n,source:r,elapsedMs:i})=>this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,package:t,outcome:n,source:r,elapsedMs:i},`[acp-threads] agent package acquired`)})}if(a===null||e.closed)return null;let o=await this.resolveLoginShellPath().catch(()=>null);if(e.closed||(e.projectSkill=await this.stageProjectSkillFor(e),e.closed))return null;let s=new w$e({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:o});a=d$e(a,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let c=a.kind===`npx`?I$(a):I$(a,e.cwd);e.child=c,e.terminals=s;let l=new Promise(e=>c.once(`close`,()=>e())),u,d=()=>c.exitCode===null&&c.signalCode===null&&c.stdout?.readableEnded!==!0&&c.stdout?.destroyed!==!0?Promise.resolve():(u??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),l.then(()=>{clearTimeout(t),e()})}),u);e.drainStderr=d;let f=``,p=``,m=!0,h=bZe(t=>{m&&(f=`${f}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())},e=>{m&&(p=`${p}${e}\n`.slice(-16e3))}),g=a.kind,_=!1,v=()=>g===`npx`&&m&&i===`available`&&eQe(p)!==null,y=()=>_||v();if(c.stderr?.setEncoding(`utf8`),c.stderr?.on(`data`,h.write),c.stderr?.on(`end`,h.end),c.stderr?.on(`data`,t=>{for(let n of t.split(`
|
|
955
|
-
`))n.trim()!==``&&e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e))}),c.on(`error`,t=>{y()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),c.on(`exit`,(t,n)=>{e.child===c&&(e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),s.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),c1(e).then(r=>{if(e.terminals!==s||s1(e)||y())return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let i=`agent exited (${n??t??`unknown`})`;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:r},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,l1({primary:i,tail:r})),this.failPendingPermissions(e)}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] exit diagnostics failed`)}))}),c.stdin===null||c.stdout===null)throw new t1(`spawn-failed`,`agent process has no stdio`);let b=Dbe(dc.toWeb(c.stdin),uc.toWeb(c.stdout)),x=txe({name:`open-knowledge`}).onRequest(BC.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(BC.client.fs.readTextFile,async t=>{this.touchTurnActivity(e);try{return await this.handleFsRead(t.params.path,t.params.line??null,t.params.limit??null)}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file read failed`),n}}).onRequest(BC.client.fs.writeTextFile,async t=>{try{return await this.handleFsWrite(e,t.params.path,t.params.content),{}}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file write failed`),n}}).onRequest(BC.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(BC.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(BC.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(BC.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(BC.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(BC.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(b);e.conn=x,x.closed.then(async()=>{await d(),!(e.conn!==x||y())&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},async t=>{await d(),!(e.conn!==x||y())&&(this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`))});let S;try{S=await x.agent.request(BC.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:c$},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(o){if(this.opts.log.warn({err:o,threadId:e.info.threadId},`[acp-threads] initialize failed`),a.kind===`npx`||a.kind===`uvx`){await d();let e=XZe(a,f,o);if(e!==null)throw e}let s=g===`npx`&&i===`available`?eQe(p):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,s))return _=!0,this.connectAgent(e,t,n,r,`spent`);throw new t1(`spawn-failed`,`initialize failed: ${i1(o)}`)}finally{m=!1,f=``,p=``}return e.closed?null:(e.lastInit=S,e.info.promptCapabilities=S.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:x,init:S,launch:a})}async clearStaleNpxCacheEntry(e,t){let n={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:p$(t)},r=this.npxCacheClears.get(t);if(r!==void 0&&Date.now()-r<3e5)return this.opts.log.warn(n,`[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again`),await this.discardFailedLaunch(e),!s1(e);let i=Date.now();this.npxCacheClears.set(t,i);let a=()=>{this.npxCacheClears.get(t)===i&&this.npxCacheClears.delete(t)};for(let e of[`package.json`,`concurrency.lock`]){let r=await cc(H(t,e)).then(()=>`present`,e=>e.code??`unknown`);if(r!==`ENOENT`)return this.opts.log.warn({...n,file:e,code:r},`[acp-threads] leaving an npx cache entry alone`),a(),!1}try{await $K(t,{recursive:!0,force:!0})}catch(e){return this.opts.log.warn({err:e,...n},`[acp-threads] stale npx cache entry could not be cleared`),a(),!1}return this.opts.log.warn(n,`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),!s1(e)}async discardFailedLaunch(e){e.drainStderr=null,e.stderrTail=[],await this.stopAgentProcess(e,`[acp-threads] terminal cleanup before relaunch failed`)}async stopAgentProcess(e,t){let n=e.child,r=e.conn,i=e.terminals;e.child=null,e.conn=null,e.terminals=null;try{r?.close()}catch{}await i?.disposeAll().catch(n=>{this.opts.log.warn({err:n,threadId:e.info.threadId},t)}),n!==null&&await z$(n,{graceMs:R$e})}async ensureLaunchable(e,t,n){let r;try{await k$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof x$)||i.code!==`command-not-found`)throw i;let a=await this.retryWithLoginShellPath(t);if(a===null)return this.fallbackToManagedRuntime(e,t,i,void 0,n);r=a}return e.closed?null:this.ensureInterpreterRuns(e,r,n)}async ensureInterpreterRuns(e,t,n){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let r=await this.probeInterpreterOnce(t);if(e.closed)return null;if(r===null)return t;if(r.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(e.closed)return null;if(j$(n.env)!==j$(t.env))try{await k$(n);let t=await this.probeInterpreterOnce(n);if(e.closed)return null;if(t===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),n;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:t.kind,detail:t.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof x$)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,failureKind:r.kind,detail:r.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let i=r.kind===`incompatible`,a=new x$(`command-not-found`,i?AQe(t,r.detail):xQe(t,r.detail)),o=new x$(`command-not-found`,i?jQe(t,r.detail):DQe(t,a.message));return this.fallbackToManagedRuntime(e,t,a,{declined:a,expired:o},n)}async fallbackToManagedRuntime(e,t,n,r,i){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let a=WQe(t.kind);if(!XQe(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof n1?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=dQe(t,o);await k$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new x$(`install-failed`,CQe(c.detail));return this.repairManagedRuntime(e,t,a,c.detail,i)}async repairManagedRuntime(e,t,n,r,i){let a={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(a,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await t$e(n,this.opts.log,this.opts.runtimeInstall?.root))throw new x$(`install-failed`,wQe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof n1?new x$(`command-not-found`,e.refusal===`timeout`?EQe(t):TQe(t)):e});if(o===null)return null;let s=dQe(t,o);await k$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;throw this.opts.log.error({...a,detail:c.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new x$(`install-failed`,c.kind===`incompatible`?CQe(c.detail):SQe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,j$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await OQe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await kQe(e,void 0,this.opts.log);if(t!==null)return{kind:`incompatible`,detail:t}}return this.healthyInterpreters.add(t),null}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(j$(t.env)===j$(e.env))return null;try{await k$(t)}catch(t){if(!(t instanceof x$))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||M$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:fQe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||M$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:pQe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await e$e(t,this.opts.log,i);let a=await $Qe(t,i).catch(()=>null);if(a!==null)return a;let o=await this.requestRuntimeConsent(e,t,n,r);if(o===`closed`||e.closed)return null;if(o!==`granted`)throw new n1(o,o===`timeout`?e1e(t):$$e(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=U$(t).displayName;throw new x$(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=U$(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:i,runtime:t,displayName:a.displayName,provides:a.provides,version:a.version,approxSizeMB:a.approxSizeMB,sourceHost:a.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(i),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:i,decision:`timeout`,ts:Date.now()}),t(`timeout`)},r);n.unref?.(),e.pendingRuntimeConsent.set(i,{resolve:t,timer:n})})}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`;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 n$e(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,n=$$){let r=[],i;if(J$e(e.agentRef))i=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)i=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:`open-knowledge`,url:`${e}/mcp`,headers:[{name:oZe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=WZe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Ie,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),i=`stdio-entry-env`)}}return i===`none`?this.opts.log.warn({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] no OK MCP transport available for this agent — it starts without OK tools`):this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,hostedMarker:i},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:i}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=QG[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 settlePiBridge(e,t){let n=this.opts.probePiAcpBridge,r=e.info.threadId;if(n===void 0)return this.opts.log.debug({threadId:r,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let i;try{i=await n(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:r},`[acp-threads] Pi bridge probe failed`),`unknown`}if(e.closed)return`unknown`;if(i.project===`unavailable`)return this.opts.log.warn({threadId:r,cwd:i.cwd,err:Error(i.error)},`[acp-threads] Pi project folder is unavailable; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:`project-path-unavailable`,bridgePath:i.bridgePath,detail:i.error,ts:Date.now()}),`unavailable`;if(i.bridgeLoadable)return this.opts.log.info({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(i.bridge===`foreign`||i.bridge===`unreadable`)return this.opts.log.warn({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:i.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:i.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:r},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let a=this.opts.ensurePiAcpBridge;if(a===void 0)return this.opts.log.warn({threadId:r},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let o=crypto.randomUUID(),s=await this.requestPiBridgeConsent(e,o,i,t);if(s===`declined`&&(e.piBridgeDeclined=!0),e.closed)return`unknown`;if(s!==`granted`)return this.opts.log.info({threadId:r,decision:s},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let c;try{c=await a(e.cwd,i.canonicalCwd)}catch(t){let n=t instanceof Error?t.message:String(t);return this.opts.log.warn({err:t,threadId:r},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,o,`bridge-failed`,i.bridgePath,{detail:n}),`unavailable`}if(c.ok)return this.opts.log.info({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),e.closed?`unknown`:(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:o,state:`ready`,bridgePath:c.bridgePath,bridge:c.bridge,trust:c.trust,ts:Date.now()}),`loadable`);let l=c.bridge===`written`||c.bridge===`refreshed`||c.bridge===`unchanged`,u=c.bridge===`refused-project-path`?`project-path-unavailable`:c.bridge===`refused-foreign`?`foreign-file`:c.bridge===`refused-unreadable`?`unreadable-file`:l?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath,err:c.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,o,u,c.bridgePath,{bridge:c.bridge,trust:c.trust,...c.error===void 0?{}:{detail:c.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i){e.closed||this.appendEvent(e,{kind:`pi_bridge_status`,requestId:t,state:n,bridgePath:r,...i,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:n.canonicalCwd,otherExtensions:n.otherExtensions,ts:Date.now()}),new Promise(n=>{let i=setTimeout(()=>{e.pendingPiBridgeConsent.delete(t),this.appendEvent(e,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:`timeout`,ts:Date.now()}),n(`timeout`)},r);i.unref?.(),e.pendingPiBridgeConsent.set(t,{resolve:n,timer:i})})}respondPiBridgeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingPiBridgeConsent.get(t);if(i===void 0)return;r.pendingPiBridgeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async startThread(e,t,n,r=$$,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await r1e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),s1(e)||await this.teardownFailedAgent(e);return}if(a===null)return;let{conn:o,init:s,launch:c}=a;await this.openSession(e,o,s,t.settings,`park`,r)===!0&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:c.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),(t.prompt!==void 0&&t.prompt!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`,a=$$){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let r=await t.agent.request(BC.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=a1e(n),e.confirmedContextWindow=n1e(e),e.info.contextWindow=e.confirmedContextWindow,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),r.modes!==void 0&&r.modes!==null&&(e.info.modes=r.modes,this.emitInfo(e)),r.configOptions!==void 0&&r.configOptions!==null&&(e.info.configOptions=r.configOptions,this.emitInfo(e))}catch(t){if(t1e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,e),authMethods:d1(n.authMethods)})}else{let n=await c1(e);this.emitStatus(e,`error`,`session setup failed: ${i1(t)}`,{reason:`session-setup`,agentMessage:i1(t),machineDetail:l1({primary:a1(t),tail:n})}),s1(e)||await this.teardownFailedAgent(e)}return!1}return s1(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),s1(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),s1(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new t1(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new t1(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.resumeInFlight=!0;let i=Date.now();try{await this.ensureLogResolved(r);let a=r.sessionId,{info:o,custom:s}=await this.resolveAgentInfo(r.agentRef);if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`spawning`);try{if(a===null)throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-session`},`[acp-threads] thread is not resumable`),new t1(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,e1);if(o===null)throw new t1(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=a1e(u),r.confirmedContextWindow=n1e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d}=await this.buildMcpServers(r,u,e1),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(BC.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(BC.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-resume-capability`},`[acp-threads] thread is not resumable`),new t1(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),g=r.info.modes?.currentModeId,_=m.modes;_!=null&&(r.info.modes=_);let v=m.configOptions;if(v!=null&&(r.info.configOptions=v),await this.applyInitialConfig(r,l,h,v==null),r.closed||g!==void 0&&(await this.applyInitialMode(r,l,g,_==null),r.closed))throw new t1(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r,await r1e(t,r)),t instanceof t1?t:t instanceof x$?new t1(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 t1(`resume-unsupported`,`couldn't resume the previous session: ${i1(t)}`))}}finally{r.resumeInFlight=!1}}hasStartedWork(e){let t=this.threads.get(e);return t!==void 0&&t.events.some(e=>e.kind===`user_message`)}async setContextWindow(e,t){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new t1(`not-ready`,`a context window must be a positive number of tokens`);let r=f$e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new t1(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new t1(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new t1(`not-ready`,`a restart is already in progress`);let i=n.launchSettings?.contextWindow,a=n.confirmedContextWindow??null;n.launchSettings={...n.launchSettings,contextWindow:Math.floor(t)},n.resumeInFlight=!0;let o=!1;try{let{custom:t}=await this.resolveAgentInfo(n.agentRef);if(await this.teardownFailedAgent(n),n.stderrTail=[],n.cancelRequested=!1,n.turnActive=!1,this.emitStatus(n,`spawning`),await this.startThread(n,{agent:n.agentRef,settings:n.launchSettings},t,e1),n.closed)throw new t1(`spawn-failed`,`thread closed during the context window change`);let r=this.getInfo(e)?.status;if(r===`ready`||r===`running`)return o=!0,{...n.info};throw new t1(`spawn-failed`,o1(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof t1)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new t1(`spawn-failed`,t)}finally{!o&&this.threads.has(e)&&(n.launchSettings={...n.launchSettings,contextWindow:i},n.confirmedContextWindow=a,n.info.contextWindow=this.getInfo(e)?.status===`ready`?a:null,this.emitInfo(n)),n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new t1(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new t1(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{zZe(),this.healthyInterpreters.clear();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,`spawning`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r,e1,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new t1(`spawn-failed`,n)}if(t.closed)throw new t1(`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 t1(`spawn-failed`,o1(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new t1(`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 t1(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new t1(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new t1(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw q$e();let t=e instanceof G$e?`the sign-in didn't complete in time — try again`:i1(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:u1(e,n),authMethods:d1(i.authMethods)}),new t1(`not-ready`,t)}if(n.closed)throw new t1(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw q$e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,e1);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,n),authMethods:d1(i.authMethods)}),t}}if(a!==!0)throw new t1(`not-ready`,o1(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,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new G$e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(BC.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(s1(e)){await this.teardownFailedAgent(e),this.emitStatus(e,`exited`,`resume failed`,t);return}e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingConsents(e);try{e.conn?.close()}catch{}let n=e.child;n!==null&&await z$(n,{graceMs:z$e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(lK(e.agentSessionId)),e.info.archived=!0,this.recordTerminalStatus(e,`exited`,`resume failed`,t),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,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new t1(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new t1(`not-ready`,`20 messages are already waiting — let the agent catch up`);let i={id:crypto.randomUUID(),content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.queue=[...e,i],r.info.lastActivityAt=Date.now(),this.emitInfo(r);return}this.dispatchPrompt(r,t,n,{echo:!0})}steerPrompt(e,t,n){let r=this.mustGet(e);this.assertSteerable(r),this.steerWith(r,t,n)}sendQueuedNow(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.find(e=>e.id===t);if(i===void 0)return!1;this.assertSteerable(n);let a=this.takeSteer(n),o=r.filter(e=>e.id!==t),s=a===null?o:[i1e(a),...o];return n.info.queue=s.length>0?s:void 0,this.steerWith(n,i.content,i.attachments),!0}assertSteerable(e){if(e.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new t1(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`)}steerWith(e,t,n){if(!e.turnActive){this.dispatchPrompt(e,t,n,{echo:!0});return}this.clearSteer(e);let r={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),e.info.steer=r,e.info.lastActivityAt=Date.now(),this.emitInfo(e);let i=setTimeout(()=>this.demoteStalledSteer(e),this.steerStallMs);i.unref?.(),e.steerStallTimer=i,this.cancelTurn(e,{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=[i1e(t),...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)}armStallTimer(e,t=this.turnStallMs){e.stallTimer!==null&&clearTimeout(e.stallTimer);let n=setTimeout(()=>this.checkStall(e),t);n.unref?.(),e.stallTimer=n}checkStall(e){if(e.stallTimer=null,e.closed||!e.turnActive||e.info.stalledSince!==void 0)return;if(e.pendingPermissions.size>0){this.armStallTimer(e);return}let t=Date.now()-e.agentActivityAt;if(t<this.turnStallMs){this.armStallTimer(e,this.turnStallMs-t);return}e.info.stalledSince=e.agentActivityAt,this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,silentMs:t},`[acp-threads] turn stalled: no agent activity`),this.emitInfo(e)}touchTurnActivity(e){let t=Date.now();if(e.agentActivityAt=t,e.info.lastActivityAt=t,e.info.stalledSince===void 0)return;let n=Date.now()-e.info.stalledSince;e.info.stalledSince=void 0,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,stalledForMs:n},`[acp-threads] turn resumed after stall`),this.emitInfo(e),e.turnActive&&this.armStallTimer(e)}clearStall(e){e.stallTimer!==null&&(clearTimeout(e.stallTimer),e.stallTimer=null),e.info.stalledSince=void 0}logTurnEnded(e,t){let n=e.turnStartedAt;e.turnStartedAt=null,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,outcome:t,durationMs:n===null?void 0:Date.now()-n},`[acp-threads] turn ended`)}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&&(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,t.attachments,{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,n){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=F$e(n,e.info.agent.name),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}let r={kind:`user_message`,content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),this.appendEvent(e,r)}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new t1(`not-ready`,`the thread is closing`);let r=Q$(t);return r===``||r===n.info.title?{...n.info}:(await this.ensureLogResolved(n),n.info.title=r,this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId),{...n.info})}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t,a=null;if(e.envNotePending&&!t.startsWith(`/`)){e.envNotePending=!1;let n=e.projectSkill,r=n!==null&&n.inlineText!==null;i=`${V$e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=W$e(n.skillPath,n.inlineText,e.info.promptCapabilities)),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,skillPath:n.skillPath,delivery:r?`inline`:`path`},`[acp-threads] skill pointer sent`))}e.turnActive=!0,e.cancelRequested=!1,e.turnStartedAt=Date.now(),e.agentActivityAt=e.turnStartedAt,this.appendEvent(e,{kind:`turn_started`,ts:e.turnStartedAt}),this.emitStatus(e,`running`),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] turn started`),this.armStallTimer(e);let o=e.sessionId;vZe(i,n,e.info.promptCapabilities,e=>this.confinePath(e).then(({abs:e,rel:t})=>({abs:e,rel:t}))).then(t=>{if(t.dropped.length>0){this.opts.log.warn({threadId:e.info.threadId,dropped:t.dropped.map(e=>({kind:e.part.kind,reason:e.reason}))},`[acp-threads] dropped attachment parts before session/prompt`);let n=Date.now();for(let r of t.dropped){let t=r.part.kind===`image`||r.part.kind===`blob`?r.part.name:r.part.name||r.part.path;this.appendEvent(e,{kind:`agent_stderr`,line:`[attachment dropped] ${t}: ${r.reason}`,ts:n})}}if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new K$e;return e.conn.agent.request(BC.agent.session.prompt,{sessionId:o,prompt:a===null?[...t.blocks]:[...t.blocks,a]})}).then(t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,t.stopReason),!s1(e)){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,t.attachments,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,n.attachments,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(async t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,e.cancelRequested?`cancelled`:`failed`),s1(e))return;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,t.attachments,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}if(t1e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,e),authMethods:d1(e.lastInit?.authMethods)});return}let n=await c1(e);this.emitStatus(e,`error`,`prompt failed: ${i1(t)}`,{reason:`prompt`,agentMessage:i1(t),machineDetail:l1({primary:a1(t),tail:n})})}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] prompt diagnostics failed`)})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){if(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)return;e.turnActive&&(e.cancelRequested=!0);let n=e.info.stalledSince!==void 0;this.clearStall(e),n&&this.emitInfo(e),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(BC.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.info.archived===!0){let e=n.info.modes;if(e==null||!e.availableModes.some(e=>e.id===t))throw new t1(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new t1(`not-ready`,`thread has no live agent session`);n.conn.agent.request(BC.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.info.archived===!0){let e=(r.info.configOptions??[]).find(e=>e.id===t);if(e===void 0)throw new t1(`not-ready`,`no such config option: ${t}`);if(!r1(e,n))throw new t1(`not-ready`,`invalid value for ${t}`);r.info.configOptions=(r.info.configOptions??[]).map(e=>e.id===t?{...e,currentValue:n}:e),this.emitInfo(r);return}if(r.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new t1(`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(BC.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,r=!1){let i=e.sessionId;if(i===null)return;let a=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,o=Object.keys(n).sort((e,t)=>Number(a(t))-Number(a(e))),s=!1,c=[];for(let a of o){let o=n[a];if(o===void 0)continue;let l=(e.info.configOptions??[]).find(e=>e.id===a);if(l===void 0||!r&&l.currentValue===o||!r1(l,o))continue;let u=typeof o==`boolean`?{sessionId:i,configId:a,type:`boolean`,value:o}:{sessionId:i,configId:a,value:o};try{let n=await t.agent.request(BC.agent.session.setConfigOption,u);e.info.configOptions=n.configOptions,s=!0}catch(t){c.push(a),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:a},`[acp-threads] initial config apply failed`)}if(e.closed)return}c.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:c,sessionStateUnknown:r},`[acp-threads] some remembered config options could not be applied to the new session`),s&&this.emitInfo(e)}async applyInitialMode(e,t,n,r=!1){let i=e.sessionId;if(i===null)return;let a=e.info.modes;if(a!=null&&a.availableModes.some(e=>e.id===n)){if(!r&&a.currentModeId===n)return;try{await t.agent.request(BC.agent.session.setMode,{sessionId:i,modeId:n}),e.info.modes={...a,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 o=(e.info.configOptions??[]).find(e=>e.category===`mode`&&r1(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(BC.agent.session.setConfigOption,{sessionId:i,configId:o.id,value:n});e.info.configOptions=r.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),this.touchTurnActivity(r),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))}setChatGrant(e,t,n){let r=this.mustGet(e);r.chatGrants.has(t)!==n&&(n?r.chatGrants.add(t):r.chatGrants.delete(t),r.info.chatGrants=r.chatGrants.size>0?[...r.chatGrants]:void 0,this.opts.log.info({threadId:e,agentId:r.info.agent.id,grant:t,enabled:n},`[acp-threads] chat grant changed`),this.emitInfo(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.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await z$(r,{graceMs:t?.killGraceMs??R$e})||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(lK(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),this.clearStall(n),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.recordTerminalStatus(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 t1(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new t1(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),this.clearStall(t),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:z$e})))}async handlePermissionRequest(e,t,n){this.touchTurnActivity(e);let r=this.opts.permissions.decide(e.info.agent.id,t,n,e.chatGrants,this.opts.autoApproveOkTools?.()??!0);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,...UG(t)===null?{}:{readOnlyShell:!0},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){this.touchTurnActivity(e);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:xZe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await ic(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await ic(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
955
|
+
`))n.trim()!==``&&e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e))}),c.on(`error`,t=>{y()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),c.on(`exit`,(t,n)=>{e.child===c&&(e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),s.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),c1(e).then(r=>{if(e.terminals!==s||s1(e)||y())return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let i=`agent exited (${n??t??`unknown`})`;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:r},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,l1({primary:i,tail:r})),this.failPendingPermissions(e)}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] exit diagnostics failed`)}))}),c.stdin===null||c.stdout===null)throw new t1(`spawn-failed`,`agent process has no stdio`);let b=Dbe(dc.toWeb(c.stdin),uc.toWeb(c.stdout)),x=txe({name:`open-knowledge`}).onRequest(BC.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(BC.client.fs.readTextFile,async t=>{this.touchTurnActivity(e);try{return await this.handleFsRead(t.params.path,t.params.line??null,t.params.limit??null)}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file read failed`),n}}).onRequest(BC.client.fs.writeTextFile,async t=>{try{return await this.handleFsWrite(e,t.params.path,t.params.content),{}}catch(n){throw this.opts.log.warn({err:n,threadId:e.info.threadId,agentId:e.info.agent.id,path:t.params.path},`[acp-threads] agent file write failed`),n}}).onRequest(BC.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(BC.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(BC.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(BC.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(BC.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(BC.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(b);e.conn=x;let S=async t=>{if(await d(),e.conn!==x||y()||(t!==null&&this.opts.log.warn({err:t.err,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status===`exited`||e.info.status===`error`))return;if(t===null){this.emitStatus(e,`exited`,`agent connection closed`);return}let{err:n}=t;this.emitStatus(e,`error`,`agent connection failed: ${n instanceof Error?n.message:String(n)}`)};x.closed.then(()=>S(null),e=>S({err:e}));let C;try{C=await x.agent.request(BC.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:c$},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(o){if(this.opts.log.warn({err:o,threadId:e.info.threadId},`[acp-threads] initialize failed`),a.kind===`npx`||a.kind===`uvx`){await d();let e=XZe(a,f,o);if(e!==null)throw e}let s=g===`npx`&&i===`available`?eQe(p):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,s))return _=!0,this.connectAgent(e,t,n,r,`spent`);throw new t1(`spawn-failed`,`initialize failed: ${i1(o)}`)}finally{m=!1,f=``,p=``}return e.closed?null:(e.lastInit=C,e.info.promptCapabilities=C.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:x,init:C,launch:a})}async clearStaleNpxCacheEntry(e,t){let n={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:p$(t)},r=this.npxCacheClears.get(t);if(r!==void 0&&Date.now()-r<3e5)return this.opts.log.warn(n,`[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again`),await this.discardFailedLaunch(e),!s1(e);let i=Date.now();this.npxCacheClears.set(t,i);let a=()=>{this.npxCacheClears.get(t)===i&&this.npxCacheClears.delete(t)};for(let e of[`package.json`,`concurrency.lock`]){let r=await cc(H(t,e)).then(()=>`present`,e=>e.code??`unknown`);if(r!==`ENOENT`)return this.opts.log.warn({...n,file:e,code:r},`[acp-threads] leaving an npx cache entry alone`),a(),!1}try{await $K(t,{recursive:!0,force:!0})}catch(e){return this.opts.log.warn({err:e,...n},`[acp-threads] stale npx cache entry could not be cleared`),a(),!1}return this.opts.log.warn(n,`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),!s1(e)}async discardFailedLaunch(e){e.drainStderr=null,e.stderrTail=[],await this.stopAgentProcess(e,`[acp-threads] terminal cleanup before relaunch failed`)}async stopAgentProcess(e,t){let n=e.child,r=e.conn,i=e.terminals;e.child=null,e.conn=null,e.terminals=null;try{r?.close()}catch{}await i?.disposeAll().catch(n=>{this.opts.log.warn({err:n,threadId:e.info.threadId},t)}),n!==null&&await z$(n,{graceMs:R$e})}async ensureLaunchable(e,t,n){let r;try{await k$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof x$)||i.code!==`command-not-found`)throw i;let a=await this.retryWithLoginShellPath(t);if(a===null)return this.fallbackToManagedRuntime(e,t,i,void 0,n);r=a}return e.closed?null:this.ensureInterpreterRuns(e,r,n)}async ensureInterpreterRuns(e,t,n){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let r=await this.probeInterpreterOnce(t);if(e.closed)return null;if(r===null)return t;if(r.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(e.closed)return null;if(j$(n.env)!==j$(t.env))try{await k$(n);let t=await this.probeInterpreterOnce(n);if(e.closed)return null;if(t===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),n;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:t.kind,detail:t.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof x$)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,failureKind:r.kind,detail:r.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let i=r.kind===`incompatible`,a=new x$(`command-not-found`,i?AQe(t,r.detail):xQe(t,r.detail)),o=new x$(`command-not-found`,i?jQe(t,r.detail):DQe(t,a.message));return this.fallbackToManagedRuntime(e,t,a,{declined:a,expired:o},n)}async fallbackToManagedRuntime(e,t,n,r,i){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let a=WQe(t.kind);if(!XQe(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof n1?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=dQe(t,o);await k$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new x$(`install-failed`,CQe(c.detail));return this.repairManagedRuntime(e,t,a,c.detail,i)}async repairManagedRuntime(e,t,n,r,i){let a={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(a,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await t$e(n,this.opts.log,this.opts.runtimeInstall?.root))throw new x$(`install-failed`,wQe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof n1?new x$(`command-not-found`,e.refusal===`timeout`?EQe(t):TQe(t)):e});if(o===null)return null;let s=dQe(t,o);await k$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;throw this.opts.log.error({...a,detail:c.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new x$(`install-failed`,c.kind===`incompatible`?CQe(c.detail):SQe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,j$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await OQe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await kQe(e,void 0,this.opts.log);if(t!==null)return{kind:`incompatible`,detail:t}}return this.healthyInterpreters.add(t),null}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(j$(t.env)===j$(e.env))return null;try{await k$(t)}catch(t){if(!(t instanceof x$))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||M$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:fQe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||M$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:pQe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await e$e(t,this.opts.log,i);let a=await $Qe(t,i).catch(()=>null);if(a!==null)return a;let o=await this.requestRuntimeConsent(e,t,n,r);if(o===`closed`||e.closed)return null;if(o!==`granted`)throw new n1(o,o===`timeout`?e1e(t):$$e(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=U$(t).displayName;throw new x$(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=U$(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:i,runtime:t,displayName:a.displayName,provides:a.provides,version:a.version,approxSizeMB:a.approxSizeMB,sourceHost:a.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(i),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:i,decision:`timeout`,ts:Date.now()}),t(`timeout`)},r);n.unref?.(),e.pendingRuntimeConsent.set(i,{resolve:t,timer:n})})}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`;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 n$e(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,n=$$){let r=[],i;if(J$e(e.agentRef))i=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)i=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:`open-knowledge`,url:`${e}/mcp`,headers:[{name:oZe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=WZe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Ie,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),i=`stdio-entry-env`)}}return i===`none`?this.opts.log.warn({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] no OK MCP transport available for this agent — it starts without OK tools`):this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,hostedMarker:i},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:i}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=QG[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 settlePiBridge(e,t){let n=this.opts.probePiAcpBridge,r=e.info.threadId;if(n===void 0)return this.opts.log.debug({threadId:r,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let i;try{i=await n(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:r},`[acp-threads] Pi bridge probe failed`),`unknown`}if(e.closed)return`unknown`;if(i.project===`unavailable`)return this.opts.log.warn({threadId:r,cwd:i.cwd,err:Error(i.error)},`[acp-threads] Pi project folder is unavailable; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:`project-path-unavailable`,bridgePath:i.bridgePath,detail:i.error,ts:Date.now()}),`unavailable`;if(i.bridgeLoadable)return this.opts.log.info({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(i.bridge===`foreign`||i.bridge===`unreadable`)return this.opts.log.warn({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:i.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:i.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:r},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let a=this.opts.ensurePiAcpBridge;if(a===void 0)return this.opts.log.warn({threadId:r},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let o=crypto.randomUUID(),s=await this.requestPiBridgeConsent(e,o,i,t);if(s===`declined`&&(e.piBridgeDeclined=!0),e.closed)return`unknown`;if(s!==`granted`)return this.opts.log.info({threadId:r,decision:s},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let c;try{c=await a(e.cwd,i.canonicalCwd)}catch(t){let n=t instanceof Error?t.message:String(t);return this.opts.log.warn({err:t,threadId:r},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,o,`bridge-failed`,i.bridgePath,{detail:n}),`unavailable`}if(c.ok)return this.opts.log.info({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),e.closed?`unknown`:(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:o,state:`ready`,bridgePath:c.bridgePath,bridge:c.bridge,trust:c.trust,ts:Date.now()}),`loadable`);let l=c.bridge===`written`||c.bridge===`refreshed`||c.bridge===`unchanged`,u=c.bridge===`refused-project-path`?`project-path-unavailable`:c.bridge===`refused-foreign`?`foreign-file`:c.bridge===`refused-unreadable`?`unreadable-file`:l?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath,err:c.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,o,u,c.bridgePath,{bridge:c.bridge,trust:c.trust,...c.error===void 0?{}:{detail:c.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i){e.closed||this.appendEvent(e,{kind:`pi_bridge_status`,requestId:t,state:n,bridgePath:r,...i,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:n.canonicalCwd,otherExtensions:n.otherExtensions,ts:Date.now()}),new Promise(n=>{let i=setTimeout(()=>{e.pendingPiBridgeConsent.delete(t),this.appendEvent(e,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:`timeout`,ts:Date.now()}),n(`timeout`)},r);i.unref?.(),e.pendingPiBridgeConsent.set(t,{resolve:n,timer:i})})}respondPiBridgeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingPiBridgeConsent.get(t);if(i===void 0)return;r.pendingPiBridgeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async startThread(e,t,n,r=$$,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await r1e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),s1(e)||await this.teardownFailedAgent(e);return}if(a===null)return;let{conn:o,init:s,launch:c}=a;await this.openSession(e,o,s,t.settings,`park`,r)===!0&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:c.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),(t.prompt!==void 0&&t.prompt!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`,a=$$){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let r=await t.agent.request(BC.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=a1e(n),e.confirmedContextWindow=n1e(e),e.info.contextWindow=e.confirmedContextWindow,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),r.modes!==void 0&&r.modes!==null&&(e.info.modes=r.modes,this.emitInfo(e)),r.configOptions!==void 0&&r.configOptions!==null&&(e.info.configOptions=r.configOptions,this.emitInfo(e))}catch(t){if(t1e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,e),authMethods:d1(n.authMethods)})}else{let n=await c1(e);this.emitStatus(e,`error`,`session setup failed: ${i1(t)}`,{reason:`session-setup`,agentMessage:i1(t),machineDetail:l1({primary:a1(t),tail:n})}),s1(e)||await this.teardownFailedAgent(e)}return!1}return s1(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),s1(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),s1(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new t1(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new t1(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.resumeInFlight=!0;let i=Date.now();try{await this.ensureLogResolved(r);let a=r.sessionId,{info:o,custom:s}=await this.resolveAgentInfo(r.agentRef);if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new t1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`spawning`);try{if(a===null)throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-session`},`[acp-threads] thread is not resumable`),new t1(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,e1);if(o===null)throw new t1(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=a1e(u),r.confirmedContextWindow=n1e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d}=await this.buildMcpServers(r,u,e1),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(BC.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(BC.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw this.opts.log.warn({threadId:e,agentId:r.info.agent.id,cause:`no-resume-capability`},`[acp-threads] thread is not resumable`),new t1(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),g=r.info.modes?.currentModeId,_=m.modes;_!=null&&(r.info.modes=_);let v=m.configOptions;if(v!=null&&(r.info.configOptions=v),await this.applyInitialConfig(r,l,h,v==null),r.closed||g!==void 0&&(await this.applyInitialMode(r,l,g,_==null),r.closed))throw new t1(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r,await r1e(t,r)),t instanceof t1?t:t instanceof x$?new t1(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 t1(`resume-unsupported`,`couldn't resume the previous session: ${i1(t)}`))}}finally{r.resumeInFlight=!1}}hasStartedWork(e){let t=this.threads.get(e);return t!==void 0&&t.events.some(e=>e.kind===`user_message`)}async setContextWindow(e,t){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new t1(`not-ready`,`a context window must be a positive number of tokens`);let r=f$e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new t1(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new t1(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new t1(`not-ready`,`a restart is already in progress`);let i=n.launchSettings?.contextWindow,a=n.confirmedContextWindow??null;n.launchSettings={...n.launchSettings,contextWindow:Math.floor(t)},n.resumeInFlight=!0;let o=!1;try{let{custom:t}=await this.resolveAgentInfo(n.agentRef);if(await this.teardownFailedAgent(n),n.stderrTail=[],n.cancelRequested=!1,n.turnActive=!1,this.emitStatus(n,`spawning`),await this.startThread(n,{agent:n.agentRef,settings:n.launchSettings},t,e1),n.closed)throw new t1(`spawn-failed`,`thread closed during the context window change`);let r=this.getInfo(e)?.status;if(r===`ready`||r===`running`)return o=!0,{...n.info};throw new t1(`spawn-failed`,o1(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof t1)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new t1(`spawn-failed`,t)}finally{!o&&this.threads.has(e)&&(n.launchSettings={...n.launchSettings,contextWindow:i},n.confirmedContextWindow=a,n.info.contextWindow=this.getInfo(e)?.status===`ready`?a:null,this.emitInfo(n)),n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new t1(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new t1(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{zZe(),this.healthyInterpreters.clear();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,`spawning`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r,e1,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new t1(`spawn-failed`,n)}if(t.closed)throw new t1(`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 t1(`spawn-failed`,o1(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new t1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new t1(`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 t1(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new t1(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new t1(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw q$e();let t=e instanceof G$e?`the sign-in didn't complete in time — try again`:i1(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:u1(e,n),authMethods:d1(i.authMethods)}),new t1(`not-ready`,t)}if(n.closed)throw new t1(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw q$e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,e1);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,n),authMethods:d1(i.authMethods)}),t}}if(a!==!0)throw new t1(`not-ready`,o1(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,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new G$e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(BC.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(s1(e)){await this.teardownFailedAgent(e),this.emitStatus(e,`exited`,`resume failed`,t);return}e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingConsents(e);try{e.conn?.close()}catch{}let n=e.child;n!==null&&await z$(n,{graceMs:z$e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(lK(e.agentSessionId)),e.info.archived=!0,this.recordTerminalStatus(e,`exited`,`resume failed`,t),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,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new t1(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new t1(`not-ready`,`20 messages are already waiting — let the agent catch up`);let i={id:crypto.randomUUID(),content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.queue=[...e,i],r.info.lastActivityAt=Date.now(),this.emitInfo(r);return}this.dispatchPrompt(r,t,n,{echo:!0})}steerPrompt(e,t,n){let r=this.mustGet(e);this.assertSteerable(r),this.steerWith(r,t,n)}sendQueuedNow(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.find(e=>e.id===t);if(i===void 0)return!1;this.assertSteerable(n);let a=this.takeSteer(n),o=r.filter(e=>e.id!==t),s=a===null?o:[i1e(a),...o];return n.info.queue=s.length>0?s:void 0,this.steerWith(n,i.content,i.attachments),!0}assertSteerable(e){if(e.info.archived===!0)throw new t1(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new t1(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`)}steerWith(e,t,n){if(!e.turnActive){this.dispatchPrompt(e,t,n,{echo:!0});return}this.clearSteer(e);let r={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),e.info.steer=r,e.info.lastActivityAt=Date.now(),this.emitInfo(e);let i=setTimeout(()=>this.demoteStalledSteer(e),this.steerStallMs);i.unref?.(),e.steerStallTimer=i,this.cancelTurn(e,{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=[i1e(t),...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)}armStallTimer(e,t=this.turnStallMs){e.stallTimer!==null&&clearTimeout(e.stallTimer);let n=setTimeout(()=>this.checkStall(e),t);n.unref?.(),e.stallTimer=n}checkStall(e){if(e.stallTimer=null,e.closed||!e.turnActive||e.info.stalledSince!==void 0)return;if(e.pendingPermissions.size>0){this.armStallTimer(e);return}let t=Date.now()-e.agentActivityAt;if(t<this.turnStallMs){this.armStallTimer(e,this.turnStallMs-t);return}e.info.stalledSince=e.agentActivityAt,this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,silentMs:t},`[acp-threads] turn stalled: no agent activity`),this.emitInfo(e)}touchTurnActivity(e){let t=Date.now();if(e.agentActivityAt=t,e.info.lastActivityAt=t,e.info.stalledSince===void 0)return;let n=Date.now()-e.info.stalledSince;e.info.stalledSince=void 0,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,stalledForMs:n},`[acp-threads] turn resumed after stall`),this.emitInfo(e),e.turnActive&&this.armStallTimer(e)}clearStall(e){e.stallTimer!==null&&(clearTimeout(e.stallTimer),e.stallTimer=null),e.info.stalledSince=void 0}logTurnEnded(e,t){let n=e.turnStartedAt;e.turnStartedAt=null,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,outcome:t,durationMs:n===null?void 0:Date.now()-n},`[acp-threads] turn ended`)}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&&(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,t.attachments,{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,n){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=F$e(n,e.info.agent.name),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}let r={kind:`user_message`,content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),this.appendEvent(e,r)}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new t1(`not-ready`,`the thread is closing`);let r=Q$(t);return r===``||r===n.info.title?{...n.info}:(await this.ensureLogResolved(n),n.info.title=r,this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId),{...n.info})}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t,a=null;if(e.envNotePending&&!t.startsWith(`/`)){e.envNotePending=!1;let n=e.projectSkill,r=n!==null&&n.inlineText!==null;i=`${V$e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=W$e(n.skillPath,n.inlineText,e.info.promptCapabilities)),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,skillPath:n.skillPath,delivery:r?`inline`:`path`},`[acp-threads] skill pointer sent`))}e.turnActive=!0,e.cancelRequested=!1,e.turnStartedAt=Date.now(),e.agentActivityAt=e.turnStartedAt,this.appendEvent(e,{kind:`turn_started`,ts:e.turnStartedAt}),this.emitStatus(e,`running`),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] turn started`),this.armStallTimer(e);let o=e.sessionId;vZe(i,n,e.info.promptCapabilities,e=>this.confinePath(e).then(({abs:e,rel:t})=>({abs:e,rel:t}))).then(t=>{if(t.dropped.length>0){this.opts.log.warn({threadId:e.info.threadId,dropped:t.dropped.map(e=>({kind:e.part.kind,reason:e.reason}))},`[acp-threads] dropped attachment parts before session/prompt`);let n=Date.now();for(let r of t.dropped){let t=r.part.kind===`image`||r.part.kind===`blob`?r.part.name:r.part.name||r.part.path;this.appendEvent(e,{kind:`agent_stderr`,line:`[attachment dropped] ${t}: ${r.reason}`,ts:n})}}if(e.sessionId===null||e.conn===null)throw new t1(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new K$e;return e.conn.agent.request(BC.agent.session.prompt,{sessionId:o,prompt:a===null?[...t.blocks]:[...t.blocks,a]})}).then(t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,t.stopReason),!s1(e)){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,t.attachments,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,n.attachments,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(async t=>{if(e.turnActive=!1,this.clearStall(e),this.logTurnEnded(e,e.cancelRequested?`cancelled`:`failed`),s1(e))return;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,t.attachments,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}if(t1e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${i1(t)}`,{reason:`auth-required`,agentMessage:i1(t),machineDetail:u1(t,e),authMethods:d1(e.lastInit?.authMethods)});return}let n=await c1(e);this.emitStatus(e,`error`,`prompt failed: ${i1(t)}`,{reason:`prompt`,agentMessage:i1(t),machineDetail:l1({primary:a1(t),tail:n})})}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] prompt diagnostics failed`)})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){if(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)return;e.turnActive&&(e.cancelRequested=!0);let n=e.info.stalledSince!==void 0;this.clearStall(e),n&&this.emitInfo(e),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(BC.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.info.archived===!0){let e=n.info.modes;if(e==null||!e.availableModes.some(e=>e.id===t))throw new t1(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new t1(`not-ready`,`thread has no live agent session`);n.conn.agent.request(BC.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.info.archived===!0){let e=(r.info.configOptions??[]).find(e=>e.id===t);if(e===void 0)throw new t1(`not-ready`,`no such config option: ${t}`);if(!r1(e,n))throw new t1(`not-ready`,`invalid value for ${t}`);r.info.configOptions=(r.info.configOptions??[]).map(e=>e.id===t?{...e,currentValue:n}:e),this.emitInfo(r);return}if(r.resumeInFlight)throw new t1(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new t1(`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(BC.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,r=!1){let i=e.sessionId;if(i===null)return;let a=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,o=Object.keys(n).sort((e,t)=>Number(a(t))-Number(a(e))),s=!1,c=[];for(let a of o){let o=n[a];if(o===void 0)continue;let l=(e.info.configOptions??[]).find(e=>e.id===a);if(l===void 0||!r&&l.currentValue===o||!r1(l,o))continue;let u=typeof o==`boolean`?{sessionId:i,configId:a,type:`boolean`,value:o}:{sessionId:i,configId:a,value:o};try{let n=await t.agent.request(BC.agent.session.setConfigOption,u);e.info.configOptions=n.configOptions,s=!0}catch(t){c.push(a),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:a},`[acp-threads] initial config apply failed`)}if(e.closed)return}c.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:c,sessionStateUnknown:r},`[acp-threads] some remembered config options could not be applied to the new session`),s&&this.emitInfo(e)}async applyInitialMode(e,t,n,r=!1){let i=e.sessionId;if(i===null)return;let a=e.info.modes;if(a!=null&&a.availableModes.some(e=>e.id===n)){if(!r&&a.currentModeId===n)return;try{await t.agent.request(BC.agent.session.setMode,{sessionId:i,modeId:n}),e.info.modes={...a,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 o=(e.info.configOptions??[]).find(e=>e.category===`mode`&&r1(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(BC.agent.session.setConfigOption,{sessionId:i,configId:o.id,value:n});e.info.configOptions=r.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),this.touchTurnActivity(r),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))}setChatGrant(e,t,n){let r=this.mustGet(e);r.chatGrants.has(t)!==n&&(n?r.chatGrants.add(t):r.chatGrants.delete(t),r.info.chatGrants=r.chatGrants.size>0?[...r.chatGrants]:void 0,this.opts.log.info({threadId:e,agentId:r.info.agent.id,grant:t,enabled:n},`[acp-threads] chat grant changed`),this.emitInfo(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.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await z$(r,{graceMs:t?.killGraceMs??R$e})||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(lK(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),this.clearStall(n),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.recordTerminalStatus(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 t1(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new t1(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),this.clearStall(t),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:z$e})))}async handlePermissionRequest(e,t,n){this.touchTurnActivity(e);let r=this.opts.permissions.decide(e.info.agent.id,t,n,e.chatGrants,this.opts.autoApproveOkTools?.()??!0);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,...UG(t)===null?{}:{readOnlyShell:!0},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){this.touchTurnActivity(e);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:xZe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await ic(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await ic(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
956
956
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
957
957
|
`)}return{content:i}}async handleFsWrite(e,t,n){this.touchTurnActivity(e);let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel},a=hK(t);try{t.dc.document.transact(()=>{let r=KQ(t.dc.document);GQ(t.dc.document,n,`replace`,i,void 0,UQ(t),a);let o=he(r,KQ(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...o===void 0?{}:{changedBlocks:o}})},t.origin)}catch(e){throw e instanceof xY?(SY(e,`acp-fs-write`),new RC(-32009,yY,{type:_Y,file:e.file,retryable:!0,retryAfterSeconds:3})):e}this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await Promise.resolve().then(()=>KK);await e(V(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return Z$e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new t1(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&EZe(n[n.length-1],t,e.info.agent))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>L$e){let t=e.events.length-L$e;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){if(s1(e)){(t===`error`||t===`auth_required`?this.opts.log.warn:this.opts.log.info).call(this.opts.log,{threadId:e.info.threadId,agentId:e.info.agent.id,status:t,suppressed:!0,detail:n===void 0?void 0:p$(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:p$(r.machineDetail)},`[acp-threads] status suppressed after thread close`);return}this.recordTerminalStatus(e,t,n,r)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),t===`error`&&r!==void 0&&LQe(r.reason)&&BQe(this.opts.localDir,{at:new Date,threadId:e.info.threadId,agentId:e.info.agent.id,agentSource:e.info.agent.source,reason:r.reason,detail:n,machineDetail:r.machineDetail}).catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] launch failure log write failed`)}),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){this.failPendingPermissions(e),this.failPendingConsents(e),e.lastInit=null,e.sessionId=null,e.info.contextWindow=null,await this.stopAgentProcess(e,`[acp-threads] terminal cleanup on failed-agent teardown failed`)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,stalledSince:i,chatGrants:a,...o}=e.info;return{version:1,info:o,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName,contextWindow:e.confirmedContextWindow??null}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingConsents(e){for(let t of[e.pendingRuntimeConsent,e.pendingPiBridgeConsent]){for(let e of t.values())clearTimeout(e.timer),e.resolve(`closed`);t.clear()}}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=_n(e.info.agent.id),i=fa[r]??Fn(e.agentSessionId);n.setPresence(lK(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now(),docTs:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function Z$e(e,t,n){let r=await oc(e),i=bs(ys(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await oc(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||ys(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(Cs).join(`/`),t=s.split(Cs).join(`/`);!QJ(e)&&!$J(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Cs).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=V(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):H(a.slice(t.length+1),o),a=t}}function Q$e(e){let t=e.info.status===`error`?`error`:`exited`;return{confirmedContextWindow:e.contextWindow??null,launchSettings:e.contextWindow==null?void 0:{contextWindow:e.contextWindow},info:{...e.info,contextWindow:null,status:t,archived:!0,resumable:e.info.resumable!==!1&&e.sessionId!==null,queue:void 0,steer:void 0,signInOutput:void 0,chatGrants:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,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,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:Date.now(),unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1,projectSkill:null,chatGrants:new Set}}function r1(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 $$e(e){let t=U$(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 e1e(e){let t=U$(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. The offer to download a private copy of ${t.displayName} expired before it was answered — start the agent again to get it back, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function t1e(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.code===-32e3||typeof t.data==`object`&&t.data!==null&&t.data.errorKind===`authentication_failed`}function i1(e){return e instanceof Error?e.message:String(e)}function a1(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return p$(JSON.stringify(t)).slice(0,300)}catch{return}}function n1e(e){return J$(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function o1(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(n!==void 0&&n.kind===`status`&&(n.status===`error`||n.status===`auth_required`))return n.detail??n.failure?.agentMessage}}async function r1e(e,t){return{reason:`connect`,agentMessage:e instanceof x$||e instanceof t1?e.message:String(e),machineDetail:l1({primary:e instanceof x$?e.machineDetail:void 0,tail:await c1(t)})}}function i1e(e){let t={id:crypto.randomUUID(),content:e.content,ts:e.ts};return e.attachments!==void 0&&e.attachments.length>0&&(t.attachments=e.attachments),t}function s1(e){return e.closed||e.info.archived===!0}async function c1(e){let t=e.stderrTail;await e.drainStderr?.();let n=p$(t.join(`
|
|
958
958
|
`)).slice(-16e3);return n===``?void 0:n}function l1({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,f$);let n=Math.min(t.length,1024),r=f$-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=f$-i.length-1;return`${i}\n${t.slice(-a)}`}function u1(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Fs as e,Go as t,Hl as n,Jn as r,No as i,Pa as a,Pd as o,gn as s,ru as c,xn as l,zt as u}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{$ as d,$a as f,$i as p,$n as m,$o as h,$r as g,$t as _,A as v,Aa as y,Ai as b,An as x,Ar as S,At as C,B as w,Ba as T,Bi as E,Bn as D,Br as O,Bt as k,C as A,Ca as j,Ci as M,Cn as N,Cr as P,Ct as F,D as I,Da as L,Di as R,Dn as z,Dr as B,Dt as V,E as H,Ea as U,Ei as W,En as G,Er as K,Et as q,F as J,Fa as Y,Fi as X,Fn as Z,Fr as Q,Ft as $,G as ee,Ga as te,Gi as ne,Gn as re,Gr as ie,Gt as ae,H as oe,Ha as se,Hi as ce,Hn as le,Ho as ue,Hr as de,Ht as fe,I as pe,Ia as me,Ii as he,In as ge,Ir as _e,It as ve,J as ye,Ja as be,Ji as xe,Jn as Se,Jo as Ce,Jr as we,Jt as Te,K as Ee,Ka as De,Ki as Oe,Kn as ke,Ko as Ae,Kr as je,Kt as Me,L as Ne,La as Pe,Li as Fe,Ln as Ie,Lr as Le,Lt as Re,M as ze,Ma as Be,Mi as Ve,Mn as He,Mr as Ue,Mt as We,N as Ge,Na as Ke,Ni as qe,Nn as Je,Nr as Ye,Nt as Xe,O as Ze,Oa as Qe,Oi as $e,On as et,Or as tt,Ot as nt,P as rt,Pa as it,Pi as at,Pn as ot,Pr as st,Pt as ct,Q as lt,Qa as ut,Qi as dt,Qn as ft,Qo as pt,Qr as mt,Qt as ht,R as gt,Ra as _t,Ri as vt,Rn as yt,Rr as bt,Rt as xt,S as St,Sa as Ct,Si as wt,Sn as Tt,Sr as Et,St as Dt,T as Ot,Ta as kt,Ti as At,Tn as jt,Tr as Mt,Tt as Nt,U as Pt,Ua as Ft,Ui as It,Un as Lt,Ur as Rt,Ut as zt,V as Bt,Va as Vt,Vi as Ht,Vn as Ut,Vo as Wt,Vr as Gt,Vt as Kt,W as qt,Wa as Jt,Wi as Yt,Wn as Xt,Wr as Zt,Wt as Qt,X as $t,Xa as en,Xi as tn,Xn as nn,Xo as rn,Xr as an,Xt as on,Y as sn,Ya as cn,Yi as ln,Yn as un,Yo as dn,Yr as fn,Yt as pn,Z as mn,Za as hn,Zi as gn,Zn as _n,Zo as vn,Zr as yn,Zt as bn,_ as xn,_a as Sn,_i as Cn,_n as wn,_o as Tn,_r as En,_t as Dn,a as On,aa as kn,ai as An,an as jn,ao as Mn,ar as Nn,at as Pn,b as Fn,ba as In,bi as Ln,bn as Rn,br as zn,bt as Bn,c as Vn,ca as Hn,ci as Un,cn as Wn,co as Gn,cr as Kn,ct as qn,d as Jn,da as Yn,di as Xn,dn as Zn,do as Qn,dr as $n,dt as er,ea as tr,ei as nr,en as rr,eo as ir,er as ar,es as or,et as sr,f as cr,fa as lr,fi as ur,fn as dr,fo as fr,fr as pr,ft as mr,g as hr,ga as gr,gi as _r,gn as vr,go as yr,gr as br,gt as xr,h as Sr,ha as Cr,hi as wr,hn as Tr,ho as Er,hr as Dr,ht as Or,i as kr,ia as Ar,ii as jr,in as Mr,io as Nr,ir as Pr,it as Fr,j as Ir,ja as Lr,ji as Rr,jn as zr,jr as Br,jt as Vr,k as Hr,ka as Ur,ki as Wr,kn as Gr,kr as Kr,kt as qr,l as Jr,la as Yr,li as Xr,ln as Zr,lo as Qr,lr as $r,lt as ei,m as ti,ma as ni,mi as ri,mn as ii,mo as ai,mr as oi,mt as si,n as ci,na as li,ni as ui,nn as di,no as fi,nr as pi,nt as mi,o as hi,oa as gi,oi as _i,on as vi,oo as yi,or as bi,ot as xi,p as Si,pa as Ci,pi as wi,pn as Ti,po as Ei,pr as Di,pt as Oi,q as ki,qa as Ai,qi as ji,qn as Mi,qo as Ni,qr as Pi,qt as Fi,r as Ii,ra as Li,ri as Ri,rn as zi,ro as Bi,rr as Vi,rt as Hi,s as Ui,sa as Wi,si as Gi,sn as Ki,so as qi,sr as Ji,st as Yi,t as Xi,ta as Zi,ti as Qi,tn as $i,to as ea,tr as ta,tt as na,u as ra,ua as ia,ui as aa,un as oa,uo as sa,ur as ca,ut as la,v as ua,va as da,vi as fa,vn as pa,vr as ma,vt as ha,w as ga,wa as _a,wi as va,wn as ya,wr as ba,wt as xa,x as Sa,xa as Ca,xi as wa,xn as Ta,xr as Ea,xt as Da,y as Oa,ya as ka,yi as Aa,yn as ja,yr as Ma,yt as Na,z as Pa,za as Fa,zi as Ia,zn as La,zr as Ra,zt as za}from"./dist-DrwvV8ac.mjs";export{Xi as AGENT_ID_MAX_LEN,ci as AGENT_ID_RE,Ii as AGENT_WRITE_ORIGIN,kr as AcpPermissionStore,On as AcpRegistry,hi as AcpThreadManager,Ui as AgentFocusBroadcaster,Vn as AgentPresenceBroadcaster,Jr as AgentSessionCapacityError,ra as AgentSessionManager,Jn as AutoStartDisabledError,cr as BUNDLE_IDS,Si as BUNDLE_SCOPE,ti as BUNDLE_SKILL_NAME,Sr as BacklinkIndex,hr as CC1Broadcaster,n as CC1_CONTRACT_VERSION,xn as CONCURRENT_REPLACE_WINDOW_MS,ua as CONFIG_FILENAME,Oa as CONFLICT_MARKER_RE,Fn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Sa as ConfigSchema,St as ConflictAuthority,A as DEFAULT_CHECKPOINT_RETENTION,ga as DEFAULT_EMBEDDINGS_DIMENSIONS,Ot as DEFAULT_PACK_ID,H as DocumentDurabilityState,I as DocumentDurabilityStateError,Ze as EMBEDDINGS_API_KEY_ENV,Hr as EPHEMERAL_PROJECT_DIR_PREFIX,v as ExposureConsentError,Ir as FEATURED_AGENT_IDS,ze as FILE_SYSTEM_WRITER,Ge as FILE_WATCHER_ORIGIN,rt as FileEmbeddingsBackend,J as GIT_PREFLIGHT_FAIL_SPAN_NAME,pe as GIT_UPSTREAM_WRITER,Wt as GitDirAccessError,Ne as GitNotAvailableError,gt as GitTooOldError,Pa as HOCUSPOCUS_AUTH_REJECTION_REASONS,w as HocuspocusAuthRejection,Bt as HocuspocusAuthTokenSchema,oe as HomeProjectRootError,Pt as INSTALLED_AGENTS_SCHEMES,qt as JSON_SCHEMA_DIALECT_2020_12,u as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ee as MANAGED_RENAME_ORIGIN,ki as MAX_ACP_THREADS,ye as MAX_AGENT_SESSIONS,sn as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,$t as MIN_EVICTABLE_IDLE_MS,mn as MIN_GIT_VERSION,lt as MISSING_OK_CONFIG_MESSAGE,ue as MalformedGitPointerError,d as McpLogger,sr as MissingOkConfigError,na as OBSERVER_SYNC_ORIGIN,mi as OK_OKIGNORE_TEMPLATE,Hi as ONBOARDING_BUNDLE_IDS,s as ORPHAN_MODES,l as PROTOCOL_VERSION,Ae as PinoLogger,Fr as ProcessLockCollisionError,Pn as ProjectGitInitError,xi as ROLLBACK_ORIGIN,Yi as ROOT_GITIGNORE_TEMPLATE,qn as RUNTIME_VERSION,ei as SERVICE_WRITER,la as SKILL_INSTALL_EVENTS_FILE_REL,r as SKILL_STATE_TARGETS,er as STARTER_FOLDER_FRONTMATTER_FILENAME,mr as STARTER_PACKS,Oi as STARTER_PACK_IDS,si as STATE_MANIFEST_FILENAME,Or as STATE_SCHEMA_VERSION,c as SYSTEM_DOC_NAME,xr as SeedPrerequisiteError,Dn as SeedRootDirError,ha as ServerLockCollisionError,Na as SingleFileNotAFileError,Bn as SingleFileNotFoundError,Da as SingleFileNotMarkdownError,Dt as SingleFileProjectOverrideError,F as StateManifestError,xa as TagIndex,Nt as USER_GLOBAL_BUNDLE_IDS,q as __getShowAllWalkStatsForTesting,V as __resetShowAllWalkStatsForTesting,nt as acquireProcessLock,qr as acquireServerLock,C as applyAgentMarkdownWrite,Vr as applyExternalChange,We as applySeed,Xe as assertCompatibleStateManifest,ct as assertGitAvailable,$ as assertNeverDiskEvent,ve as assertNotHomeProjectRoot,Re as attachAcpThreadSocket,xt as attachCollabClientCounter,za as attachIdleShutdown,k as bindConflictAuthority,Kt as bootServer,fe as buildAndOpenSkill,zt as buildConfigYmlContent,Qt as buildExecResult,ae as buildIngressPolicy,Me as buildOkMcpStdioCommand,Fi as buildSkillZip,Te as buildStarterFolderFrontmatterYaml,pn as buildWipTree,on as bundleSkillMdPath,bn as canonicalProjectKey,ht as canonicalizeForCompare,_ as classifyEvents,rr as classifyFsPath,$i as clearAllEmbeddingsKeys,di as coercePackId,zi as collectServerHostSnapshot,a as colorFromSeed,Mr as commitUpstreamImport,jn as commitWip,vi as commitWipFromTree,Ki as compareSemver,Wn as composeEffectiveLinterConfig,Zr as composeFrontmatterSchemasConfig,oa as containsConflictMarkers,Zn as contentHash,dr as contributorCount,Ti as countShadowObjects,ii as countStaleAgentWipRefs,Tr as countWipRefs,vr as createApiExtension,wn as createAssetServeMiddleware,pa as createCollaborationHost,ja as createContentFilter,Rn as createContentFilterAsync,Ta as createEmbeddingsSecretStore,Tt as createEphemeralProjectDir,N as createExternalChangeHandler,ya as createFileLogger,jt as createLiveDerivedIndexExtension,G as createMcpHttpHandler,z as createOsProbe,et as createPersistenceExtension,Gr as createProbeFailureReporter,x as createServer,zr as createServerObserverExtension,He as createServerProbeResolver,Je as createStreamingErrorWriter,Ni as createTestLogger,ot as describeStoredEmbeddingsKey,Z as detectClaudeDesktopPresence,ge as detectGit,Ie as detectProjectShape,yt as detectUserSkillHosts,La as discoverLockDirs,D as discoverMarkdownlintConfig,Ut as emitPreflightFailureSpan,le as encodeDocName,Lt as encodeFolderRoute,Xt as encodeSkillRoute,re as ensureProjectGit,ke as errorResponse,Mi as evictStaleTrackerEntries,Se as extractHeadings,un as extractOkBinaryPath,nn as extractWikiLinksFromMarkdown,_n as fallbackPaths,ft as findEnclosingGitRoot,m as findEnclosingProjectRoot,ar as findNativeMarkdownlintFile,ta as flushFileLogger,pi as formatAuditBrokenLinkSuppressionLine,Vi as formatAuthRejectionWire,Pr as formatContributorsFrom,Nn as formatPackRationale,bi as gcCheckpointRefs,Ji as getCurrentMcpLogger,Kn as getIngressContext,$r as getLocalDir,ca as getLogFilePath,Ce as getLogger,$n as getLogsDir,pr as getMachineId,Di as getMeter,oi as getMetrics,Dr as getTracer,br as handleCollabSocketError,En as handleSpawnCursor,ma as hasForwardingHeaders,Ma as hasGcLogLatch,i as iconFromClientName,zn as incrementCollabSocketFilteredError,Ea as incrementServerObserverFire,Et as initContent,P as initShadowRepo,ba as initTelemetry,Mt as initToleranceTelemetryWriter,K as installJsonSchemaDialect,B as installPrettyZodErrors,dn as installTestLoggers,tt as installUserSkill,Kr as isAllowedApiOrigin,S as isAllowedWorkspaceHostHeader,Br as isConfigDoc,Ue as isDefunctProcess,Ye as isDocInConflict,st as isHocuspocusAuthRejectionReason,Q as isHomeDir,_e as isHostAdmitted,Le as isKnownPackId,bt as isLinkIndexExcludedDoc,Ra as isLockProcessRunning,O as isLoopbackAddress,Gt as isManagedArtifactDoc,de as isOriginAdmitted,t as isOrphanMode,Rt as isPairedWriteOrigin,Zt as isPathWithinDir,ie as isPeerAdmitted,je as isProcessAlive,Pi as isProjectRoot,we as isReservedForUserTree,fn as isSelfWrite,an as isSystemDoc,yn as isToleranceTelemetryEnabled,mt as isValidLockPid,g as lastKnownHash,nr as listRescueCheckpoints,Qi as listStarterPacks,ui as loadCustomAgents,Ri as loadPrincipal,jr as lockAdvertisesUi,An as lockBaseUrl,_i as lockFilePath,rn as loggerFactory,Gi as loginShapedUserinfoUser,vn as logsCurrentPath,pt as logsPreviousPath,Un as makeLazyEmbeddingsKeyStore,Xr as markServerLockDraining,aa as mountMcpAndApi,Xn as normalizeFsPath,ur as observeReadiness,wi as packageVersionMajorMinor,ri as parseAuthRejectionWire,wr as parseGitVersion,_r as parseHocuspocusAuthToken,Cn as parseKeepaliveConnectionId,fa as pathToDocName,Aa as planSeed,Ln as prepareSingleFileOpen,wa as processCommand,wt as processUsage,M as readAllTargets,va as readBundleDecision,At as readDeclaredGitHubHosts,W as readOriginGitHubRepo,R as readOwnNativeRules,$e as readProcessLock,Wr as readProcessLockDetailed,b as readProcessState,Rr as readProjectHeadState,Ve as readProjectLocalSemanticConfig,qe as readServerLock,at as readServerPackageVersion,X as readSkillInstallStateSnapshot,he as readStateManifest,Fe as readTargetRecordedAt,vt as readTargetVersion,Ia as reconcile,E as recordContributor,Ht as recordSkillInstallEvent,ce as redactShareSubprocessStderr,It as registerAllTools,Yt as registerWrite,ne as releaseProcessLock,Oe as releaseServerLock,ji as removeLastKnownHash,xe as removeProjectSkillGitignoreBlock,ln as reportSkillInstall,tn as resetMetrics,gn as resolveBuiltinSkillHosts,e as resolveBundleEnabled,dt as resolveBundledSkillDir,p as resolveContentDir,tr as resolveCursorBinaryDefault,Zi as resolveCursorSpawnInvocation,li as resolveEffectiveLinterConfig,Li as resolveEmbeddingsCredential,Ar as resolveGitHubAccountFromUrl,kn as resolveGitHubAuthHost,gi as resolveLockDir,Wi as resolveNativeConfigForDoc,Hn as resolveNativeMarkdownlintConfig,Yr as resolvePack,ia as resolvePackageVersion,Yn as resolveSkillInstallReportSettings,lr as resolveUiInfo,Ci as restoreContributors,ni as rewriteMarkdownLinksForDocumentRename,Cr as rewriteWikiLinksForDocumentRename,gr as runAuthReposSubprocess,Sn as runAuthStatusSubprocess,da as runCloneSubprocess,ka as runDeviceFlowSubprocess,In as runWithMcpLogger,Ca as safeContentPath,Ct as safeSubdir,j as safetyCheckpoint,_a as sameGitHubLogin,kt as sanitizeClientName,U as saveInMemoryCheckpoint,L as saveVersion,Qe as scanLockProcesses,Ur as seedBasenameIndex,y as seedEphemeralProjectDir,Lr as serializeError,Be as setActiveSpanAttributes,Ke as setupServerObservers,it as shadowGit,Y as shutdownTelemetry,h as spansCurrentPath,or as spansPreviousPath,me as spawnDetached,Pe as splitMarkdownBlocks,_t as startWatcher,Fa as strategiesFor,T as streamingProblemEvent,Vt as swapContributors,se as teardownToleranceTelemetryWriter,Ft as toBroadcasterKey,Jt as tracedAppendFileSync,te as tracedLinkSync,De as tracedMkdir,Ai as tracedMkdirSync,be as tracedRename,cn as tracedRenameSync,en as tracedRmSync,hn as tracedRmdirSync,ut as tracedUnlinkSync,f as tracedWriteFile,ir as tracedWriteFileSync,ea as trustSystemCertificates,fi as updateLastKnownHash,Bi as updateProcessLockPort,Nr as updateServerLockPort,Mn as validateAgentId,yi as validateCloneInputs,qi as validateSkillZip,Gn as waitForServerLockDrain,Qr as withHiddenWindowsConsole,sa as withSpan,Qn as withSpanSync,fr as writeBundleDecision,Ei as writeMarkdownlintRule,ai as writeRootGitignoreForNewRepo,Er as writeStateManifest,yr as writeTargetVersion,Tn as writeTracker};
|
|
1
|
+
import{Fs as e,Go as t,Hl as n,Jn as r,No as i,Pa as a,Pd as o,gn as s,ru as c,xn as l,zt as u}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{$ as d,$a as f,$i as p,$n as m,$o as h,$r as g,$t as _,A as v,Aa as y,Ai as b,An as x,Ar as S,At as C,B as w,Ba as T,Bi as E,Bn as D,Br as O,Bt as k,C as A,Ca as j,Ci as M,Cn as N,Cr as P,Ct as F,D as I,Da as L,Di as R,Dn as z,Dr as B,Dt as V,E as H,Ea as U,Ei as W,En as G,Er as K,Et as q,F as J,Fa as Y,Fi as X,Fn as Z,Fr as Q,Ft as $,G as ee,Ga as te,Gi as ne,Gn as re,Gr as ie,Gt as ae,H as oe,Ha as se,Hi as ce,Hn as le,Ho as ue,Hr as de,Ht as fe,I as pe,Ia as me,Ii as he,In as ge,Ir as _e,It as ve,J as ye,Ja as be,Ji as xe,Jn as Se,Jo as Ce,Jr as we,Jt as Te,K as Ee,Ka as De,Ki as Oe,Kn as ke,Ko as Ae,Kr as je,Kt as Me,L as Ne,La as Pe,Li as Fe,Ln as Ie,Lr as Le,Lt as Re,M as ze,Ma as Be,Mi as Ve,Mn as He,Mr as Ue,Mt as We,N as Ge,Na as Ke,Ni as qe,Nn as Je,Nr as Ye,Nt as Xe,O as Ze,Oa as Qe,Oi as $e,On as et,Or as tt,Ot as nt,P as rt,Pa as it,Pi as at,Pn as ot,Pr as st,Pt as ct,Q as lt,Qa as ut,Qi as dt,Qn as ft,Qo as pt,Qr as mt,Qt as ht,R as gt,Ra as _t,Ri as vt,Rn as yt,Rr as bt,Rt as xt,S as St,Sa as Ct,Si as wt,Sn as Tt,Sr as Et,St as Dt,T as Ot,Ta as kt,Ti as At,Tn as jt,Tr as Mt,Tt as Nt,U as Pt,Ua as Ft,Ui as It,Un as Lt,Ur as Rt,Ut as zt,V as Bt,Va as Vt,Vi as Ht,Vn as Ut,Vo as Wt,Vr as Gt,Vt as Kt,W as qt,Wa as Jt,Wi as Yt,Wn as Xt,Wr as Zt,Wt as Qt,X as $t,Xa as en,Xi as tn,Xn as nn,Xo as rn,Xr as an,Xt as on,Y as sn,Ya as cn,Yi as ln,Yn as un,Yo as dn,Yr as fn,Yt as pn,Z as mn,Za as hn,Zi as gn,Zn as _n,Zo as vn,Zr as yn,Zt as bn,_ as xn,_a as Sn,_i as Cn,_n as wn,_o as Tn,_r as En,_t as Dn,a as On,aa as kn,ai as An,an as jn,ao as Mn,ar as Nn,at as Pn,b as Fn,ba as In,bi as Ln,bn as Rn,br as zn,bt as Bn,c as Vn,ca as Hn,ci as Un,cn as Wn,co as Gn,cr as Kn,ct as qn,d as Jn,da as Yn,di as Xn,dn as Zn,do as Qn,dr as $n,dt as er,ea as tr,ei as nr,en as rr,eo as ir,er as ar,es as or,et as sr,f as cr,fa as lr,fi as ur,fn as dr,fo as fr,fr as pr,ft as mr,g as hr,ga as gr,gi as _r,gn as vr,go as yr,gr as br,gt as xr,h as Sr,ha as Cr,hi as wr,hn as Tr,ho as Er,hr as Dr,ht as Or,i as kr,ia as Ar,ii as jr,in as Mr,io as Nr,ir as Pr,it as Fr,j as Ir,ja as Lr,ji as Rr,jn as zr,jr as Br,jt as Vr,k as Hr,ka as Ur,ki as Wr,kn as Gr,kr as Kr,kt as qr,l as Jr,la as Yr,li as Xr,ln as Zr,lo as Qr,lr as $r,lt as ei,m as ti,ma as ni,mi as ri,mn as ii,mo as ai,mr as oi,mt as si,n as ci,na as li,ni as ui,nn as di,no as fi,nr as pi,nt as mi,o as hi,oa as gi,oi as _i,on as vi,oo as yi,or as bi,ot as xi,p as Si,pa as Ci,pi as wi,pn as Ti,po as Ei,pr as Di,pt as Oi,q as ki,qa as Ai,qi as ji,qn as Mi,qo as Ni,qr as Pi,qt as Fi,r as Ii,ra as Li,ri as Ri,rn as zi,ro as Bi,rr as Vi,rt as Hi,s as Ui,sa as Wi,si as Gi,sn as Ki,so as qi,sr as Ji,st as Yi,t as Xi,ta as Zi,ti as Qi,tn as $i,to as ea,tr as ta,tt as na,u as ra,ua as ia,ui as aa,un as oa,uo as sa,ur as ca,ut as la,v as ua,va as da,vi as fa,vn as pa,vr as ma,vt as ha,w as ga,wa as _a,wi as va,wn as ya,wr as ba,wt as xa,x as Sa,xa as Ca,xi as wa,xn as Ta,xr as Ea,xt as Da,y as Oa,ya as ka,yi as Aa,yn as ja,yr as Ma,yt as Na,z as Pa,za as Fa,zi as Ia,zn as La,zr as Ra,zt as za}from"./dist-D0NB38wf.mjs";export{Xi as AGENT_ID_MAX_LEN,ci as AGENT_ID_RE,Ii as AGENT_WRITE_ORIGIN,kr as AcpPermissionStore,On as AcpRegistry,hi as AcpThreadManager,Ui as AgentFocusBroadcaster,Vn as AgentPresenceBroadcaster,Jr as AgentSessionCapacityError,ra as AgentSessionManager,Jn as AutoStartDisabledError,cr as BUNDLE_IDS,Si as BUNDLE_SCOPE,ti as BUNDLE_SKILL_NAME,Sr as BacklinkIndex,hr as CC1Broadcaster,n as CC1_CONTRACT_VERSION,xn as CONCURRENT_REPLACE_WINDOW_MS,ua as CONFIG_FILENAME,Oa as CONFLICT_MARKER_RE,Fn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Sa as ConfigSchema,St as ConflictAuthority,A as DEFAULT_CHECKPOINT_RETENTION,ga as DEFAULT_EMBEDDINGS_DIMENSIONS,Ot as DEFAULT_PACK_ID,H as DocumentDurabilityState,I as DocumentDurabilityStateError,Ze as EMBEDDINGS_API_KEY_ENV,Hr as EPHEMERAL_PROJECT_DIR_PREFIX,v as ExposureConsentError,Ir as FEATURED_AGENT_IDS,ze as FILE_SYSTEM_WRITER,Ge as FILE_WATCHER_ORIGIN,rt as FileEmbeddingsBackend,J as GIT_PREFLIGHT_FAIL_SPAN_NAME,pe as GIT_UPSTREAM_WRITER,Wt as GitDirAccessError,Ne as GitNotAvailableError,gt as GitTooOldError,Pa as HOCUSPOCUS_AUTH_REJECTION_REASONS,w as HocuspocusAuthRejection,Bt as HocuspocusAuthTokenSchema,oe as HomeProjectRootError,Pt as INSTALLED_AGENTS_SCHEMES,qt as JSON_SCHEMA_DIALECT_2020_12,u as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ee as MANAGED_RENAME_ORIGIN,ki as MAX_ACP_THREADS,ye as MAX_AGENT_SESSIONS,sn as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,$t as MIN_EVICTABLE_IDLE_MS,mn as MIN_GIT_VERSION,lt as MISSING_OK_CONFIG_MESSAGE,ue as MalformedGitPointerError,d as McpLogger,sr as MissingOkConfigError,na as OBSERVER_SYNC_ORIGIN,mi as OK_OKIGNORE_TEMPLATE,Hi as ONBOARDING_BUNDLE_IDS,s as ORPHAN_MODES,l as PROTOCOL_VERSION,Ae as PinoLogger,Fr as ProcessLockCollisionError,Pn as ProjectGitInitError,xi as ROLLBACK_ORIGIN,Yi as ROOT_GITIGNORE_TEMPLATE,qn as RUNTIME_VERSION,ei as SERVICE_WRITER,la as SKILL_INSTALL_EVENTS_FILE_REL,r as SKILL_STATE_TARGETS,er as STARTER_FOLDER_FRONTMATTER_FILENAME,mr as STARTER_PACKS,Oi as STARTER_PACK_IDS,si as STATE_MANIFEST_FILENAME,Or as STATE_SCHEMA_VERSION,c as SYSTEM_DOC_NAME,xr as SeedPrerequisiteError,Dn as SeedRootDirError,ha as ServerLockCollisionError,Na as SingleFileNotAFileError,Bn as SingleFileNotFoundError,Da as SingleFileNotMarkdownError,Dt as SingleFileProjectOverrideError,F as StateManifestError,xa as TagIndex,Nt as USER_GLOBAL_BUNDLE_IDS,q as __getShowAllWalkStatsForTesting,V as __resetShowAllWalkStatsForTesting,nt as acquireProcessLock,qr as acquireServerLock,C as applyAgentMarkdownWrite,Vr as applyExternalChange,We as applySeed,Xe as assertCompatibleStateManifest,ct as assertGitAvailable,$ as assertNeverDiskEvent,ve as assertNotHomeProjectRoot,Re as attachAcpThreadSocket,xt as attachCollabClientCounter,za as attachIdleShutdown,k as bindConflictAuthority,Kt as bootServer,fe as buildAndOpenSkill,zt as buildConfigYmlContent,Qt as buildExecResult,ae as buildIngressPolicy,Me as buildOkMcpStdioCommand,Fi as buildSkillZip,Te as buildStarterFolderFrontmatterYaml,pn as buildWipTree,on as bundleSkillMdPath,bn as canonicalProjectKey,ht as canonicalizeForCompare,_ as classifyEvents,rr as classifyFsPath,$i as clearAllEmbeddingsKeys,di as coercePackId,zi as collectServerHostSnapshot,a as colorFromSeed,Mr as commitUpstreamImport,jn as commitWip,vi as commitWipFromTree,Ki as compareSemver,Wn as composeEffectiveLinterConfig,Zr as composeFrontmatterSchemasConfig,oa as containsConflictMarkers,Zn as contentHash,dr as contributorCount,Ti as countShadowObjects,ii as countStaleAgentWipRefs,Tr as countWipRefs,vr as createApiExtension,wn as createAssetServeMiddleware,pa as createCollaborationHost,ja as createContentFilter,Rn as createContentFilterAsync,Ta as createEmbeddingsSecretStore,Tt as createEphemeralProjectDir,N as createExternalChangeHandler,ya as createFileLogger,jt as createLiveDerivedIndexExtension,G as createMcpHttpHandler,z as createOsProbe,et as createPersistenceExtension,Gr as createProbeFailureReporter,x as createServer,zr as createServerObserverExtension,He as createServerProbeResolver,Je as createStreamingErrorWriter,Ni as createTestLogger,ot as describeStoredEmbeddingsKey,Z as detectClaudeDesktopPresence,ge as detectGit,Ie as detectProjectShape,yt as detectUserSkillHosts,La as discoverLockDirs,D as discoverMarkdownlintConfig,Ut as emitPreflightFailureSpan,le as encodeDocName,Lt as encodeFolderRoute,Xt as encodeSkillRoute,re as ensureProjectGit,ke as errorResponse,Mi as evictStaleTrackerEntries,Se as extractHeadings,un as extractOkBinaryPath,nn as extractWikiLinksFromMarkdown,_n as fallbackPaths,ft as findEnclosingGitRoot,m as findEnclosingProjectRoot,ar as findNativeMarkdownlintFile,ta as flushFileLogger,pi as formatAuditBrokenLinkSuppressionLine,Vi as formatAuthRejectionWire,Pr as formatContributorsFrom,Nn as formatPackRationale,bi as gcCheckpointRefs,Ji as getCurrentMcpLogger,Kn as getIngressContext,$r as getLocalDir,ca as getLogFilePath,Ce as getLogger,$n as getLogsDir,pr as getMachineId,Di as getMeter,oi as getMetrics,Dr as getTracer,br as handleCollabSocketError,En as handleSpawnCursor,ma as hasForwardingHeaders,Ma as hasGcLogLatch,i as iconFromClientName,zn as incrementCollabSocketFilteredError,Ea as incrementServerObserverFire,Et as initContent,P as initShadowRepo,ba as initTelemetry,Mt as initToleranceTelemetryWriter,K as installJsonSchemaDialect,B as installPrettyZodErrors,dn as installTestLoggers,tt as installUserSkill,Kr as isAllowedApiOrigin,S as isAllowedWorkspaceHostHeader,Br as isConfigDoc,Ue as isDefunctProcess,Ye as isDocInConflict,st as isHocuspocusAuthRejectionReason,Q as isHomeDir,_e as isHostAdmitted,Le as isKnownPackId,bt as isLinkIndexExcludedDoc,Ra as isLockProcessRunning,O as isLoopbackAddress,Gt as isManagedArtifactDoc,de as isOriginAdmitted,t as isOrphanMode,Rt as isPairedWriteOrigin,Zt as isPathWithinDir,ie as isPeerAdmitted,je as isProcessAlive,Pi as isProjectRoot,we as isReservedForUserTree,fn as isSelfWrite,an as isSystemDoc,yn as isToleranceTelemetryEnabled,mt as isValidLockPid,g as lastKnownHash,nr as listRescueCheckpoints,Qi as listStarterPacks,ui as loadCustomAgents,Ri as loadPrincipal,jr as lockAdvertisesUi,An as lockBaseUrl,_i as lockFilePath,rn as loggerFactory,Gi as loginShapedUserinfoUser,vn as logsCurrentPath,pt as logsPreviousPath,Un as makeLazyEmbeddingsKeyStore,Xr as markServerLockDraining,aa as mountMcpAndApi,Xn as normalizeFsPath,ur as observeReadiness,wi as packageVersionMajorMinor,ri as parseAuthRejectionWire,wr as parseGitVersion,_r as parseHocuspocusAuthToken,Cn as parseKeepaliveConnectionId,fa as pathToDocName,Aa as planSeed,Ln as prepareSingleFileOpen,wa as processCommand,wt as processUsage,M as readAllTargets,va as readBundleDecision,At as readDeclaredGitHubHosts,W as readOriginGitHubRepo,R as readOwnNativeRules,$e as readProcessLock,Wr as readProcessLockDetailed,b as readProcessState,Rr as readProjectHeadState,Ve as readProjectLocalSemanticConfig,qe as readServerLock,at as readServerPackageVersion,X as readSkillInstallStateSnapshot,he as readStateManifest,Fe as readTargetRecordedAt,vt as readTargetVersion,Ia as reconcile,E as recordContributor,Ht as recordSkillInstallEvent,ce as redactShareSubprocessStderr,It as registerAllTools,Yt as registerWrite,ne as releaseProcessLock,Oe as releaseServerLock,ji as removeLastKnownHash,xe as removeProjectSkillGitignoreBlock,ln as reportSkillInstall,tn as resetMetrics,gn as resolveBuiltinSkillHosts,e as resolveBundleEnabled,dt as resolveBundledSkillDir,p as resolveContentDir,tr as resolveCursorBinaryDefault,Zi as resolveCursorSpawnInvocation,li as resolveEffectiveLinterConfig,Li as resolveEmbeddingsCredential,Ar as resolveGitHubAccountFromUrl,kn as resolveGitHubAuthHost,gi as resolveLockDir,Wi as resolveNativeConfigForDoc,Hn as resolveNativeMarkdownlintConfig,Yr as resolvePack,ia as resolvePackageVersion,Yn as resolveSkillInstallReportSettings,lr as resolveUiInfo,Ci as restoreContributors,ni as rewriteMarkdownLinksForDocumentRename,Cr as rewriteWikiLinksForDocumentRename,gr as runAuthReposSubprocess,Sn as runAuthStatusSubprocess,da as runCloneSubprocess,ka as runDeviceFlowSubprocess,In as runWithMcpLogger,Ca as safeContentPath,Ct as safeSubdir,j as safetyCheckpoint,_a as sameGitHubLogin,kt as sanitizeClientName,U as saveInMemoryCheckpoint,L as saveVersion,Qe as scanLockProcesses,Ur as seedBasenameIndex,y as seedEphemeralProjectDir,Lr as serializeError,Be as setActiveSpanAttributes,Ke as setupServerObservers,it as shadowGit,Y as shutdownTelemetry,h as spansCurrentPath,or as spansPreviousPath,me as spawnDetached,Pe as splitMarkdownBlocks,_t as startWatcher,Fa as strategiesFor,T as streamingProblemEvent,Vt as swapContributors,se as teardownToleranceTelemetryWriter,Ft as toBroadcasterKey,Jt as tracedAppendFileSync,te as tracedLinkSync,De as tracedMkdir,Ai as tracedMkdirSync,be as tracedRename,cn as tracedRenameSync,en as tracedRmSync,hn as tracedRmdirSync,ut as tracedUnlinkSync,f as tracedWriteFile,ir as tracedWriteFileSync,ea as trustSystemCertificates,fi as updateLastKnownHash,Bi as updateProcessLockPort,Nr as updateServerLockPort,Mn as validateAgentId,yi as validateCloneInputs,qi as validateSkillZip,Gn as waitForServerLockDrain,Qr as withHiddenWindowsConsole,sa as withSpan,Qn as withSpanSync,fr as writeBundleDecision,Ei as writeMarkdownlintRule,ai as writeRootGitignoreForNewRepo,Er as writeStateManifest,yr as writeTargetVersion,Tn as writeTracker};
|
package/dist/index.mjs
CHANGED
|
@@ -1535,6 +1535,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1535
1535
|
`);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
|
|
1536
1536
|
`)?`
|
|
1537
1537
|
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const gje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function _je(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const vje=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function yje(e){let t={contentDir:e.contentDir};for(let n of vje)for(let r of P9(N(e.stagingDir,n)))_je(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=me(n);n.endsWith(`.jsonl`)?j9(n,t):gje.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function bje(e){return N(e,...I9,z9)}function xje(e){return N(e,...I9,B9)}function Sje(e){return N(e,...L9,V9)}function Cje(e){return N(e,...L9,H9)}function wje(e){return N(e,...R9,U9)}function Tje(e){return N(e,...R9,W9)}const G9=1e3;async function Eje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function Dje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function Oje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function kje(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
|
|
1538
|
-
`)}\n`:null}catch{return null}}function Aje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function jje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function Mje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Nje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function Pje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Pje(e.maxBytes)}function Fje(e){let t=J9(RX(`project`,e)),n=J9(RX(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function Ije(e){return Ne(`sha256`).update(e).digest(`hex`)}function Lje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Rje=[`"doc.name"`,`"docName"`];function zje(e){let t=S(e,`utf-8`),n=0;for(let e of Rje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Bje=new Set([`.jsonl`]);function Vje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Bje.has(e.slice(t))}const Hje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Uje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Hje.has(e.slice(t))}function Wje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Uje(r))continue;let{redacted:i,patterns:a,lineCount:o}=kB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function Gje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Eje,a=r.fetchAgentEffects??Dje,o=r.fetchWatcherRecent??Oje,s=r.readShadowHead??Aje,c=r.readCheckpointRefs??jje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.78.0-beta.
|
|
1538
|
+
`)}\n`:null}catch{return null}}function Aje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function jje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function Mje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Nje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function Pje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Pje(e.maxBytes)}function Fje(e){let t=J9(RX(`project`,e)),n=J9(RX(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function Ije(e){return Ne(`sha256`).update(e).digest(`hex`)}function Lje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Rje=[`"doc.name"`,`"docName"`];function zje(e){let t=S(e,`utf-8`),n=0;for(let e of Rje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Bje=new Set([`.jsonl`]);function Vje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Bje.has(e.slice(t))}const Hje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Uje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Hje.has(e.slice(t))}function Wje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Uje(r))continue;let{redacted:i,patterns:a,lineCount:o}=kB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function Gje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Eje,a=r.fetchAgentEffects??Dje,o=r.fetchWatcherRecent??Oje,s=r.readShadowHead??Aje,c=r.readCheckpointRefs??jje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.78.0-beta.1`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??Mje,h=r.isOtlpPushEnabled??Nje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(bje(n),N(_,`telemetry`,z9)),Z9(xje(n),N(_,`telemetry`,B9)),Z9(Sje(n),N(_,`logs`,V9)),Z9(Cje(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,eR,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=kje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(wje(n),N(_,`state`,U9)),Z9(Tje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Ru),N(_,`state`,Ru)),Z9(N(b,zu),N(_,`state`,zu)),Z9(N(b,Lu),N(_,`state`,Lu));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
|
|
1539
1539
|
`:`not-running (${w})\n`;re(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(e.diagnosticReports,y);if(re(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&yje({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=Wje(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??me(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=Fje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Vje(t)?Lje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=zje(e))}let fe={applied:k};ce!==null&&(fe.secretScrub=ce);let pe={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:Ije(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:A};re(N(_,`manifest.json`),`${JSON.stringify(pe,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:pe,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function Kje(e){let{collected:t,outputPath:n}=e,r=M(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new JCe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function qje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=G8(t)?t.content:void 0,i=G8(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return be(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return be(e)}async function Jje(e,t,n,r,i){let a=E7(t,e.logger),o=await Gje({contentDir:qje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...iAe(a,e.userLogsDir??N(k(),`.ok`,`logs`)),...O7(e.cachesDir??N(k(),`Library`,`Caches`))],userStateFiles:k7(e.bugReportsDir??T7()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(M(e.outputPath),{recursive:!0}),await Kje({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Yje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>$ke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Jje(e,t,n,r,i());let{zipPath:a,summary:o}=await lAe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:O7(e.cachesDir??N(k(),`Library`,`Caches`)),bugReportLedgerFiles:k7(e.bugReportsDir??T7()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Q8 as ALL_EDITOR_IDS,$8 as EDITOR_LABELS,k5 as EDITOR_TARGETS,bOe as HOSTS_WITH_USER_SKILL_DIR,zke as LAUNCH_CONFIG_NAME,QAe as PATH_SHIM_BEGIN,eje as PATH_SHIM_BLOCK_RE,$Ae as PATH_SHIM_END,I5 as ProjectPathSafetyError,_ke as addOkPathsToGitExclude,L5 as assertProjectPathSafe,d5 as buildManagedServerEntry,HAe as buildMcpConfigDeclineEvent,UAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Yje as collectReportBundle,aje as createCliProbeResolver,on as createTokenStore,tAe as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,Uke as detectInstalledEditors,b5 as droppedManagedKeys,VOe as editorConfigPathDisplay,BOe as editorEntryLocator,jAe as ensurePiBridge,Q5 as formatTrackedRemediation,bke as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,yOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,l5 as isEntryUpToDate,f5 as isOwnManagedEntry,YAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,XAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,tje as pathInstallMarkerPath,nke as previewContent,Wke as probeOwnManagedEditorMcpEntry,kAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,yke as readSharingMode,kB as redactContent,vke as removeOkPathsFromGitExclude,RAe as removeOwnMcpEntry,mke as removeProjectSkill,sje as removeUserGlobalSkillBundle,pje as removeUserSkill,cke as resolveProjectRoot,KAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,fje as userSkillPresentAnywhere,ZAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,uje as writeProjectAiIntegrations,U5 as writeProjectSkill,Hke as writeUserMcpConfigs,dje as writeUserSkill};
|
|
1540
1540
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$l as r,Bd as i,Gd as a,Kd as o,Mt as s,Pd as c,Ud as l,Uu as u,Vd as d,Vl as f,Xd as p,Yd as m,Yl as h,gs as g,ic as _,qu as v,vs as y,zu as b}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{Do as x,Eo as S,Fr as ee,Gn as te,Go as ne,H as re,Ji as ie,L as ae,No as C,Oo as oe,Or as se,Qi as ce,Qt as le,R as ue,Rn as de,Sr as fe,To as pe,Tt as me,Yi as he,at as ge,da as _e,fo as ve,ko as ye,lo as be,m as xe,mo as Se,qr as Ce,rt as we,zo as Te}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$l as r,Bd as i,Gd as a,Kd as o,Mt as s,Pd as c,Ud as l,Uu as u,Vd as d,Vl as f,Xd as p,Yd as m,Yl as h,gs as g,ic as _,qu as v,vs as y,zu as b}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{Do as x,Eo as S,Fr as ee,Gn as te,Go as ne,H as re,Ji as ie,L as ae,No as C,Oo as oe,Or as se,Qi as ce,Qt as le,R as ue,Rn as de,Sr as fe,To as pe,Tt as me,Yi as he,at as ge,da as _e,fo as ve,ko as ye,lo as be,m as xe,mo as Se,qr as Ce,rt as we,zo as Te}from"./dist-D0NB38wf.mjs";import{i as w,n as T,o as E,r as Ee,s as D,t as O}from"./colors-r_owlCuY.mjs";import{t as k}from"./is-object-BGze3w87.mjs";import{t as De}from"./constants-CqnSfysY.mjs";import{t as Oe}from"./preview-CJ4lC6m4.mjs";import{createRequire as ke}from"node:module";import{execFileSync as Ae}from"node:child_process";import je,{basename as Me,dirname as A,isAbsolute as Ne,join as j,posix as Pe,relative as M,resolve as N,sep as P,win32 as Fe}from"node:path";import F from"node:process";import{fileURLToPath as Ie}from"node:url";import{cpSync as Le,existsSync as I,lstatSync as Re,mkdirSync as ze,readFileSync as L,readdirSync as Be,readlinkSync as Ve,realpathSync as He,rmSync as Ue,statSync as We,writeFileSync as Ge}from"node:fs";import{homedir as R}from"node:os";import{inspect as Ke,stripVTControlCharacters as qe,styleText as z}from"node:util";import*as Je from"node:readline";import{AsyncLocalStorage as Ye,AsyncResource as Xe}from"node:async_hooks";var Ze=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),Qe=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),$e=n((e=>{let{humanReadableArgName:t}=Qe();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
2
2
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
3
3
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),et=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&C(e,g,{mode:Ca(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const _o=e=>e!==`project`,vo=e=>e!==`user`;async function yo(){let e=await Ma({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function bo(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??yo)():`both`}async function xo(e){return La({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:"OK config stays on this machine only; teammates do not see it. Safe escape hatch via `ok config-sharing share`."}]})}async function So(e){if(e.sharing!==void 0)return e.sharing;let t=Ki(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??xo)(t):t}var Co=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}};function wo(e){if(e===void 0||e===!0)return new Set(we);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(me.filter(e=>t.includes(e)))}function To(e,t,n){let r=N(n,e),i;try{i=We(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Co(`--content-dir path does not exist: ${r}`):new Co(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Co(`--content-dir must be a directory: ${r}`);let a=Eo(t),o=Eo(r),s=M(a,o);if(s.startsWith(`..`)||Ne(s))throw new Co(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Eo(e){try{return He(e)}catch{return e}}const Do=`open-knowledge-ui`;function Oo(e,t,n){try{let r=e.detectPath?.(t,n)??A(e.configPath(t,n));return I(r)}catch{return!1}}function ko(e,t,n){try{let r=N(A(e.configPath(t,n))),i=N(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+P)}catch{return!1}}function Ao(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!I(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||ko(e,t,r);if(!i&&c&&!Oo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{oa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return Mo(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||ze(A(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{Te(`${o}.lock`,()=>{let t=Xa(o).writePath;if(s||ze(A(t),{recursive:!0}),e.format===`toml`){let r=po(Hr(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=go(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=fo(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const jo={pi:Ha};function Mo(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=jo[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{ze(A(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{Te(`${t}.lock`,()=>{let e=null;try{e=L(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}C(t,c,e===null?void 0:{mode:Ca(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function No(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!I(n)))return{editorId:e.id,label:e.label,path:n}}async function Po(e){let t=zi(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>Ao(t,``,n,e.home))}function Fo(e,t,n,r){let i=Lo(e,t,n,r);return i.kind===`present`?i.entry:null}function Io(e,t,n,r){let i=uo(e,t,r);if(!k(i))return{kind:`no-entry`};let a=i[n];return k(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function Lo(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!I(i))return{kind:`absent`};try{if(We(i).size>io)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:ya(e)}}let a;try{a=L(i,`utf-8`)}catch(e){return{kind:`decline`,reason:ya(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:Va(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=Hr().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return Io(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,J.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:Io(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=$a(a);return s?eo(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:Io(S(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function Ro(e={}){let t=N(e.cwd??process.cwd()),n=Ga(t,{homeDir:e.home}),i=n.projectRoot;if(ee(i,e.home??R()))throw new re(i);let a=!I(j(i,`.ok`)),o=n.gitRootPromoted?M(i,t):void 0,s=e.contentDir===void 0?n.defaultContentDir:To(e.contentDir,i,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${i}`):n.gitRootPromoted&&a&&s===`.`&&process.stderr.write(`${D(`[ok] Content scope promoted to the git repo root: ${i}`)}\n Ran in ${o}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`ok init --content-dir .\`, or set content.dir: ${o} in .ok/config.yml.\n`);let c={mode:e.devMcp?`dev`:`published`},l=await te(i),u;try{u=fe(i,{contentDir:s})}catch(t){let r=$.claude.configPath(i,e.home);return{projectRoot:i,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:l.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let d=u.created.includes(De),f=!1;if(l.didInit)try{f=Se(i)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${i}: ${e instanceof Error?e.message:String(e)}`)}try{ie(i)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${i}: ${e instanceof Error?e.message:String(e)}`)}let p=await bo({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),m=e.editors??Wo(i,e.home),h=e.editors??m,g=zi(m),_=zi(h),v=e.mcp===!1||p===null,y=Array.from(new Map([...g,...v?[]:_].map(e=>[e.id,e])).values()),b=g.filter(t=>Oo(t,i,e.home)),x=[],S=[],ne=new Set;for(let t of y){if(v){let n=``;try{n=t.configPath(i,e.home)}catch{}x.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(i)});continue}if(_o(p)&&g.includes(t)&&t.scope===`global`&&x.push(Ao(t,i,c,e.home)),vo(p)&&_.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(i),r=Ao(t,i,c,e.home,n);x.push(r),(r.action===`written`||r.action===`overwritten`)&&ne.add(n)}}let ae=new Set;for(let t of _){let n=t.projectSkillPath?.(i);!n||ae.has(n)||(ae.add(n),S.push(_a(t,i,{home:e.home})))}let C=ga(i,_.map(e=>e.id));C&&S.push(C);let oe=S.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(oe.length>0){let t=e.home??R();he({source:r,skills:[xe.project],agents:oe,scope:i},{home:t,enabled:_e(t).enabled})}let ce=!v&&p!==null&&vo(p)?_.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,le=v?[]:b.map(e=>No(e,i)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ue=e.installUserSkill??se,pe=e.home??R(),ge=wo(e.skills),ye=!1,be=!1,Ce=!1,we=!1,Te=!1;for(let t of me){if(!ge.has(t))continue;await ve(pe,xe[t],!0).catch(()=>{}),ye=!0;let n=await ue({home:e.home,bundleId:t,force:!0});n===`installed`?be=!0:n===`failed`?Ce=!0:n===`no-hosts`?Te=!0:we=!0}let w=Ce?`failed`:be?`installed`:ye&&we?`skip-current`:ye&&Te?`no-hosts`:`declined`,T=be?de(pe).map(e=>e.editorId):[],E=v?`skipped-flag`:`skipped-missing`,Ee=x.find(e=>e.editorId===`claude`)??x[0]??{action:E,configPath:$.claude.configPath(i,e.home)},O=await zo({projectRoot:i,desiredMode:await So({sharing:e.sharing,projectRoot:i,isTTY:e.isTTY,freshProject:a,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:i,contentCreated:u.created,contentUpdated:u.updated,contentSkipped:u.skipped,editors:x,projectSkills:S,legacyProjectConfigs:le,skillInstall:w,skillHosts:T,didGitInit:l.didInit,rootGitignoreCreated:f,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDir:d?s:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Ee.action,mcpPath:Ee.configPath,mcpError:`error`in Ee?Ee.error:void 0,projectScopeUnsupportedLabels:ce,sharing:O}}async function zo(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=Ki(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=Hi(t);if(n===`local-only`){let e=Wi(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:Bo(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=Gi(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:Bo(t,o,`remove`)}function Bo(e,t,n){let r=Ki(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function Vo(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function Ho(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let s=j(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`Content scaffolded at ${s}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(O(`Content already present at ${s}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(O(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let e=r.configPath.startsWith(t)?M(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),i=r.serverName===`open-knowledge`?``:` (${r.serverName})`,a=r.configScope===`project`?` (project)`:``,o=`${r.label}${a}`,s=` `.repeat(Math.max(1,20-o.length)),c=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${o}${s}${e} ${E(`registered`)}${i}${c}`);break;case`overwritten`:n.push(` ${o}${s}${e} ${E(`updated`)}${i}${c}`);break;case`skipped-missing`:n.push(` ${o}${s}${e} config root missing; skipped`);break;case`failed`:n.push(` ${o}${s}${e} ${Ee(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${o}${s}${e} left unchanged (${Vo(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(O(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?M(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${E(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${E(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${Ee(`FAILED`)}: ${r.error}`)}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${M(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(O(`User-global skill:`)),e.skillInstall){case`installed`:{let t=(e.skillHosts??[]).map(e=>X[e]??e),r=t.length>0?t.join(`, `):`the shared ~/.agents store`;n.push(` open-knowledge ${E(`installed for ${r}`)}`),n.push(` ${T(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${T(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`);break}case`skip-current`:n.push(` open-knowledge ${E(`already installed at current version`)}`);break;case`declined`:n.push(` open-knowledge ${T(`skipped for this run (--no-skills)`)}`),n.push(` ${T(`Nothing was installed or removed. Any built-in skills already on this`)}`),n.push(` ${T(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${T(` ok init`)}`);break;case`no-hosts`:n.push(` open-knowledge ${T(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${D(`open-knowledge install failed — MCP still configured; retry with:`)}`),n.push(` ${D(` ok repair-skills`)}`)}if(e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(D(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(D(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`ok init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(" To scope to just that sub-folder, re-run `ok init --content-dir .` from there, or set"),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(Oe(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...qo(e.sharing,t)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${E(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${w(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${w(`ok seed --list-packs`)} — browse the starter packs`),n.push(` - ${w(`ok seed`)} — scaffold an empty repo`),n.push(` 4. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}return n.join(`
|
|
691
691
|
`)}function Uo(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function Wo(e,t){let n=[];for(let r of Wr)r!==`claude-desktop`&&Oo($[r],e,t)&&n.push(r);return n}function Go(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:Ke(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function Ko(){return new ut(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new ft(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new ft(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new ft(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?Go():null;try{let r;try{r=await Ro({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Co||e instanceof re){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof ae||e instanceof ue){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof ge){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-BaY7osJS.mjs`),{resolveContentDir:s}=await import(`./dist-H727Mac0.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-rn0piPQ2.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(Uo(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${Ho(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function qo(e,t){let n=[];switch(e.kind){case`applied`:return n.push(O(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${E(`local-only`)} — appended ${e.appended.length} path(s) to ${O(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${E(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${E(`local-only`)} — already excluded; nothing to do.`):n.push(` ${E(`local-only`)}`):e.action===`removed`?n.push(` ${E(`shared`)} — removed OK paths from ${O(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${E(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(D(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${w(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(D(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${w(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${w(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(D(`Sharing mode unavailable: ${e.reason}.`));return n}}export{yi as $,wa as A,Wi as B,Ga as C,ut as Ct,Ma as D,La as E,oa as F,Ji as G,qi as H,sa as I,Wr as J,Ki as K,va as L,ya as M,aa as N,Ca as O,la as P,Z as Q,ua as R,Xa as S,St,Ba as T,ft as Tt,Ui as U,Qi as V,Hi as W,$ as X,X as Y,Gr as Z,Ro as _,Hn as _t,Uo as a,Si as at,Po as b,Jt as bt,Ho as c,Pi as ct,Oo as d,Hr as dt,vi as et,Fo as f,Y as ft,So as g,$n as gt,To as h,Pr as ht,zo as i,ii as it,ba as j,Sa as k,qo as l,ci as lt,bo as m,jr as mt,Do as n,xi as nt,Lo as o,Q as ot,wo as p,Mr as pt,Gi as q,jo as r,ti as rt,Wo as s,Ci as st,Co as t,bi as tt,Ko as u,Ur as ut,co as v,Qt as vt,Ha as w,ct as wt,ko as x,V as xt,Ao as y,Yt as yt,_a as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-D0NB38wf.mjs";import{_ as e}from"./init-C0ht_YRB.mjs";export{e as runInit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Eo as e,No as t,ko as n}from"./dist-
|
|
1
|
+
import{Eo as e,No as t,ko as n}from"./dist-D0NB38wf.mjs";import{A as r,M as i,O as a}from"./init-C0ht_YRB.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-BJLJdU25.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:i(e)}}let g=[],_=n(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=r(h,[`configurations`,y]);return x?(t(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-BwEW4OHx.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ol as e,cl as t,gl as n,no as r,ol as i,os as a,zu as o}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{Fo as s,Lo as c,x as l}from"./dist-
|
|
1
|
+
import{Ol as e,cl as t,gl as n,no as r,ol as i,os as a,zu as o}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{Fo as s,Lo as c,x as l}from"./dist-D0NB38wf.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-CqnSfysY.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=o();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(n){let o=n??process.cwd(),u=[],p=[],m=[],h=[],g=c(`user`,o),_=s({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(t,n=!1)=>{let a=v(t);if(a.diagnostic!==void 0&&p.push(a.diagnostic),a.value===null)return{};let o=i({value:a.value,file:a.path,source:a.source,doc:a.doc});p.push(...o),u.push(t);let s=o.length>0?e(a.value):a.value;return n&&h.push(...r({value:s,file:a.path,source:a.source,doc:a.doc})),s},x=f(o,`.ok`,d),S=b(x,!0),C=b(c(`project-local`,o)),w=a(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),n={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(t(n))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{lo as e}from"./dist-
|
|
1
|
+
import{lo as e}from"./dist-D0NB38wf.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|