@inkeep/open-knowledge 0.77.9-beta.4 → 0.77.9-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-CFxJJ9cG.mjs +1 -0
  3. package/dist/{dist-BaFVilsg.mjs → dist-CNo9_UDM.mjs} +2 -2
  4. package/dist/{dist-BX9Hv99X.mjs → dist-CnJNy-bS.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-Ds2qtmIW.mjs → init-BByey1I0.mjs} +2 -2
  7. package/dist/init-NMflbaUx.mjs +1 -0
  8. package/dist/{launch-json-removal-DT6OqkDI.mjs → launch-json-removal-CKskytRd.mjs} +1 -1
  9. package/dist/{loader-DCgutE9k.mjs → loader-CXm1l7nf.mjs} +1 -1
  10. package/dist/loader-Svz-LLuj.mjs +1 -0
  11. package/dist/{open-browser-DLNa40Nd.mjs → open-browser-CujV-JOE.mjs} +1 -1
  12. package/dist/{preview-D4dB1WSS.mjs → preview-CGOmiCOB.mjs} +1 -1
  13. package/dist/preview-D5inGBaA.mjs +1 -0
  14. package/dist/{registry-probes-DpMpO4Mq.mjs → registry-probes-DCS9YHMm.mjs} +1 -1
  15. package/dist/{removal-file-path-Cp1kYlUX.mjs → removal-file-path-cPiYyGfY.mjs} +1 -1
  16. package/dist/{repair-launch-json-B49YnV9x.mjs → repair-launch-json-C93mzIzK.mjs} +1 -1
  17. package/dist/{repair-mcp-configs-BuDYGfQe.mjs → repair-mcp-configs-BD-4yZ9w.mjs} +1 -1
  18. package/dist/{src-Q85kXb9h.mjs → src-BV_1tpSB.mjs} +1 -1
  19. package/dist/src-Lf_tsvZf.mjs +1 -0
  20. package/dist/start-BODrVK-4.mjs +1 -0
  21. package/dist/{start-BSDM41Hx.mjs → start-Z4klo3Gn.mjs} +3 -3
  22. package/package.json +4 -4
  23. package/dist/constants-ByTAEAJs.mjs +0 -1
  24. package/dist/init-CjGJekxT.mjs +0 -1
  25. package/dist/loader-gXn13YKu.mjs +0 -1
  26. package/dist/preview-BFPuAmPS.mjs +0 -1
  27. package/dist/src-CHicwWyW.mjs +0 -1
  28. package/dist/start-CFJgJeiy.mjs +0 -1
