@inkeep/open-knowledge 0.77.8-beta.2 → 0.77.8-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-yOzobrhh.mjs +1 -0
  3. package/dist/{dist-D0GERgOV.mjs → dist-BRmQARr7.mjs} +3 -3
  4. package/dist/{dist-bFhnQLtf.mjs → dist-DGV6rhfK.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-CsXF5-ya.mjs +1 -0
  7. package/dist/{init-CJaDf2v4.mjs → init-DsTCcpDC.mjs} +2 -2
  8. package/dist/{launch-json-removal-DsF5byxI.mjs → launch-json-removal-CCGm5be9.mjs} +1 -1
  9. package/dist/{loader-nxRUPb1I.mjs → loader-DS42TXVp.mjs} +1 -1
  10. package/dist/loader-DeMtKnw7.mjs +1 -0
  11. package/dist/{open-browser-B_rRgmVZ.mjs → open-browser-bOzBzOZ6.mjs} +1 -1
  12. package/dist/{preview-CNug1Bpu.mjs → preview-CCBcJaWe.mjs} +1 -1
  13. package/dist/preview-psySLe-m.mjs +1 -0
  14. package/dist/public/assets/{ActivityModeContent-M2k3YwfN.js → ActivityModeContent-B-hO8XoC.js} +1 -1
  15. package/dist/public/assets/{AddPropertiesButton-CF3xs1vF.js → AddPropertiesButton-Cn36zBGX.js} +1 -1
  16. package/dist/public/assets/{AgentDiffPane-COuPkRtG.js → AgentDiffPane-RT1EJk87.js} +1 -1
  17. package/dist/public/assets/{CodeMirrorPropInput-IRKh744X.js → CodeMirrorPropInput-9Pzq9NMc.js} +1 -1
  18. package/dist/public/assets/{DocumentContext-DN3lHA0f.js → DocumentContext-CryGGw7A.js} +1 -1
  19. package/dist/public/assets/{EditorModeToggle-BNW3Mc3U.js → EditorModeToggle-TMh_nblT.js} +1 -1
  20. package/dist/public/assets/{EnableSyncConfirmDialog-C5vyStvZ.js → EnableSyncConfirmDialog-nb0a_Y_I.js} +1 -1
  21. package/dist/public/assets/{ExcalidrawDocEditor-DJ1kVVQQ.js → ExcalidrawDocEditor-1HBEbe2y.js} +1 -1
  22. package/dist/public/assets/FeedbackForm-BlFN1t8r.js +1 -0
  23. package/dist/public/assets/{ImportSkillDialog-ZHBp0kBI.js → ImportSkillDialog-BYz3KOoa.js} +1 -1
  24. package/dist/public/assets/{LintConfigEditor-DGelEZH6.js → LintConfigEditor-D19LqNap.js} +1 -1
  25. package/dist/public/assets/ManagedArtifactProperties-BvR71kG0.js +1 -0
  26. package/dist/public/assets/{ManagedArtifactProperties-DWrCvKHd.js → ManagedArtifactProperties-CKJfXiSF.js} +1 -1
  27. package/dist/public/assets/{MermaidDocEditor-BGHacCHW.js → MermaidDocEditor-3Wu_aV0u.js} +1 -1
  28. package/dist/public/assets/{PropertyDisplayRow-BPvh08wu.js → PropertyDisplayRow-ilF4Lim8.js} +1 -1
  29. package/dist/public/assets/{SchemaConfigEditor-7DP1DDaJ.js → SchemaConfigEditor-D7Nv3buA.js} +1 -1
  30. package/dist/public/assets/{SessionsHost-Cgl3LOrn.js → SessionsHost-CoUniN0l.js} +2 -2
  31. package/dist/public/assets/{SettingsDialogBody-0b_jtYPb.js → SettingsDialogBody-DwmjT0E6.js} +1 -1
  32. package/dist/public/assets/{ShareReceiveMissDialog-BxhkG5Bj.js → ShareReceiveMissDialog-75pEhVsb.js} +1 -1
  33. package/dist/public/assets/{SkillToolbarControls-BIOQTgH1.js → SkillToolbarControls-DV2Do60S.js} +1 -1
  34. package/dist/public/assets/{SourceEditor-CniCNTCo.js → SourceEditor-W0p2ZR-o.js} +1 -1
  35. package/dist/public/assets/{TerminalWindowApp-Dl09UNeQ.js → TerminalWindowApp-De4jhHmQ.js} +1 -1
  36. package/dist/public/assets/{TextDocEditor-BmeCpFYS.js → TextDocEditor-DPEVJwA_.js} +1 -1
  37. package/dist/public/assets/ThreadView-BfAMc1P_.js +20 -0
  38. package/dist/public/assets/{TimelineDiffPane-Dq31of3V.js → TimelineDiffPane-Cp-9Nruq.js} +1 -1
  39. package/dist/public/assets/{auth-state-cache-lm2-OPjo.js → auth-state-cache-Bbm6ItZO.js} +1 -1
  40. package/dist/public/assets/{comment-chips-Da3EBbGr.js → comment-chips-BkxWfTOo.js} +1 -1
  41. package/dist/public/assets/{config-provider-2QXsvFX3.js → config-provider-D6VHe73Z.js} +1 -1
  42. package/dist/public/assets/{doc-undo-manager-oaq6VHBD.js → doc-undo-manager-9fTPMH6P.js} +1 -1
  43. package/dist/public/assets/{index-m11UgwXb.js → index-BBx8twze.js} +7 -7
  44. package/dist/public/assets/{messages-C1VeyNl0.js → messages-B6fPULdH.js} +1 -1
  45. package/dist/public/assets/{messages-BW4p1NtB.js → messages-BO8Ur6U8.js} +1 -1
  46. package/dist/public/assets/{messages-DNpYLZfq.js → messages-CAGYSgOW.js} +1 -1
  47. package/dist/public/assets/{messages-Dcr562Y0.js → messages-CUqAhDwc.js} +1 -1
  48. package/dist/public/assets/{messages-BbtT8UWj.js → messages-CcuMMt_D.js} +1 -1
  49. package/dist/public/assets/{messages-D_2aHJUi.js → messages-D1uegjd4.js} +1 -1
  50. package/dist/public/assets/{messages-DvaMLKsL.js → messages-D4bsF8Ez.js} +1 -1
  51. package/dist/public/assets/{messages-CMn1fNZK.js → messages-D6CV5EZE.js} +1 -1
  52. package/dist/public/assets/{messages-DVQlq8SU.js → messages-DQ7ZSf6D.js} +1 -1
  53. package/dist/public/assets/{messages-D6rUTZQ6.js → messages-FJiaC8Cm.js} +1 -1
  54. package/dist/public/assets/{messages-Dz2z2MLj.js → messages-OBTquc1q.js} +1 -1
  55. package/dist/public/assets/{messages-DK3V0faN.js → messages-wxuroV5q.js} +1 -1
  56. package/dist/public/assets/{pending-receive-nav-store-BLPPywaR.js → pending-receive-nav-store-B4hLMw0G.js} +1 -1
  57. package/dist/public/assets/{progress-CbsOEU6k.js → progress-BBuf2EFz.js} +1 -1
  58. package/dist/public/assets/{selection-context-Djo41sqY.js → selection-context-palu4Wg2.js} +1 -1
  59. package/dist/public/assets/{src-BmrKqIrD.js → src-Di9YbZKE.js} +1 -1
  60. package/dist/public/assets/{typing-burst-detector-DMDqi5dA.js → typing-burst-detector-Bx2NWBvb.js} +1 -1
  61. package/dist/public/assets/{uninstall-CjAeJKDn.js → uninstall-h45bTK0V.js} +1 -1
  62. package/dist/public/assets/{use-activity-panel-DC73mzAa.js → use-activity-panel-BnjfL-NR.js} +1 -1
  63. package/dist/public/assets/{use-apply-config-language-7Y1kLw_A.js → use-apply-config-language-C5u45vmj.js} +2 -2
  64. package/dist/public/assets/{use-open-skill-BBWxh7W0.js → use-open-skill-Beqsr0la.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-BhsY-vIc.js → use-terminal-enabled-BCnLa4co.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-DSNKKDKd.js → use-timeline-entry-diff-BcenCe43.js} +1 -1
  67. package/dist/public/index.html +18 -18
  68. package/dist/public/uninstall.html +3 -3
  69. package/dist/{registry-probes-fM52ElWS.mjs → registry-probes-Beqzfmr0.mjs} +1 -1
  70. package/dist/{removal-file-path-CEyW2N1T.mjs → removal-file-path-Cnl2z2nZ.mjs} +1 -1
  71. package/dist/{repair-launch-json-CtWN_wjb.mjs → repair-launch-json-PBGk9h6X.mjs} +1 -1
  72. package/dist/{repair-mcp-configs-B1cBMF6e.mjs → repair-mcp-configs-xwCf2Kvv.mjs} +1 -1
  73. package/dist/{src-C3WNbreu.mjs → src-B-KYOts7.mjs} +1 -1
  74. package/dist/src-DN8vMqtE.mjs +1 -0
  75. package/dist/start-D3_5v14j.mjs +1 -0
  76. package/dist/{start-CG9CZQY6.mjs → start-DNI4Wwj4.mjs} +3 -3
  77. package/package.json +4 -4
  78. package/dist/constants-BNK29qYp.mjs +0 -1
  79. package/dist/init-DgOht2HX.mjs +0 -1
  80. package/dist/loader-Yd3uPWLw.mjs +0 -1
  81. package/dist/preview-Bbq_JB1Y.mjs +0 -1
  82. package/dist/public/assets/FeedbackForm-B60zvRQ5.js +0 -1
  83. package/dist/public/assets/ManagedArtifactProperties-Bw8Ex5op.js +0 -1
  84. package/dist/public/assets/ThreadView-BPAWyKRD.js +0 -20
  85. package/dist/src-fpVtWdEO.mjs +0 -1
  86. package/dist/start-CX7I8t-q.mjs +0 -1
@@ -946,10 +946,10 @@ ${_Ue.join(`
946
946
  `).map(e=>e.trim()).find(e=>e!==``),r=t??`exit code ${e}`;d(n===void 0?r:`${r}: ${n.slice(0,300)}`)})})}function sZe(e,t=5e3,n){let r=process.platform===`win32`,i=dZe(e);return new Promise(a=>{let o;try{o=ns(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<N$&&(s+=e)}),o.stderr?.setEncoding(`utf8`),o.stderr?.on(`data`,e=>{c.length<N$&&(c+=e)});let l=!1,u=e=>{l||(l=!0,clearTimeout(d),a(e))},d=setTimeout(()=>{H$(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(`
947
947
  `).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 cZe(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 lZe(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 P$(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()===`path`)return n;return process.env.PATH}function F$(e){let t=process.platform===`win32`;return cs(e)||e.includes(`/`)||t&&e.includes(`\\`)}async function uZe(e,t){let n=process.platform===`win32`;if(F$(e))return I$(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(os))if(n!==``){for(let t of r)if(await I$(H(n,e+t)))return!0}return!1}async function I$(e){try{return(await Zs(e)).isFile()?(process.platform===`win32`||await Us(e,bs.X_OK),!0):!1}catch{return!1}}function L$(e,t){if(cs(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(os))if(r!==``)for(let t of n){let n=H(r,e+t);try{if(Ps(n).isFile())return n}catch{}}return e}function dZe(e,t=process.platform){if(t!==`win32`)return`node`;let n=P$(e.env),r=L$(e.cmd,n);if(r!==e.cmd||cs(r)||r.includes(`/`)||r.includes(`\\`)){let e=H(V(r),`node.exe`);try{if(Ps(e).isFile())return e}catch{}}return L$(`node`,n)}function fZe(e){return e===``?`""`:/[\s"&()<>^|%]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function R$(e,t){let n=[`"${e}"`,...t.map(fZe)].join(` `);return{cmd:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,`"${n}"`]}}function pZe(){let e=H(zs(),`.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 z$(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`:!cs(t))throw Error(`spawnAcpAgent requires an absolute cwd, got: ${t}`);let n=e.kind===`npx`?pZe():t,r=process.platform===`win32`,i=r?L$(e.cmd,P$(e.env)):e.cmd,a=r&&/\.(cmd|bat)$/i.test(i),{cmd:o,args:s}=a?R$(i,e.args):{cmd:i,args:e.args};return ns(o,s,{cwd:n,env:DXe(e.env),stdio:[`pipe`,`pipe`,`pipe`],shell:!1,detached:!r,windowsHide:!0,windowsVerbatimArguments:a})}function B$(e){return e.exitCode!==null||e.signalCode!==null}function V$(e,t){return B$(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 mZe(e,t){let n=e.pid;if(!(n===void 0||B$(e))){try{process.kill(-n,t);return}catch{}try{e.kill(t)}catch{}}}async function H$(e,t){let n=t.forceWaitMs??2e3;if(B$(e))return!0;if(process.platform===`win32`){if(e.pid!==void 0)try{ns(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`,shell:!1,windowsHide:!0}).unref()}catch{try{e.kill(`SIGKILL`)}catch{}}return V$(e,Math.max(t.graceMs,n))}return mZe(e,`SIGTERM`),await V$(e,t.graceMs)?!0:(mZe(e,`SIGKILL`),V$(e,n))}const U$=`v24.18.0`,W$=`0.11.28`,hZe=`https://nodejs.org/dist`,gZe=`https://github.com/astral-sh/uv/releases/download`,_Ze={node:45,uv:20};function vZe(e){return e===`npx`?`node`:`uv`}function G$(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:U$,approxSizeMB:_Ze.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:W$,approxSizeMB:_Ze.uv,sourceHost:`github.com/astral-sh`}}function yZe(){return H(zs(),`.ok`)}function K$(){return H(yZe(),`runtimes`)}function q$(e){return e===`node`?U$:W$}function bZe(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function xZe(){let e=Vs(),t=Rs(),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:`${hZe}/${U$}/${a}`,checksumUrl:`${hZe}/${U$}/SHASUMS256.txt`,archiveName:a,isZip:i}}function SZe(){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`}[`${Vs()}-${Rs()}`];if(e===void 0)return null;let t=Vs()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${gZe}/${W$}/${n}`,checksumUrl:`${gZe}/${W$}/${n}.sha256`,archiveName:n,isZip:t}}function CZe(e){return e===`node`?xZe():SZe()}function wZe(e){return CZe(e)!==null}async function TZe(e){try{let t=await Zs(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await Us(e,Ws.X_OK),!0)}catch{return!1}}async function J$(e,t,n){let r;try{r=await Js(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 EZe(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 DZe(e,t=K$()){let n=H(t,e,p$(q$(e)));try{if(!(await Zs(n)).isDirectory())return null}catch{return null}let r=await J$(n,bZe(e),3);return r===null||!await TZe(r)?null:EZe(e,r,t)}var Y$=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function OZe(e,t,n=K$()){await S$(H(n,e),t,`[managed-runtime]`)}async function kZe(e,t,n=K$()){let r=H(n,e,p$(q$(e))),i=H(V(r),`.install-damaged-${p$(q$(e))}-${ic()}`);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 AZe(e,t,n={}){let r=n.root??K$(),i=H(r,e,p$(q$(e)));try{return await C$({versionDir:i,stagingLabel:p$(q$(e)),findInstalled:()=>DZe(e,r),prepare:async r=>{let i=CZe(e);if(i===null)throw new Y$(`no ${e} build for ${Vs()}-${Rs()}`);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([qYe(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),JYe(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=YYe(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 KYe(a,l,i.isZip);let u=await J$(l,bZe(e),3);if(u===null||!f$(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 jZe=`CODEX_CONFIG`;function MZe(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 NZe(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function PZe(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function FZe(e){if(e===void 0||e.trim()===``)return{};try{return PZe(JSON.parse(e))}catch{return{}}}function IZe(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...FZe(e[jZe]),model_context_window:Math.floor(t)};return{...e,[jZe]:JSON.stringify(n)}}function LZe(e){return(e.visibility??`list`)===`list`}const RZe={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function X$(e){return RZe[e]??`none`}function zZe(e,t,n){if(n===null||X$(t)!==`codex-config-env`)return e;let r=IZe(e.env,n);return r===e.env?e:{...e,env:r}}function BZe(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 ks(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);Ps(i).isDirectory()?Z$(i,a,n):sJ(a,K(i))}}const VZe=`open-knowledge`,HZe=`SKILL.md`,Q$=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function UZe(e){return H(e,`agent-skill`,VZe)}function WZe(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 GZe(e,t){let n=ks(e),r;try{r=new Set(ks(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(Ps(n).isDirectory()){let e;try{e=Ps(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&Q$.has(t))return!1;throw e}if(!e||!GZe(n,a))return!1}else if(!WZe(n,a))return!1}return!0}var KZe=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 qZe(e){let t;try{t=await Gs(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new KZe(e)}async function JZe(e){let t=UZe(e.localDir),n=V(t),r=async()=>{await qZe(n),await qZe(t)};return C$({versionDir:t,stagingLabel:VZe,findInstalled:async()=>(await r(),GZe(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 YZe=2e3;function XZe(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function ZZe(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:XZe(n.subarray(n.length-t)).toString(`utf8`)}function $$(e){if(e.outputBytes<=e.byteLimit)return;let t=XZe(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var QZe=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=DXe(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:cs(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?L$(e.command,P$(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?R$(o,e.args??[]):{cmd:o,args:e.args??[]},u=ns(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 H$(t.child,{graceMs:YZe})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await H$(t.child,{graceMs:YZe}),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=T$(e);return this.loginShellPath===null||E$(e)?t:k$(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=ZZe(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 $Ze=`threads`;var eQe=class{primaryThreadsDir;legacyThreadsDir;cwd;log;writeThreadsDir;homeByThread=new Map;writeQueues=new Map;appendBroken=new Set;constructor(e){this.primaryThreadsDir=H(e.primaryDir,$Ze),this.legacyThreadsDir=e.legacyDir==null?null:H(e.legacyDir,$Ze),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(`
948
948
  `)}\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 rQe(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 Js(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 qs(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 rQe(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(nQe(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=xs(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=pae({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 tQe(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function tQe(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 nQe(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function rQe(e){try{return await Ys(e)}catch{return W(e)}}const iQe=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`),aQe=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,oQe=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function sQe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function cQe(e){return(e.trim().split(`
949
- `)[0]??``).trim()}function e1(e){let t=cQe(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 lQe(e,t){let n=cQe(e),r=n.replace(aQe,``);if(t!==void 0&&t.trim()!==``){let e=sQe(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(iQe,``);if(e===r)break;r=e}r=r.replace(oQe,``).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 uQe=8,dQe=5e3,t1=3e5,n1=45e3,fQe=5e3,pQe=2e3,mQe=`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 hQe(e){if(e===null)return mQe;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`${mQe}\n\n${t}`}const gQe=new Set([`gemini`]);function _Qe(e){return e.source===`registry`&&gQe.has(e.id)}function vQe(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:hs(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${HZe} ---\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 w${refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},yQe=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},bQe=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function xQe(){return new r1(`not-ready`,`the thread was restarted during the sign-in`)}function SQe(e){return e.source===`registry`&&rq[e.id]===`pi`}function CQe(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=>l$(e,EXe())))(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 wQe=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;persistence;resolveLoginShellPath;healthyInterpreters=new Set;projectSkillStaging=null;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>x$(e.log)()),this.maxThreads=e.maxThreads??8,this.idleReapMs=e.idleReapMs??36e5,this.steerStallMs=e.steerStallMs??1e4,this.authenticateTimeoutMs=e.authenticateTimeoutMs??3e5,this.unwatchedTurnCancelMs=e.unwatchedTurnCancelMs??6e5,this.unwatchedTurnKillMs=e.unwatchedTurnKillMs??12e5,this.persistence=new eQe({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,EQe(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 Sq({site:`acp-thread`,agentId:n===null?ne(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,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint,envNotePending:!1,projectSkill:null};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 lq(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??=JZe({localDir:this.opts.localDir,sourceDir:t??i$(`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}f$(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,HZe);if(!_Qe(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await qs(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){let i;if(t!==null)i=await this.ensureLaunchable(e,HXe(t),r);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new r1(`unknown-agent`,`agent vanished`);i=await OXe(t,oq(),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(i===null||e.closed)return null;let a=await this.resolveLoginShellPath().catch(()=>null);if(e.closed||(e.projectSkill=await this.stageProjectSkillFor(e),e.closed))return null;let o=new QZe({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:a});i=zZe(i,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let s=i.kind===`npx`?z$(i):z$(i,e.cwd);e.child=s,e.terminals=o;let c=new Promise(e=>s.once(`close`,()=>e())),l,u=()=>s.exitCode===null&&s.signalCode===null&&s.stdout?.readableEnded!==!0&&s.stdout?.destroyed!==!0?Promise.resolve():(l??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),c.then(()=>{clearTimeout(t),e()})}),l);e.drainStderr=u;let d=``,f=!0,p=nXe(t=>{f&&(d=`${d}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())});if(s.stderr?.setEncoding(`utf8`),s.stderr?.on(`data`,p.write),s.stderr?.on(`end`,p.end),s.stderr?.on(`data`,t=>{for(let n of t.split(`
950
- `))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))}),s.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),s.on(`exit`,(t,n)=>{e.child===s&&(e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),o.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!==o||l1(e))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`)}))}),s.stdin===null||s.stdout===null)throw new r1(`spawn-failed`,`agent process has no stdio`);let m=nve(ec.toWeb(s.stdin),$s.toWeb(s.stdout)),h=Pve({name:`open-knowledge`}).onRequest(tT.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(tT.client.fs.readTextFile,async t=>{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(tT.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(tT.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),o.create(t.params))).onRequest(tT.client.terminal.output,e=>o.output(e.params.terminalId)).onRequest(tT.client.terminal.waitForExit,e=>o.waitForExit(e.params.terminalId)).onRequest(tT.client.terminal.kill,async e=>(await o.kill(e.params.terminalId),{})).onRequest(tT.client.terminal.release,async e=>(await o.release(e.params.terminalId),{})).onNotification(tT.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(m);e.conn=h,h.closed.then(()=>{e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let g;try{g=await h.agent.request(tT.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:d$},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){if(this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),i.kind===`npx`||i.kind===`uvx`){await u();let e=MXe(i,d,t);if(e!==null)throw e}throw new r1(`spawn-failed`,`initialize failed: ${o1(t)}`)}finally{f=!1,d=``}return e.closed?null:(e.lastInit=g,e.info.promptCapabilities=g.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:h,init:g,launch:i})}async ensureLaunchable(e,t,n){let r;try{await M$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof w$)||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(P$(n.env)!==P$(t.env))try{await M$(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 w$)||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 w$(`command-not-found`,i?cZe(t,r.detail):$Xe(t,r.detail)),o=new w$(`command-not-found`,i?lZe(t,r.detail):aZe(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=vZe(t.kind);if(!wZe(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=UXe(t,o);await M$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new w$(`install-failed`,tZe(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 kZe(n,this.opts.log,this.opts.runtimeInstall?.root))throw new w$(`install-failed`,nZe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof i1?new w$(`command-not-found`,e.refusal===`timeout`?iZe(t):rZe(t)):e});if(o===null)return null;let s=UXe(t,o);await M$(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 w$(`install-failed`,c.kind===`incompatible`?tZe(c.detail):eZe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,P$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await oZe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await sZe(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(P$(t.env)===P$(e.env))return null;try{await M$(t)}catch(t){if(!(t instanceof w$))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||F$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:WXe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||F$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:GXe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await OZe(t,this.opts.log,i);let a=await DZe(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`?OQe(t):DQe(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=G$(t).displayName;throw new w$(`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 AZe(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(SQe(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:HYe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=EXe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:tn,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=rq[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 jQe(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(tT.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=NQe(n),e.confirmedContextWindow=AQe(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(kQe(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=NQe(u),r.confirmedContextWindow=AQe(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(tT.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(tT.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 jQe(t,r)),t instanceof r1?t:t instanceof w$?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=BZe({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{xXe(),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 xQe();let t=e instanceof yQe?`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 xQe();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 yQe),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(tT.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 H$(n,{graceMs:pQe}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(mq(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:[MQe(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=[MQe(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)}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=lQe(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=`${hQe(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=vQe(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,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let o=e.sessionId;eXe(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 bQe;return e.conn.agent.request(tT.agent.session.prompt,{sessionId:o,prompt:a===null?[...t.blocks]:[...t.blocks,a]})}).then(t=>{if(e.turnActive=!1,!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,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(kQe(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){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),e.conn!==null&&e.sessionId!==null&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(tT.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(tT.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(tT.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(tT.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(tT.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(tT.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),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await H$(r,{graceMs:t?.killGraceMs??fQe})||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(mq(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.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),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:pQe})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:rXe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await qs(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await qs(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
949
+ `)[0]??``).trim()}function e1(e){let t=cQe(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 lQe(e,t){let n=cQe(e),r=n.replace(aQe,``);if(t!==void 0&&t.trim()!==``){let e=sQe(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(iQe,``);if(e===r)break;r=e}r=r.replace(oQe,``).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 uQe=8,dQe=5e3,t1=3e5,n1=45e3,fQe=5e3,pQe=2e3,mQe=`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 hQe(e){if(e===null)return mQe;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`${mQe}\n\n${t}`}const gQe=new Set([`gemini`]);function _Qe(e){return e.source===`registry`&&gQe.has(e.id)}function vQe(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:hs(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${HZe} ---\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 w${refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},yQe=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},bQe=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function xQe(){return new r1(`not-ready`,`the thread was restarted during the sign-in`)}function SQe(e){return e.source===`registry`&&rq[e.id]===`pi`}function CQe(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=>l$(e,EXe())))(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 wQe=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;turnStallMs;persistence;resolveLoginShellPath;healthyInterpreters=new Set;projectSkillStaging=null;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>x$(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 eQe({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,EQe(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 Sq({site:`acp-thread`,agentId:n===null?ne(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};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 lq(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??=JZe({localDir:this.opts.localDir,sourceDir:t??i$(`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}f$(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,HZe);if(!_Qe(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await qs(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){let i;if(t!==null)i=await this.ensureLaunchable(e,HXe(t),r);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new r1(`unknown-agent`,`agent vanished`);i=await OXe(t,oq(),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(i===null||e.closed)return null;let a=await this.resolveLoginShellPath().catch(()=>null);if(e.closed||(e.projectSkill=await this.stageProjectSkillFor(e),e.closed))return null;let o=new QZe({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:a});i=zZe(i,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let s=i.kind===`npx`?z$(i):z$(i,e.cwd);e.child=s,e.terminals=o;let c=new Promise(e=>s.once(`close`,()=>e())),l,u=()=>s.exitCode===null&&s.signalCode===null&&s.stdout?.readableEnded!==!0&&s.stdout?.destroyed!==!0?Promise.resolve():(l??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),c.then(()=>{clearTimeout(t),e()})}),l);e.drainStderr=u;let d=``,f=!0,p=nXe(t=>{f&&(d=`${d}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())});if(s.stderr?.setEncoding(`utf8`),s.stderr?.on(`data`,p.write),s.stderr?.on(`end`,p.end),s.stderr?.on(`data`,t=>{for(let n of t.split(`
950
+ `))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))}),s.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),s.on(`exit`,(t,n)=>{e.child===s&&(e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),o.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!==o||l1(e))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`)}))}),s.stdin===null||s.stdout===null)throw new r1(`spawn-failed`,`agent process has no stdio`);let m=nve(ec.toWeb(s.stdin),$s.toWeb(s.stdout)),h=Pve({name:`open-knowledge`}).onRequest(tT.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(tT.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(tT.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(tT.client.terminal.create,t=>(this.touchTurnActivity(e),o.create(t.params))).onRequest(tT.client.terminal.output,t=>(this.touchTurnActivity(e),o.output(t.params.terminalId))).onRequest(tT.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),o.waitForExit(t.params.terminalId))).onRequest(tT.client.terminal.kill,async t=>(this.touchTurnActivity(e),await o.kill(t.params.terminalId),{})).onRequest(tT.client.terminal.release,async t=>(this.touchTurnActivity(e),await o.release(t.params.terminalId),{})).onNotification(tT.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(m);e.conn=h,h.closed.then(()=>{e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let g;try{g=await h.agent.request(tT.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:d$},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){if(this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),i.kind===`npx`||i.kind===`uvx`){await u();let e=MXe(i,d,t);if(e!==null)throw e}throw new r1(`spawn-failed`,`initialize failed: ${o1(t)}`)}finally{f=!1,d=``}return e.closed?null:(e.lastInit=g,e.info.promptCapabilities=g.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:h,init:g,launch:i})}async ensureLaunchable(e,t,n){let r;try{await M$(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof w$)||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(P$(n.env)!==P$(t.env))try{await M$(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 w$)||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 w$(`command-not-found`,i?cZe(t,r.detail):$Xe(t,r.detail)),o=new w$(`command-not-found`,i?lZe(t,r.detail):aZe(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=vZe(t.kind);if(!wZe(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=UXe(t,o);await M$(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new w$(`install-failed`,tZe(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 kZe(n,this.opts.log,this.opts.runtimeInstall?.root))throw new w$(`install-failed`,nZe(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof i1?new w$(`command-not-found`,e.refusal===`timeout`?iZe(t):rZe(t)):e});if(o===null)return null;let s=UXe(t,o);await M$(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 w$(`install-failed`,c.kind===`incompatible`?tZe(c.detail):eZe(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,P$(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await oZe(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await sZe(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(P$(t.env)===P$(e.env))return null;try{await M$(t)}catch(t){if(!(t instanceof w$))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||F$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:WXe(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||F$(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:GXe(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await OZe(t,this.opts.log,i);let a=await DZe(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`?OQe(t):DQe(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=G$(t).displayName;throw new w$(`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 AZe(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(SQe(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:HYe,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=EXe();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:tn,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=rq[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 jQe(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(tT.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=NQe(n),e.confirmedContextWindow=AQe(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(kQe(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=NQe(u),r.confirmedContextWindow=AQe(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(tT.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(tT.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 jQe(t,r)),t instanceof r1?t:t instanceof w$?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=BZe({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{xXe(),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 xQe();let t=e instanceof yQe?`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 xQe();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 yQe),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(tT.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 H$(n,{graceMs:pQe}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(mq(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:[MQe(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=[MQe(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=lQe(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=`${hQe(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=vQe(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;eXe(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 bQe;return e.conn.agent.request(tT.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(kQe(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(tT.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(tT.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(tT.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(tT.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(tT.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(tT.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))}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 H$(r,{graceMs:t?.killGraceMs??fQe})||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(mq(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:pQe})))}async handlePermissionRequest(e,t,n){this.touchTurnActivity(e);let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){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:rXe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await qs(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await qs(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
951
951
  `),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
952
- `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel},a=bq(t);try{t.dc.document.transact(()=>{let r=YQ(t.dc.document);JQ(t.dc.document,n,`replace`,i,void 0,KQ(t),a);let o=wn(r,YQ(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 VY?(HY(e,`acp-fs-write`),new $w(-32009,fWe,{type:BY,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 TQe(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&&cXe(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>dQe){let t=e.events.length-dQe;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:g$(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:g$(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)),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`),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);let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null,e.sessionId=null,e.info.contextWindow=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await H$(t,{graceMs:fQe})}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,...i}=e.info;return{version:1,info:i,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=cn(e.info.agent.id),i=la[r]??ze(e.agentSessionId);n.setPresence(mq(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 TQe(e,t,n){let r=await Ys(e),i=ls(cs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await Ys(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||cs(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(fs).join(`/`),t=s.split(fs).join(`/`);!DY(e)&&!OY(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(fs).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 EQe(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},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,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1,projectSkill:null}}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 DQe(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 OQe(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 kQe(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 g$(JSON.stringify(t)).slice(0,300)}catch{return}}function AQe(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 jQe(e,t){return{reason:`connect`,agentMessage:e instanceof w$||e instanceof r1?e.message:String(e),machineDetail:d1({primary:e instanceof w$?e.machineDetail:void 0,tail:await u1(t)})}}function MQe(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=g$(t.join(`
952
+ `)}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=bq(t);try{t.dc.document.transact(()=>{let r=YQ(t.dc.document);JQ(t.dc.document,n,`replace`,i,void 0,KQ(t),a);let o=wn(r,YQ(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 VY?(HY(e,`acp-fs-write`),new $w(-32009,fWe,{type:BY,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 TQe(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&&cXe(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>dQe){let t=e.events.length-dQe;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:g$(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:g$(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`),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);let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null,e.sessionId=null,e.info.contextWindow=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await H$(t,{graceMs:fQe})}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,...a}=e.info;return{version:1,info:a,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=cn(e.info.agent.id),i=la[r]??ze(e.agentSessionId);n.setPresence(mq(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 TQe(e,t,n){let r=await Ys(e),i=ls(cs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await Ys(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||cs(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(fs).join(`/`),t=s.split(fs).join(`/`);!DY(e)&&!OY(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(fs).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 EQe(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},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}}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 DQe(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 OQe(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 kQe(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 g$(JSON.stringify(t)).slice(0,300)}catch{return}}function AQe(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 jQe(e,t){return{reason:`connect`,agentMessage:e instanceof w$||e instanceof r1?e.message:String(e),machineDetail:d1({primary:e instanceof w$?e.machineDetail:void 0,tail:await u1(t)})}}function MQe(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=g$(t.join(`
953
953
  `)).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,h$);let n=Math.min(t.length,1024),r=h$-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=h$-i.length-1;return`${i}\n${t.slice(-a)}`}function f1(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
954
954
  `);return d1({primary:s1(e),tail:n})}function NQe(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function p1(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}function PQe(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(FQe(e,t,n));e.on(`message`,e=>{let s=Lve(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,attachments:s.attachments,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt,s.attachments);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content,s.attachments);return;case`steer`:t.steerPrompt(s.threadId,s.content,s.attachments);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`queue_send_now`:t.sendQueuedNow(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`pi_bridge_consent_response`:t.respondPiBridgeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:{let e=await t.renameThread(s.threadId,s.title);r.has(s.threadId)||i({op:`info`,info:e});return}case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`set_context_window`:{let e=await t.setContextWindow(s.threadId,s.tokens);i({op:`context_window_set`,reqId:s.reqId,info:e});return}case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof r1?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof r1)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function FQe(e,t,n){return{op:`error`,code:e,message:t,...n}}var IQe=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){hq(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){hq(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(Kr);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),LQe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function LQe(e){return e?.awareness??null}var RQe=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!hq(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!hq(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!hq(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!hq(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return oUe(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Kr);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),zQe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function zQe(e){return e?.awareness??null}function BQe(e){let{env:t,resolve:n}=e;return e=>n===void 0?null:t===`remote-web`&&e.scope===`user`?{state:`unprobed`}:n(e)}async function m1(e){return{probes:await Oe({env:e.env,resolve:BQe(e)}),detection:Mne}}const VQe=sc(Yie);function h1(e){return H(e,...kt)}async function g1(e,t){let n=h1(e);await oJ(V(n),{recursive:!0});try{return await vk(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const HQe={warn:(e,t)=>q(`skills`).warn(e,t)};async function _1(e,t=HQe){let n=h1(e),r;try{r=await VQe(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,lk.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=ba.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function v1(e,t){let n=ba.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=h1(e);await oJ(V(r),{recursive:!0});let i=(0,lk.parseDocument)(``);i.contents=i.createNode(n.data),await gk(r,i.toString(),{fs:_J})}async function y1(e,t,n){let r=await _1(e,n);return r===null?null:r.targets[t]?.version??null}async function UQe(e,t,n){let r=await _1(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function b1(e,t,n,r,i){if(!Cee.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await g1(e,async()=>{let a=await _1(e,i)??Sa(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await v1(e,{...a,targets:{...a.targets,[t]:l}})})}async function WQe(e,t,n){let r=(await _1(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function GQe(e,t,n,r){await g1(e,async()=>{let i=await _1(e,r)??Sa();await v1(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function KQe(e,t){let n=await _1(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function qQe(e,t,n){t.length!==0&&await g1(e,async()=>{let r=await _1(e,n)??Sa(),i=new Set([...r.installsReported??[],...t]);await v1(e,{...r,installsReported:[...i].sort()})})}async function JQe(e,t,n){t.length!==0&&await g1(e,async()=>{let r=await _1(e,n);if(!r?.installsReported?.length)return;let i=new Set(t),a=r.installsReported.filter(e=>!i.has(e));a.length!==r.installsReported.length&&await v1(e,{...r,installsReported:a})})}async function x1(){let e=new URL(`../package.json`,import.meta.url),t=await VQe(ms(e),`utf-8`),n=JSON.parse(t);if(typeof n.version!=`string`||n.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return n.version}async function YQe(e,t){let[n,r]=await Promise.all([x1(),XQe(e,t)]);return{currentVersion:n,targets:r}}async function XQe(e,t=HQe){let n=null;try{n=await _1(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:h1(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=Aee.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const ZQe=q(`agent-registry-apply`);function QQe(e){return{probes:yne(e),detection:Mne}}const $Qe=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function e$e(e,t){try{return await e()}catch(e){return ZQe.warn({err:e},`host snapshot failed; claiming nothing`),QQe(t)}}async function t$e(e,t){let n=await e$e(t.snapshot,t.env),r=ie({probes:n.probes,detection:n.detection}),i=rte(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await zte(i,t.execute??$Qe),{decisionHome:o}=t,s=n$e(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await GQe(o,QQ.discovery,c).catch(e=>{ZQe.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await e$e(t.snapshot,t.env)}}function n$e(e){let t=e.actions.filter(e=>e.piece===`skill`&&e.scope===`user`);return t.some(e=>e.action===`written`||e.action===`overwritten`)?`installed`:t.some(e=>e.action===`removed`)?`removed`:null}const r$e=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function S1(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(r$e,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function C1(e,t){let n=S1(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=xq(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.suppliedWriterId!==void 0?{kind:`agent`,writerId:r.suppliedWriterId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:gq(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}function i$e(e){if(e===`null`||e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function w1(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function a$e(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function T1(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function o$e(e,t){return e!==void 0&&T1(e)===t}const s$e=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function c$e(e){return s$e.some(t=>e.headers[t]!==void 0)}const E1=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var l$e=class extends Error{};const u$e=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function d$e(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function D1(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(d$e).filter(e=>!u$e.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:T1(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function O1(e,t){return w1(e)?!0:t.allowExternal&&e!==void 0}function f$e(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function k1(e,t){if(a$e(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=f$e(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&o$e(e,t.externalOrigin.host)}function A1(e,t){if(i$e(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&T1(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=d$e(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function j1(e,t){return!t.tolerateForwardedHeaders&&c$e(e)}let p$e=!1;function M1(e,t){p$e||(p$e=!0,e.warn({handler:t},`[ingress] refused a request carrying a forwarding header (X-Forwarded-For etc.) — without external-exposure consent, every surface except the /healthz + /readyz probes refuses proxied requests (APIs 403, /collab upgrades dropped). To front this server with a proxy, set server.externalUrl to the public origin in .ok/config.yml (or OK_EXTERNAL_URL) AND consent with server.allowExternal: true in .ok/local/config.yml (or OK_ALLOW_EXTERNAL=1) — the keys live in different files because consent is per-machine and never travels. allowExternal consents to exposure on a server with NO authentication — restrict access at the edge. Removing server.externalUrl does not lift this refusal (it fires on the header, not the URL) and would un-admit that Host/Origin everywhere else. Warned once per process; every refusal is still logged at warn level (HTTP refusals additionally as api.error, counted in ok.api.error.count).`))}const m$e=new WeakMap;function h$e(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:w1(n)?`loopback`:`external`,actor:void 0};return m$e.set(e,r),r}function g$e(e){return m$e.get(e)}const N1=q(`local-op-security`),_$e=jF,v$e=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function P1(e){return!e||typeof e!=`string`||v$e.some(t=>t.test(e))?!1:_$e.some(t=>t.test(e))}function F1(e){return e===`~`?zs():e.startsWith(`~/`)?H(zs(),e.slice(2)):e}function y$e(e,t){let n=V(e);for(;n!==t&&n!==V(n);){let e;try{e=Cs(n)}catch(e){let t=GX(e);return N1.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return N1.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=V(n)}return!1}function b$e(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=As(t)}catch(e){let n=GX(e);return N1.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=W(F1(e)),i=[],a=r;for(;;){let e=null;try{e=Cs(a)}catch(e){let t=GX(e);if(t!==`ENOENT`)return N1.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=As(a)}catch(n){let i=GX(n);if(e.isSymbolicLink())return N1.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(y$e(a,t))return N1.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;N1.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return N1.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:H(r,...i),s=U(n,o);return s===``||!s.startsWith(`..`)&&!cs(s)}let r=V(a);if(r===a)return!1;i.unshift(as(a)),a=r}}function I1(e){return b$e(e,zs())}function x$e(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function S$e(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&C$e(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function C$e(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function w$e(e,t,n){let r=n.policy??D1({});return!x$e(e)&&!O1(e.socket.remoteAddress,r)?(X(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):S$e(e,r)?!0:(X(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function T$e(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const E$e=new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256);function D$e(e){E$e.push(e)}const O$e=ma.cursor,k$e=ma.codex,A$e=ma[`claude-desktop`],j$e={app:null,signals_fired:[]};function M$e(e){if(!e)return{...j$e};let t=[],n=e.ua,r=e.referer,i=!!n&&O$e.test(n),a=!!r&&r.includes(`?strategy=C_iframe`);if(i&&t.push(`cursor_ua_regex`),a&&t.push(`cursor_referer_strategy_iframe`),i||a)return{app:`cursor`,signals_fired:t};let o=!!n&&k$e.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&A$e.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...j$e}}function L1(e,t={}){let{dynamic:n}=t,r=new Set(t.mutating??[]),i=t.mutatingPrefixes??[],a=Object.keys(e);if(n!==void 0&&!n.prefix.endsWith(`/`))throw Error(`dynamic.prefix '${n.prefix}' must end in '/' — a bare prefix mounts a wildcard that also swallows unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);for(let e of i){if(!e.endsWith(`/`))throw Error(`mutatingPrefixes entry '${e}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`);if(e!==n?.prefix&&!a.some(t=>t.startsWith(e)))throw Error(`mutatingPrefixes entry '${e}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`)}let o=new Map(Object.entries(e)),s={resolve(e){let t=o.get(e);return t?{template:e,dispatch:(e,n)=>t(e,n)}:n!==void 0&&e.startsWith(n.prefix)?{template:n.template,dispatch:n.dispatch(e.slice(n.prefix.length))}:null},isMutating:e=>r.has(e)||i.some(t=>e.startsWith(t))};return{paths:n===void 0?a:[...a.filter(e=>!e.startsWith(n.prefix)),`${n.prefix}*`],table:s}}let R1=null;Mq(()=>{R1=null});function N$e(){return R1||=Fq().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),R1}function P$e(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??D1({}),a=e=>k1(e,i);return async(e,o)=>{let s=e.url?.split(`?`)[0];if(!s)return!1;let c=r.resolve(s);if(!c)return!1;let l=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};D$e({ts:Date.now(),url:s,method:e.method??``,ua:l(`user-agent`),origin:l(`origin`),referer:l(`referer`),host:l(`host`),remote:e.socket?.remoteAddress,secChUa:l(`sec-ch-ua`),secChUaMobile:l(`sec-ch-ua-mobile`),secChUaPlatform:l(`sec-ch-ua-platform`),secFetchSite:l(`sec-fetch-site`),secFetchDest:l(`sec-fetch-dest`),secFetchMode:l(`sec-fetch-mode`),secFetchUser:l(`sec-fetch-user`)});let u=e.method??`GET`,d=c.template,f=s.startsWith(`/api/`)?oWe(e):void 0;if(h$e(e,{requestId:f}),f!==void 0&&(cWe(e,f),typeof o.setHeader==`function`&&o.setHeader(FY,f),typeof o.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:f,method:u,route:d,status:o.statusCode,durationMs:Date.now()-e,...o.writableFinished?{}:{aborted:!0}},`${u} ${d} ${o.statusCode}`))};o.once(`finish`,r),o.once(`close`,r)}if(s.startsWith(`/api/`)){let t=e.headers.origin;if(t!==void 0&&!A1(t,i))return X(o,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`}),!0;if(typeof o.setHeader==`function`&&(t!==void 0&&(o.setHeader(`Access-Control-Allow-Origin`,t),o.setHeader(`Vary`,`Origin`)),o.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),o.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${FY}, ${O.protocol}, ${O.runtime}, ${O.kind}`),o.setHeader(`Access-Control-Expose-Headers`,FY)),e.method===`OPTIONS`)return o.writeHead(204),o.end(),!0}if(r.isMutating(s)){let t=e.socket?.remoteAddress;if(t!==void 0&&!O1(t,i))return X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(e.headers.host))return X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:E1}),!0}if(s.startsWith(`/api/`)){let t=n?`api-ephemeral-gate`:`api-read-gate`,r=e.socket?.remoteAddress;if(r!==void 0&&!O1(r,i))return X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:t}),!0;if(!a(e.headers.host))return X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:t,detail:E1}),!0}if(!s.startsWith(`/api/`))return!1;let p=Ja.extract(Wa.active(),e.headers),m=Pq(),h=Date.now();return await Wa.with(p,()=>m.startActiveSpan(`HTTP ${u} ${d}`,{kind:Sie.SERVER,attributes:{[oC]:u,[cC]:d,[dC]:s,[fC]:`http`,[pC]:e.headers[`user-agent`]??``,"ok.request.id":f}},async t=>{try{let n=c.dispatch;n===void 0?X(o,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${u} ${s}`}):await n(e,o);let r=o.statusCode;t.setAttribute(sC,r),r>=500&&t.setStatus({code:Ya.ERROR,message:`status ${r}`})}catch(e){throw t.recordException(e),t.setStatus({code:Ya.ERROR,message:e instanceof Error?e.message:String(e)}),!o.headersSent&&!o.writableEnded&&!o.destroyed&&X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:d,cause:e}),t.setAttribute(sC,o.statusCode),e}finally{t.end();let e=(Date.now()-h)/1e3;N$e().record(e,{[oC]:u,[cC]:d,[sC]:o.statusCode})}})),!0}}function z1(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof vr||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;X(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function F$e(e){return B1(e,{maxBytes:1048576,timeoutMs:3e4})}async function B1(e,t){let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new H1(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new V1(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var V1=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${I$e(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},H1=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function I$e(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function U1(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return X(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:a}),{ok:!1}}function Z(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=U1(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await F$e(r)}catch(e){if(e instanceof V1){X(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof H1){X(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}X(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=U1(e,o,i,n);s.ok&&await t(r,i,s.value)}}const W1=()=>q(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){W1().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),RY().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){W1().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){W1().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),X(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function L$e(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return L1({"/api/agent-integrations/apply":Z(yre,z1(async(e,n,s)=>{let c=C1(s,r);if(c.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`agent-integrations-apply`});return}let l=x$e(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await t$e(s.intents,{execute:o?.execute,env:l,snapshot:()=>m1({env:l,resolve:o?.probe}),decisionHome:i??zs(),...o?.userSkillPresentAnywhere===void 0?{}:{userSkillPresentAnywhere:o.userSkillPresentAnywhere},projectDir:a});t.info({actor:c.kind,applied:u.actions.length,failed:u.actions.filter(e=>e.errorId!==void 0).length,conflicts:u.conflicts.map(e=>e.kind)},`[agent-integrations] batch applied`),Q(n,200,ote,{...u,snapshot:d},{handler:`agent-integrations-apply`})},{handler:`agent-integrations-apply`,title:`Failed to apply AI tool connections.`}),{handler:`agent-integrations-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`agent-integrations-apply`})})},{mutating:[`/api/agent-integrations/apply`]})}let R$e=0;const z$e=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function G1(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++R$e,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},z$e)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),aUe(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}let K1=new Map;function q1(e,t,n,r,i,a,o,s){let c=K1.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},K1.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function B$e(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of K1){for(let e of t)n.docs.delete(e);n.docs.size===0&&K1.delete(e)}}function V$e(){let e=K1;return K1=new Map,e}function H$e(e){for(let[t,n]of e){let e=K1.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},K1.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function U$e(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
955
955
  `)}function W$e(e,t){let n=K1.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},K1.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries]),t.previousPaths.length>0&&(n.previousPaths=[...t.previousPaths,...n.previousPaths])}function J1(){return K1.size}function G$e(e){return K1.has(e)}const Y1={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function X1(e,t,n,r,i,a,o){Uq(e,t,`file-watcher`,n&&r?{resolveEmbed:n,resolveSize:i,sourcePath:r}:void 0,o,a)}const K$e=q(`external-change-attribution`),Z1=new Map;function q$e(e){for(let[t,n]of Z1)n.expiresAtMs<=e&&Z1.delete(t)}function J$e(e,t,n=Date.now(),r=3e4){if(q$e(n),Z1.size>=256&&!Z1.has(e)){let e=Z1.keys().next();e.done||Z1.delete(e.value)}Z1.set(e,{...t,expiresAtMs:n+r})}function Y$e(e,t=Date.now()){let n=Z1.get(e);if(!n)return;if(Z1.delete(e),n.expiresAtMs<=t){K$e.debug({docName:e},`external-change claim expired before its write arrived`);return}let{expiresAtMs:r,...i}=n;return i}function X$e(e){Z1.delete(e)}function Z$e(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`;return e instanceof vr?e.toLog({verbose:t}):e instanceof Da?ha(e.violation,{verbose:t}):e instanceof Error?e.message:String(e)}function Q1(e,t,n,r,i,a,o,s){if(DY(n)||OY(n)||AY(n)||jY(n)||MY(n))return;let c=t.documents.get(n);if(!c)return;let l=c.getText(`source`).toString(),u=l===r,d=Ee(l).frontmatter,{frontmatter:f}=Ee(r),p=o&&hY(Y1.context.origin)?{report:e=>o(n,e,iY.id,`file-watcher-intake`),baselineFullMd:l}:void 0;try{c.transact(()=>{X1(c,r,i,n,a,p,s)},Y1)}catch(t){try{e.setReconciledBase(n,c.getText(`source`).toString())}catch(e){q(`reconcile`).error({err:e,originalError:Z$e(t),docName:n},`Unable to persist the reconciled base after an external-change failure`)}throw t}if(d!==f&&YZ(`file-watcher`),!u){let e=Y$e(n)??{writerId:iY.id,displayName:iY.name,colorSeed:iY.id};q1(n,e.writerId,e.displayName,e.colorSeed,hpe(n))}e.setReconciledBase(n,r)}function Q$e(e,t,n,r,i){return async(a,o)=>{try{Q1(e,t,a,o,n,r,i),q(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof Da||e instanceof vr)throw e;IHe(),q(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const $1=`stale-external-write`;function e0(e,t,n,r){let i=e.getStaleExternalWrite(n)?.retainedContent;if(i!==void 0&&i!==e.getReconciledBase(n))return;e.clearStaleExternalWrite(n),r?.dissolveReconcile(n,$1);let a=t?.getMap(`lifecycle`);a?.get(`reason`)===$1&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`))}function $$e(e){switch(e){case`conflict-markers`:return`refused-conflict-markers`;case`no-base`:return`refused-no-base`;case`too-large`:return`refused-too-large`;default:throw Error(`unhandled reconcile refusal reason: ${String(e)}`)}}function t0(e,t,n,r,i,a){let o=e.getReconciledBase(n),s=e.getStaleExternalWrite(n),c=(r,a)=>{let s=e.recordStaleExternalWrite(n,r,a);i&&i.raise({kind:`reconcile`,file:i.fileOf(n),reason:$1,detectedAt:s.detectedAt,stages:{base:o??r,ours:s.retainedContent??(t===void 0?o??r:r0(t)),theirs:s.diskContent}})};return s?.retainedContent!==void 0&&s.retainedContent!==o?(c(r,a??s.retainedContent),!0):o===r?(e0(e,t,n,i),!1):e.staleExternalWriteMatches(n,r)?(c(r,a??s?.retainedContent),!0):e.isDisplacedVersion(n,r)?(q(`reconcile`).warn({docName:n,diskBytes:r.length},`[reconcile] refused stale external write for ${n}; disk restores a version this server already displaced`),c(r,a),!0):(e0(e,t,n,i),!1)}const n0={reconciled:!1,baseBytes:0,diskBytes:0};function r0(e){let t=e.getText(`source`).toString(),{frontmatter:n,body:r}=Ee(t);return La(n,r)}function i0(e,t,n,r,i,a,o){if(DY(n)||OY(n)||AY(n)||jY(n)||MY(n))return n0;let s=t.documents.get(n);if(s&&WZ(s)&&s.getMap(`lifecycle`).get(`reason`)!==$1)return n0;let c=e.getReconciledBase(n);if(c===void 0)return n0;let l;try{let e=HX(n,r);if(!G(e))return n0;l=As(e)}catch{return n0}if(!UX(l,r))return q(`reconcile`).warn({docName:n,canonical:l,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),n0;let u;try{u=K(l,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&q(`reconcile`).warn({docName:n,canonical:l,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),n0}let d=hi(u);if(u===c)return e0(e,s,n,o),n0;let f=e.inFlightFlushCount(n);if(f>0){if(e.hasInFlightFlush(n,d))return LHe(),q(`reconcile`).debug({docName:n,diskBytes:u.length,pendingFlushes:f},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),n0;RHe(),q(`reconcile`).warn({docName:n,diskBytes:u.length,pendingFlushes:f},`[reconcile] disk matches none of ${f} in-flight flush snapshot(s) for ${n}; falling through to merge`)}if(!s||t0(e,s,n,u,o)||d===hi(c))return n0;let p=r0(s),m=TX({docName:n,base:c,ours:p,theirs:u});switch(q(`reconcile`).info({docName:n,result:m.kind,baseBytes:c.length,diskBytes:u.length},`[reconcile] before-agent-write ${n} result=${m.kind}`),m.kind){case`noop`:return n0;case`conflicts`:case`refused`:return o.raise({kind:`reconcile`,file:o.fileOf(n),reason:m.kind===`conflicts`?`merged-with-markers`:$$e(m.reason),stages:{base:c,ours:p,theirs:u}}),n0;case`clean`:case`merged`:{let r=m.kind===`clean`?u:m.newContent;return m.kind===`merged`&&m.dedupSkipped&&(DVe(),q(`reconcile`).warn({docName:n},`[reconcile] ${n} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`)),Q1(e,t,n,r,i,void 0,a),m.kind===`merged`&&e.setReconciledBase(n,u),{reconciled:!0,baseBytes:Buffer.byteLength(c,`utf8`),diskBytes:Buffer.byteLength(u,`utf8`),mergeOutcome:m.kind}}}}const e1e={agent:{"reserved-log-policy":"a reserved `log.md` records history whose links are expected not to resolve. Nothing here is yours to repair — repairing them rewrites the history the log exists to keep, and turning the project setting off yourself is not a workaround. If the user asks to see these findings, point them at Settings ▸ This project ▸ Preferences ▸ Content rules."},human:{"reserved-log-policy":'a reserved `log.md` records history whose links are expected not to resolve. These findings stay out of the repair queue to protect that history. Set `validation.suppressLogLinkAdvisories: false` in `.ok/config.yml` to bring them back, or turn off "Ignore broken links in log.md" under Settings ▸ This project ▸ Preferences ▸ Content rules.'}},t1e={agent:e=>`this build does not recognize the project policy "${e}", so it cannot say why. Treat the withheld findings as not yours to repair and ask the user if they need to see them.`,human:e=>`this build does not recognize the project policy "${e}", so it cannot explain why these findings were withheld.`},n1e={agent:`inspect it only when the user asks, not as a repair queue.`,human:`inspect it when you need the unfiltered view, not as a repair queue.`},r1e={cli:{audience:`human`},mcp:{audience:`agent`}};function i1e(e){return Xee.includes(e)}function a1e(e,t){return i1e(e)?e1e[t][e]:t1e[t](e)}function o1e(e){throw Error(`Unhandled AuditSuppressionTarget: ${JSON.stringify(e)}`)}function s1e(e){switch(e.surface){case`cli`:return`${e.serverBaseUrl}/api/dead-links`;case`mcp`:return`links({ kind: "dead" })`;default:return o1e(e)}}function a0(e){return`${e.count} broken-link finding${e.count===1?``:`s`}`}function c1e(e){return e>0?{reason:`reserved-log-policy`,count:e}:void 0}function l1e(e){return`ℹ ${a0(e)} withheld by project policy, so \`brokenLinks: []\` above does NOT mean every link resolves — ${a1e(e.reason,`agent`)}`}function u1e(e){return`ℹ ${a0(e)} withheld by project policy (see brokenLinkSuppression); this filtered result does NOT mean every link resolves, and there is nothing to repair.`}function d1e(e,t){let{audience:n}=r1e[t.surface];return`ℹ ${a0(e)} withheld by project policy. This audit result is filtered, so it does NOT prove every link resolves — ${a1e(e.reason,n)} Raw state remains available through ${s1e(t)} — ${n1e[n]}`}function f1e(e){let{audience:t}=r1e[e.surface];return`Broken-link findings were withheld by project policy in a form this build cannot read. This audit result is filtered, so it does NOT prove every link resolves. Raw state remains available through ${s1e(e)} — ${n1e[t]}`}function p1e(e,t){return t&&jee(e)}function o0(e,t,n){return e.length===0||!p1e(t,n)?{brokenLinks:e}:{brokenLinks:[],brokenLinkSuppression:c1e(e.length)}}const s0=q(`mermaid-validator`);let m1e=null;function h1e(e){let t=[],n=e.split(`
@@ -1 +1 @@
1
- import{Bt as e,Fa as t,Iu as n,Mo as r,Pl as i,Ps as a,Sn as o,Wo as s,Yl as c,Yn as l,_n as u}from"./md-manager-BGnqyqi1-DKflYxqj.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-D0GERgOV.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,i 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,e 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,n 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,o 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,l 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,c 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,t 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,s 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{Bt as e,Fa as t,Iu as n,Mo as r,Pl as i,Ps as a,Sn as o,Wo as s,Yl as c,Yn as l,_n as u}from"./md-manager-BGnqyqi1-DKflYxqj.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-BRmQARr7.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,i 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,e 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,n 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,o 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,l 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,c 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,t 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,s 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 rje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function ije(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const aje=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function oje(e){let t={contentDir:e.contentDir};for(let n of aje)for(let r of P9(N(e.stagingDir,n)))ije(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):rje.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 sje(e){return N(e,...I9,z9)}function cje(e){return N(e,...I9,B9)}function lje(e){return N(e,...L9,V9)}function uje(e){return N(e,...L9,H9)}function dje(e){return N(e,...R9,U9)}function fje(e){return N(e,...R9,W9)}const G9=1e3;async function pje(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 mje(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 hje(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 gje(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 _je(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function vje(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/`],W6({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 yje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function bje(){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 xje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return xje(e.maxBytes)}function Sje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`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 Cje(e){return Ne(`sha256`).update(e).digest(`hex`)}function wje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Tje=[`"doc.name"`,`"docName"`];function Eje(e){let t=S(e,`utf-8`),n=0;for(let e of Tje){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 Dje=new Set([`.jsonl`]);function Oje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Dje.has(e.slice(t))}const kje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Aje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&kje.has(e.slice(t))}function jje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Aje(r))continue;let{redacted:i,patterns:a,lineCount:o}=CB(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 Mje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??pje,a=r.fetchAgentEffects??mje,o=r.fetchWatcherRecent??hje,s=r.readShadowHead??_je,c=r.readCheckpointRefs??vje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.8-beta.2`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??yje,h=r.isOtlpPushEnabled??bje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(sje(n),N(_,`telemetry`,z9)),Z9(cje(n),N(_,`telemetry`,B9)),Z9(lje(n),N(_,`logs`,V9)),Z9(uje(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(_,qL,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=gje(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(dje(n),N(_,`state`,U9)),Z9(fje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Pu),N(_,`state`,Pu)),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 _je(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function vje(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/`],W6({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 yje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function bje(){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 xje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return xje(e.maxBytes)}function Sje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`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 Cje(e){return Ne(`sha256`).update(e).digest(`hex`)}function wje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Tje=[`"doc.name"`,`"docName"`];function Eje(e){let t=S(e,`utf-8`),n=0;for(let e of Tje){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 Dje=new Set([`.jsonl`]);function Oje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Dje.has(e.slice(t))}const kje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Aje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&kje.has(e.slice(t))}function jje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Aje(r))continue;let{redacted:i,patterns:a,lineCount:o}=CB(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 Mje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??pje,a=r.fetchAgentEffects??mje,o=r.fetchWatcherRecent??hje,s=r.readShadowHead??_je,c=r.readCheckpointRefs??vje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.8-beta.3`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??yje,h=r.isOtlpPushEnabled??bje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(sje(n),N(_,`telemetry`,z9)),Z9(cje(n),N(_,`telemetry`,B9)),Z9(lje(n),N(_,`logs`,V9)),Z9(uje(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(_,qL,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=gje(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(dje(n),N(_,`state`,U9)),Z9(fje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Pu),N(_,`state`,Pu)),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&&oje({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=jje(_));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=Sje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Oje(t)?wje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=Eje(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:Cje(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 Nje(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 FCe.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 Pje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=q8(t)?t.content:void 0,i=q8(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 Fje(e,t,n,r,i){let a=E7(t,e.logger),o=await Mje({contentDir:Pje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Gke(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 Nje({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 Ije(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>Vke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Fje(e,t,n,r,i());let{zipPath:a,summary:o}=await Xke({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{e5 as ALL_EDITOR_IDS,t5 as EDITOR_LABELS,j5 as EDITOR_TARGETS,sOe as HOSTS_WITH_USER_SKILL_DIR,Dke as LAUNCH_CONFIG_NAME,zAe as PATH_SHIM_BEGIN,VAe as PATH_SHIM_BLOCK_RE,BAe as PATH_SHIM_END,ake as addOkPathsToGitExclude,R5 as assertProjectPathSafe,p5 as buildManagedServerEntry,kAe as buildMcpConfigDeclineEvent,AAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Ije as collectReportBundle,KAe as createCliProbeResolver,on as createTokenStore,Hke as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,jke as detectInstalledEditors,S5 as droppedManagedKeys,OOe as editorConfigPathDisplay,DOe as editorEntryLocator,vAe as ensurePiBridge,Q5 as formatTrackedRemediation,cke as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,oOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,d5 as isEntryUpToDate,m5 as isOwnManagedEntry,IAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,LAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,HAe as pathInstallMarkerPath,UOe as previewContent,Mke as probeOwnManagedEditorMcpEntry,gAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,ske as readSharingMode,CB as redactContent,oke as removeOkPathsFromGitExclude,TAe as removeOwnMcpEntry,tke as removeProjectSkill,JAe as removeUserGlobalSkillBundle,eje as removeUserSkill,YOe as resolveProjectRoot,NAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,$Ae as userSkillPresentAnywhere,RAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,ZAe as writeProjectAiIntegrations,W5 as writeProjectSkill,Ake as writeUserMcpConfigs,QAe as writeUserSkill};
1540
1540
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ import"./dist-BRmQARr7.mjs";import{_ as e}from"./init-DsTCcpDC.mjs";export{e as runInit};