@@ -949,10 +949,10 @@ ${OWe.join(`
949
949
  `).entries())t>0&&i(),!r&&(n.length+a.length>16e3?(n=``,r=!0):n+=a)},end:i}}const g$=16e3;function _$(e){return e.length<=g$?e:`${e.slice(0,g$)}\n… [truncated ${e.length-g$} chars]`}function mZe(e){let t=e;if(t.sessionUpdate!==`tool_call`&&t.sessionUpdate!==`tool_call_update`||!Array.isArray(t.content))return e;let n=!1,r=t.content.map(e=>{let t=e;if(t.type===`diff`){let r=typeof t.oldText==`string`?_$(t.oldText):t.oldText,i=typeof t.newText==`string`?_$(t.newText):t.newText;return r!==t.oldText||i!==t.newText?(n=!0,{...t,oldText:r,newText:i}):e}if(t.type===`content`){let r=t.content;if(r?.type===`text`&&typeof r.text==`string`){let e=_$(r.text);if(e!==r.text)return n=!0,{...t,content:{...r,text:e}}}return e}return e});return n?{...e,content:r}:e}const hZe=new Set([`agent_message_chunk`,`agent_thought_chunk`,`user_message_chunk`]),gZe=16e3;function _Ze(e){if(typeof e!=`object`||!e)return null;let t=e;return t.type===`text`&&typeof t.text==`string`?t.text:null}function vZe(e){return typeof e.messageId==`string`?e.messageId:`default`}function yZe(e,t,n){if(e.kind===`terminal_output`&&t.kind===`terminal_output`)return e.terminalId!==t.terminalId||e.chunk.length>=gZe?!1:(e.chunk+=t.chunk,!0);if(e.kind!==`session_update`||t.kind!==`session_update`||lF(e.update,n)||lF(t.update,n))return!1;let r=e.update,i=t.update;if(r.sessionUpdate!==i.sessionUpdate||!hZe.has(i.sessionUpdate)||vZe(r)!==vZe(i))return!1;let a=_Ze(r.content),o=_Ze(i.content);return a===null||o===null||a.length>=gZe?!1:(r.content={type:`text`,text:a+o},!0)}const bZe=`__OK_PATH_BEGIN__`,xZe=`__OK_PATH_END__`,SZe=`printf %s ${bZe}; printenv PATH; printf %s ${xZe}`;function CZe(){return[`-l`,`-i`,`-c`,SZe]}function wZe(){return[`-i`,`-c`,SZe]}const TZe=new Set([`bash`,`sh`]);function EZe(e){let t=e.lastIndexOf(bZe);if(t===-1)return null;let n=t+17,r=e.indexOf(xZe,n);if(r===-1)return null;let i=e.slice(n,r).trim();return i===``?null:i}function v$(e,t,n){let r=(e??``).split(n).filter(e=>e!==``),i=new Set(r);for(let e of t.split(n))e===``||i.has(e)||(i.add(e),r.push(e));return r.join(n)}function DZe(e,t,n){return v$(t,e??``,n)}const OZe=new Set([`false`,`nologin`,`sync`]),kZe=(e,t,n)=>new Promise(r=>{let i;try{i=fs(e,[...t],{stdio:[`ignore`,`pipe`,`ignore`],windowsHide:!0})}catch{r(null);return}let a=``,o=!1,s=e=>{o||(o=!0,clearTimeout(c),r(e))},c=setTimeout(()=>{i.kill(`SIGKILL`),s(null)},n);c.unref?.(),i.stdout?.setEncoding(`utf8`),i.stdout?.on(`data`,e=>{a.length>=524288||(a+=e)}),i.on(`error`,()=>s(null)),i.on(`close`,()=>s(a))});async function AZe(e,t,n,r,i){let a=Date.now(),o=await i(t,n,r).catch(()=>null),s=Date.now()-a;if(o===null)return e.log.debug({shell:t,args:n,elapsed:s},`[login-shell-path] probe produced no output`),null;let c=EZe(o);return c===null?(e.log.debug({shell:t,args:n,elapsed:s},`[login-shell-path] probe output carried no PATH`),null):c}function jZe(e){let t=e.platform??process.platform,n=e.shell??process.env.SHELL,r=e.timeoutMs??5e3,i=e.runProbe??kZe,a=e.now??Date.now,o=null,s=0,c=async()=>{if(t===`win32`)return null;if(n===void 0||n===``)return e.log.debug({},`[login-shell-path] no $SHELL; skipping probe`),null;let a=n.slice(n.lastIndexOf(`/`)+1);if(OZe.has(a))return e.log.debug({shell:n},`[login-shell-path] login-refusing shell; skipping probe`),null;let o=await AZe(e,n,CZe(),r,i);if(!TZe.has(a))return o;let s=await AZe(e,n,wZe(),r,i);return o===null?s:s===null?o:v$(o,s,gs)};return()=>{if(o!==null)return o;if(a()<s)return Promise.resolve(null);let e=c().catch(()=>null);return o=e,e.then(e=>{e===null&&(o=null,s=a()+6e4)}),e}}let y$=null;function b$(e){return y$??=jZe({log:e}),y$}function MZe(){y$=null}const NZe=new Set([`EPERM`,`EACCES`,`EBUSY`]);async function PZe(e,t,n={}){let r=n.attempts??6,i=n.renameImpl??aJ,a=n.baseDelayMs??100;for(let n=1;;n+=1)try{return await i(e,t)}catch(e){let t=e.code;if(n>=r||t===void 0||!NZe.has(t))throw e;await new Promise(e=>setTimeout(e,a)),a*=2}}async function x$(e,t,n){let r;try{r=await ic(e,{withFileTypes:!0})}catch(r){r.code!==`ENOENT`&&t.warn({err:r,parentDir:e},`${n} could not read install dir for cleanup`);return}let i=Date.now()-864e5;for(let a of r){let r=a.isDirectory()&&a.name.startsWith(`.install-`),o=a.isFile()&&(a.name.endsWith(`.install.lock`)||a.name.startsWith(`.install-`));if(!r&&!o)continue;let s=H(e,a.name);try{if((await sc(s)).mtimeMs>=i)continue;await iJ(s,{recursive:!0,force:!0})}catch(e){if(e.code===`ENOENT`)continue;t.warn({err:e,path:s},`${n} stale install artifact cleanup failed`)}}}async function S$(e){let t=V(e.versionDir),n=await e.findInstalled();if(n!==null)return await x$(t,e.log,e.logPrefix),n;await oJ(t,{recursive:!0}),await x$(t,e.log,e.logPrefix);let r=H(t,`.install-${e.stagingLabel}-${process.pid}-${dc()}`);await oJ(r,{recursive:!0});try{let t=await e.prepare(r),n=await e.findInstalled();if(n!==null)return n;await e.beforeCommit?.();try{return await cw(`${e.versionDir}.install.lock`,async()=>{let n=await e.findInstalled();if(n!==null)return n;await iJ(e.versionDir,{recursive:!0,force:!0,maxRetries:5,retryDelay:100}),await PZe(t,e.versionDir),e.log.info({...e.logContext,versionDir:e.versionDir},`${e.logPrefix} ${e.installedMessage}`);let r=await e.findInstalled();if(r===null)throw Error(e.missingAfterCommitMessage);return r},{timeoutMs:e.commitLockTimeoutMs??6e4,onWarn:(t,n)=>{e.log.warn({...n,...e.logContext},`${e.logPrefix} ${t}`)}})}catch(t){if(t instanceof sw){let n=await e.findInstalled();if(n!==null)return n;e.log.warn({...e.logContext,lockPath:t.lockPath,timeoutMs:t.timeoutMs},`${e.logPrefix} install commit lock timed out with no winner installed`)}throw t}}finally{await iJ(r,{recursive:!0,force:!0}).catch(t=>{e.log.warn({err:t,...e.logContext,stagingDir:r},`${e.logPrefix} install staging cleanup failed`)})}}var C$=class extends Error{machineDetail;code;constructor(e,t,n){super(t,n),this.name=`AgentLaunchError`,this.code=e,this.machineDetail=n?.machineDetail===void 0?void 0:h$(n.machineDetail).slice(-16e3)}};function FZe(){return H(Ys(),`.ok`,`acp-agents`)}function IZe(e){try{return Ws(e).isDirectory()}catch{return!1}}function w$(e){let t={};for(let[e,n]of Object.entries(process.env))n!==void 0&&e.toLowerCase()!==`npm_config_overrides`&&(t[e]=n);return t[k$(t)]=cr(N$(t),{platform:process.platform,homeDir:Ys(),isDir:IZe,delimiter:gs}),{...t,...e}}function LZe(){return N$(w$())}function T$(e){return e!==void 0&&Object.keys(e).some(e=>e.toLowerCase()===`path`)}function RZe(e){return{...e,[Xte]:`1`}}async function zZe(e,t,n,r=FZe(),i,a){let o=e.distribution;if(o.npx!==void 0){let e={cmd:`npx`,args:[`-y`,o.npx.package,...o.npx.args??[]],env:w$(o.npx.env),kind:`npx`,pathFromOverlay:T$(o.npx.env)},t=i===void 0?e:await i(e);if(t===null)return null;let r=/^(?<name>(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+)@(?<version>(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/.exec(o.npx.package);if(r?.groups===void 0)return t;let s=await eQe(t,r.groups.name,r.groups.version,n,a);return{...t,args:[`-y`,s,...o.npx.args??[]]}}if(o.uvx!==void 0){let e=/^(?<name>[A-Za-z0-9][A-Za-z0-9._-]*)(?:==|@)(?<version>\d+\.\d+\.\d+)$/.exec(o.uvx.package),t={cmd:`uvx`,args:[...e?.groups===void 0?[o.uvx.package]:[`--from`,`${e.groups.name}<=${e.groups.version}`,`--isolated`,`--upgrade-package`,e.groups.name,e.groups.name],...o.uvx.args??[]],env:w$(o.uvx.env),kind:`uvx`,pathFromOverlay:T$(o.uvx.env)};return i===void 0?t:i(t)}if(o.binary!==void 0){if(t===null||o.binary[t]===void 0)throw new C$(`unsupported-platform`,`${e.name} has no build for this platform`);let a=o.binary[t],s=await fQe(e.id,e.version,a,r,n),c=W(s,a.cmd.replace(/\\/g,`/`));if(!d$(s,c))throw new C$(`install-failed`,`${e.name} manifest cmd escapes its archive`);let l={cmd:c,args:[...a.args??[]],env:w$(a.env),kind:`binary`,pathFromOverlay:T$(a.env)};return i===void 0?l:i(l)}throw new C$(`no-distribution`,`${e.name} has no supported distribution`)}const E$=I({name:z(),version:z().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)}),BZe=bi([F(E$),L(z(),E$).transform(e=>Object.values(e))]).pipe(Tre([E$]));function VZe(e,t){let n=t.split(`.`).map(BigInt);for(let[t,r]of e.split(`.`).map(BigInt).entries())if(r!==n[t])return r<n[t];return!0}function HZe(e){return/\bETARGET\b/.test(e)&&/with a date before/.test(e)}function UZe(e,t,n){let r=e.kind===`npx`&&HZe(t),i=e.kind===`uvx`&&/No solution found when resolving tool dependencies/.test(t)&&/filtered by `exclude-newer`/.test(t);return!r&&!i?null:new C$(`install-failed`,`No allowed release is available under your package manager's release-date policy. Try again after an allowed release becomes available.`,{cause:n,machineDetail:t})}const WZe=[/^npm (?:error|ERR!) path (.+?)\s*$/m,/ENOENT: no such file or directory, open '([^'\n]+)'/],GZe=/^((?:[A-Za-z]:)?[\\/](?:.*[\\/])?_npx[\\/][0-9a-f]{8,64})[\\/]package\.json$/i,KZe=/(?:^|[\\/])\.\.(?:[\\/]|$)/;function qZe(e){if(!/\bENOENT\b/.test(e))return null;for(let t of WZe){let n=t.exec(e)?.[1],r=n===void 0?void 0:GZe.exec(n)?.[1];if(r!==void 0&&!KZe.test(r))return r}return null}async function JZe(e){let t=e.cmd;if(!P$(t)){if(process.platform===`win32`)t=I$(t,N$(e.env));else for(let n of(N$(e.env)??``).split(gs))if(n!==``&&await F$(H(n,t))){t=H(n,t);break}}if(!P$(t))throw new C$(`install-failed`,`Could not locate npm for the selected agent runtime.`);let n=H(V(t),hs(t).replace(/^npx/i,`npm`));return await F$(n)?n:null}async function YZe(e,t,n){let r=R$({...e,kind:`npx`,cmd:n,args:[`pack`,t,`--dry-run`,`--ignore-scripts`,`--json`]}),i=``,a=``,o=0,s,c=e=>{s===void 0&&(s=e,V$(r,{graceMs:100}))},l=setTimeout(()=>c(`npm package acquisition timed out.`),3e4);l.unref(),r.stdout?.setEncoding(`utf8`),r.stderr?.setEncoding(`utf8`),r.stdout?.on(`data`,e=>{o+=Buffer.byteLength(e),o>16777216?c(`npm package acquisition output exceeded its limit.`):i+=e});let u=pZe(e=>{a=`${a}${e}\n`.slice(-16e3)});r.stderr?.on(`end`,u.end),r.stderr?.on(`data`,e=>{o+=Buffer.byteLength(e),u.write(e),o>16777216&&c(`npm package acquisition output exceeded its limit.`)}),r.once(`error`,e=>{s=e.message});try{let e=await new Promise(e=>r.once(`close`,e)),t=`${i}\n${a}`.trim();if(s!==void 0)throw new C$(`install-failed`,s,{machineDetail:t});return{code:e,stdout:i,detail:t}}finally{clearTimeout(l),await V$(r,{graceMs:100})}}const D$=new Map;function XZe(e,t,n){let r=Object.entries(e.env).sort(([e],[t])=>e<t?-1:+(e>t));return JSON.stringify([e.cmd,r,t,n])}function ZZe(e){return e===void 0||e.state===`probing`?null:e}function QZe(e){return e===void 0||e.state===`held`?null:e.probe}function $Ze(e){return e.outcome===`exact`||Date.now()-e.probedAt<36e5}function eQe(e,t,n,r,i){let a=XZe(e,t,n),o=D$.get(a),s=ZZe(o);if(i?.reacquire!==!0&&s!==null&&$Ze(s))return i?.onResolved?.({acquired:s.acquired,outcome:s.outcome,source:`memo`,elapsedMs:0}),Promise.resolve(s.acquired);let c=QZe(o),l=c??tQe(a,s,e,t,n,r,i),u=c===null?`probe`:`joined`;return l.then(e=>(i?.onResolved?.({...e,source:u}),e.acquired))}function tQe(e,t,n,r,i,a,o){let s=nQe(n,r,i,a,o),c=t===null?{state:`probing`,probe:s}:{...t,state:`revalidating`,probe:s};D$.set(e,c);let l=t=>{D$.get(e)===c&&(t===null?D$.delete(e):D$.set(e,t))},u=()=>l(t===null?null:{...t,state:`held`});return s.then(e=>{e.outcome===`forwarded`?u():l({state:`held`,acquired:e.acquired,outcome:e.outcome,probedAt:Date.now()})},u),s}async function nQe(e,t,n,r,i){let a=`${t}@${n}`,o=await JZe(e);if(o===null)return r.warn({package:a},`[acp-launch] package acquisition probe skipped: no executable npm sibling; forwarding the catalog pin to npx`),{outcome:`forwarded`,acquired:a,elapsedMs:0};i?.onProbeStart?.();let s=Date.now(),c=await YZe(e,a,o),l=!1;if(c.code!==0&&HZe(c.detail)&&(l=!0,a=`${t}@0.0.0 - ${n}`,c=await YZe(e,a,o)),c.code!==0)throw new C$(`install-failed`,l&&/\b(?:ETARGET|ENOVERSIONS)\b/.test(c.detail)?`No release of ${t} at or below ${n} is available under your package manager's release-date policy. Try again after an allowed release becomes available.`:`Could not acquire ${a}.`,{machineDetail:c.detail});let u;try{[u]=BZe.parse(JSON.parse(c.stdout))}catch(e){throw new C$(`install-failed`,`npm returned invalid package acquisition metadata.`,{cause:e,machineDetail:c.detail})}if(u.name!==t||!VZe(u.version,n)||!l&&u.version!==n)throw new C$(`install-failed`,`npm returned ${u.name}@${u.version} outside the requested constraint ${a}.`,{machineDetail:c.detail});return{outcome:l?`release-age-bounded`:`exact`,acquired:`${t}@${u.version}`,elapsedMs:Date.now()-s}}function rQe(e){return{cmd:e.command,args:[...e.args??[]],env:w$(e.env),kind:`custom`,pathFromOverlay:T$(e.env)}}function iQe(e,t){let n={...e.env};n[k$(n)]=sQe(t.binDir,N$(n));let r=e.pathFromOverlay;return t.kind===`node`?(n.npm_config_cache=t.cacheDir,{cmd:t.npxBin,args:[...e.args],env:n,kind:`npx`,pathFromOverlay:r}):(n.UV_CACHE_DIR=t.cacheDir,{cmd:t.uvxBin,args:[...e.args],env:n,kind:`uvx`,pathFromOverlay:r})}function aQe(e,t){return{...e,env:O$(e.env,t)}}function oQe(e,t){let n={...e.env};return n[k$(n)]=DZe(N$(n),t,gs),{...e,env:n}}function O$(e,t){let n={...e};return n[k$(n)]=v$(N$(n),t,gs),n}function k$(e){for(let t of Object.keys(e))if(t.toLowerCase()===`path`)return t;return`PATH`}function sQe(e,t){return t!==void 0&&t!==``?`${e}${gs}${t}`:e}async function cQe(e,t,n){try{if(!(await sc(e)).isDirectory())return null}catch(t){return t.code!==`ENOENT`&&n.warn({err:t,versionDir:e},`[acp-launch] could not inspect cached agent binary`),null}let r=W(e,t.cmd.replace(/\\/g,`/`));return!d$(e,r)||!await F$(r)?null:e}var A$=class extends Error{};function lQe(e,t){return H(e,`.install-failed-${f$(t)}`)}async function uQe(e,t,n){let r,i;try{r=(await sc(e)).mtimeMs,i=await rc(e,`utf8`)}catch(t){return t.code!==`ENOENT`&&n.warn({err:t,markerPath:e},`[acp-launch] could not read the install failure marker`),null}if(Date.now()-r>864e5)return null;try{let e=JSON.parse(i);return e.archive!==t.archive||e.cmd!==t.cmd||e.sha256!==(t.sha256??null)?null:typeof e.reason==`string`?e.reason:null}catch{return n.warn({markerPath:e},`[acp-launch] install failure marker is malformed — treating it as absent`),null}}async function dQe(e,t,n,r){await nJ(e,JSON.stringify({archive:t.archive,cmd:t.cmd,sha256:t.sha256??null,reason:n})).catch(t=>{r.warn({err:t,markerPath:e},`[acp-launch] could not record the failed binary install`)})}async function fQe(e,t,n,r,i,a={}){let o=H(r,f$(e),f$(t)),s=lQe(V(o),t);try{return await S$({versionDir:o,stagingLabel:f$(t),findInstalled:()=>cQe(o,n,i),prepare:async r=>{let o=await uQe(s,n,i);if(o!==null)throw Error(`${o} (remembered from a recent attempt — retried when the manifest changes or after a day)`);await iJ(s,{force:!0}),i.info({id:e,version:t,archive:n.archive},`[acp-launch] downloading agent binary`);let c=/\.zip$/i.test(new URL(n.archive).pathname),l=H(r,c?`archive.zip`:`archive.tar.gz`),u=await iZe(n.archive,l,{signal:AbortSignal.timeout(12e4),fetchImpl:a.fetchImpl});if(n.sha256!==void 0){if(u!==n.sha256.toLowerCase())throw Error(`archive checksum mismatch: expected ${n.sha256}, got ${u}`)}else i.warn({id:e,version:t,archive:n.archive},`[acp-launch] manifest carries no sha256 for the binary archive — installing unverified`);let d=H(r,`extracted`);await oJ(d,{recursive:!0}),await rZe(l,d,c);let f=W(d,n.cmd.replace(/\\/g,`/`));if(!d$(d,f))throw new A$(`manifest cmd escapes the extracted archive`);if(await qie(f,493).catch(()=>{}),!await F$(f))throw new A$(`extracted agent archive has no usable command at ${n.cmd}`);return d},log:i,logPrefix:`[acp-launch]`,logContext:{id:e,version:t},installedMessage:`agent binary installed`,missingAfterCommitMessage:`installed agent binary not found after extract`,beforeCommit:a.beforeCommit,commitLockTimeoutMs:a.commitLockTimeoutMs})}catch(r){throw r instanceof A$&&await dQe(s,n,r.message,i),new C$(`install-failed`,`installing ${e}@${t} failed: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}async function j$(e){if(!await TQe(e.cmd,N$(e.env)))throw new C$(`command-not-found`,pQe(e))}function pQe(e){switch(e.kind){case`npx`:return`\`${e.cmd}\` was not found. This agent runs through npx, which ships with Node.js — install Node.js (https://nodejs.org) and make sure it is on your PATH.`;case`uvx`:return`\`${e.cmd}\` was not found. This agent runs through uvx, which ships with uv — install uv (https://docs.astral.sh/uv/getting-started/installation/) and make sure it is on your PATH.`;case`binary`:return`the agent binary at ${e.cmd} is missing or not executable.`;case`custom`:return`\`${e.cmd}\` was not found on your PATH. A desktop app launched from the Dock or Finder doesn't inherit your shell's PATH, so an agent installed only in a shell-configured location won't be visible here — use an absolute path to the command, or install it to a standard location.`}}function mQe(e,t){let n=e.kind===`uvx`?`That usually means its uv is broken. Reinstall or repair uv and try again.`:"That usually means its Node.js is broken — on macOS a common cause is a Homebrew `node` whose `icu4c` library was upgraded out from under it. Reinstall or repair Node.js and try again.";return`\`${e.cmd}\` is installed but failed to run (${t}). ${n}`}function hQe(e,t){return`OK downloaded a fresh copy of ${e.kind===`uvx`?`uv`:`Node.js`} and it still can't run (${t}). Something on this machine is stopping it — antivirus, a security policy, or an unsupported CPU are the usual causes.`}function gQe(e){return`OK's private Node.js runtime is incompatible (${e}). Update Open Knowledge and try again.`}function _Qe(e,t){return`OK's own copy of ${e.kind===`uvx`?`uv`:`Node.js`} is damaged (${t}) and couldn't be replaced — another agent may still be using it. Close other agent threads and try again.`}function vQe(e){return`OK's own copy of ${e.kind===`uvx`?`uv`:`Node.js`} is damaged and can't run this agent. Start the agent again to let OK download a fresh copy.`}function yQe(e){return`OK's own copy of ${e.kind===`uvx`?`uv`:`Node.js`} is damaged and can't run this agent. The offer to download a fresh copy expired before it was answered — start the agent again to get it back.`}function bQe(e,t){return`${t} The offer to download a private copy of ${e.kind===`uvx`?`uv`:`Node.js`} expired before it was answered — start the agent again to get it back.`}const M$=2e3;function xQe(e,t=5e3,n){let r=process.platform===`win32`,i=r?I$(e.cmd,N$(e.env)):e.cmd,a=r&&/\.(cmd|bat)$/i.test(i),{cmd:o,args:s}=a?L$(i,[`--version`]):{cmd:i,args:[`--version`]};return new Promise(i=>{let c;try{c=fs(o,s,{env:e.env,stdio:[`ignore`,`ignore`,`pipe`],shell:!1,detached:!r,windowsHide:!0,windowsVerbatimArguments:a})}catch(e){i(e instanceof Error?e.message:String(e));return}let l=``;c.stderr?.setEncoding(`utf8`),c.stderr?.on(`data`,e=>{l.length<M$&&(l+=e)});let u=!1,d=e=>{u||(u=!0,clearTimeout(f),i(e))},f=setTimeout(()=>{V$(c,{graceMs:0,forceWaitMs:0}).catch(()=>{}),n?.debug({cmd:e.cmd,kind:e.kind,timeoutMs:t},`[acp-launch] interpreter health probe timed out — proceeding with the launch`),d(null)},t);f.unref?.(),c.on(`error`,e=>d(e.message)),c.on(`exit`,(e,t)=>{if(t===null&&(e===null||e===0)){d(null);return}let n=l.split(`
950
950
  `).map(e=>e.trim()).find(e=>e!==``),r=t??`exit code ${e}`;d(n===void 0?r:`${r}: ${n.slice(0,300)}`)})})}function SQe(e,t=5e3,n){let r=process.platform===`win32`,i=EQe(e);return new Promise(a=>{let o;try{o=fs(i,[`--version`],{env:e.env,stdio:[`ignore`,`pipe`,`pipe`],shell:!1,detached:!r,windowsHide:!0})}catch(e){a(`Node.js version probe could not start: ${e instanceof Error?e.message:String(e)}`);return}let s=``,c=``;o.stdout?.setEncoding(`utf8`),o.stdout?.on(`data`,e=>{s.length<M$&&(s+=e)}),o.stderr?.setEncoding(`utf8`),o.stderr?.on(`data`,e=>{c.length<M$&&(c+=e)});let l=!1,u=e=>{l||(l=!0,clearTimeout(d),a(e))},d=setTimeout(()=>{V$(o,{graceMs:0,forceWaitMs:0}).catch(()=>{}),n?.debug({cmd:e.cmd,kind:e.kind,timeoutMs:t},`[acp-launch] Node.js compatibility probe timed out — proceeding with the launch`),u(null)},t);d.unref?.(),o.on(`error`,e=>u(`Node.js version probe failed: ${e.message}`)),o.on(`close`,(e,t)=>{if(t!==null||e!==null&&e!==0){let n=c.split(`
951
951
  `).map(e=>e.trim()).find(e=>e!==``),r=t??`exit code ${e}`;u(n===void 0?`Node.js version probe failed with ${r}`:`Node.js version probe failed with ${r}: ${n.slice(0,300)}`);return}let n=s.trim(),r=/^v?(\d+)(?:\.|$)/.exec(n);if(r===null){u(n===``?`Node.js version probe returned no version`:`Node.js reported an unrecognized version: ${n.slice(0,300)}`);return}let i=Number.parseInt(r[1]??``,10);u(i>=22?null:`Node.js ${n} is incompatible; Node.js 22 or newer is required`)})})}function CQe(e,t){return`\`${e.cmd}\` cannot run this agent with the selected Node.js runtime (${t}). Upgrade Node.js or let Open Knowledge download a private compatible copy.`}function wQe(e,t){return`\`${e.cmd}\` cannot run this agent with the selected Node.js runtime (${t}). The offer to download a private compatible copy of Node.js expired before it was answered — upgrade Node.js, or start the agent again to get it back.`}function N$(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()===`path`)return n;return process.env.PATH}function P$(e){let t=process.platform===`win32`;return vs(e)||e.includes(`/`)||t&&e.includes(`\\`)}async function TQe(e,t){let n=process.platform===`win32`;if(P$(e))return F$(e);let r=n?[``,...(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).map(e=>e.trim()).filter(e=>e!==``)]:[``];for(let n of(t??``).split(gs))if(n!==``){for(let t of r)if(await F$(H(n,e+t)))return!0}return!1}async function F$(e){try{return(await sc(e)).isFile()?(process.platform===`win32`||await $s(e,As.X_OK),!0):!1}catch{return!1}}function I$(e,t){if(vs(e)||e.includes(`\\`)||e.includes(`/`))return e;let n=(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).map(e=>e.trim()).filter(e=>e!==``);for(let r of(t??``).split(gs))if(r!==``)for(let t of n){let n=H(r,e+t);try{if(Ws(n).isFile())return n}catch{}}return e}function EQe(e,t=process.platform){if(t!==`win32`)return`node`;let n=N$(e.env),r=I$(e.cmd,n);if(r!==e.cmd||vs(r)||r.includes(`/`)||r.includes(`\\`)){let e=H(V(r),`node.exe`);try{if(Ws(e).isFile())return e}catch{}}return I$(`node`,n)}function DQe(e){return e===``?`""`:/[\s"&()<>^|%]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function L$(e,t){let n=[`"${e}"`,...t.map(DQe)].join(` `);return{cmd:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,`"${n}"`]}}function OQe(){let e=H(Ys(),`.ok`,`acp-npx-cwd`);lJ(e,{recursive:!0,mode:448});let t=H(e,`package.json`);return G(t)||sJ(t,`${JSON.stringify({name:`openknowledge-acp-npx-isolated`,version:`0.0.0`,private:!0},null,2)}\n`),e}function R$(e,t){if(e.kind===`npx`&&t!==void 0)throw Error(`spawnAcpAgent does not accept a project cwd for npx launches.`);if(t===void 0?e.kind!==`npx`:!vs(t))throw Error(`spawnAcpAgent requires an absolute cwd, got: ${t}`);let n=e.kind===`npx`?OQe():t,r=process.platform===`win32`,i=r?I$(e.cmd,N$(e.env)):e.cmd,a=r&&/\.(cmd|bat)$/i.test(i),{cmd:o,args:s}=a?L$(i,e.args):{cmd:i,args:e.args};return fs(o,s,{cwd:n,env:RZe(e.env),stdio:[`pipe`,`pipe`,`pipe`],shell:!1,detached:!r,windowsHide:!0,windowsVerbatimArguments:a})}function z$(e){return e.exitCode!==null||e.signalCode!==null}function B$(e,t){return z$(e)?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{e.removeListener(`exit`,r),n(!1)},t);i.unref?.(),e.once(`exit`,r)})}function kQe(e,t){let n=e.pid;if(!(n===void 0||z$(e))){try{process.kill(-n,t);return}catch{}try{e.kill(t)}catch{}}}async function V$(e,t){let n=t.forceWaitMs??2e3;if(z$(e))return!0;if(process.platform===`win32`){if(e.pid!==void 0)try{fs(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`,shell:!1,windowsHide:!0}).unref()}catch{try{e.kill(`SIGKILL`)}catch{}}return B$(e,Math.max(t.graceMs,n))}return kQe(e,`SIGTERM`),await B$(e,t.graceMs)?!0:(kQe(e,`SIGKILL`),B$(e,n))}function AQe(e){return e===`connect`||e===`session-setup`}function jQe(e){return H(e,oe)}function MQe(e){let t=[`=== acp launch failure ${e.at.toISOString()} thread=${e.threadId} agent=${e.agentId} source=${e.agentSource} reason=${e.reason} ===`];return e.detail!==void 0&&e.detail!==``&&t.push(e.detail),e.machineDetail!==void 0&&e.machineDetail!==``&&t.push(`--- stderr tail ---`,e.machineDetail),h$(`${t.join(`
952
- `)}\n\n`)}const H$=new Map;function NQe(e,t){let n=jQe(e),r=MQe(t),i=(H$.get(n)??Promise.resolve()).catch(()=>void 0).then(async()=>{let e=await sc(n).then(e=>e.size,()=>void 0);Ra(e)===`w`?await nJ(n,r):await rJ(n,r)});return H$.set(n,i),i.finally(()=>{H$.get(n)===i&&H$.delete(n)}),i}const U$=`v24.18.0`,W$=`0.11.28`,PQe=`https://nodejs.org/dist`,FQe=`https://github.com/astral-sh/uv/releases/download`,IQe={node:45,uv:20};function LQe(e){return e===`npx`?`node`:`uv`}function G$(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:U$,approxSizeMB:IQe.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:W$,approxSizeMB:IQe.uv,sourceHost:`github.com/astral-sh`}}function RQe(){return H(Ys(),`.ok`)}function K$(){return H(RQe(),`runtimes`)}function q$(e){return e===`node`?U$:W$}function zQe(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function BQe(){let e=Zs(),t=Js(),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-${U$}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${PQe}/${U$}/${a}`,checksumUrl:`${PQe}/${U$}/SHASUMS256.txt`,archiveName:a,isZip:i}}function VQe(){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`}[`${Zs()}-${Js()}`];if(e===void 0)return null;let t=Zs()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${FQe}/${W$}/${n}`,checksumUrl:`${FQe}/${W$}/${n}.sha256`,archiveName:n,isZip:t}}function HQe(e){return e===`node`?BQe():VQe()}function UQe(e){return HQe(e)!==null}async function WQe(e){try{let t=await sc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await $s(e,ec.X_OK),!0)}catch{return!1}}async function J$(e,t,n){let r;try{r=await ic(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 J$(H(e,i.name),t,n-1);if(r!==null)return r}return null}function GQe(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 KQe(e,t=K$()){let n=H(t,e,f$(q$(e)));try{if(!(await sc(n)).isDirectory())return null}catch{return null}let r=await J$(n,zQe(e),3);return r===null||!await WQe(r)?null:GQe(e,r,t)}var Y$=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function qQe(e,t,n=K$()){await x$(H(n,e),t,`[managed-runtime]`)}async function JQe(e,t,n=K$()){let r=H(n,e,f$(q$(e))),i=H(V(r),`.install-damaged-${f$(q$(e))}-${dc()}`);try{await aJ(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 iJ(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function YQe(e,t,n={}){let r=n.root??K$(),i=H(r,e,f$(q$(e)));try{return await S$({versionDir:i,stagingLabel:f$(q$(e)),findInstalled:()=>KQe(e,r),prepare:async r=>{let i=HQe(e);if(i===null)throw new Y$(`no ${e} build for ${Zs()}-${Js()}`);let a=H(r,i.archiveName);t.info({kind:e,version:q$(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let[o,s]=await Promise.all([iZe(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),aZe(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=oZe(s,i.archiveName);if(c===null)throw new Y$(`no published checksum for ${i.archiveName}`);if(o!==c)throw new Y$(`checksum mismatch for ${i.archiveName}: got ${o}, expected ${c}`);let l=H(r,`extracted`);await oJ(l,{recursive:!0}),await rZe(a,l,i.isZip);let u=await J$(l,zQe(e),3);if(u===null||!d$(l,u))throw new Y$(`extracted ${e} archive has no usable launcher`);return l},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:q$(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof Y$?t:new Y$(`installing ${e} ${q$(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const XQe=`CODEX_CONFIG`;function ZQe(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 QQe(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function $Qe(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function e$e(e){if(e===void 0||e.trim()===``)return{};try{return $Qe(JSON.parse(e))}catch{return{}}}function t$e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...e$e(e[XQe]),model_context_window:Math.floor(t)};return{...e,[XQe]:JSON.stringify(n)}}function n$e(e){return(e.visibility??`list`)===`list`}const r$e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function X$(e){return r$e[e]??`none`}function i$e(e,t,n){if(n===null||X$(t)!==`codex-config-env`)return e;let r=t$e(e.env,n);return r===e.env?e:{...e,env:r}}function a$e(e){return X$(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function Z$(e,t,n={}){lJ(t,{recursive:!0});for(let r of zs(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);Ws(i).isDirectory()?Z$(i,a,n):sJ(a,K(i))}}const o$e=`open-knowledge`,s$e=`SKILL.md`,Q$=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function c$e(e){return H(e,`agent-skill`,o$e)}function l$e(e,t){let n;try{n=K(t)}catch(e){let t=e.code;if(t!==void 0&&Q$.has(t))return!1;throw e}return K(e).equals(n)}function u$e(e,t){let n=zs(e),r;try{r=new Set(zs(t))}catch(e){let t=e.code;if(t!==void 0&&Q$.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(Ws(n).isDirectory()){let e;try{e=Ws(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&Q$.has(t))return!1;throw e}if(!e||!u$e(n,a))return!1}else if(!l$e(n,a))return!1}return!0}var d$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 f$e(e){let t;try{t=await tc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new d$e(e)}async function p$e(e){let t=c$e(e.localDir),n=V(t),r=async()=>{await f$e(n),await f$e(t)};return S$({versionDir:t,stagingLabel:o$e,findInstalled:async()=>(await r(),u$e(e.sourceDir,t)?t:null),prepare:async t=>(Z$(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 m$e=2e3;function h$e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function g$e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:h$e(n.subarray(n.length-t)).toString(`utf8`)}function $$(e){if(e.outputBytes<=e.byteLimit)return;let t=h$e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var _$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=RZe(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:vs(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?I$(e.command,N$(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?L$(o,e.args??[]):{cmd:o,args:e.args??[]},u=fs(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 $$(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 V$(t.child,{graceMs:m$e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await V$(t.child,{graceMs:m$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=w$(e);return this.loginShellPath===null||T$(e)?t:O$(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?$$(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=g$e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,$$(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 v$e=`threads`;var y$e=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=H(e.primaryDir,v$e),this.legacyThreadsDir=e.legacyDir==null?null:H(e.legacyDir,v$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 oJ(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 oJ(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(`
952
+ `)}\n\n`)}const H$=new Map;function NQe(e,t){let n=jQe(e),r=MQe(t),i=(H$.get(n)??Promise.resolve()).then(async()=>{let e=await sc(n).then(e=>e.size,()=>void 0);Ra(e)===`w`?await nJ(n,r):await rJ(n,r)}),a=i.then(()=>void 0,()=>void 0);return H$.set(n,a),a.then(()=>{H$.get(n)===a&&H$.delete(n)}),i}const U$=`v24.18.0`,W$=`0.11.28`,PQe=`https://nodejs.org/dist`,FQe=`https://github.com/astral-sh/uv/releases/download`,IQe={node:45,uv:20};function LQe(e){return e===`npx`?`node`:`uv`}function G$(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:U$,approxSizeMB:IQe.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:W$,approxSizeMB:IQe.uv,sourceHost:`github.com/astral-sh`}}function RQe(){return H(Ys(),`.ok`)}function K$(){return H(RQe(),`runtimes`)}function q$(e){return e===`node`?U$:W$}function zQe(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function BQe(){let e=Zs(),t=Js(),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-${U$}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${PQe}/${U$}/${a}`,checksumUrl:`${PQe}/${U$}/SHASUMS256.txt`,archiveName:a,isZip:i}}function VQe(){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`}[`${Zs()}-${Js()}`];if(e===void 0)return null;let t=Zs()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${FQe}/${W$}/${n}`,checksumUrl:`${FQe}/${W$}/${n}.sha256`,archiveName:n,isZip:t}}function HQe(e){return e===`node`?BQe():VQe()}function UQe(e){return HQe(e)!==null}async function WQe(e){try{let t=await sc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await $s(e,ec.X_OK),!0)}catch{return!1}}async function J$(e,t,n){let r;try{r=await ic(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 J$(H(e,i.name),t,n-1);if(r!==null)return r}return null}function GQe(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 KQe(e,t=K$()){let n=H(t,e,f$(q$(e)));try{if(!(await sc(n)).isDirectory())return null}catch{return null}let r=await J$(n,zQe(e),3);return r===null||!await WQe(r)?null:GQe(e,r,t)}var Y$=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function qQe(e,t,n=K$()){await x$(H(n,e),t,`[managed-runtime]`)}async function JQe(e,t,n=K$()){let r=H(n,e,f$(q$(e))),i=H(V(r),`.install-damaged-${f$(q$(e))}-${dc()}`);try{await aJ(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 iJ(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function YQe(e,t,n={}){let r=n.root??K$(),i=H(r,e,f$(q$(e)));try{return await S$({versionDir:i,stagingLabel:f$(q$(e)),findInstalled:()=>KQe(e,r),prepare:async r=>{let i=HQe(e);if(i===null)throw new Y$(`no ${e} build for ${Zs()}-${Js()}`);let a=H(r,i.archiveName);t.info({kind:e,version:q$(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let[o,s]=await Promise.all([iZe(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),aZe(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=oZe(s,i.archiveName);if(c===null)throw new Y$(`no published checksum for ${i.archiveName}`);if(o!==c)throw new Y$(`checksum mismatch for ${i.archiveName}: got ${o}, expected ${c}`);let l=H(r,`extracted`);await oJ(l,{recursive:!0}),await rZe(a,l,i.isZip);let u=await J$(l,zQe(e),3);if(u===null||!d$(l,u))throw new Y$(`extracted ${e} archive has no usable launcher`);return l},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:q$(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof Y$?t:new Y$(`installing ${e} ${q$(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const XQe=`CODEX_CONFIG`;function ZQe(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 QQe(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function $Qe(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function e$e(e){if(e===void 0||e.trim()===``)return{};try{return $Qe(JSON.parse(e))}catch{return{}}}function t$e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...e$e(e[XQe]),model_context_window:Math.floor(t)};return{...e,[XQe]:JSON.stringify(n)}}function n$e(e){return(e.visibility??`list`)===`list`}const r$e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function X$(e){return r$e[e]??`none`}function i$e(e,t,n){if(n===null||X$(t)!==`codex-config-env`)return e;let r=t$e(e.env,n);return r===e.env?e:{...e,env:r}}function a$e(e){return X$(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function Z$(e,t,n={}){lJ(t,{recursive:!0});for(let r of zs(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);Ws(i).isDirectory()?Z$(i,a,n):sJ(a,K(i))}}const o$e=`open-knowledge`,s$e=`SKILL.md`,Q$=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function c$e(e){return H(e,`agent-skill`,o$e)}function l$e(e,t){let n;try{n=K(t)}catch(e){let t=e.code;if(t!==void 0&&Q$.has(t))return!1;throw e}return K(e).equals(n)}function u$e(e,t){let n=zs(e),r;try{r=new Set(zs(t))}catch(e){let t=e.code;if(t!==void 0&&Q$.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(Ws(n).isDirectory()){let e;try{e=Ws(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&Q$.has(t))return!1;throw e}if(!e||!u$e(n,a))return!1}else if(!l$e(n,a))return!1}return!0}var d$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 f$e(e){let t;try{t=await tc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new d$e(e)}async function p$e(e){let t=c$e(e.localDir),n=V(t),r=async()=>{await f$e(n),await f$e(t)};return S$({versionDir:t,stagingLabel:o$e,findInstalled:async()=>(await r(),u$e(e.sourceDir,t)?t:null),prepare:async t=>(Z$(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 m$e=2e3;function h$e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function g$e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:h$e(n.subarray(n.length-t)).toString(`utf8`)}function $$(e){if(e.outputBytes<=e.byteLimit)return;let t=h$e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var _$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=RZe(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:vs(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?I$(e.command,N$(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?L$(o,e.args??[]):{cmd:o,args:e.args??[]},u=fs(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 $$(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 V$(t.child,{graceMs:m$e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await V$(t.child,{graceMs:m$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=w$(e);return this.loginShellPath===null||T$(e)?t:O$(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?$$(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=g$e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,$$(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 v$e=`threads`;var y$e=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=H(e.primaryDir,v$e),this.legacyThreadsDir=e.legacyDir==null?null:H(e.legacyDir,v$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 oJ(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 oJ(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 rJ(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 nJ(r,n),await aJ(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await iJ(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 S$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 ic(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 rc(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 S$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(x$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=>iJ(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=js(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=lae({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 b$e(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function b$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 x$e(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function S$e(e){try{return await ac(e)}catch{return W(e)}}const C$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`),w$e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,T$e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function E$e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function D$e(e){return(e.trim().split(`
954
954
  `)[0]??``).trim()}function e1(e){let t=D$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 O$e(e,t){let n=D$e(e),r=n.replace(w$e,``);if(t!==void 0&&t.trim()!==``){let e=E$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(C$e,``);if(e===r)break;r=e}r=r.replace(T$e,``).trim();let i=r.split(/\s+/).filter(e=>e!==``).length;return!(r!==``&&(i>=2||r.length>=12))||r===n?e1(n):e1(r.charAt(0).toUpperCase()+r.slice(1))}const k$e=8,A$e=5e3,t1=3e5,n1=45e3,j$e=5e3,M$e=2e3,N$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 P$e(e){if(e===null)return N$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`${N$e}\n\n${t}`}const F$e=new Set([`gemini`]);function I$e(e){return e.source===`registry`&&F$e.has(e.id)}function L$e(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:Ts(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${s$e} ---\n${t}\n--- End skill ---`}}var r1=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},i1=class extends C${refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},R$e=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},z$e=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function B$e(){return new r1(`not-ready`,`the thread was restarted during the sign-in`)}function V$e(e){return e.source===`registry`&&aq[e.id]===`pi`}function H$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=>c$(e,LZe())))(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 U$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??(()=>b$(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 y$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,G$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 r1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(await wq({site:`acp-thread`,agentId:n===null?dee(t.id)??t.id:t.id,mode:`acp`,log:this.opts.log,snapshot:this.opts.hostSnapshot}),this.destroyed)throw new r1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`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 dq(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new r1(`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 r1(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new r1(`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??=p$e({localDir:this.opts.localDir,sourceDir:t??r$(`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}d$(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,s$e);if(!I$e(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await rc(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,rQe(t),r);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new r1(`unknown-agent`,`agent vanished`);a=await zZe(t,cq(),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 _$e({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:o});a=i$e(a,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let c=a.kind===`npx`?R$(a):R$(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=pZe(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`&&qZe(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`)}),u1(e).then(r=>{if(e.terminals!==s||l1(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`,d1({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 r1(`spawn-failed`,`agent process has no stdio`);let b=hye(Qie.toWeb(c.stdin),lc.toWeb(c.stdout)),x=Uye({name:`open-knowledge`}).onRequest(qw.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(qw.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(qw.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(qw.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(qw.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(qw.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(qw.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(qw.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(qw.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(b);e.conn=x,x.closed.then(async()=>{await d(),!y()&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},async t=>{await d(),!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(qw.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:u$},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=UZe(a,f,o);if(e!==null)throw e}let s=g===`npx`&&i===`available`?qZe(p):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,s))return _=!0,this.connectAgent(e,t,n,r,`spent`);throw new r1(`spawn-failed`,`initialize failed: ${o1(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:h$(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),!l1(e);this.npxCacheClears.set(t,Date.now());for(let e of[`package.json`,`concurrency.lock`]){let r=await sc(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`),!1}try{await iJ(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`),!1}return this.opts.log.warn(n,`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),!l1(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 V$(n,{graceMs:j$e})}async ensureLaunchable(e,t,n){let r;try{await j$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof C$)||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(N$(n.env)!==N$(t.env))try{await j$(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 C$)||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 C$(`command-not-found`,i?CQe(t,r.detail):mQe(t,r.detail)),o=new C$(`command-not-found`,i?wQe(t,r.detail):bQe(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=LQe(t.kind);if(!UQe(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof i1?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=iQe(t,o);await j$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new C$(`install-failed`,gQe(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 JQe(n,this.opts.log,this.opts.runtimeInstall?.root))throw new C$(`install-failed`,_Qe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof i1?new C$(`command-not-found`,e.refusal===`timeout`?yQe(t):vQe(t)):e});if(o===null)return null;let s=iQe(t,o);await j$(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 C$(`install-failed`,c.kind===`incompatible`?gQe(c.detail):hQe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,N$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await xQe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await SQe(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(N$(t.env)===N$(e.env))return null;try{await j$(t)}catch(t){if(!(t instanceof C$))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||P$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:aQe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||P$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:oQe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await qQe(t,this.opts.log,i);let a=await KQe(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 i1(o,o===`timeout`?q$e(t):K$e(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=G$(t).displayName;throw new C$(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=G$(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 YQe(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=t1){let r=[],i;if(V$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:$Xe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=LZe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Xte,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=aq[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=t1,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await X$e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),l1(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=t1){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let r=await t.agent.request(qw.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=Q$e(n),e.confirmedContextWindow=Y$e(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(J$e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,e),authMethods:p1(n.authMethods)})}else{let n=await u1(e);this.emitStatus(e,`error`,`session setup failed: ${o1(t)}`,{reason:`session-setup`,agentMessage:o1(t),machineDetail:d1({primary:s1(t),tail:n})}),l1(e)||await this.teardownFailedAgent(e)}return!1}return l1(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),l1(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),l1(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new r1(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new r1(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new r1(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`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 r1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`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 r1(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,n1);if(o===null)throw new r1(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=Q$e(u),r.confirmedContextWindow=Y$e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d}=await this.buildMcpServers(r,u,n1),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(qw.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(qw.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 r1(`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 r1(`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 X$e(t,r)),t instanceof r1?t:t instanceof C$?new r1(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 r1(`resume-unsupported`,`couldn't resume the previous session: ${o1(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 r1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new r1(`not-ready`,`a context window must be a positive number of tokens`);let r=a$e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new r1(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new r1(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new r1(`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,n1),n.closed)throw new r1(`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 r1(`spawn-failed`,c1(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof r1)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new r1(`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 r1(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new r1(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new r1(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new r1(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{MZe(),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,n1,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new r1(`spawn-failed`,n)}if(t.closed)throw new r1(`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 r1(`spawn-failed`,c1(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new r1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new r1(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new r1(`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 r1(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new r1(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new r1(`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 B$e();let t=e instanceof R$e?`the sign-in didn't complete in time — try again`:o1(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:f1(e,n),authMethods:p1(i.authMethods)}),new r1(`not-ready`,t)}if(n.closed)throw new r1(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw B$e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,n1);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: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,n),authMethods:p1(i.authMethods)}),t}}if(a!==!0)throw new r1(`not-ready`,c1(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 R$e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(qw.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(l1(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 V$(n,{graceMs:M$e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(gq(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 r1(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new r1(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new r1(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new r1(`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:[Z$e(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 r1(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new r1(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new r1(`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=[Z$e(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=O$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 r1(`not-ready`,`the thread is closing`);let r=e1(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 r1(`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=`${P$e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=L$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;dZe(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 r1(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new z$e;return e.conn.agent.request(qw.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),!l1(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`),l1(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(J$e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,e),authMethods:p1(e.lastInit?.authMethods)});return}let n=await u1(e);this.emitStatus(e,`error`,`prompt failed: ${o1(t)}`,{reason:`prompt`,agentMessage:o1(t),machineDetail:d1({primary:s1(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(qw.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 r1(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new r1(`not-ready`,`thread has no live agent session`);n.conn.agent.request(qw.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 r1(`not-ready`,`no such config option: ${t}`);if(!a1(e,n))throw new r1(`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 r1(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new r1(`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(qw.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||!a1(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(qw.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(qw.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`&&a1(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(qw.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 V$(r,{graceMs:t?.killGraceMs??j$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(gq(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 r1(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new r1(`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:M$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,...XK(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:mZe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await rc(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await rc(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`)}),u1(e).then(r=>{if(e.terminals!==s||l1(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`,d1({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 r1(`spawn-failed`,`agent process has no stdio`);let b=hye(Qie.toWeb(c.stdin),lc.toWeb(c.stdout)),x=Uye({name:`open-knowledge`}).onRequest(qw.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(qw.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(qw.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(qw.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(qw.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(qw.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(qw.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(qw.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(qw.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(qw.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:u$},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=UZe(a,f,o);if(e!==null)throw e}let s=g===`npx`&&i===`available`?qZe(p):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,s))return _=!0,this.connectAgent(e,t,n,r,`spent`);throw new r1(`spawn-failed`,`initialize failed: ${o1(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:h$(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),!l1(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 sc(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 iJ(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),!l1(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 V$(n,{graceMs:j$e})}async ensureLaunchable(e,t,n){let r;try{await j$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof C$)||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(N$(n.env)!==N$(t.env))try{await j$(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 C$)||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 C$(`command-not-found`,i?CQe(t,r.detail):mQe(t,r.detail)),o=new C$(`command-not-found`,i?wQe(t,r.detail):bQe(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=LQe(t.kind);if(!UQe(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof i1?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=iQe(t,o);await j$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new C$(`install-failed`,gQe(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 JQe(n,this.opts.log,this.opts.runtimeInstall?.root))throw new C$(`install-failed`,_Qe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof i1?new C$(`command-not-found`,e.refusal===`timeout`?yQe(t):vQe(t)):e});if(o===null)return null;let s=iQe(t,o);await j$(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 C$(`install-failed`,c.kind===`incompatible`?gQe(c.detail):hQe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,N$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await xQe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await SQe(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(N$(t.env)===N$(e.env))return null;try{await j$(t)}catch(t){if(!(t instanceof C$))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||P$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:aQe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||P$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:oQe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await qQe(t,this.opts.log,i);let a=await KQe(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 i1(o,o===`timeout`?q$e(t):K$e(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=G$(t).displayName;throw new C$(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=G$(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 YQe(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=t1){let r=[],i;if(V$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:$Xe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=LZe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Xte,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=aq[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=t1,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await X$e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),l1(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=t1){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let r=await t.agent.request(qw.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=Q$e(n),e.confirmedContextWindow=Y$e(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(J$e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,e),authMethods:p1(n.authMethods)})}else{let n=await u1(e);this.emitStatus(e,`error`,`session setup failed: ${o1(t)}`,{reason:`session-setup`,agentMessage:o1(t),machineDetail:d1({primary:s1(t),tail:n})}),l1(e)||await this.teardownFailedAgent(e)}return!1}return l1(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),l1(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),l1(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new r1(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new r1(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new r1(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`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 r1(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new r1(`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 r1(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,n1);if(o===null)throw new r1(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=Q$e(u),r.confirmedContextWindow=Y$e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d}=await this.buildMcpServers(r,u,n1),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(qw.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(qw.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 r1(`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 r1(`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 X$e(t,r)),t instanceof r1?t:t instanceof C$?new r1(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 r1(`resume-unsupported`,`couldn't resume the previous session: ${o1(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 r1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new r1(`not-ready`,`a context window must be a positive number of tokens`);let r=a$e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new r1(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new r1(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new r1(`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,n1),n.closed)throw new r1(`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 r1(`spawn-failed`,c1(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof r1)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new r1(`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 r1(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new r1(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new r1(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new r1(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{MZe(),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,n1,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new r1(`spawn-failed`,n)}if(t.closed)throw new r1(`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 r1(`spawn-failed`,c1(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new r1(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new r1(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new r1(`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 r1(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new r1(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new r1(`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 B$e();let t=e instanceof R$e?`the sign-in didn't complete in time — try again`:o1(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:f1(e,n),authMethods:p1(i.authMethods)}),new r1(`not-ready`,t)}if(n.closed)throw new r1(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw B$e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,n1);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: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,n),authMethods:p1(i.authMethods)}),t}}if(a!==!0)throw new r1(`not-ready`,c1(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 R$e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(qw.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(l1(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 V$(n,{graceMs:M$e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(gq(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 r1(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new r1(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new r1(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new r1(`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:[Z$e(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 r1(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new r1(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new r1(`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=[Z$e(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=O$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 r1(`not-ready`,`the thread is closing`);let r=e1(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 r1(`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=`${P$e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=L$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;dZe(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 r1(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new z$e;return e.conn.agent.request(qw.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),!l1(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`),l1(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(J$e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${o1(t)}`,{reason:`auth-required`,agentMessage:o1(t),machineDetail:f1(t,e),authMethods:p1(e.lastInit?.authMethods)});return}let n=await u1(e);this.emitStatus(e,`error`,`prompt failed: ${o1(t)}`,{reason:`prompt`,agentMessage:o1(t),machineDetail:d1({primary:s1(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(qw.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 r1(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new r1(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new r1(`not-ready`,`thread has no live agent session`);n.conn.agent.request(qw.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 r1(`not-ready`,`no such config option: ${t}`);if(!a1(e,n))throw new r1(`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 r1(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new r1(`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(qw.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||!a1(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(qw.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(qw.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`&&a1(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(qw.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 V$(r,{graceMs:t?.killGraceMs??j$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(gq(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 r1(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new r1(`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:M$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,...XK(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:mZe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await rc(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await rc(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=Sq(t);try{t.dc.document.transact(()=>{let r=JQ(t.dc.document);qQ(t.dc.document,n,`replace`,i,void 0,GQ(t),a);let o=qi(r,JQ(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 BY?(VY(e,`acp-fs-write`),new Gw(-32009,CGe,{type:zY,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(()=>Zq);await e(V(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return W$e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new r1(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&yZe(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>A$e){let t=e.events.length-A$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(l1(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:h$(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:h$(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&&AQe(r.reason)&&NQe(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=Ve(e.info.agent.id),i=ga[r]??pt(e.agentSessionId);n.setPresence(gq(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 W$e(e,t,n){let r=await ac(e),i=ys(vs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await ac(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||vs(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(Ss).join(`/`),t=s.split(Ss).join(`/`);!EY(e)&&!DY(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Ss).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 G$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 a1(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 K$e(e){let t=G$(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 q$e(e){let t=G$(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 J$e(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 o1(e){return e instanceof Error?e.message:String(e)}function s1(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return h$(JSON.stringify(t)).slice(0,300)}catch{return}}function Y$e(e){return X$(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function c1(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 X$e(e,t){return{reason:`connect`,agentMessage:e instanceof C$||e instanceof r1?e.message:String(e),machineDetail:d1({primary:e instanceof C$?e.machineDetail:void 0,tail:await u1(t)})}}function Z$e(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 l1(e){return e.closed||e.info.archived===!0}async function u1(e){let t=e.stderrTail;await e.drainStderr?.();let n=h$(t.join(`
958
958
  `)).slice(-16e3);return n===``?void 0:n}function d1({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,m$);let n=Math.min(t.length,1024),r=m$-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=m$-i.length-1;return`${i}\n${t.slice(-a)}`}function f1(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
@@ -1 +1 @@
1
- import{$l as e,Ad as t,Cn as n,Fo as r,Ia as i,Ls as a,Rl as o,Vt as s,Xn as c,qo as l,vn as u}from"./md-manager-BGnqyqi1-BmeBaisX.mjs";import{$ as d,$a as f,$i as p,$n as m,$r as h,$t as g,A as _,Aa as v,Ai as y,An as b,Ar as x,At as S,B as C,Ba as w,Bi as T,Bn as E,Bo 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,Go as ie,Gr as ae,Gt as oe,H as se,Ha as ce,Hi as le,Hn 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,Vr as Wt,Vt as Gt,W as Kt,Wa as qt,Wi as Jt,Wn as Yt,Wo 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,_r as Tn,_t as En,a as Dn,aa as On,ai as kn,an as An,ao as jn,ar as Mn,at as Nn,b as Pn,ba as Fn,bi as In,bn as Ln,br as Rn,bt as zn,c as Bn,ca as Vn,ci as Hn,cn as Un,co as Wn,cr as Gn,ct as Kn,d as qn,da as Jn,di as Yn,dn as Xn,do as Zn,dr as Qn,dt as $n,ea as er,ei as tr,en as nr,eo as rr,er as ir,et as ar,f as or,fa as sr,fi as cr,fn as lr,fo as ur,fr as dr,ft as fr,g as pr,ga as mr,gi as hr,gn as gr,gr as _r,gt as vr,h as yr,ha as br,hi as xr,hn as Sr,ho as Cr,hr as wr,ht as Tr,i as Er,ia as Dr,ii as Or,in as kr,io as Ar,ir as jr,it as Mr,j as Nr,ja as Pr,ji as Fr,jn as Ir,jr as Lr,jt as Rr,k as zr,ka as Br,ki as Vr,kn as Hr,kr as Ur,kt as Wr,l as Gr,la as Kr,li as qr,ln as Jr,lo as Yr,lr as Xr,lt as Zr,m as Qr,ma as $r,mi as ei,mn as ti,mo as ni,mr as ri,mt as ii,n as ai,na as oi,ni as si,nn as ci,no as li,nr as ui,nt as di,o as fi,oa as pi,oi as mi,on as hi,oo as gi,or as _i,ot as vi,p as yi,pa as bi,pi as xi,pn as Si,po as Ci,pr as wi,pt as Ti,q as Ei,qa as Di,qi as Oi,qn as ki,qo as Ai,qr as ji,qt as Mi,r as Ni,ra as Pi,ri as Fi,rn as Ii,ro as Li,rr as Ri,rt as zi,s as Bi,sa as Vi,si as Hi,sn as Ui,so as Wi,sr as Gi,st as Ki,t as qi,ta as Ji,ti as Yi,tn as Xi,to as Zi,tr as Qi,tt as $i,u as ea,ua as ta,ui as na,un as ra,uo as ia,ur as aa,ut as oa,v as sa,va as ca,vi as la,vn as ua,vr as da,vt as fa,w as pa,wa as ma,wi as ha,wn as ga,wr as _a,wt as va,x as ya,xa as ba,xi as xa,xn as Sa,xr as Ca,xt as wa,y as Ta,ya as Ea,yi as Da,yn as Oa,yr as ka,yt as Aa,z as ja,za as Ma,zi as Na,zn as Pa,zo as Fa,zr as Ia,zt as La}from"./dist-BaFVilsg.mjs";export{qi as AGENT_ID_MAX_LEN,ai as AGENT_ID_RE,Ni as AGENT_WRITE_ORIGIN,Er as AcpPermissionStore,Dn as AcpRegistry,fi as AcpThreadManager,Bi as AgentFocusBroadcaster,Bn as AgentPresenceBroadcaster,Gr as AgentSessionCapacityError,ea as AgentSessionManager,qn as AutoStartDisabledError,or as BUNDLE_IDS,yi as BUNDLE_SCOPE,Qr as BUNDLE_SKILL_NAME,yr as BacklinkIndex,pr as CC1Broadcaster,o as CC1_CONTRACT_VERSION,xn as CONCURRENT_REPLACE_WINDOW_MS,sa as CONFIG_FILENAME,Ta as CONFLICT_MARKER_RE,Pn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ya as ConfigSchema,St as ConflictAuthority,A as DEFAULT_CHECKPOINT_RETENTION,pa as DEFAULT_EMBEDDINGS_DIMENSIONS,Ot as DEFAULT_PACK_ID,H as DocumentDurabilityState,I as DocumentDurabilityStateError,Ze as EMBEDDINGS_API_KEY_ENV,zr as EPHEMERAL_PROJECT_DIR_PREFIX,_ as ExposureConsentError,Nr 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,Fa as GitDirAccessError,Ne as GitNotAvailableError,gt as GitTooOldError,ja as HOCUSPOCUS_AUTH_REJECTION_REASONS,C as HocuspocusAuthRejection,Bt as HocuspocusAuthTokenSchema,se as HomeProjectRootError,Pt as INSTALLED_AGENTS_SCHEMES,Kt as JSON_SCHEMA_DIALECT_2020_12,s as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ee as MANAGED_RENAME_ORIGIN,Ei as MAX_ACP_THREADS,ye as MAX_AGENT_SESSIONS,sn as MCP_CONNECTION_ID_HEADER,t as MCP_SERVER_NAME,$t as MIN_EVICTABLE_IDLE_MS,mn as MIN_GIT_VERSION,lt as MISSING_OK_CONFIG_MESSAGE,D as MalformedGitPointerError,d as McpLogger,ar as MissingOkConfigError,$i as OBSERVER_SYNC_ORIGIN,di as OK_OKIGNORE_TEMPLATE,zi as ONBOARDING_BUNDLE_IDS,u as ORPHAN_MODES,n as PROTOCOL_VERSION,Xt as PinoLogger,Mr as ProcessLockCollisionError,Nn as ProjectGitInitError,vi as ROLLBACK_ORIGIN,Ki as ROOT_GITIGNORE_TEMPLATE,Kn as RUNTIME_VERSION,Zr as SERVICE_WRITER,oa as SKILL_INSTALL_EVENTS_FILE_REL,c as SKILL_STATE_TARGETS,$n as STARTER_FOLDER_FRONTMATTER_FILENAME,fr as STARTER_PACKS,Ti as STARTER_PACK_IDS,ii as STATE_MANIFEST_FILENAME,Tr as STATE_SCHEMA_VERSION,e as SYSTEM_DOC_NAME,vr as SeedPrerequisiteError,En as SeedRootDirError,fa as ServerLockCollisionError,Aa as SingleFileNotAFileError,zn as SingleFileNotFoundError,wa as SingleFileNotMarkdownError,Dt as SingleFileProjectOverrideError,F as StateManifestError,va as TagIndex,Nt as USER_GLOBAL_BUNDLE_IDS,q as __getShowAllWalkStatsForTesting,V as __resetShowAllWalkStatsForTesting,nt as acquireProcessLock,Wr as acquireServerLock,S as applyAgentMarkdownWrite,Rr as applyExternalChange,We as applySeed,Xe as assertCompatibleStateManifest,ct as assertGitAvailable,$ as assertNeverDiskEvent,ve as assertNotHomeProjectRoot,Re as attachAcpThreadSocket,xt as attachCollabClientCounter,La as attachIdleShutdown,k as bindConflictAuthority,Gt as bootServer,fe as buildAndOpenSkill,zt as buildConfigYmlContent,Qt as buildExecResult,oe as buildIngressPolicy,Me as buildOkMcpStdioCommand,Mi as buildSkillZip,Te as buildStarterFolderFrontmatterYaml,pn as buildWipTree,on as bundleSkillMdPath,bn as canonicalProjectKey,ht as canonicalizeForCompare,g as classifyEvents,nr as classifyFsPath,Xi as clearAllEmbeddingsKeys,ci as coercePackId,Ii as collectServerHostSnapshot,i as colorFromSeed,kr as commitUpstreamImport,An as commitWip,hi as commitWipFromTree,Ui as compareSemver,Un as composeEffectiveLinterConfig,Jr as composeFrontmatterSchemasConfig,ra as containsConflictMarkers,Xn as contentHash,lr as contributorCount,Si as countShadowObjects,ti as countStaleAgentWipRefs,Sr as countWipRefs,gr as createApiExtension,wn as createAssetServeMiddleware,ua as createCollaborationHost,Oa as createContentFilter,Ln as createContentFilterAsync,Sa as createEmbeddingsSecretStore,Tt as createEphemeralProjectDir,N as createExternalChangeHandler,ga as createFileLogger,jt as createLiveDerivedIndexExtension,G as createMcpHttpHandler,z as createOsProbe,et as createPersistenceExtension,Hr as createProbeFailureReporter,b as createServer,Ir as createServerObserverExtension,He as createServerProbeResolver,Je as createStreamingErrorWriter,ie as createTestLogger,ot as describeStoredEmbeddingsKey,Z as detectClaudeDesktopPresence,ge as detectGit,Ie as detectProjectShape,yt as detectUserSkillHosts,Pa as discoverLockDirs,E as discoverMarkdownlintConfig,Ut as emitPreflightFailureSpan,ue as encodeDocName,Lt as encodeFolderRoute,Yt as encodeSkillRoute,re as ensureProjectGit,ke as errorResponse,ki as evictStaleTrackerEntries,Se as extractHeadings,un as extractOkBinaryPath,nn as extractWikiLinksFromMarkdown,_n as fallbackPaths,ft as findEnclosingGitRoot,m as findEnclosingProjectRoot,ir as findNativeMarkdownlintFile,Qi as flushFileLogger,ui as formatAuditBrokenLinkSuppressionLine,Ri as formatAuthRejectionWire,jr as formatContributorsFrom,Mn as formatPackRationale,_i as gcCheckpointRefs,Gi as getCurrentMcpLogger,Gn as getIngressContext,Xr as getLocalDir,aa as getLogFilePath,Ae as getLogger,Qn as getLogsDir,dr as getMachineId,wi as getMeter,ri as getMetrics,wr as getTracer,_r as handleCollabSocketError,Tn as handleSpawnCursor,da as hasForwardingHeaders,ka as hasGcLogLatch,r as iconFromClientName,Rn as incrementCollabSocketFilteredError,Ca as incrementServerObserverFire,Et as initContent,P as initShadowRepo,_a as initTelemetry,Mt as initToleranceTelemetryWriter,K as installJsonSchemaDialect,B as installPrettyZodErrors,Ai as installTestLoggers,tt as installUserSkill,Ur as isAllowedApiOrigin,x as isAllowedWorkspaceHostHeader,Lr as isConfigDoc,Ue as isDefunctProcess,Ye as isDocInConflict,st as isHocuspocusAuthRejectionReason,Q as isHomeDir,_e as isHostAdmitted,Le as isKnownPackId,bt as isLinkIndexExcludedDoc,Ia as isLockProcessRunning,O as isLoopbackAddress,Wt as isManagedArtifactDoc,de as isOriginAdmitted,l as isOrphanMode,Rt as isPairedWriteOrigin,Zt as isPathWithinDir,ae as isPeerAdmitted,je as isProcessAlive,ji as isProjectRoot,we as isReservedForUserTree,fn as isSelfWrite,an as isSystemDoc,yn as isToleranceTelemetryEnabled,mt as isValidLockPid,h as lastKnownHash,tr as listRescueCheckpoints,Yi as listStarterPacks,si as loadCustomAgents,Fi as loadPrincipal,Or as lockAdvertisesUi,kn as lockBaseUrl,mi as lockFilePath,Ce as loggerFactory,Hi as loginShapedUserinfoUser,dn as logsCurrentPath,rn as logsPreviousPath,Hn as makeLazyEmbeddingsKeyStore,qr as markServerLockDraining,na as mountMcpAndApi,Yn as normalizeFsPath,cr as observeReadiness,xi as originGitHubHost,ei as packageVersionMajorMinor,xr as parseAuthRejectionWire,hr as parseGitVersion,Cn as parseHocuspocusAuthToken,la as parseKeepaliveConnectionId,Da as pathToDocName,In as planSeed,xa as prepareSingleFileOpen,wt as processCommand,M as processUsage,ha as readAllTargets,At as readBundleDecision,W as readOwnNativeRules,R as readProcessLock,$e as readProcessLockDetailed,Vr as readProcessState,y as readProjectHeadState,Fr as readProjectLocalSemanticConfig,Ve as readServerLock,qe as readServerPackageVersion,at as readSkillInstallStateSnapshot,X as readStateManifest,he as readTargetRecordedAt,Fe as readTargetVersion,vt as reconcile,Na as recordContributor,T as recordSkillInstallEvent,Ht as redactShareSubprocessStderr,le as registerAllTools,It as registerWrite,Jt as releaseProcessLock,ne as releaseServerLock,Oe as removeLastKnownHash,Oi as removeProjectSkillGitignoreBlock,xe as reportSkillInstall,ln as resetMetrics,tn as resolveBuiltinSkillHosts,a as resolveBundleEnabled,gn as resolveBundledSkillDir,dt as resolveContentDir,p as resolveCursorBinaryDefault,er as resolveCursorSpawnInvocation,Ji as resolveEffectiveLinterConfig,oi as resolveEmbeddingsCredential,Pi as resolveGitHubAccountFromUrl,Dr as resolveLockDir,On as resolveNativeConfigForDoc,pi as resolveNativeMarkdownlintConfig,Vi as resolvePack,Vn as resolvePackageVersion,Kr as resolveSkillInstallReportSettings,ta as resolveUiInfo,Jn as restoreContributors,sr as rewriteMarkdownLinksForDocumentRename,bi as rewriteWikiLinksForDocumentRename,$r as runAuthReposSubprocess,br as runAuthStatusSubprocess,mr as runCloneSubprocess,Sn as runDeviceFlowSubprocess,ca as runWithMcpLogger,Ea as safeContentPath,Fn as safeSubdir,ba as safetyCheckpoint,Ct as sameGitHubLogin,j as sanitizeClientName,ma as saveInMemoryCheckpoint,kt as saveVersion,U as scanLockProcesses,L as seedBasenameIndex,Qe as seedEphemeralProjectDir,Br as serializeError,v as setActiveSpanAttributes,Pr as setupServerObservers,Be as shadowGit,Ke as shutdownTelemetry,vn as spansCurrentPath,pt as spansPreviousPath,it as spawnDetached,Y as splitMarkdownBlocks,me as startWatcher,Pe as strategiesFor,_t as streamingProblemEvent,Ma as swapContributors,w as teardownToleranceTelemetryWriter,Vt as toBroadcasterKey,ce as tracedAppendFileSync,Ft as tracedLinkSync,qt as tracedMkdir,te as tracedMkdirSync,De as tracedRename,Di as tracedRenameSync,be as tracedRmSync,cn as tracedRmdirSync,en as tracedUnlinkSync,hn as tracedWriteFile,ut as tracedWriteFileSync,f as trustSystemCertificates,rr as updateLastKnownHash,Zi as updateProcessLockPort,li as updateServerLockPort,Li as validateAgentId,Ar as validateCloneInputs,jn as validateSkillZip,gi as waitForServerLockDrain,Wi as withHiddenWindowsConsole,Wn as withSpan,Yr as withSpanSync,ia as writeBundleDecision,Zn as writeMarkdownlintRule,ur as writeRootGitignoreForNewRepo,Ci as writeStateManifest,ni as writeTargetVersion,Cr as writeTracker};
1
+ import{$l as e,Ad as t,Cn as n,Fo as r,Ia as i,Ls as a,Rl as o,Vt as s,Xn as c,qo as l,vn as u}from"./md-manager-BGnqyqi1-BmeBaisX.mjs";import{$ as d,$a as f,$i as p,$n as m,$r as h,$t as g,A as _,Aa as v,Ai as y,An as b,Ar as x,At as S,B as C,Ba as w,Bi as T,Bn as E,Bo 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,Go as ie,Gr as ae,Gt as oe,H as se,Ha as ce,Hi as le,Hn 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,Vr as Wt,Vt as Gt,W as Kt,Wa as qt,Wi as Jt,Wn as Yt,Wo 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,_r as Tn,_t as En,a as Dn,aa as On,ai as kn,an as An,ao as jn,ar as Mn,at as Nn,b as Pn,ba as Fn,bi as In,bn as Ln,br as Rn,bt as zn,c as Bn,ca as Vn,ci as Hn,cn as Un,co as Wn,cr as Gn,ct as Kn,d as qn,da as Jn,di as Yn,dn as Xn,do as Zn,dr as Qn,dt as $n,ea as er,ei as tr,en as nr,eo as rr,er as ir,et as ar,f as or,fa as sr,fi as cr,fn as lr,fo as ur,fr as dr,ft as fr,g as pr,ga as mr,gi as hr,gn as gr,gr as _r,gt as vr,h as yr,ha as br,hi as xr,hn as Sr,ho as Cr,hr as wr,ht as Tr,i as Er,ia as Dr,ii as Or,in as kr,io as Ar,ir as jr,it as Mr,j as Nr,ja as Pr,ji as Fr,jn as Ir,jr as Lr,jt as Rr,k as zr,ka as Br,ki as Vr,kn as Hr,kr as Ur,kt as Wr,l as Gr,la as Kr,li as qr,ln as Jr,lo as Yr,lr as Xr,lt as Zr,m as Qr,ma as $r,mi as ei,mn as ti,mo as ni,mr as ri,mt as ii,n as ai,na as oi,ni as si,nn as ci,no as li,nr as ui,nt as di,o as fi,oa as pi,oi as mi,on as hi,oo as gi,or as _i,ot as vi,p as yi,pa as bi,pi as xi,pn as Si,po as Ci,pr as wi,pt as Ti,q as Ei,qa as Di,qi as Oi,qn as ki,qo as Ai,qr as ji,qt as Mi,r as Ni,ra as Pi,ri as Fi,rn as Ii,ro as Li,rr as Ri,rt as zi,s as Bi,sa as Vi,si as Hi,sn as Ui,so as Wi,sr as Gi,st as Ki,t as qi,ta as Ji,ti as Yi,tn as Xi,to as Zi,tr as Qi,tt as $i,u as ea,ua as ta,ui as na,un as ra,uo as ia,ur as aa,ut as oa,v as sa,va as ca,vi as la,vn as ua,vr as da,vt as fa,w as pa,wa as ma,wi as ha,wn as ga,wr as _a,wt as va,x as ya,xa as ba,xi as xa,xn as Sa,xr as Ca,xt as wa,y as Ta,ya as Ea,yi as Da,yn as Oa,yr as ka,yt as Aa,z as ja,za as Ma,zi as Na,zn as Pa,zo as Fa,zr as Ia,zt as La}from"./dist-CNo9_UDM.mjs";export{qi as AGENT_ID_MAX_LEN,ai as AGENT_ID_RE,Ni as AGENT_WRITE_ORIGIN,Er as AcpPermissionStore,Dn as AcpRegistry,fi as AcpThreadManager,Bi as AgentFocusBroadcaster,Bn as AgentPresenceBroadcaster,Gr as AgentSessionCapacityError,ea as AgentSessionManager,qn as AutoStartDisabledError,or as BUNDLE_IDS,yi as BUNDLE_SCOPE,Qr as BUNDLE_SKILL_NAME,yr as BacklinkIndex,pr as CC1Broadcaster,o as CC1_CONTRACT_VERSION,xn as CONCURRENT_REPLACE_WINDOW_MS,sa as CONFIG_FILENAME,Ta as CONFLICT_MARKER_RE,Pn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ya as ConfigSchema,St as ConflictAuthority,A as DEFAULT_CHECKPOINT_RETENTION,pa as DEFAULT_EMBEDDINGS_DIMENSIONS,Ot as DEFAULT_PACK_ID,H as DocumentDurabilityState,I as DocumentDurabilityStateError,Ze as EMBEDDINGS_API_KEY_ENV,zr as EPHEMERAL_PROJECT_DIR_PREFIX,_ as ExposureConsentError,Nr 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,Fa as GitDirAccessError,Ne as GitNotAvailableError,gt as GitTooOldError,ja as HOCUSPOCUS_AUTH_REJECTION_REASONS,C as HocuspocusAuthRejection,Bt as HocuspocusAuthTokenSchema,se as HomeProjectRootError,Pt as INSTALLED_AGENTS_SCHEMES,Kt as JSON_SCHEMA_DIALECT_2020_12,s as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ee as MANAGED_RENAME_ORIGIN,Ei as MAX_ACP_THREADS,ye as MAX_AGENT_SESSIONS,sn as MCP_CONNECTION_ID_HEADER,t as MCP_SERVER_NAME,$t as MIN_EVICTABLE_IDLE_MS,mn as MIN_GIT_VERSION,lt as MISSING_OK_CONFIG_MESSAGE,D as MalformedGitPointerError,d as McpLogger,ar as MissingOkConfigError,$i as OBSERVER_SYNC_ORIGIN,di as OK_OKIGNORE_TEMPLATE,zi as ONBOARDING_BUNDLE_IDS,u as ORPHAN_MODES,n as PROTOCOL_VERSION,Xt as PinoLogger,Mr as ProcessLockCollisionError,Nn as ProjectGitInitError,vi as ROLLBACK_ORIGIN,Ki as ROOT_GITIGNORE_TEMPLATE,Kn as RUNTIME_VERSION,Zr as SERVICE_WRITER,oa as SKILL_INSTALL_EVENTS_FILE_REL,c as SKILL_STATE_TARGETS,$n as STARTER_FOLDER_FRONTMATTER_FILENAME,fr as STARTER_PACKS,Ti as STARTER_PACK_IDS,ii as STATE_MANIFEST_FILENAME,Tr as STATE_SCHEMA_VERSION,e as SYSTEM_DOC_NAME,vr as SeedPrerequisiteError,En as SeedRootDirError,fa as ServerLockCollisionError,Aa as SingleFileNotAFileError,zn as SingleFileNotFoundError,wa as SingleFileNotMarkdownError,Dt as SingleFileProjectOverrideError,F as StateManifestError,va as TagIndex,Nt as USER_GLOBAL_BUNDLE_IDS,q as __getShowAllWalkStatsForTesting,V as __resetShowAllWalkStatsForTesting,nt as acquireProcessLock,Wr as acquireServerLock,S as applyAgentMarkdownWrite,Rr as applyExternalChange,We as applySeed,Xe as assertCompatibleStateManifest,ct as assertGitAvailable,$ as assertNeverDiskEvent,ve as assertNotHomeProjectRoot,Re as attachAcpThreadSocket,xt as attachCollabClientCounter,La as attachIdleShutdown,k as bindConflictAuthority,Gt as bootServer,fe as buildAndOpenSkill,zt as buildConfigYmlContent,Qt as buildExecResult,oe as buildIngressPolicy,Me as buildOkMcpStdioCommand,Mi as buildSkillZip,Te as buildStarterFolderFrontmatterYaml,pn as buildWipTree,on as bundleSkillMdPath,bn as canonicalProjectKey,ht as canonicalizeForCompare,g as classifyEvents,nr as classifyFsPath,Xi as clearAllEmbeddingsKeys,ci as coercePackId,Ii as collectServerHostSnapshot,i as colorFromSeed,kr as commitUpstreamImport,An as commitWip,hi as commitWipFromTree,Ui as compareSemver,Un as composeEffectiveLinterConfig,Jr as composeFrontmatterSchemasConfig,ra as containsConflictMarkers,Xn as contentHash,lr as contributorCount,Si as countShadowObjects,ti as countStaleAgentWipRefs,Sr as countWipRefs,gr as createApiExtension,wn as createAssetServeMiddleware,ua as createCollaborationHost,Oa as createContentFilter,Ln as createContentFilterAsync,Sa as createEmbeddingsSecretStore,Tt as createEphemeralProjectDir,N as createExternalChangeHandler,ga as createFileLogger,jt as createLiveDerivedIndexExtension,G as createMcpHttpHandler,z as createOsProbe,et as createPersistenceExtension,Hr as createProbeFailureReporter,b as createServer,Ir as createServerObserverExtension,He as createServerProbeResolver,Je as createStreamingErrorWriter,ie as createTestLogger,ot as describeStoredEmbeddingsKey,Z as detectClaudeDesktopPresence,ge as detectGit,Ie as detectProjectShape,yt as detectUserSkillHosts,Pa as discoverLockDirs,E as discoverMarkdownlintConfig,Ut as emitPreflightFailureSpan,ue as encodeDocName,Lt as encodeFolderRoute,Yt as encodeSkillRoute,re as ensureProjectGit,ke as errorResponse,ki as evictStaleTrackerEntries,Se as extractHeadings,un as extractOkBinaryPath,nn as extractWikiLinksFromMarkdown,_n as fallbackPaths,ft as findEnclosingGitRoot,m as findEnclosingProjectRoot,ir as findNativeMarkdownlintFile,Qi as flushFileLogger,ui as formatAuditBrokenLinkSuppressionLine,Ri as formatAuthRejectionWire,jr as formatContributorsFrom,Mn as formatPackRationale,_i as gcCheckpointRefs,Gi as getCurrentMcpLogger,Gn as getIngressContext,Xr as getLocalDir,aa as getLogFilePath,Ae as getLogger,Qn as getLogsDir,dr as getMachineId,wi as getMeter,ri as getMetrics,wr as getTracer,_r as handleCollabSocketError,Tn as handleSpawnCursor,da as hasForwardingHeaders,ka as hasGcLogLatch,r as iconFromClientName,Rn as incrementCollabSocketFilteredError,Ca as incrementServerObserverFire,Et as initContent,P as initShadowRepo,_a as initTelemetry,Mt as initToleranceTelemetryWriter,K as installJsonSchemaDialect,B as installPrettyZodErrors,Ai as installTestLoggers,tt as installUserSkill,Ur as isAllowedApiOrigin,x as isAllowedWorkspaceHostHeader,Lr as isConfigDoc,Ue as isDefunctProcess,Ye as isDocInConflict,st as isHocuspocusAuthRejectionReason,Q as isHomeDir,_e as isHostAdmitted,Le as isKnownPackId,bt as isLinkIndexExcludedDoc,Ia as isLockProcessRunning,O as isLoopbackAddress,Wt as isManagedArtifactDoc,de as isOriginAdmitted,l as isOrphanMode,Rt as isPairedWriteOrigin,Zt as isPathWithinDir,ae as isPeerAdmitted,je as isProcessAlive,ji as isProjectRoot,we as isReservedForUserTree,fn as isSelfWrite,an as isSystemDoc,yn as isToleranceTelemetryEnabled,mt as isValidLockPid,h as lastKnownHash,tr as listRescueCheckpoints,Yi as listStarterPacks,si as loadCustomAgents,Fi as loadPrincipal,Or as lockAdvertisesUi,kn as lockBaseUrl,mi as lockFilePath,Ce as loggerFactory,Hi as loginShapedUserinfoUser,dn as logsCurrentPath,rn as logsPreviousPath,Hn as makeLazyEmbeddingsKeyStore,qr as markServerLockDraining,na as mountMcpAndApi,Yn as normalizeFsPath,cr as observeReadiness,xi as originGitHubHost,ei as packageVersionMajorMinor,xr as parseAuthRejectionWire,hr as parseGitVersion,Cn as parseHocuspocusAuthToken,la as parseKeepaliveConnectionId,Da as pathToDocName,In as planSeed,xa as prepareSingleFileOpen,wt as processCommand,M as processUsage,ha as readAllTargets,At as readBundleDecision,W as readOwnNativeRules,R as readProcessLock,$e as readProcessLockDetailed,Vr as readProcessState,y as readProjectHeadState,Fr as readProjectLocalSemanticConfig,Ve as readServerLock,qe as readServerPackageVersion,at as readSkillInstallStateSnapshot,X as readStateManifest,he as readTargetRecordedAt,Fe as readTargetVersion,vt as reconcile,Na as recordContributor,T as recordSkillInstallEvent,Ht as redactShareSubprocessStderr,le as registerAllTools,It as registerWrite,Jt as releaseProcessLock,ne as releaseServerLock,Oe as removeLastKnownHash,Oi as removeProjectSkillGitignoreBlock,xe as reportSkillInstall,ln as resetMetrics,tn as resolveBuiltinSkillHosts,a as resolveBundleEnabled,gn as resolveBundledSkillDir,dt as resolveContentDir,p as resolveCursorBinaryDefault,er as resolveCursorSpawnInvocation,Ji as resolveEffectiveLinterConfig,oi as resolveEmbeddingsCredential,Pi as resolveGitHubAccountFromUrl,Dr as resolveLockDir,On as resolveNativeConfigForDoc,pi as resolveNativeMarkdownlintConfig,Vi as resolvePack,Vn as resolvePackageVersion,Kr as resolveSkillInstallReportSettings,ta as resolveUiInfo,Jn as restoreContributors,sr as rewriteMarkdownLinksForDocumentRename,bi as rewriteWikiLinksForDocumentRename,$r as runAuthReposSubprocess,br as runAuthStatusSubprocess,mr as runCloneSubprocess,Sn as runDeviceFlowSubprocess,ca as runWithMcpLogger,Ea as safeContentPath,Fn as safeSubdir,ba as safetyCheckpoint,Ct as sameGitHubLogin,j as sanitizeClientName,ma as saveInMemoryCheckpoint,kt as saveVersion,U as scanLockProcesses,L as seedBasenameIndex,Qe as seedEphemeralProjectDir,Br as serializeError,v as setActiveSpanAttributes,Pr as setupServerObservers,Be as shadowGit,Ke as shutdownTelemetry,vn as spansCurrentPath,pt as spansPreviousPath,it as spawnDetached,Y as splitMarkdownBlocks,me as startWatcher,Pe as strategiesFor,_t as streamingProblemEvent,Ma as swapContributors,w as teardownToleranceTelemetryWriter,Vt as toBroadcasterKey,ce as tracedAppendFileSync,Ft as tracedLinkSync,qt as tracedMkdir,te as tracedMkdirSync,De as tracedRename,Di as tracedRenameSync,be as tracedRmSync,cn as tracedRmdirSync,en as tracedUnlinkSync,hn as tracedWriteFile,ut as tracedWriteFileSync,f as trustSystemCertificates,rr as updateLastKnownHash,Zi as updateProcessLockPort,li as updateServerLockPort,Li as validateAgentId,Ar as validateCloneInputs,jn as validateSkillZip,gi as waitForServerLockDrain,Wi as withHiddenWindowsConsole,Wn as withSpan,Yr as withSpanSync,ia as writeBundleDecision,Zn as writeMarkdownlintRule,ur as writeRootGitignoreForNewRepo,Ci as writeStateManifest,ni as writeTargetVersion,Cr 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 lje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function uje(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const dje=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function fje(e){let t={contentDir:e.contentDir};for(let n of dje)for(let r of P9(N(e.stagingDir,n)))uje(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):lje.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 pje(e){return N(e,...I9,z9)}function mje(e){return N(e,...I9,B9)}function hje(e){return N(e,...L9,V9)}function gje(e){return N(e,...L9,H9)}function _je(e){return N(e,...R9,U9)}function vje(e){return N(e,...R9,W9)}const G9=1e3;async function yje(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 bje(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 xje(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 Sje(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 Cje(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 wje(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 Tje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Eje(){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 Dje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Dje(e.maxBytes)}function Oje(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 kje(e){return Ne(`sha256`).update(e).digest(`hex`)}function Aje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const jje=[`"doc.name"`,`"docName"`];function Mje(e){let t=S(e,`utf-8`),n=0;for(let e of jje){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 Nje=new Set([`.jsonl`]);function Pje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Nje.has(e.slice(t))}const Fje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Ije(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Fje.has(e.slice(t))}function Lje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Ije(r))continue;let{redacted:i,patterns:a,lineCount:o}=TB(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 Rje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??yje,a=r.fetchAgentEffects??bje,o=r.fetchWatcherRecent??xje,s=r.readShadowHead??Cje,c=r.readCheckpointRefs??wje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.9-beta.4`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??Tje,h=r.isOtlpPushEnabled??Eje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(pje(n),N(_,`telemetry`,z9)),Z9(mje(n),N(_,`telemetry`,B9)),Z9(hje(n),N(_,`logs`,V9)),Z9(gje(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(_,JL,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=Sje(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(_je(n),N(_,`state`,U9)),Z9(vje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Iu),N(_,`state`,Iu)),Z9(N(b,Lu),N(_,`state`,Lu)),Z9(N(b,Fu),N(_,`state`,Fu));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
1538
+ `)}\n`:null}catch{return null}}function Cje(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 wje(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 Tje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Eje(){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 Dje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Dje(e.maxBytes)}function Oje(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 kje(e){return Ne(`sha256`).update(e).digest(`hex`)}function Aje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const jje=[`"doc.name"`,`"docName"`];function Mje(e){let t=S(e,`utf-8`),n=0;for(let e of jje){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 Nje=new Set([`.jsonl`]);function Pje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Nje.has(e.slice(t))}const Fje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Ije(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Fje.has(e.slice(t))}function Lje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Ije(r))continue;let{redacted:i,patterns:a,lineCount:o}=TB(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 Rje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??yje,a=r.fetchAgentEffects??bje,o=r.fetchWatcherRecent??xje,s=r.readShadowHead??Cje,c=r.readCheckpointRefs??wje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.9-beta.5`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??Tje,h=r.isOtlpPushEnabled??Eje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(pje(n),N(_,`telemetry`,z9)),Z9(mje(n),N(_,`telemetry`,B9)),Z9(hje(n),N(_,`logs`,V9)),Z9(gje(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(_,JL,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=Sje(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(_je(n),N(_,`state`,U9)),Z9(vje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Iu),N(_,`state`,Iu)),Z9(N(b,Lu),N(_,`state`,Lu)),Z9(N(b,Fu),N(_,`state`,Fu));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&&fje({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=Lje(_));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=Oje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Pje(t)?Aje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=Mje(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:kje(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 zje(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 VCe.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 Bje(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 Vje(e,t,n,r,i){let a=E7(t,e.logger),o=await Rje({contentDir:Bje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Zke(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 zje({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 Hje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>Kke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Vje(e,t,n,r,i());let{zipPath:a,summary:o}=await nAe({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,pOe as HOSTS_WITH_USER_SKILL_DIR,Mke as LAUNCH_CONFIG_NAME,GAe as PATH_SHIM_BEGIN,qAe as PATH_SHIM_BLOCK_RE,KAe as PATH_SHIM_END,I5 as ProjectPathSafetyError,uke as addOkPathsToGitExclude,L5 as assertProjectPathSafe,d5 as buildManagedServerEntry,FAe as buildMcpConfigDeclineEvent,IAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Hje as collectReportBundle,QAe as createCliProbeResolver,on as createTokenStore,Jke as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,Ike as detectInstalledEditors,b5 as droppedManagedKeys,POe as editorConfigPathDisplay,NOe as editorEntryLocator,wAe as ensurePiBridge,Q5 as formatTrackedRemediation,pke as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,fOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,l5 as isEntryUpToDate,f5 as isOwnManagedEntry,HAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,UAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,JAe as pathInstallMarkerPath,YOe as previewContent,Lke as probeOwnManagedEditorMcpEntry,SAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,fke as readSharingMode,TB as redactContent,dke as removeOkPathsFromGitExclude,jAe as removeOwnMcpEntry,ske as removeProjectSkill,eje as removeUserGlobalSkillBundle,oje as removeUserSkill,tke as resolveProjectRoot,zAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,aje as userSkillPresentAnywhere,WAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,rje as writeProjectAiIntegrations,U5 as writeProjectSkill,Fke as writeUserMcpConfigs,ije as writeUserSkill};
1540
1540
  //# sourceMappingURL=index.mjs.map