@inkeep/open-knowledge 0.86.8 → 0.86.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-AVpciYuS.mjs +1 -0
  3. package/dist/{dist-BlSdA1nb.mjs → dist-DEBeS2ZG.mjs} +2 -2
  4. package/dist/{dist-DVqxZomd.mjs → dist-DmYr-0z7.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-BCe_tjcH.mjs → init-BlXG9J4y.mjs} +2 -2
  7. package/dist/init-DvPfSTSj.mjs +1 -0
  8. package/dist/{launch-json-removal-BbCnNyIl.mjs → launch-json-removal-v9j_deDf.mjs} +1 -1
  9. package/dist/loader-B-XZbhiY.mjs +1 -0
  10. package/dist/{loader-DJLRHTZY.mjs → loader-BYPzS6xp.mjs} +1 -1
  11. package/dist/{open-browser-xdMmGbvs.mjs → open-browser-CnTPF5YI.mjs} +1 -1
  12. package/dist/{preview-Dp6gd5yO.mjs → preview-CiI_cXDW.mjs} +1 -1
  13. package/dist/preview-W9UMo-ZZ.mjs +1 -0
  14. package/dist/public/assets/{AccountSection-DtkxvXx9.js → AccountSection-CJuqWQpv.js} +1 -1
  15. package/dist/public/assets/{ActivityModeContent-CgyrR9N-.js → ActivityModeContent-zfT-fkuW.js} +1 -1
  16. package/dist/public/assets/{AddPropertiesButton-Df4BzZbW.js → AddPropertiesButton-QPaDy7qS.js} +1 -1
  17. package/dist/public/assets/{AgentDiffPane-DcahQVWo.js → AgentDiffPane-Ctg9e13V.js} +1 -1
  18. package/dist/public/assets/{AttachmentsSection-YJWs92f8.js → AttachmentsSection-BHpGHTwP.js} +1 -1
  19. package/dist/public/assets/{CodeMirrorPropInput-C4wZXnop.js → CodeMirrorPropInput-BCnj3pdn.js} +1 -1
  20. package/dist/public/assets/{ContentRulesSection-CojD6GPn.js → ContentRulesSection-CwtLTmbA.js} +1 -1
  21. package/dist/public/assets/{DocumentContext-vGSKK5Nc.js → DocumentContext-DARBW5YB.js} +1 -1
  22. package/dist/public/assets/{EditorModeToggle-C4XyEK9q.js → EditorModeToggle-DZJKO9dQ.js} +1 -1
  23. package/dist/public/assets/{ExcalidrawDocEditor-CVFGVyCa.js → ExcalidrawDocEditor-CyKdb3fY.js} +1 -1
  24. package/dist/public/assets/FeedbackForm-CUqZ-4ej.js +1 -0
  25. package/dist/public/assets/{ImportSkillDialog-WhgVePm-.js → ImportSkillDialog-Budzn51E.js} +1 -1
  26. package/dist/public/assets/{LinkPreviewsSection-B3wLDGmw.js → LinkPreviewsSection-DLzRBrLq.js} +1 -1
  27. package/dist/public/assets/{LintConfigEditor-C0peQpGZ.js → LintConfigEditor-Ck4_shio.js} +1 -1
  28. package/dist/public/assets/{LintingSection-rzGPFPrx.js → LintingSection-BO-fThw2.js} +1 -1
  29. package/dist/public/assets/{ManagedArtifactProperties-BSQWw0KX.js → ManagedArtifactProperties-D6JRTEb3.js} +1 -1
  30. package/dist/public/assets/ManagedArtifactProperties-DaAak5RL.js +1 -0
  31. package/dist/public/assets/{MermaidDocEditor-DcbAFF7w.js → MermaidDocEditor-BxtCCNdb.js} +1 -1
  32. package/dist/public/assets/{NetworkAccessSection-Cd4qmCmC.js → NetworkAccessSection-DUXlWxKD.js} +1 -1
  33. package/dist/public/assets/{PropertyDisplayRow-DeCUWKRR.js → PropertyDisplayRow-BqBk3Nya.js} +1 -1
  34. package/dist/public/assets/{PublishToGitHubDialog-CdU1KDWZ.js → PublishToGitHubDialog-8HcawWye.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-CSs3cZP1.js → SchemaConfigEditor-BKnDSh9l.js} +1 -1
  36. package/dist/public/assets/{SearchSection-CNofwaZ_.js → SearchSection-CGaKXDN8.js} +1 -1
  37. package/dist/public/assets/{SessionsHost-Dz-kv7py.js → SessionsHost-ujXuGvc3.js} +2 -2
  38. package/dist/public/assets/{SettingsDialogBody-cp7iluKc.js → SettingsDialogBody-CcUWmHa6.js} +2 -2
  39. package/dist/public/assets/{ShareReceiveMissDialog-BaHgTGTK.js → ShareReceiveMissDialog-BkqWJXsX.js} +1 -1
  40. package/dist/public/assets/{SkillToolbarControls-DFR1F5MK.js → SkillToolbarControls-Ck7Uywje.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-BZnLFZ0r.js → SourceEditor-C8PZC8d_.js} +1 -1
  42. package/dist/public/assets/{SyncSection-taNv-4-I.js → SyncSection-RzoP-xOe.js} +1 -1
  43. package/dist/public/assets/{SyncStatusBadge-CbdGcxBQ.js → SyncStatusBadge-BdAnoPq_.js} +1 -1
  44. package/dist/public/assets/{TerminalSection-8MFTnhGW.js → TerminalSection-B3ez1rqn.js} +1 -1
  45. package/dist/public/assets/{TerminalWindowApp-Dpg-6ZV-.js → TerminalWindowApp-jbskrWnW.js} +1 -1
  46. package/dist/public/assets/{TextDocEditor-Cd3RfPgb.js → TextDocEditor-WuB1VpRo.js} +1 -1
  47. package/dist/public/assets/{ThreadView-OE-aI1Ve.js → ThreadView-CdUq-SgP.js} +1 -1
  48. package/dist/public/assets/{TimelineDiffPane-DHsNAJGa.js → TimelineDiffPane-D8Lokukv.js} +1 -1
  49. package/dist/public/assets/{client-version-_tmJbiyb.js → client-version-D4a0Tgs5.js} +1 -1
  50. package/dist/public/assets/{comment-chips-CXeeHVZ0.js → comment-chips-BRUZD-Av.js} +1 -1
  51. package/dist/public/assets/{config-provider-_ANSlVZK.js → config-provider-DPe-D_Om.js} +1 -1
  52. package/dist/public/assets/{doc-undo-manager-B9nKMoJY.js → doc-undo-manager-CzXqaM3J.js} +1 -1
  53. package/dist/public/assets/{index-VaITM1Qd.js → index-DazxsqZf.js} +8 -8
  54. package/dist/public/assets/{lint-plugins-BglGcXZZ.js → lint-plugins-CqlbXO7c.js} +1 -1
  55. package/dist/public/assets/{pending-receive-nav-store-Cezz1f7T.js → pending-receive-nav-store-DmTFF3wG.js} +1 -1
  56. package/dist/public/assets/{preferred-session-events-DpI3ZYo1.js → preferred-session-events-Dp74P9LP.js} +1 -1
  57. package/dist/public/assets/{progress-Beh-ohCz.js → progress-C9KsqE5k.js} +1 -1
  58. package/dist/public/assets/{selection-context-BFVstJw3.js → selection-context-CreAErsk.js} +1 -1
  59. package/dist/public/assets/{src-BlAQMlAU.js → src-E4YaNbY-.js} +1 -1
  60. package/dist/public/assets/{telemetry-impl-Ca7EhcL5.js → telemetry-impl-DWGo1H1g.js} +1 -1
  61. package/dist/public/assets/{telemetry-startup-DySlH5ZI.js → telemetry-startup-C7b575ky.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-CEWeo0vN.js → typing-burst-detector-x6ARQVxv.js} +1 -1
  63. package/dist/public/assets/{use-activity-panel-CNXjBq64.js → use-activity-panel-Cgg5wFWr.js} +1 -1
  64. package/dist/public/assets/{use-open-skill-XkDfRrZN.js → use-open-skill-CcXYACfH.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-B2O8_jTb.js → use-terminal-enabled-BtbnUsEM.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-CBocV1wH.js → use-timeline-entry-diff-D6R9BdZt.js} +1 -1
  67. package/dist/public/index.html +18 -18
  68. package/dist/{registry-probes-CsmfKoeC.mjs → registry-probes-B03QRAUz.mjs} +1 -1
  69. package/dist/{removal-file-path-DkvPAu6X.mjs → removal-file-path-CZejQ8cP.mjs} +1 -1
  70. package/dist/{repair-launch-json-CgBVK8WS.mjs → repair-launch-json-DVL7PlPc.mjs} +1 -1
  71. package/dist/{repair-mcp-configs-BF_txJWZ.mjs → repair-mcp-configs-r_rr4JWy.mjs} +1 -1
  72. package/dist/{src-BQymYJ7Z.mjs → src-BVIDZaLQ.mjs} +1 -1
  73. package/dist/src-DQbJZYYa.mjs +1 -0
  74. package/dist/start-DH2PbULY.mjs +1 -0
  75. package/dist/{start-BPPuJdor.mjs → start-SXQXzeho.mjs} +3 -3
  76. package/package.json +4 -4
  77. package/dist/constants-BAHeXK4v.mjs +0 -1
  78. package/dist/init-D0pqXoSa.mjs +0 -1
  79. package/dist/loader-Bc2fwUgO.mjs +0 -1
  80. package/dist/preview-COHlbKvD.mjs +0 -1
  81. package/dist/public/assets/FeedbackForm-BRKh0t_P.js +0 -1
  82. package/dist/public/assets/ManagedArtifactProperties-e_apIki7.js +0 -1
  83. package/dist/src-Lj__JFVN.mjs +0 -1
  84. package/dist/start-D45tiSx4.mjs +0 -1
@@ -1043,9 +1043,9 @@ ${pYe.join(`
1043
1043
  `)}\n`;this.enqueue(e,async()=>{if(!this.appendBroken.has(e))try{await zG(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 RG(r,n),await VG(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await BG(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 y6e(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 gc(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 hc(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}if(!zQ(o.info.threadId)||a!==`${o.info.threadId}.meta.json`){this.log.warn({path:i},`[acp-persist] skipping a thread meta whose id OpenKnowledge did not mint`);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 y6e(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(v6e(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=>BG(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=Ws(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=kae({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 _6e(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function _6e(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 v6e(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function y6e(e){try{return await _c(e)}catch{return W(e)}}const b6e=`@playwright/mcp@0.0.82`,BQ=`ok-browser`,x6e=`codex-acp`,S6e=new Set([`claude-acp`,x6e]),C6e=/^browser_[a-z_]+$/,w6e=/^(?:mcp[^a-z0-9]+)?ok[^a-z0-9]?browser[^a-z0-9]+(browser_[a-z_]+)$/,T6e=/^mcp__(.+?)__(.+)$/,E6e=/^mcp\.([^.]+)\.(.+)$/,D6e=/^Tool: ([^/\s]+)\/(\S+)$/,O6e=[`DISPLAY`,`WAYLAND_DISPLAY`,`XAUTHORITY`,`XDG_RUNTIME_DIR`],VQ=`npm_config_cache`,HQ=`npm_config_prefer_offline`;function k6e(e){return e.source===`registry`&&S6e.has(e.id)}const UQ={kind:`none`},WQ={kind:`unverified`};function A6e(e,t){return e===BQ?C6e.test(t)?{kind:`browser`,tool:t}:WQ:UQ}function j6e(e){let t=E6e.exec((e.title??``).trim());if(t===null)return WQ;let[,n=``,r=``]=t;return M6e(e,n,r)}function M6e(e,t,n){let r=qS(e.rawInput),i=JS(r,`server`),a=JS(r,`tool`);return i!==null&&i!==t||a!==null&&a!==n?WQ:A6e(t,n)}function N6e(e,t){if(!t.browserInjected)return UQ;let n=qS(e._meta),r=JS(qS(n?.claudeCode),`toolName`);if(r!==null){let e=T6e.exec(r);return e===null?UQ:A6e(e[1]??``,e[2]??``)}let i=t.agentId===x6e;if(i&&n?.is_mcp_tool_call===!0)return j6e(e);let a=(e.title??``).trim(),o=i?D6e.exec(a):null;if(o!=null)return M6e(e,o[1]??``,o[2]??``);let s=w6e.exec(a.toLowerCase())?.[1];if(s!==void 0)return{kind:`browser`,tool:s};if(!i)return WQ;let c=qS(e.rawInput),l=JS(c,`serverName`)??JS(c,`server_name`)??JS(c,`server`);if(qS(t.requestMeta)?.is_mcp_tool_approval===!0||l!==null)return l!==null&&l.toLowerCase()!==BQ?UQ:WQ;let u=c!==null&&(c.command!==void 0||c.changes!==void 0);return e.kind!=null&&e.kind!==`other`&&u?UQ:WQ}function P6e(e,t,n){return N6e(e,{requestMeta:t,browserInjected:!0,agentId:n}).kind===`unverified`}function F6e(e,t=oJ,n=()=>!0){for(let r of e){if(r==null||r===``)continue;let e=t(`npx`,r);if(e!==null&&n(e))return{npx:e,path:r}}return null}function I6e(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()===VQ&&n!==``)return n;return null}function L6e(e,t,n,r=_Q()){let i={};for(let[e,n]of Object.entries(r)){let r=e.toLowerCase();r!==`path`&&r!==HQ&&(t===null||r!==VQ)&&(i[e]=n)}return i.PATH=e.path,i[HQ]=n===`cached`?`true`:`false`,t!==null&&(i[VQ]=t),{cmd:e.npx,args:[],env:i,kind:`npx`,pathFromOverlay:!0}}function R6e(e){try{return rc(e).isFile()}catch{return!1}}const z6e=`(${K4e.toString()})(require('node:child_process'), require('node:url'), ${JSON.stringify([`browser_click`,`browser_close`,`browser_console_messages`,`browser_drag`,`browser_drop`,`browser_emulate_media`,`browser_evaluate`,`browser_file_upload`,`browser_fill_form`,`browser_find`,`browser_handle_dialog`,`browser_hover`,`browser_navigate`,`browser_navigate_back`,`browser_network_request`,`browser_network_requests`,`browser_press_key`,`browser_resize`,`browser_select_option`,`browser_snapshot`,`browser_tabs`,`browser_take_screenshot`,`browser_type`,`browser_wait_for`])});`;function B6e(e){let t=e.platform??process.platform,n=e.env??process.env,r=V6e(e.npx.npx,t,e.exists??R6e);if(r===null)return null;let i=t===`linux`&&(n.DISPLAY??``)===``&&(n.WAYLAND_DISPLAY??``)===``,a=t===`linux`&&!i?O6e.flatMap(e=>{let t=n[e];return t===void 0||t===``?[]:[{name:e,value:t}]}):[];return{name:BQ,command:r.node,args:[`-e`,z6e,e.folders.npm,e.folders.files,...r.npx,`--prefix`,e.folders.npm,`--yes=false`,b6e,`--isolated`,`--no-webmcp`,`--output-dir`,e.folders.files,`--file-paths`,`absolute`,...i?[`--headless`]:[]],env:[{name:`PATH`,value:e.npx.path},{name:HQ,value:`true`},...e.npmCache==null?[]:[{name:VQ,value:e.npmCache}],...a]}}function V6e(e,t,n){let r=V(e);if(t!==`win32`){let t=H(r,`node`);return n(t)?{node:t,npx:[e]}:null}let i=H(r,`node.exe`),a=H(r,`node_modules`,`npm`,`bin`,`npx-cli.js`);return n(i)&&n(a)?{node:i,npx:[i,a]}:null}function H6e(e,t={}){return V6e(e,t.platform??process.platform,t.exists??R6e)!==null}function U6e(e,t){return zQ(t)?W(e,`agent-browser`,t):null}async function W6e(e,t){let n=U6e(e,t);if(n===null)throw Error(`browser folders need a chat id OpenKnowledge minted`);let r={npm:H(n,`npm`),files:H(n,`files`)};return await HG(V(n),{recursive:!0,mode:448}),await HG(n,{recursive:!0,mode:448}),await BG(r.npm,{recursive:!0,force:!0}),await HG(r.npm,{mode:448}),await RG(H(r.npm,`package.json`),`${JSON.stringify({name:`openknowledge-agent-browser`,version:`0.0.0`,private:!0},null,2)}\n`),await HG(r.files,{recursive:!0,mode:448}),r}async function G6e(e,t){let n=U6e(e,t);n!==null&&await BG(n,{recursive:!0,force:!0})}const K6e=/command not found|not recognized as an internal or external command/i,q6e=/permission denied/i,J6e=/cannot find module|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND/i,Y6e=/out of memory|ENOMEM/i,X6e=new Set([`SIGTERM`,`SIGINT`,`SIGHUP`]);function Z6e({exitCode:e,signal:t,tail:n}){if(t!==null)return t===`SIGKILL`?`killed`:X6e.has(t)?`stopped`:`signal`;if(e===0)return`clean`;if(e===null)return`unknown`;if(e===127)return`command-not-found`;if(e===126)return`not-executable`;let r=n===void 0?``:JSe(n);return Y6e.test(r)?`out-of-memory`:K6e.test(r)?`command-not-found`:q6e.test(r)?`not-executable`:J6e.test(r)?`missing-module`:`unknown`}function Q6e(e){return{exitCode:e.exitCode,signal:e.signal,cause:Z6e(e)}}function $6e(e){return{reason:`exited`,exit:Q6e(e),machineDetail:e.tail}}function e8e(e){return e===`connect`||e===`session-setup`}function t8e(e){return H(e,Hr)}function n8e(e){let t=[`=== acp launch failure ${e.at.toISOString()} thread=${e.threadId} agent=${e.agentId} source=${e.agentSource} reason=${e.reason} ===`];return e.detail!==void 0&&e.detail!==``&&t.push(e.detail),e.machineDetail!==void 0&&e.machineDetail!==``&&t.push(`--- stderr tail ---`,e.machineDetail),cQ(`${t.join(`
1044
1044
  `)}\n\n`)}const GQ=new Map;function r8e(e,t){let n=t8e(e),r=n8e(t),i=(GQ.get(n)??Promise.resolve()).then(async()=>{let e=await yc(n).then(e=>e.size,()=>void 0);Ha(e)===`w`?await RG(n,r):await zG(n,r)}),a=i.then(()=>void 0,()=>void 0);return GQ.set(n,a),a.then(()=>{GQ.get(n)===a&&GQ.delete(n)}),i}const KQ=`v24.18.0`,qQ=`0.11.28`,i8e=`https://nodejs.org/dist`,a8e=`https://github.com/astral-sh/uv/releases/download`,o8e={node:45,uv:20};function s8e(e){return e===`npx`?`node`:`uv`}function JQ(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:KQ,approxSizeMB:o8e.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:qQ,approxSizeMB:o8e.uv,sourceHost:`github.com/astral-sh`}}function YQ(){return H(ZS(),`runtimes`)}function XQ(e){return e===`node`?KQ:qQ}function c8e(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function l8e(){let e=uc(),t=sc(),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-${KQ}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${i8e}/${KQ}/${a}`,checksumUrl:`${i8e}/${KQ}/SHASUMS256.txt`,archiveName:a,isZip:i}}function u8e(){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`}[`${uc()}-${sc()}`];if(e===void 0)return null;let t=uc()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${a8e}/${qQ}/${n}`,checksumUrl:`${a8e}/${qQ}/${n}.sha256`,archiveName:n,isZip:t}}function d8e(e){return e===`node`?l8e():u8e()}function f8e(e){return d8e(e)!==null}async function p8e(e){try{let t=await yc(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await fc(e,dae.X_OK),!0)}catch{return!1}}async function ZQ(e,t,n){let r;try{r=await gc(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 ZQ(H(e,i.name),t,n-1);if(r!==null)return r}return null}function m8e(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 h8e(e,t=YQ()){let n=H(t,e,aQ(XQ(e)));try{if(!(await yc(n)).isDirectory())return null}catch{return null}let r=await ZQ(n,c8e(e),3);return r===null||!await p8e(r)?null:m8e(e,r,t)}var QQ=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function g8e(e,t,n=YQ()){await pQ(H(n,e),t,`[managed-runtime]`)}async function _8e(e,t,n=YQ()){let r=H(n,e,aQ(XQ(e))),i=H(V(r),`.install-damaged-${aQ(XQ(e))}-${Cc()}`);try{await VG(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 BG(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function v8e(e,t,n={}){let r=n.root??YQ(),i=H(r,e,aQ(XQ(e)));try{return await mQ({versionDir:i,stagingLabel:aQ(XQ(e)),findInstalled:()=>h8e(e,r),prepare:async r=>{let i=d8e(e);if(i===null)throw new QQ(`no ${e} build for ${uc()}-${sc()}`);let a=H(r,i.archiveName);t.info({kind:e,version:XQ(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let[o,s]=await Promise.all([R4e(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),z4e(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=B4e(s,i.archiveName);if(c===null)throw new QQ(`no published checksum for ${i.archiveName}`);if(o!==c)throw new QQ(`checksum mismatch for ${i.archiveName}: got ${o}, expected ${c}`);let l=H(r,`extracted`);await HG(l,{recursive:!0}),await L4e(a,l,i.isZip);let u=await ZQ(l,c8e(e),3);if(u===null||!iQ(l,u))throw new QQ(`extracted ${e} archive has no usable launcher`);return l},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:XQ(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof QQ?t:new QQ(`installing ${e} ${XQ(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const y8e=`CODEX_CONFIG`;function b8e(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 x8e(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function S8e(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function C8e(e){if(e===void 0||e.trim()===``)return{};try{return S8e(JSON.parse(e))}catch{return{}}}function w8e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...C8e(e[y8e]),model_context_window:Math.floor(t)};return{...e,[y8e]:JSON.stringify(n)}}function T8e(e){return(e.visibility??`list`)===`list`}const E8e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function $Q(e){return E8e[e]??`none`}function D8e(e,t,n){if(n===null||$Q(t)!==`codex-config-env`)return e;let r=w8e(e.env,n);return r===e.env?e:{...e,env:r}}function O8e(e){return $Q(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function e$(e,t,n={}){GG(t,{recursive:!0});for(let r of Qs(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);rc(i).isDirectory()?e$(i,a,n):UG(a,K(i))}}const k8e=`open-knowledge`,A8e=`SKILL.md`,t$=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function j8e(e){return H(e,`agent-skill`,k8e)}function M8e(e,t){let n;try{n=K(t)}catch(e){let t=e.code;if(t!==void 0&&t$.has(t))return!1;throw e}return K(e).equals(n)}function N8e(e,t){let n=Qs(e),r;try{r=new Set(Qs(t))}catch(e){let t=e.code;if(t!==void 0&&t$.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(rc(n).isDirectory()){let e;try{e=rc(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&t$.has(t))return!1;throw e}if(!e||!N8e(n,a))return!1}else if(!M8e(n,a))return!1}return!0}var P8e=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 F8e(e){let t;try{t=await pc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new P8e(e)}async function I8e(e){let t=j8e(e.localDir),n=V(t),r=async()=>{await F8e(n),await F8e(t)};return mQ({versionDir:t,stagingLabel:k8e,findInstalled:async()=>(await r(),N8e(e.sourceDir,t)?t:null),prepare:async t=>(e$(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`})}function L8e(e,t=process.env){let n=(e.kind===`npx`||e.kind===`uvx`)&&js(e.cmd),r={};for(let[n,i]of Object.entries(e.env))n.toLowerCase()===`path`||!Va(n)||i.includes(`\0`)||t[n]!==i&&(r[n]=i);return{executable:e.cmd,args:e.kind===`npx`?x3e(e.args):[...e.args],env:r,pathPrepend:n?[V(e.cmd)]:[]}}function R8e(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function z8e(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r!=`string`||r.includes(`\0`)||Va(n)&&(t[n]=r);return t}function B8e(e){return typeof e==`object`&&e?e:null}function V8e(e,t){return{executable:t.executable,args:[...t.args,...R8e(e.args)],env:{...t.env,...z8e(e.env)},pathPrepend:[...t.pathPrepend]}}function n$(e,t){return(e??[]).flatMap(e=>{let n=B8e(e);if(n===null)return[];let{id:r,name:i,description:a,type:o}=n;if(typeof r!=`string`||typeof i!=`string`)return[];let s=o===`terminal`&&t!==null;return[{id:r,name:i,...typeof a==`string`?{description:a}:{},...typeof o==`string`?{kind:o}:{},...s?{terminalLaunchAvailable:!0}:{}}]})}function H8e(e,t,n){if(t===null)return null;for(let r of e??[]){let e=B8e(r);if(e!==null&&e.id===n&&e.type===`terminal`)return V8e(e,t)}return null}const U8e=2e3;function W8e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function G8e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:W8e(n.subarray(n.length-t)).toString(`utf8`)}function r$(e){if(e.outputBytes<=e.byteLimit)return;let t=W8e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var K8e=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=u3e(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:js(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?MQ(e.command,kQ(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?NQ(o,e.args??[]):{cmd:o,args:e.args??[]},u=Ts(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 r$(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 LQ(t.child,{graceMs:U8e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await LQ(t.child,{graceMs:U8e}),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=_Q(e);return this.loginShellPath===null||yQ(e)?t:wQ(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?r$(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=G8e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,r$(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 q8e=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`),J8e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,Y8e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function X8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Z8e(e){return(e.trim().split(`
1045
1045
  `)[0]??``).trim()}function i$(e){let t=Z8e(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 Q8e(e,t){let n=Z8e(e),r=n.replace(J8e,``);if(t!==void 0&&t.trim()!==``){let e=X8e(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(q8e,``);if(e===r)break;r=e}r=r.replace(Y8e,``).trim();let i=r.split(/\s+/).filter(e=>e!==``).length;return!(r!==``&&(i>=2||r.length>=12))||r===n?i$(n):i$(r.charAt(0).toUpperCase()+r.slice(1))}const $8e=8,e5e=5e3,a$=3e5,o$=45e3,t5e=5e3,n5e=2e3,r5e=new Set([`ready`,`auth_required`,`authenticating`]),i5e=`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 a5e(e){if(e===null)return i5e;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`${i5e}\n\n${t}`}const o5e=new Set([`gemini`]);function s5e(e){return e.source===`registry`&&o5e.has(e.id)}function c5e(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:Rs(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${A8e} ---\n${t}\n--- End skill ---`}}var s$=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},c$=class extends gQ{refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},l5e=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},u5e=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function d5e(){return new s$(`not-ready`,`the thread was restarted during the sign-in`)}function f5e(e){return e.source===`registry`&&_Ke[e.id]===`pi`}function p5e(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=>oJ(e,vQ())))(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 m5e=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;turnStallMs;browserInstallWaitMs;persistence;npxCacheClears=new Map;resolveLoginShellPath;healthyInterpreters=new Set;projectSkillStaging=null;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>fQ(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.browserInstallWaitMs=e.browserInstallWaitMs??12e4;let[t,n=null]=m6e(e.globalDir,e.localDir);this.persistence=new g6e({primaryDir:t,legacyDir:n,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,g5e(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 s$(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(await dG({site:`acp-thread`,agentId:n===null?ute(t.id)??t.id:t.id,mode:`acp`,log:this.opts.log,snapshot:this.opts.hostSnapshot}),this.destroyed)throw new s$(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`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,terminalAuthBase:null,sessionId:null,sessionBeforeRestart: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,reportedToolCalls:new Map,toolCallReportWaiters:new Map,browserInjected:!1,browserNotice:null,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:i,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint,envNotePending:!1,projectSkill:null,chatGrants:new Set};return this.threads.set(r,a),this.emitStatus(a,`spawning`),this.startThread(a,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await iG(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new s$(`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 s$(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new s$(`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??=I8e({localDir:this.opts.localDir,sourceDir:t??nQ(`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}iQ(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,A8e);if(!s5e(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await hc(i,`utf8`)}}catch(e){return this.opts.log.warn({err:e,...n,skillPath:i},`[acp-threads] skill inline read failed; skipping skill delivery`),null}}async connectAgent(e,t,n=`reuse`,r,i=`available`){let a;if(t!==null)a=await this.ensureLaunchable(e,B3e(t),r);else{let o=await this.opts.registry.getAgent(e.agentRef.id);if(o===void 0)throw new s$(`unknown-agent`,`agent vanished`);try{a=await d3e(o,yKe(),this.opts.log,void 0,t=>this.ensureLaunchable(e,t,r),{reacquire:n===`reacquire`,install:!0,onAcquiring:()=>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`)})}catch(n){if(n instanceof gQ&&n.npxCacheEntry!==void 0&&i===`available`&&await this.clearStaleNpxCacheEntry(e,n.npxCacheEntry))return this.connectAgent(e,t,`reacquire`,r,`spent`);throw n}}if(a===null||p$(e))return null;let o=await this.resolveLoginShellPath().catch(()=>null);if(p$(e)||(e.projectSkill=await this.stageProjectSkillFor(e),p$(e)))return null;let s=new K8e({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:o});e.terminalAuthBase=L8e(a),e.agentLaunchPath=kQ(a.env),e.agentNpmCache=I6e(a.env),a=D8e(a,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let c=a.kind===`npx`?PQ(a):PQ(a,e.cwd);e.child=c,e.terminals=s;let l=new Promise(e=>c.once(`close`,()=>e())),u,d=()=>c.exitCode===null&&c.signalCode===null&&c.stdout?.readableEnded!==!0&&c.stdout?.destroyed!==!0?Promise.resolve():(u??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),l.then(()=>{clearTimeout(t),e()})}),u);e.drainStderr=d;let f=``,p=``,m=!0,h=lQ(t=>{m&&(f=`${f}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())},e=>{m&&(p=`${p}${e}\n`.slice(-16e3))}),g=a.kind,_=!1,v=()=>g===`npx`&&m&&i===`available`&&(xQ(p)!==null||y3e(p)),y=()=>_||v();if(c.stderr?.setEncoding(`utf8`),c.stderr?.on(`data`,h.write),c.stderr?.on(`end`,h.end),c.stderr?.on(`data`,t=>{for(let n of t.split(`
1046
- `))n.trim()!==``&&e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e))}),c.on(`error`,t=>{y()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),c.on(`exit`,(t,n)=>{if(e.child!==c)return;let r=r5e.has(e.info.status);e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),s.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),m$(e).then(i=>{if(e.terminals!==s||p$(e)||y())return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let a=`agent exited (${n??t??`unknown`})`;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:i},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,a,r?$6e({exitCode:t,signal:n,tail:i}):void 0),this.failPendingPermissions(e)}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] exit diagnostics failed`)})}),c.stdin===null||c.stdout===null)throw new s$(`spawn-failed`,`agent process has no stdio`);let b=mSe(_ae.toWeb(c.stdin),xc.toWeb(c.stdout)),x=KSe({name:`open-knowledge`}).onRequest(VC.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options,t.params._meta)).onRequest(VC.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(VC.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(VC.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(VC.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(VC.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(VC.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(VC.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(VC.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(b);e.conn=x;let S=async t=>{if(await d(),e.conn!==x||y()||(t!==null&&this.opts.log.warn({err:t.err,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status===`exited`||e.info.status===`error`))return;if(t===null){this.emitStatus(e,`exited`,`agent connection closed`);return}let{err:n}=t;this.emitStatus(e,`error`,`agent connection failed: ${n instanceof Error?n.message:String(n)}`)};x.closed.then(()=>S(null),e=>S({err:e}));let C;try{C=await x.agent.request(VC.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:rQ},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,...this.opts.terminalAuthAvailable===!0?{auth:{terminal:!0}}:{},session:{configOptions:{boolean:{}}}}})}catch(n){if(this.opts.log.warn({err:n,threadId:e.info.threadId},`[acp-threads] initialize failed`),a.kind===`npx`||a.kind===`uvx`){await d();let e=h3e(a,f,n);if(e!==null)throw e}let o=g===`npx`&&i===`available`?xQ(p):null;if(o!==null&&await this.clearStaleNpxCacheEntry(e,o)||g===`npx`&&i===`available`&&y3e(p)&&await this.discardRefusedNpxLaunch(e,a))return _=!0,this.connectAgent(e,t,`reacquire`,r,`spent`);throw new s$(`spawn-failed`,`initialize failed: ${u$(n)}`)}finally{m=!1,f=``,p=``}return p$(e)?null:(e.lastInit=C,e.info.promptCapabilities=C.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:x,init:C,launch:a})}async discardRefusedNpxLaunch(e,t){return!p$(e)&&(this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,package:S3e(t.args)},`[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch`),await this.discardFailedLaunch(e),!p$(e))}async clearStaleNpxCacheEntry(e,t){let n={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:cQ(t)},r=await this.removeStaleNpxCacheEntry(t,n);return r===`kept`?!1:p$(e)?(r===`removed`&&this.opts.log.warn(n,`[acp-threads] cleared a stale npx cache entry; the thread was closed, so the agent is not relaunched`),!1):(this.opts.log.warn(n,r===`recently-removed`?`[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again`:`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),!p$(e))}async removeStaleNpxCacheEntry(e,t){let n=this.npxCacheClears.get(e);if(n!==void 0&&Date.now()-n<3e5)return`recently-removed`;let r=Date.now();this.npxCacheClears.set(e,r);let i=()=>{this.npxCacheClears.get(e)===r&&this.npxCacheClears.delete(e)};for(let n of[`package.json`,`concurrency.lock`]){let r=await yc(H(e,n)).then(()=>`present`,e=>e.code??`unknown`);if(r!==`ENOENT`)return this.opts.log.warn({...t,file:n,code:r},`[acp-threads] leaving an npx cache entry alone`),i(),`kept`}try{await BG(e,{recursive:!0,force:!0})}catch(e){return this.opts.log.warn({err:e,...t},`[acp-threads] stale npx cache entry could not be cleared`),i(),`kept`}return`removed`}async discardFailedLaunch(e){e.drainStderr=null,e.stderrTail=[],await this.stopAgentProcess(e,`[acp-threads] terminal cleanup before relaunch failed`)}async stopAgentProcess(e,t){let n=e.child,r=e.conn,i=e.terminals;e.child=null,e.conn=null,e.terminals=null;try{r?.close()}catch{}await i?.disposeAll().catch(n=>{this.opts.log.warn({err:n,threadId:e.info.threadId},t)}),n!==null&&await LQ(n,{graceMs:t5e})}async ensureLaunchable(e,t,n){let r;try{await DQ(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof gQ)||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 p$(e)?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(p$(e))return null;if(r===null)return t;if(r.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(p$(e))return null;if(kQ(n.env)!==kQ(t.env))try{await DQ(n);let t=await this.probeInterpreterOnce(n);if(p$(e))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 gQ)||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 gQ(`command-not-found`,i?o6e(t,r.detail):Z3e(t,r.detail)),o=new gQ(`command-not-found`,i?s6e(t,r.detail):r6e(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=s8e(t.kind);if(!f8e(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof c$?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=V3e(t,o);await DQ(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new gQ(`install-failed`,$3e(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 _8e(n,this.opts.log,this.opts.runtimeInstall?.root))throw new gQ(`install-failed`,e6e(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof c$?new gQ(`command-not-found`,e.refusal===`timeout`?n6e(t):t6e(t)):e});if(o===null)return null;let s=V3e(t,o);await DQ(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 gQ(`install-failed`,c.kind===`incompatible`?$3e(c.detail):Q3e(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,kQ(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await i6e(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await a6e(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(kQ(t.env)===kQ(e.env))return null;try{await DQ(t)}catch(t){if(!(t instanceof gQ))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||AQ(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:H3e(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||AQ(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:U3e(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await g8e(t,this.opts.log,i);let a=await h8e(t,i).catch(()=>null);if(a!==null)return a;let o=await this.requestRuntimeConsent(e,t,n,r);if(o===`closed`||p$(e))return null;if(o!==`granted`)throw new c$(o,o===`timeout`?v5e(t):_5e(t));try{let n=await this.downloadRuntime(e,t);return p$(e)?null:n}catch(e){let n=JQ(t).displayName;throw new gQ(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=JQ(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 v8e(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,!p$(e)&&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=a$){let r=[],i=null,a;if(f5e(e.agentRef))a=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)a=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:de(),url:`${e}/mcp`,headers:[{name:N4e,value:`1`}]}),a=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=vQ();e==null?a=`none`:(r.push({name:de(),command:e.command,args:[...e.args],env:[{name:Ba,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),a=`stdio-entry-env`)}}if(e.browserInjected=!1,this.opts.agentBrowserTools?.()===!0){if(k6e(e.agentRef)){let t=await this.agentBrowserServer(e,n);typeof t==`string`?i=t:(r.push(t),e.browserInjected=!0)}else this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] browser tools are on, but only Claude Code and Codex chats get the browser`)}return a===`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:a},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:a,browserUnavailable:i}}noteBrowserUnavailable(e,t){if(e.browserInjected){e.browserNotice=null;return}t!==null&&t!==e.browserNotice&&(e.browserNotice=t,this.appendEvent(e,{kind:`browser_unavailable`,reason:t,ts:Date.now()}))}async agentBrowserServer(e,t){let n={threadId:e.info.threadId,agentId:e.agentRef.id},r=this.opts.globalDir;if(r===null)return this.opts.log.warn(n,`[acp-threads] browser tools are on but there is no per-user OpenKnowledge folder to start the browser from — the chat starts without a browser`),`failed`;let i=await this.resolveLoginShellPath().catch(()=>null),a=[],o=(this.opts.resolveBrowserNpx??F6e)([e.agentLaunchPath,i,vQ()],void 0,t=>!(iQ(this.opts.contentDir,t)||iQ(e.cwd,t))&&H6e(t)?!0:(a.push(t),!1));if(o===null)return this.opts.log.warn({...n,rejectedNpx:a},`[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser`),`no-node`;let s=e.agentNpmCache??null,c;try{c=B6e({npx:o,folders:await W6e(r,e.info.threadId),npmCache:s})}catch(e){return this.opts.log.warn({...n,err:e},`[acp-threads] preparing the browser failed — the chat starts without a browser`),`failed`}if(c===null)return this.opts.log.warn({...n,npx:o.npx},`[acp-threads] the npx found cannot start the browser — the chat starts without a browser`),`no-node`;let l=Math.min(this.browserInstallWaitMs,t),u,d=await Promise.race([this.installBrowserPackage(e,o,s),new Promise(e=>{u=setTimeout(()=>e(`still-installing`),l),u.unref?.()})]).finally(()=>clearTimeout(u));return d===`still-installing`?(this.opts.log.warn({...n,waitedMs:l},`[acp-threads] installing the browser is taking too long — the chat starts without a browser`),`failed`):d?(this.opts.log.info({...n,command:c.command,npx:o.npx},`[acp-threads] browser MCP injected`),c):`failed`}async installBrowserPackage(e,t,n,r=`cached`,i=`available`){let a={threadId:e.info.threadId,agentId:e.agentRef.id},o=this.opts.ensureBrowserPackage??D3e,s=L6e(t,n,r);try{return await o(s,b6e,this.opts.log,{reacquire:!0}),!0}catch(o){if(o instanceof gQ&&o.npxCacheEntry!==void 0&&i===`available`){let i={...a,npxCacheEntry:cQ(o.npxCacheEntry)},s=await this.removeStaleNpxCacheEntry(o.npxCacheEntry,i);if(s!==`kept`)return this.opts.log.warn(i,s===`removed`?`[acp-threads] cleared a stale browser npx cache entry; reinstalling the browser`:`[acp-threads] browser npx cache entry was cleared by another launch moments ago; reinstalling the browser without clearing it again`),this.installBrowserPackage(e,t,n,r,`spent`)}return r===`cached`?(this.opts.log.info({...a,err:o},`[acp-threads] installing the browser from npm's cached package data failed; installing it again with fresh package data`),this.installBrowserPackage(e,t,n,`fresh`,i)):(this.opts.log.warn({...a,err:o},`[acp-threads] installing the browser failed — the chat starts without a browser`),!1)}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=_Ke[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=a$,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await x5e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),p$(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=a$){e.info.availableCommands=null;let{servers:o,browserUnavailable:s}=await this.buildMcpServers(e,n,a);if(p$(e))return!1;this.noteBrowserUnavailable(e,s);try{let r=await t.agent.request(VC.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=C5e(n),e.confirmedContextWindow=b5e(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(y5e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,e),authMethods:n$(n.authMethods,e.terminalAuthBase)})}else{let n=await m$(e);this.emitStatus(e,`error`,`session setup failed: ${u$(t)}`,{reason:`session-setup`,agentMessage:u$(t),machineDetail:h$({primary:d$(t),tail:n})}),p$(e)||await this.teardownFailedAgent(e)}return!1}return p$(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),p$(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),p$(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new s$(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new s$(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`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 s$(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`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 s$(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,o$);if(o===null)throw new s$(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=C5e(u),r.confirmedContextWindow=b5e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d,browserUnavailable:f}=await this.buildMcpServers(r,u,o$);if(p$(r))throw new s$(`not-ready`,`thread closed during resume`);this.noteBrowserUnavailable(r,f);let p=u.agentCapabilities,m=p?.sessionCapabilities?.resume!=null,h;if(m)h=await l.agent.request(VC.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(p?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{h=await l.agent.request(VC.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 s$(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let g=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),_=r.info.modes?.currentModeId,v=h.modes;v!=null&&(r.info.modes=v);let y=h.configOptions;if(y!=null&&(r.info.configOptions=y),await this.applyInitialConfig(r,l,g,y==null),p$(r)||_!==void 0&&(await this.applyInitialMode(r,l,_,v==null),p$(r)))throw new s$(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:m?`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 x5e(t,r)),t instanceof s$?t:t instanceof gQ?new s$(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 s$(`resume-unsupported`,`couldn't resume the previous session: ${u$(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 s$(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new s$(`not-ready`,`a context window must be a positive number of tokens`);let r=O8e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new s$(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new s$(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new s$(`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;n.sessionBeforeRestart={sessionId:n.sessionId,contextWindow:n.info.contextWindow};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,o$),p$(n))throw new s$(`not-ready`,`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 s$(`spawn-failed`,f$(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof s$)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new s$(`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.endRestart(n),this.emitInfo(n)),n.sessionBeforeRestart=null,n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new s$(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new s$(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new s$(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0,t.sessionBeforeRestart={sessionId:t.sessionId,contextWindow:t.info.contextWindow};try{a3e(),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,o$,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new s$(`spawn-failed`,n)}if(p$(t))throw new s$(`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 s$(`spawn-failed`,f$(t)??`the agent failed to start`)}finally{this.threads.has(e)&&this.endRestart(t)&&this.emitInfo(t),t.resumeInFlight=!1}}terminalAuthLaunch(e,t){let n=this.mustGet(e),r=H8e(n.lastInit?.authMethods,n.terminalAuthBase,t);if(r===null)throw new s$(`not-ready`,`this agent offers no terminal sign-in by that name`);return r}async authenticateThread(e,t){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new s$(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new s$(`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 s$(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new s$(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new s$(`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(await n.drainStderr?.(),n.conn!==r)throw d5e();let t=e instanceof l5e?`the sign-in didn't complete in time — try again`:u$(e);throw n.child===null?new s$(`agent-exited`,t):(this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:g$(e,n),authMethods:n$(i.authMethods,n.terminalAuthBase)}),new s$(`not-ready`,t))}if(p$(n))throw new s$(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw d5e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,o$);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: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,n),authMethods:n$(i.authMethods,n.terminalAuthBase)}),t}}if(a!==!0)throw new s$(`not-ready`,f$(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 l5e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(VC.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(p$(e)){await this.stopFailedAgent(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 LQ(n,{graceMs:n5e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(sG(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 s$(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new s$(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new s$(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new s$(`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:[S5e(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 s$(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new s$(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new s$(`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=[S5e(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=Q8e(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 s$(`not-ready`,`the thread is closing`);let r=i$(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 s$(`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=`${a5e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=c5e(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;W4e(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 s$(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new u5e;return e.conn.agent.request(VC.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),!p$(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`),p$(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(y5e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,e),authMethods:n$(e.lastInit?.authMethods,e.terminalAuthBase)});return}let n=await m$(e);this.emitStatus(e,`error`,`prompt failed: ${u$(t)}`,{reason:`prompt`,agentMessage:u$(t),machineDetail:h$({primary:d$(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(VC.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 s$(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new s$(`not-ready`,`thread has no live agent session`);n.conn.agent.request(VC.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 s$(`not-ready`,`no such config option: ${t}`);if(!l$(e,n))throw new s$(`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 s$(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new s$(`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(VC.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=!1,o=new Set,s=t=>(e.info.configOptions??[]).find(e=>e.id===t),c=Object.keys(n).length+1,l=Object.entries(n);for(let u=0;l.length>0&&u<c;u+=1){let c=e=>s(e)?.category===`model`,d=!1,f=[...l].sort(([e],[t])=>Number(c(t))-Number(c(e)));for(let[n,c]of f){let l=s(n);if(l===void 0||(!r||u>0)&&l.currentValue===c||!l$(l,c))continue;let f=typeof c==`boolean`?{sessionId:i,configId:n,type:`boolean`,value:c}:{sessionId:i,configId:n,value:c};try{let r=await t.agent.request(VC.agent.session.setConfigOption,f);e.info.configOptions=r.configOptions,o.delete(n),a=!0,d=!0}catch(t){o.add(n),this.opts.log.info({err:t,threadId:e.info.threadId,configId:n,pass:u},`[acp-threads] initial config apply attempt failed`)}if(e.closed)return}if(!d)break;l=Object.entries(n).filter(([e,t])=>s(e)?.currentValue!==t)}o.size>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:[...o],sessionStateUnknown:r},`[acp-threads] some remembered config options could not be applied to the new session`);let u=[],d=[];for(let[e,t]of Object.entries(n)){if(o.has(e))continue;let n=s(e);n===void 0?u.push(e):n.currentValue!==t&&d.push(e)}(u.length>0||d.length>0)&&this.opts.log.info({threadId:e.info.threadId,missingConfigIds:u,unmatchedConfigIds:d,sessionStateUnknown:r},`[acp-threads] some remembered config options did not come back in the new session`),a&&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(VC.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`&&l$(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(VC.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.offeredOptionIds.has(n.optionId)?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}setChatGrant(e,t,n){let r=this.mustGet(e);r.chatGrants.has(t)!==n&&(n?r.chatGrants.add(t):r.chatGrants.delete(t),r.info.chatGrants=r.chatGrants.size>0?[...r.chatGrants]:void 0,this.opts.log.info({threadId:e,agentId:r.info.agent.id,grant:t,enabled:n},`[acp-threads] chat grant changed`),this.emitInfo(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await LQ(r,{graceMs:t?.killGraceMs??t5e})||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(sG(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 s$(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new s$(`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.globalDir!==null&&await G6e(this.opts.globalDir,e).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] removing browser folders failed`)}),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:n5e})))}async handlePermissionRequest(e,t,n,r){this.touchTurnActivity(e);let i=w5e(await E5e(e,t,r,this.opts.log),t),a={...t,...t.title==null&&i.title!=null?{title:i.title}:{},...t.rawInput===void 0&&i.rawInput!==void 0?{rawInput:i.rawInput}:{}},o=N6e(i,{requestMeta:r,browserInjected:e.browserInjected,agentId:e.info.agent.id}),s=this.opts.permissions.decide(e.info.agent.id,t,n,o,e.chatGrants,this.opts.autoApproveOkTools?.()??!0);if(s.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:s.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:s.auto.optionId}}}let c=crypto.randomUUID(),l=dKe(o,n);return this.appendEvent(e,{kind:`permission_request`,requestId:c,toolCall:a,options:l,...UGe(t)===null?{}:{readOnlyShell:!0},ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(n=>{let r=setTimeout(()=>{e.pendingPermissions.delete(c),this.appendEvent(e,{kind:`permission_resolved`,requestId:c,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),n({outcome:{outcome:`cancelled`}})},6e5);r.unref?.(),e.pendingPermissions.set(c,{timer:r,offeredOptionIds:new Set(l.map(e=>e.optionId)),resolve:r=>{if(r.outcome.outcome===`selected`){let n=r.outcome.optionId,i=l.find(e=>e.optionId===n);i!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,i,o)}n(r)}})})}handleSessionUpdate(e,t){this.touchTurnActivity(e);let n=t.update;if(e.browserInjected&&(n.sessionUpdate===`tool_call`||n.sessionUpdate===`tool_call_update`)&&T5e(e,n),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:cGe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await hc(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await hc(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
1046
+ `))n.trim()!==``&&e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e))}),c.on(`error`,t=>{y()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),c.on(`exit`,(t,n)=>{if(e.child!==c)return;let r=r5e.has(e.info.status);e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),s.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),m$(e).then(i=>{if(e.terminals!==s||p$(e)||y())return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let a=`agent exited (${n??t??`unknown`})`;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:i},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,a,r?$6e({exitCode:t,signal:n,tail:i}):void 0),this.failPendingPermissions(e)}).catch(t=>{this.opts.log.error({err:t,threadId:e.info.threadId},`[acp-threads] exit diagnostics failed`)})}),c.stdin===null||c.stdout===null)throw new s$(`spawn-failed`,`agent process has no stdio`);let b=mSe(_ae.toWeb(c.stdin),xc.toWeb(c.stdout)),x=KSe({name:`open-knowledge`}).onRequest(VC.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options,t.params._meta)).onRequest(VC.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(VC.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(VC.client.terminal.create,t=>(this.touchTurnActivity(e),s.create(t.params))).onRequest(VC.client.terminal.output,t=>(this.touchTurnActivity(e),s.output(t.params.terminalId))).onRequest(VC.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),s.waitForExit(t.params.terminalId))).onRequest(VC.client.terminal.kill,async t=>(this.touchTurnActivity(e),await s.kill(t.params.terminalId),{})).onRequest(VC.client.terminal.release,async t=>(this.touchTurnActivity(e),await s.release(t.params.terminalId),{})).onNotification(VC.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(b);e.conn=x;let S=async t=>{if(await d(),e.conn!==x||y()||(t!==null&&this.opts.log.warn({err:t.err,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),e.info.status===`exited`||e.info.status===`error`))return;if(t===null){this.emitStatus(e,`exited`,`agent connection closed`);return}let{err:n}=t;this.emitStatus(e,`error`,`agent connection failed: ${n instanceof Error?n.message:String(n)}`)};x.closed.then(()=>S(null),e=>S({err:e}));let C;try{C=await x.agent.request(VC.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:rQ},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,...this.opts.terminalAuthAvailable===!0?{auth:{terminal:!0}}:{},session:{configOptions:{boolean:{}}}}})}catch(n){if(this.opts.log.warn({err:n,threadId:e.info.threadId},`[acp-threads] initialize failed`),a.kind===`npx`||a.kind===`uvx`){await d();let e=h3e(a,f,n);if(e!==null)throw e}let o=g===`npx`&&i===`available`?xQ(p):null;if(o!==null&&await this.clearStaleNpxCacheEntry(e,o)||g===`npx`&&i===`available`&&y3e(p)&&await this.discardRefusedNpxLaunch(e,a))return _=!0,this.connectAgent(e,t,`reacquire`,r,`spent`);throw new s$(`spawn-failed`,`initialize failed: ${u$(n)}`)}finally{m=!1,f=``,p=``}return p$(e)?null:(e.lastInit=C,e.info.promptCapabilities=C.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:x,init:C,launch:a})}async discardRefusedNpxLaunch(e,t){return!p$(e)&&(this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,package:S3e(t.args)},`[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch`),await this.discardFailedLaunch(e),!p$(e))}async clearStaleNpxCacheEntry(e,t){let n={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:cQ(t)},r=await this.removeStaleNpxCacheEntry(t,n);return r===`kept`?!1:p$(e)?(r===`removed`&&this.opts.log.warn(n,`[acp-threads] cleared a stale npx cache entry; the thread was closed, so the agent is not relaunched`),!1):(this.opts.log.warn(n,r===`recently-removed`?`[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again`:`[acp-threads] cleared a stale npx cache entry; relaunching the agent`),await this.discardFailedLaunch(e),!p$(e))}async removeStaleNpxCacheEntry(e,t){let n=this.npxCacheClears.get(e);if(n!==void 0&&Date.now()-n<3e5)return`recently-removed`;let r=Date.now();this.npxCacheClears.set(e,r);let i=()=>{this.npxCacheClears.get(e)===r&&this.npxCacheClears.delete(e)};for(let n of[`package.json`,`concurrency.lock`]){let r=await yc(H(e,n)).then(()=>`present`,e=>e.code??`unknown`);if(r!==`ENOENT`)return this.opts.log.warn({...t,file:n,code:r},`[acp-threads] leaving an npx cache entry alone`),i(),`kept`}try{await BG(e,{recursive:!0,force:!0})}catch(e){return this.opts.log.warn({err:e,...t},`[acp-threads] stale npx cache entry could not be cleared`),i(),`kept`}return`removed`}async discardFailedLaunch(e){e.drainStderr=null,e.stderrTail=[],await this.stopAgentProcess(e,`[acp-threads] terminal cleanup before relaunch failed`)}async stopAgentProcess(e,t){let n=e.child,r=e.conn,i=e.terminals;e.child=null,e.conn=null,e.terminals=null;try{r?.close()}catch{}await i?.disposeAll().catch(n=>{this.opts.log.warn({err:n,threadId:e.info.threadId},t)}),n!==null&&await LQ(n,{graceMs:t5e})}async ensureLaunchable(e,t,n){let r;try{await DQ(t),r=await this.withLoginShellPathIfEligible(t)}catch(i){if(!(i instanceof gQ)||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 p$(e)?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(p$(e))return null;if(r===null)return t;if(r.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(p$(e))return null;if(kQ(n.env)!==kQ(t.env))try{await DQ(n);let t=await this.probeInterpreterOnce(n);if(p$(e))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 gQ)||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 gQ(`command-not-found`,i?o6e(t,r.detail):Z3e(t,r.detail)),o=new gQ(`command-not-found`,i?s6e(t,r.detail):r6e(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=s8e(t.kind);if(!f8e(a))throw n;let o=await this.provideManagedRuntime(e,a,r===void 0?`missing`:`broken`,i).catch(e=>{throw r!==void 0&&e instanceof c$?e.refusal===`timeout`?r.expired:r.declined:e});if(o===null)return null;let s=V3e(t,o);await DQ(s);let c=await this.probeInterpreterOnce(s);if(c===null)return s;if(c.kind===`incompatible`)throw new gQ(`install-failed`,$3e(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 _8e(n,this.opts.log,this.opts.runtimeInstall?.root))throw new gQ(`install-failed`,e6e(t,r));let o=await this.provideManagedRuntime(e,n,`damaged`,i).catch(e=>{throw e instanceof c$?new gQ(`command-not-found`,e.refusal===`timeout`?n6e(t):t6e(t)):e});if(o===null)return null;let s=V3e(t,o);await DQ(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 gQ(`install-failed`,c.kind===`incompatible`?$3e(c.detail):Q3e(s,c.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,kQ(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await i6e(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await a6e(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(kQ(t.env)===kQ(e.env))return null;try{await DQ(t)}catch(t){if(!(t instanceof gQ))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||AQ(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:H3e(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||AQ(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:U3e(e,t)}async provideManagedRuntime(e,t,n,r){let i=this.opts.runtimeInstall?.root;await g8e(t,this.opts.log,i);let a=await h8e(t,i).catch(()=>null);if(a!==null)return a;let o=await this.requestRuntimeConsent(e,t,n,r);if(o===`closed`||p$(e))return null;if(o!==`granted`)throw new c$(o,o===`timeout`?v5e(t):_5e(t));try{let n=await this.downloadRuntime(e,t);return p$(e)?null:n}catch(e){let n=JQ(t).displayName;throw new gQ(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=JQ(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 v8e(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,!p$(e)&&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=a$){let r=[],i=null,a;if(f5e(e.agentRef))a=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)a=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:de(),url:`${e}/mcp`,headers:[{name:N4e,value:`1`}]}),a=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=vQ();e==null?a=`none`:(r.push({name:de(),command:e.command,args:[...e.args],env:[{name:Ba,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),a=`stdio-entry-env`)}}if(e.browserInjected=!1,this.opts.agentBrowserTools?.()===!0){if(k6e(e.agentRef)){let t=await this.agentBrowserServer(e,n);typeof t==`string`?i=t:(r.push(t),e.browserInjected=!0)}else this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] browser tools are on, but only Claude Code and Codex chats get the browser`)}return a===`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:a},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:a,browserUnavailable:i}}noteBrowserUnavailable(e,t){if(e.browserInjected){e.browserNotice=null;return}t!==null&&t!==e.browserNotice&&(e.browserNotice=t,this.appendEvent(e,{kind:`browser_unavailable`,reason:t,ts:Date.now()}))}async agentBrowserServer(e,t){let n={threadId:e.info.threadId,agentId:e.agentRef.id},r=this.opts.globalDir;if(r===null)return this.opts.log.warn(n,`[acp-threads] browser tools are on but there is no per-user OpenKnowledge folder to start the browser from — the chat starts without a browser`),`failed`;let i=await this.resolveLoginShellPath().catch(()=>null),a=[],o=(this.opts.resolveBrowserNpx??F6e)([e.agentLaunchPath,i,vQ()],void 0,t=>!(iQ(this.opts.contentDir,t)||iQ(e.cwd,t))&&H6e(t)?!0:(a.push(t),!1));if(o===null)return this.opts.log.warn({...n,rejectedNpx:a},`[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser`),`no-node`;let s=e.agentNpmCache??null,c;try{c=B6e({npx:o,folders:await W6e(r,e.info.threadId),npmCache:s})}catch(e){return this.opts.log.warn({...n,err:e},`[acp-threads] preparing the browser failed — the chat starts without a browser`),`failed`}if(c===null)return this.opts.log.warn({...n,npx:o.npx},`[acp-threads] the npx found cannot start the browser — the chat starts without a browser`),`no-node`;let l=Math.min(this.browserInstallWaitMs,t),u,d=await Promise.race([this.installBrowserPackage(e,o,s),new Promise(e=>{u=setTimeout(()=>e(`still-installing`),l),u.unref?.()})]).finally(()=>clearTimeout(u));return d===`still-installing`?(this.opts.log.warn({...n,waitedMs:l},`[acp-threads] installing the browser is taking too long — the chat starts without a browser`),`failed`):d?(this.opts.log.info({...n,command:c.command,npx:o.npx},`[acp-threads] browser MCP injected`),c):`failed`}async installBrowserPackage(e,t,n,r=`cached`,i=`available`){let a={threadId:e.info.threadId,agentId:e.agentRef.id},o=this.opts.ensureBrowserPackage??D3e,s=L6e(t,n,r);try{return await o(s,b6e,this.opts.log,{reacquire:!0}),!0}catch(o){if(o instanceof gQ&&o.npxCacheEntry!==void 0&&i===`available`){let i={...a,npxCacheEntry:cQ(o.npxCacheEntry)},s=await this.removeStaleNpxCacheEntry(o.npxCacheEntry,i);if(s!==`kept`)return this.opts.log.warn(i,s===`removed`?`[acp-threads] cleared a stale browser npx cache entry; reinstalling the browser`:`[acp-threads] browser npx cache entry was cleared by another launch moments ago; reinstalling the browser without clearing it again`),this.installBrowserPackage(e,t,n,r,`spent`)}return r===`cached`?(this.opts.log.info({...a,err:o},`[acp-threads] installing the browser from npm's cached package data failed; installing it again with fresh package data`),this.installBrowserPackage(e,t,n,`fresh`,i)):(this.opts.log.warn({...a,err:o},`[acp-threads] installing the browser failed — the chat starts without a browser`),!1)}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=_Ke[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=a$,i=`reuse`){let a;try{a=await this.connectAgent(e,n,i,r)}catch(t){let n=await x5e(t,e);this.emitStatus(e,`error`,n.agentMessage,n),p$(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=a$){e.info.availableCommands=null;let{servers:o,browserUnavailable:s}=await this.buildMcpServers(e,n,a);if(p$(e))return!1;this.noteBrowserUnavailable(e,s);try{let r=await t.agent.request(VC.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=r.sessionId,e.info.resumable=C5e(n),e.confirmedContextWindow=b5e(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(y5e(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,e),authMethods:n$(n.authMethods,e.terminalAuthBase)})}else{let n=await m$(e);this.emitStatus(e,`error`,`session setup failed: ${u$(t)}`,{reason:`session-setup`,agentMessage:u$(t),machineDetail:h$({primary:d$(t),tail:n})}),p$(e)||await this.teardownFailedAgent(e)}return!1}return p$(e)||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),p$(e))||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),p$(e))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new s$(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new s$(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`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 s$(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new s$(`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 s$(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s,`reuse`,o$);if(o===null)throw new s$(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o;r.info.resumable=C5e(u),r.confirmedContextWindow=b5e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:d,browserUnavailable:f}=await this.buildMcpServers(r,u,o$);if(p$(r))throw new s$(`not-ready`,`thread closed during resume`);this.noteBrowserUnavailable(r,f);let p=u.agentCapabilities,m=p?.sessionCapabilities?.resume!=null,h;if(m)h=await l.agent.request(VC.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(p?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{h=await l.agent.request(VC.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 s$(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let g=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),_=r.info.modes?.currentModeId,v=h.modes;v!=null&&(r.info.modes=v);let y=h.configOptions;if(y!=null&&(r.info.configOptions=y),await this.applyInitialConfig(r,l,g,y==null),p$(r)||_!==void 0&&(await this.applyInitialMode(r,l,_,v==null),p$(r)))throw new s$(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:m?`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 x5e(t,r)),t instanceof s$?t:t instanceof gQ?new s$(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 s$(`resume-unsupported`,`couldn't resume the previous session: ${u$(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 s$(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(!Number.isFinite(t)||t<=0)throw new s$(`not-ready`,`a context window must be a positive number of tokens`);let r=O8e({agentId:n.agentRef.id,archived:n.info.archived===!0,turnActive:n.turnActive,hasStartedWork:this.hasStartedWork(e)});if(r.kind===`unsupported`)throw new s$(`not-ready`,`this agent takes its context window from the model`);if(r.kind===`needs-new-chat`)throw new s$(`not-ready`,`start a new chat to change the context window`);if(n.resumeInFlight)throw new s$(`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;n.sessionBeforeRestart={sessionId:n.sessionId,resumable:n.info.resumable,contextWindow:n.info.contextWindow};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,o$),p$(n))throw new s$(`not-ready`,`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 s$(`spawn-failed`,f$(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof s$)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new s$(`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.endRestart(n),this.emitInfo(n)),n.sessionBeforeRestart=null,n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new s$(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new s$(`not-ready`,`this thread did not fail to start`);if(t.resumeInFlight)throw new s$(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0,t.sessionBeforeRestart={sessionId:t.sessionId,resumable:t.info.resumable,contextWindow:t.info.contextWindow};try{a3e(),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,o$,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new s$(`spawn-failed`,n)}if(p$(t))throw new s$(`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 s$(`spawn-failed`,f$(t)??`the agent failed to start`)}finally{this.threads.has(e)&&this.endRestart(t)&&this.emitInfo(t),t.resumeInFlight=!1}}terminalAuthLaunch(e,t){let n=this.mustGet(e),r=H8e(n.lastInit?.authMethods,n.terminalAuthBase,t);if(r===null)throw new s$(`not-ready`,`this agent offers no terminal sign-in by that name`);return r}async authenticateThread(e,t){if(this.destroyed)throw new s$(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new s$(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new s$(`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 s$(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new s$(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new s$(`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(await n.drainStderr?.(),n.conn!==r)throw d5e();let t=e instanceof l5e?`the sign-in didn't complete in time — try again`:u$(e);throw n.child===null?new s$(`agent-exited`,t):(this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:g$(e,n),authMethods:n$(i.authMethods,n.terminalAuthBase)}),new s$(`not-ready`,t))}if(p$(n))throw new s$(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw d5e();let a=await this.openSession(n,r,i,n.launchSettings,`report`,o$);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: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,n),authMethods:n$(i.authMethods,n.terminalAuthBase)}),t}}if(a!==!0)throw new s$(`not-ready`,f$(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 l5e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(VC.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(p$(e)){await this.stopFailedAgent(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 LQ(n,{graceMs:n5e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(sG(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 s$(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new s$(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new s$(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new s$(`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:[S5e(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 s$(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new s$(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new s$(`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=[S5e(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=Q8e(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 s$(`not-ready`,`the thread is closing`);let r=i$(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 s$(`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=`${a5e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=c5e(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;W4e(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 s$(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new u5e;return e.conn.agent.request(VC.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),!p$(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`),p$(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(y5e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${u$(t)}`,{reason:`auth-required`,agentMessage:u$(t),machineDetail:g$(t,e),authMethods:n$(e.lastInit?.authMethods,e.terminalAuthBase)});return}let n=await m$(e);this.emitStatus(e,`error`,`prompt failed: ${u$(t)}`,{reason:`prompt`,agentMessage:u$(t),machineDetail:h$({primary:d$(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(VC.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 s$(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new s$(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new s$(`not-ready`,`thread has no live agent session`);n.conn.agent.request(VC.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 s$(`not-ready`,`no such config option: ${t}`);if(!l$(e,n))throw new s$(`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 s$(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new s$(`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(VC.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=!1,o=new Set,s=t=>(e.info.configOptions??[]).find(e=>e.id===t),c=Object.keys(n).length+1,l=Object.entries(n);for(let u=0;l.length>0&&u<c;u+=1){let c=e=>s(e)?.category===`model`,d=!1,f=[...l].sort(([e],[t])=>Number(c(t))-Number(c(e)));for(let[n,c]of f){let l=s(n);if(l===void 0||(!r||u>0)&&l.currentValue===c||!l$(l,c))continue;let f=typeof c==`boolean`?{sessionId:i,configId:n,type:`boolean`,value:c}:{sessionId:i,configId:n,value:c};try{let r=await t.agent.request(VC.agent.session.setConfigOption,f);e.info.configOptions=r.configOptions,o.delete(n),a=!0,d=!0}catch(t){o.add(n),this.opts.log.info({err:t,threadId:e.info.threadId,configId:n,pass:u},`[acp-threads] initial config apply attempt failed`)}if(e.closed)return}if(!d)break;l=Object.entries(n).filter(([e,t])=>s(e)?.currentValue!==t)}o.size>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:[...o],sessionStateUnknown:r},`[acp-threads] some remembered config options could not be applied to the new session`);let u=[],d=[];for(let[e,t]of Object.entries(n)){if(o.has(e))continue;let n=s(e);n===void 0?u.push(e):n.currentValue!==t&&d.push(e)}(u.length>0||d.length>0)&&this.opts.log.info({threadId:e.info.threadId,missingConfigIds:u,unmatchedConfigIds:d,sessionStateUnknown:r},`[acp-threads] some remembered config options did not come back in the new session`),a&&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(VC.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`&&l$(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(VC.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.offeredOptionIds.has(n.optionId)?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}setChatGrant(e,t,n){let r=this.mustGet(e);r.chatGrants.has(t)!==n&&(n?r.chatGrants.add(t):r.chatGrants.delete(t),r.info.chatGrants=r.chatGrants.size>0?[...r.chatGrants]:void 0,this.opts.log.info({threadId:e,agentId:r.info.agent.id,grant:t,enabled:n},`[acp-threads] chat grant changed`),this.emitInfo(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await LQ(r,{graceMs:t?.killGraceMs??t5e})||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(sG(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 s$(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new s$(`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.globalDir!==null&&await G6e(this.opts.globalDir,e).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] removing browser folders failed`)}),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:n5e})))}async handlePermissionRequest(e,t,n,r){this.touchTurnActivity(e);let i=w5e(await E5e(e,t,r,this.opts.log),t),a={...t,...t.title==null&&i.title!=null?{title:i.title}:{},...t.rawInput===void 0&&i.rawInput!==void 0?{rawInput:i.rawInput}:{}},o=N6e(i,{requestMeta:r,browserInjected:e.browserInjected,agentId:e.info.agent.id}),s=this.opts.permissions.decide(e.info.agent.id,t,n,o,e.chatGrants,this.opts.autoApproveOkTools?.()??!0);if(s.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:s.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:s.auto.optionId}}}let c=crypto.randomUUID(),l=dKe(o,n);return this.appendEvent(e,{kind:`permission_request`,requestId:c,toolCall:a,options:l,...UGe(t)===null?{}:{readOnlyShell:!0},ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(n=>{let r=setTimeout(()=>{e.pendingPermissions.delete(c),this.appendEvent(e,{kind:`permission_resolved`,requestId:c,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),n({outcome:{outcome:`cancelled`}})},6e5);r.unref?.(),e.pendingPermissions.set(c,{timer:r,offeredOptionIds:new Set(l.map(e=>e.optionId)),resolve:r=>{if(r.outcome.outcome===`selected`){let n=r.outcome.optionId,i=l.find(e=>e.optionId===n);i!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,i,o)}n(r)}})})}handleSessionUpdate(e,t){this.touchTurnActivity(e);let n=t.update;if(e.browserInjected&&(n.sessionUpdate===`tool_call`||n.sessionUpdate===`tool_call_update`)&&T5e(e,n),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:cGe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await hc(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await hc(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
1047
1047
  `),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
1048
- `)}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=NKe(t);try{t.dc.document.transact(()=>{let r=qZ(t.dc.document);KZ(t.dc.document,n,`replace`,i,void 0,WZ(t),a);let o=Lc(r,qZ(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 JJ?(YJ(e,`acp-fs-write`),new zC(-32009,wQe,{type:qJ,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(()=>NG);await e(V(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return h5e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new s$(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&fGe(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>e5e){let t=e.events.length-e5e;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(p$(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:cQ(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:cQ(r.machineDetail)},`[acp-threads] status suppressed after thread close`);return}this.recordTerminalStatus(e,t,n,r)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),t===`error`&&r!==void 0&&e8e(r.reason)&&r8e(this.opts.localDir,{at:new Date,threadId:e.info.threadId,agentId:e.info.agent.id,agentSource:e.info.agent.source,reason:r.reason,detail:n,machineDetail:r.machineDetail}).catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] launch failure log write failed`)}),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){e.sessionId=null,e.info.contextWindow=null,await this.stopFailedAgent(e)}endRestart(e){let t=e.sessionBeforeRestart;return e.sessionBeforeRestart=null,t===null||e.sessionId!==null?!1:(p$(e)&&(e.sessionId=t.sessionId,e.info.contextWindow=t.contextWindow),!0)}async stopFailedAgent(e){this.failPendingPermissions(e),this.failPendingConsents(e),e.lastInit=null,await this.stopAgentProcess(e,`[acp-threads] terminal cleanup on failed-agent teardown failed`)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,stalledSince:i,chatGrants:a,...o}=e.info;return{version:1,info:o,sessionId:e.sessionId??e.sessionBeforeRestart?.sessionId??null,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName,contextWindow:e.confirmedContextWindow??null,browserNotice:e.browserNotice}}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=je(e.info.agent.id),i=ve[r]??zr(e.agentSessionId);n.setPresence(sG(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 h5e(e,t,n){let r=await _c(e),i=Ms(js(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await _c(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||js(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(`/`);!cq(e)&&!lq(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 g5e(e){let t=e.info.status===`error`?`error`:`exited`;return{confirmedContextWindow:e.contextWindow??null,launchSettings:e.contextWindow==null?void 0:{contextWindow:e.contextWindow},info:{...e.info,contextWindow:null,status:t,archived:!0,resumable:e.info.resumable!==!1&&e.sessionId!==null,queue:void 0,steer:void 0,signInOutput:void 0,chatGrants:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,terminalAuthBase:null,sessionId:e.sessionId,sessionBeforeRestart:null,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,reportedToolCalls:new Map,toolCallReportWaiters:new Map,browserInjected:!1,browserNotice:e.browserNotice??null,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:Date.now(),unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1,projectSkill:null,chatGrants:new Set}}function l$(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 _5e(e){let t=JQ(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 v5e(e){let t=JQ(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 y5e(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 u$(e){return e instanceof Error?e.message:String(e)}function d$(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return cQ(JSON.stringify(t)).slice(0,300)}catch{return}}function b5e(e){return $Q(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function f$(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 x5e(e,t){return{reason:`connect`,agentMessage:e instanceof gQ||e instanceof s$?e.message:String(e),machineDetail:h$({primary:e instanceof gQ?e.machineDetail:void 0,tail:await m$(t)})}}function S5e(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 p$(e){return e.closed||e.info.archived===!0}async function m$(e){let t=e.stderrTail;await e.drainStderr?.();let n=cQ(t.join(`
1048
+ `)}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=NKe(t);try{t.dc.document.transact(()=>{let r=qZ(t.dc.document);KZ(t.dc.document,n,`replace`,i,void 0,WZ(t),a);let o=Lc(r,qZ(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 JJ?(YJ(e,`acp-fs-write`),new zC(-32009,wQe,{type:qJ,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(()=>NG);await e(V(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return h5e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new s$(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&fGe(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>e5e){let t=e.events.length-e5e;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(p$(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:cQ(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:cQ(r.machineDetail)},`[acp-threads] status suppressed after thread close`);return}this.recordTerminalStatus(e,t,n,r)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),t===`error`&&r!==void 0&&e8e(r.reason)&&r8e(this.opts.localDir,{at:new Date,threadId:e.info.threadId,agentId:e.info.agent.id,agentSource:e.info.agent.source,reason:r.reason,detail:n,machineDetail:r.machineDetail}).catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] launch failure log write failed`)}),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){e.sessionId=null,e.info.resumable=!1,e.info.contextWindow=null,await this.stopFailedAgent(e)}endRestart(e){let t=e.sessionBeforeRestart;return e.sessionBeforeRestart=null,t===null||e.sessionId!==null?!1:(p$(e)&&(e.sessionId=t.sessionId,e.info.resumable=t.resumable,e.info.contextWindow=t.contextWindow),!0)}async stopFailedAgent(e){this.failPendingPermissions(e),this.failPendingConsents(e),e.lastInit=null,await this.stopAgentProcess(e,`[acp-threads] terminal cleanup on failed-agent teardown failed`)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,stalledSince:i,chatGrants:a,...o}=e.info,s=e.sessionId===null?e.sessionBeforeRestart:null;return{version:1,info:s===null?o:{...o,resumable:s.resumable},sessionId:e.sessionId??s?.sessionId??null,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName,contextWindow:e.confirmedContextWindow??null,browserNotice:e.browserNotice}}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=je(e.info.agent.id),i=ve[r]??zr(e.agentSessionId);n.setPresence(sG(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 h5e(e,t,n){let r=await _c(e),i=Ms(js(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await _c(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||js(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(`/`);!cq(e)&&!lq(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 g5e(e){let t=e.info.status===`error`?`error`:`exited`;return{confirmedContextWindow:e.contextWindow??null,launchSettings:e.contextWindow==null?void 0:{contextWindow:e.contextWindow},info:{...e.info,contextWindow:null,status:t,archived:!0,resumable:e.info.resumable!==!1&&e.sessionId!==null,queue:void 0,steer:void 0,signInOutput:void 0,chatGrants:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,terminalAuthBase:null,sessionId:e.sessionId,sessionBeforeRestart:null,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,reportedToolCalls:new Map,toolCallReportWaiters:new Map,browserInjected:!1,browserNotice:e.browserNotice??null,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],drainStderr:null,authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,stallTimer:null,turnStartedAt:null,agentActivityAt:Date.now(),unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1,projectSkill:null,chatGrants:new Set}}function l$(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 _5e(e){let t=JQ(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 v5e(e){let t=JQ(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 y5e(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 u$(e){return e instanceof Error?e.message:String(e)}function d$(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return cQ(JSON.stringify(t)).slice(0,300)}catch{return}}function b5e(e){return $Q(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function f$(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 x5e(e,t){return{reason:`connect`,agentMessage:e instanceof gQ||e instanceof s$?e.message:String(e),machineDetail:h$({primary:e instanceof gQ?e.machineDetail:void 0,tail:await m$(t)})}}function S5e(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 p$(e){return e.closed||e.info.archived===!0}async function m$(e){let t=e.stderrTail;await e.drainStderr?.();let n=cQ(t.join(`
1049
1049
  `)).slice(-16e3);return n===``?void 0:n}function h$({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,sQ);let n=Math.min(t.length,1024),r=sQ-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=sQ-i.length-1;return`${i}\n${t.slice(-a)}`}function g$(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
1050
1050
  `);return h$({primary:d$(e),tail:n})}function C5e(e){let t=e.agentCapabilities;return t?.sessionCapabilities?.resume!=null||t?.loadSession===!0}function w5e(e,t){let n=qS(e?._meta),r=qS(t._meta);return{title:t.title??e?.title??null,kind:t.kind??e?.kind??null,rawInput:t.rawInput??e?.rawInput,...n!==null||r!==null?{_meta:{...n,...r}}:{}}}function T5e(e,t){let n=w5e(e.reportedToolCalls.get(t.toolCallId),t);if(e.reportedToolCalls.delete(t.toolCallId),e.reportedToolCalls.set(t.toolCallId,n),e.reportedToolCalls.size>256){let t=e.reportedToolCalls.keys().next().value;t!==void 0&&e.reportedToolCalls.delete(t)}let r=e.toolCallReportWaiters.get(t.toolCallId);if(r!==void 0){e.toolCallReportWaiters.delete(t.toolCallId);for(let e of r)e()}}async function E5e(e,t,n,r){let i=t.toolCallId,a=e.reportedToolCalls.get(i);return a!==void 0||!e.browserInjected||!P6e(t,n,e.info.agent.id)?a:(await new Promise(t=>{let n=e.toolCallReportWaiters.get(i)??[],a=()=>{clearTimeout(o);let n=(e.toolCallReportWaiters.get(i)??[]).filter(e=>e!==a);n.length>0?e.toolCallReportWaiters.set(i,n):e.toolCallReportWaiters.delete(i),t()},o=setTimeout(()=>{r.warn({threadId:e.info.threadId,toolCallId:i},`[acp-threads] no tool call report arrived for a permission request in a chat with the browser; asking with no option to always allow it`),a()},1e3);o.unref?.(),n.push(a),e.toolCallReportWaiters.set(i,n)}),e.reportedToolCalls.get(i))}function D5e(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(O5e(e,t,n));e.on(`message`,e=>{let s=ZSe(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`terminal_auth_launch`:{let e=t.terminalAuthLaunch(s.threadId,s.methodId);i({op:`terminal_auth_launch_ready`,reqId:s.reqId,launch: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`set_chat_grant`:t.setChatGrant(s.threadId,s.grant,s.enabled);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 s$?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 s$)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 O5e(e,t,n){return{op:`error`,code:e,message:t,...n}}var k5e=class{hocuspocus;log=q(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){cG(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){cG(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(_i);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),A5e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function A5e(e){return e?.awareness??null}var j5e=class{hocuspocus;log=q(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!cG(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(!cG(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(!cG(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(!cG(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 nYe(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(_i);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),M5e(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function M5e(e){return e?.awareness??null}function N5e(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 _$(e){return{probes:await Ine({env:e.env,resolve:N5e(e)}),detection:_}}const P5e=Ec(rae);function v$(e){return H(ZS(e),Iee)}async function y$(e,t){let n=v$(e);await HG(V(n),{recursive:!0});try{return await nC(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const F5e={warn:(e,t)=>q(`skills`).warn(e,t)};async function b$(e,t=F5e){let n=v$(e),r;try{r=await P5e(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,Vc.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=Di.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 x$(e,t){let n=Di.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=v$(e);await HG(V(r),{recursive:!0});let i=(0,Vc.parseDocument)(``);i.contents=i.createNode(n.data),await eC(r,i.toString(),{fs:$G})}async function S$(e,t,n){let r=await b$(e,n);return r===null?null:r.targets[t]?.version??null}async function I5e(e,t,n){let r=await b$(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function C$(e,t,n,r,i){if(!mie.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await y$(e,async()=>{let a=await b$(e,i)??v(),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 x$(e,{...a,targets:{...a.targets,[t]:l}})})}async function L5e(e,t,n){let r=(await b$(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function R5e(e,t,n,r){await y$(e,async()=>{let i=await b$(e,r)??v();await x$(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function z5e(e,t){let n=await b$(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function B5e(e,t,n){t.length!==0&&await y$(e,async()=>{let r=await b$(e,n)??v(),i=new Set([...r.installsReported??[],...t]);await x$(e,{...r,installsReported:[...i].sort()})})}async function V5e(e,t,n){t.length!==0&&await y$(e,async()=>{let r=await b$(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 x$(e,{...r,installsReported:a})})}async function w$(){let e=new URL(`../package.json`,import.meta.url),t=await P5e(Ls(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 H5e(e,t){let[n,r]=await Promise.all([w$(),U5e(e,t)]);return{currentVersion:n,targets:r}}async function U5e(e,t=F5e){let n=null;try{n=await b$(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:v$(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=Wre.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const W5e=q(`agent-registry-apply`);function G5e(e){return{probes:hre(e),detection:_}}const K5e=()=>({action:`skipped-unsupported`,errorId:`no-writer`});async function q5e(e,t){try{return await e()}catch(e){return W5e.warn({err:e},`host snapshot failed; claiming nothing`),G5e(t)}}async function J5e(e,t){let n=await q5e(t.snapshot,t.env),r=Are({probes:n.probes,detection:n.detection}),i=Uee(e.map(e=>({satisfierId:e?.satisfierId,desired:e?.desired})),r),a=await Kte(i,t.execute??K5e),{decisionHome:o}=t,s=Y5e(a),c=s===`installed`?!0:s===`removed`&&t.userSkillPresentAnywhere!==void 0&&!t.userSkillPresentAnywhere(o)?!1:null;return c!==null&&await R5e(o,XZ.discovery,c).catch(e=>{W5e.warn({err:e},`user-skill decision not recorded`)}),{report:a,snapshot:await q5e(t.snapshot,t.env)}}function Y5e(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 X5e=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function T$(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(X5e,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function E$(e,t){let n=T$(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=PKe(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:lG(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}}const Z5e=new Set([`GET`,`HEAD`,`OPTIONS`]);function Q5e(e){return Z5e.has(e??`GET`)}function $5e(e){return e===`null`||e.toLowerCase().startsWith(`file:`)}function e7e(e){if(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 D$(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function t7e(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 O$(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function n7e(e,t){return e!==void 0&&O$(e)===t}const r7e=[`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 k$(e){return r7e.some(t=>e.headers[t]!==void 0)}const A$=`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 i7e=class extends Error{};const a7e=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function o7e(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function j$(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(o7e).filter(e=>!a7e.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:O$(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function M$(e,t){return D$(e)?!0:t.allowExternal&&e!==void 0}function s7e(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 N$(e,t){if(t7e(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=s7e(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&n7e(e,t.externalOrigin.host)}function P$(e,t){if(e7e(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&&O$(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=o7e(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function c7e(e,t,n){if(e===void 0)return{admitted:!0,corsGrant:!0};let r=$5e(e);return!P$(e,n)||r&&!Q5e(t)?{admitted:!1,detail:r?`Requests from a null origin, and writes from a file: origin, are refused. Send the request from a loopback page, the OpenKnowledge app, or a client that sends no Origin header.`:void 0}:{admitted:!0,corsGrant:!r}}function F$(e,t){return!t.tolerateForwardedHeaders&&k$(e)}let l7e=!1;function I$(e,t){l7e||(l7e=!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 u7e=new WeakMap;function d7e(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:D$(n)?`loopback`:`external`,clientSurface:t.clientSurface,actor:void 0};return u7e.set(e,r),r}function f7e(e){return u7e.get(e)}const L$=q(`local-op-security`),p7e=eP,m7e=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function R$(e){return!e||typeof e!=`string`||m7e.some(t=>t.test(e))?!1:p7e.some(t=>t.test(e))}function z$(e){return e===`~`?cc():e.startsWith(`~/`)?H(cc(),e.slice(2)):e}function h7e(e,t){let n=V(e);for(;n!==t&&n!==V(n);){let e;try{e=Ks(n)}catch(e){let t=bq(e);return L$.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return L$.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=V(n)}return!1}function g7e(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=$s(t)}catch(e){let n=bq(e);return L$.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=W(z$(e)),i=[],a=r;for(;;){let e=null;try{e=Ks(a)}catch(e){let t=bq(e);if(t!==`ENOENT`)return L$.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=$s(a)}catch(n){let i=bq(n);if(e.isSymbolicLink())return L$.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(h7e(a,t))return L$.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;L$.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 L$.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(`..`)&&!js(s)}let r=V(a);if(r===a)return!1;i.unshift(Os(a)),a=r}}function B$(e){return g7e(e,cc())}function _7e(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function v7e(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&&y7e(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 y7e(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function b7e(e,t,n){let r=n.policy??j$({});return!_7e(e)&&!M$(e.socket.remoteAddress,r)?(X(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):v7e(e,r)?!0:(X(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function x7e(){let e=new Set;return{tryAcquire(t){return!e.has(t)&&(e.add(t),!0)},release(t){e.delete(t)}}}const S7e=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 C7e(e){S7e.push(e)}const w7e=zc.cursor,T7e=zc.codex,E7e=zc[`claude-desktop`],D7e={app:null,signals_fired:[]};function O7e(e){if(!e)return{...D7e};let t=[],n=e.ua,r=e.referer,i=!!n&&w7e.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&&T7e.test(n);if(o&&t.push(`codex_ua_regex`),o)return{app:`codex`,signals_fired:t};let s=!!n&&E7e.test(n);return s&&t.push(`claude_ua_regex`),s?{app:`claude`,signals_fired:t}:{...D7e}}const k7e=new Set([`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/agent-undo`,`/api/agent-write-batch`,`/api/comments`,`/api/comment`,`/api/client-logs`,`/api/frontmatter-patch`,`/api/save-version`,`/api/rollback`,`/api/lint/fix`,`/api/folder-config`,`/api/template`,`/api/agent-integrations/apply`]);function V$(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 H$=null;vG(()=>{H$=null});function A7e(){return H$||=xG().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),H$}function j7e(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??j$({}),a=e=>N$(e,i);return async(o,s)=>{let c=o.url?.split(`?`)[0];if(!c)return!1;let l=r.resolve(c);if(!l)return!1;let u=e=>{let t=o.headers[e];if(t!==void 0)return Array.isArray(t)?t.join(`, `):t};C7e({ts:Date.now(),url:c,method:o.method??``,ua:u(`user-agent`),origin:u(`origin`),referer:u(`referer`),host:u(`host`),remote:o.socket?.remoteAddress,secChUa:u(`sec-ch-ua`),secChUaMobile:u(`sec-ch-ua-mobile`),secChUaPlatform:u(`sec-ch-ua-platform`),secFetchSite:u(`sec-fetch-site`),secFetchDest:u(`sec-fetch-dest`),secFetchMode:u(`sec-fetch-mode`),secFetchUser:u(`sec-fetch-user`)});let d=o.method??`GET`,f=l.template,p=Yae(u(Mc.kind)),m=c.startsWith(`/api/`)?vQe(o):void 0;if(d7e(o,{requestId:m,clientSurface:p}),m!==void 0&&(bQe(o,m),typeof s.setHeader==`function`&&s.setHeader(HJ,m),typeof s.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:m,method:d,route:f,status:s.statusCode,durationMs:Date.now()-e,...p===void 0?{}:{clientSurface:p},...s.writableFinished?{}:{aborted:!0}},`${d} ${f} ${s.statusCode}`))};s.once(`finish`,r),s.once(`close`,r)}if(c.startsWith(`/api/`)){typeof s.setHeader==`function`&&s.setHeader(`Cache-Control`,`no-store`);let e=o.headers.origin,t=c7e(e,d,i);if(!t.admitted)return X(s,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`,detail:t.detail}),!0;if(typeof s.setHeader==`function`&&(e!==void 0&&s.setHeader(`Vary`,`Origin`),t.corsGrant&&(e!==void 0&&s.setHeader(`Access-Control-Allow-Origin`,e),s.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),s.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${HJ}, ${Mc.protocol}, ${Mc.runtime}, ${Mc.kind}`),s.setHeader(`Access-Control-Expose-Headers`,HJ))),o.method===`OPTIONS`)return s.writeHead(204),s.end(),!0}if(r.isMutating(c)){if(n&&l.dispatch!==void 0&&(d===`POST`||d===`PUT`||d===`DELETE`)&&!k7e.has(c))return X(s,403,`urn:ok:error:single-file-mode`,`Single-file previews cannot manage project files.`,{handler:`api-preview-content-scope`}),!0;let e=o.socket?.remoteAddress;if(e!==void 0&&!M$(e,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:A$}),!0}if(c.startsWith(`/api/`)){let e=n?`api-ephemeral-gate`:`api-read-gate`,t=o.socket?.remoteAddress;if(t!==void 0&&!M$(t,i))return X(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:e}),!0;if(!a(o.headers.host))return X(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:e,detail:A$}),!0}if(!c.startsWith(`/api/`))return!1;let h=vo.extract(mo.active(),o.headers),g=bG(),_=Date.now();return await mo.with(h,()=>g.startActiveSpan(`HTTP ${d} ${f}`,{kind:kie.SERVER,attributes:{[Nx]:d,[Fx]:f,[Rx]:c,[zx]:`http`,[Bx]:o.headers[`user-agent`]??``,"ok.request.id":m,"ok.client.surface":p}},async t=>{try{let n=l.dispatch;n===void 0?X(s,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${d} ${c}`}):r.isMutating(c)&&e.dispatchMutation!==void 0?await e.dispatchMutation(()=>n(o,s),c):await n(o,s);let i=s.statusCode;t.setAttribute(Px,i),i>=500&&t.setStatus({code:yo.ERROR,message:`status ${i}`})}catch(e){throw t.recordException(e),t.setStatus({code:yo.ERROR,message:e instanceof Error?e.message:String(e)}),!s.headersSent&&!s.writableEnded&&!s.destroyed&&X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:f,cause:e}),t.setAttribute(Px,s.statusCode),e}finally{t.end();let e=(Date.now()-_)/1e3;A7e().record(e,{[Nx]:d,[Fx]:f,[Px]:s.statusCode})}})),!0}}function U$(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof Ui||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 M7e(e){return W$(e,{maxBytes:1048576,timeoutMs:3e4})}function N7e(e){let t=e?.split(`;`,1)[0]?.trim().toLowerCase();return t===void 0?!1:t===`application/json`||/^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(t)}function P7e(e){return e.headers[`transfer-encoding`]!==void 0||Number(e.headers[`content-length`]??0)>0}async function W$(e,t){if(P7e(e)&&!N7e(e.headers[`content-type`]))throw new G$;let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new J$(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new q$(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var G$=class extends Error{constructor(){super(`Request body is not labeled as JSON`),this.name=`UnsupportedMediaTypeError`}};function K$(e,t){X(e,415,`urn:ok:error:unsupported-media-type`,`Request body must be JSON.`,{handler:t,detail:`Send the request body as JSON with the header Content-Type: application/json.`})}var q$=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${F7e(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},J$=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 F7e(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function Y$(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.some(e=>e.code===`custom`&&e.params?.contentControlAdmission===!0),o=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `),s=a?`${o} Offsets count the full submitted field after caller composition, including any frontmatter.`:o;return X(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:s,...a?{extensions:{contentControlAdmission:!0}}:{}}),{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=Y$(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await M7e(r)}catch(e){if(e instanceof G$){K$(i,n.handler);return}if(e instanceof q$){X(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof J$){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=Y$(e,o,i,n);s.ok&&await t(r,i,s.value)}}const X$=()=>q(`http`);function Q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){X$().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),GJ().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){X$().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){X$().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 I7e(e){let{log:t,checkLocalOpSecurity:n,getPrincipal:r,homeDirOverride:i,projectDir:a,agentIntegrations:o}=e;return V$({"/api/agent-integrations/apply":Z(yte,U$(async(e,n,s)=>{let c=E$(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=_7e(e)?`local-web`:`remote-web`,{report:u,snapshot:d}=await J5e(s.intents,{execute:o?.execute,env:l,snapshot:()=>_$({env:l,resolve:o?.probe}),decisionHome:i??cc(),...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,Mre,{...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 L7e=0;const R7e=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function Z$(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++L7e,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)}},R7e)}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})),tYe(),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 Q$=new Map;function $$(e,t,n,r,i,a,o,s){let c=Q$.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},Q$.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 z7e(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of Q$){for(let e of t)n.docs.delete(e);n.docs.size===0&&Q$.delete(e)}}function B7e(){let e=Q$;return Q$=new Map,e}function V7e(e){for(let[t,n]of e){let e=Q$.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},Q$.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 H7e(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(`
1051
1051
  `)}function U7e(e,t){let n=Q$.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},Q$.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 e1(){return Q$.size}function W7e(e){return Q$.has(e)}const t1={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function n1(e,t,n,r,i,a,o){DG(e,t,`file-watcher`,n&&r?{resolveEmbed:n,resolveSize:i,sourcePath:r}:void 0,o,a)}const G7e=q(`external-change-attribution`),r1=new Map;function K7e(e){for(let[t,n]of r1)n.expiresAtMs<=e&&r1.delete(t)}function q7e(e,t,n=Date.now(),r=3e4){if(K7e(n),r1.size>=256&&!r1.has(e)){let e=r1.keys().next();e.done||r1.delete(e.value)}r1.set(e,{...t,expiresAtMs:n+r})}function J7e(e,t=Date.now()){let n=r1.get(e);if(!n)return;if(r1.delete(e),n.expiresAtMs<=t){G7e.debug({docName:e},`external-change claim expired before its write arrived`);return}let{expiresAtMs:r,...i}=n;return i}function Y7e(e){r1.delete(e)}function X7e(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`;return e instanceof Ui?e.toLog({verbose:t}):e instanceof Ka?fn(e.violation,{verbose:t}):e instanceof Error?e.message:String(e)}function i1(e,t,n,r,i,a,o,s){if(cq(n)||lq(n)||dq(n)||fq(n)||pq(n))return;let c=t.documents.get(n);if(!c)return;let l=c.getText(`source`).toString(),u=l===r,d=fi(l).frontmatter,{frontmatter:f}=fi(r),p=o&&YK(t1.context.origin)?{report:e=>o(n,e,RK.id,`file-watcher-intake`),baselineFullMd:l}:void 0;try{c.transact(()=>{n1(c,r,i,n,a,p,s)},t1)}catch(t){try{e.setReconciledBase(n,c.getText(`source`).toString())}catch(e){q(`reconcile`).error({err:e,originalError:X7e(t),docName:n},`Unable to persist the reconciled base after an external-change failure`)}throw t}if(d!==f&&qX(`file-watcher`),!u){let e=J7e(n)??{writerId:RK.id,displayName:RK.name,colorSeed:RK.id};$$(n,e.writerId,e.displayName,e.colorSeed,Mge(n))}e.setReconciledBase(n,r)}function Z7e(e,t,n,r,i){return async(a,o)=>{try{i1(e,t,a,o,n,r,i),q(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof Ka||e instanceof Ui)throw e;MJe(),q(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const a1=`stale-external-write`;function o1(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,a1);let a=t?.getMap(`lifecycle`);a?.get(`reason`)===a1&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`))}function Q7e(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 s1(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:a1,detectedAt:s.detectedAt,stages:{base:o??r,ours:s.retainedContent??(t===void 0?o??r:l1(t)),theirs:s.diskContent}})};return s?.retainedContent!==void 0&&s.retainedContent!==o?(c(r,a??s.retainedContent),!0):o===r?(o1(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):(o1(e,t,n,i),!1)}const c1={reconciled:!1,baseBytes:0,diskBytes:0};function l1(e){let t=e.getText(`source`).toString(),{frontmatter:n,body:r}=fi(t);return Gt(n,r)}function u1(e,t,n,r,i,a,o){if(cq(n)||lq(n)||dq(n)||fq(n)||pq(n))return c1;let s=t.documents.get(n);if(s&&HX(s)&&s.getMap(`lifecycle`).get(`reason`)!==a1)return c1;let c=e.getReconciledBase(n);if(c===void 0)return c1;let l,u;try{if(l=Oq(n,r),!G(l))return c1;u=$s(l)}catch{return c1}if(SJ(l,u,r))return q(`reconcile`).warn({docName:n,canonical:u,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),c1;let d;try{d=K(u,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&q(`reconcile`).warn({docName:n,canonical:u,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),c1}let f=k(d);if(d===c)return o1(e,s,n,o),c1;let p=e.inFlightFlushCount(n);if(p>0){if(e.hasInFlightFlush(n,f))return NJe(),q(`reconcile`).debug({docName:n,diskBytes:d.length,pendingFlushes:p},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),c1;PJe(),q(`reconcile`).warn({docName:n,diskBytes:d.length,pendingFlushes:p},`[reconcile] disk matches none of ${p} in-flight flush snapshot(s) for ${n}; falling through to merge`)}if(!s||s1(e,s,n,d,o)||f===k(c))return c1;let m=l1(s),h=sY({docName:n,base:c,ours:m,theirs:d});switch(q(`reconcile`).info({docName:n,result:h.kind,baseBytes:c.length,diskBytes:d.length},`[reconcile] before-agent-write ${n} result=${h.kind}`),h.kind){case`noop`:return c1;case`conflicts`:case`refused`:return o.raise({kind:`reconcile`,file:o.fileOf(n),reason:h.kind===`conflicts`?`merged-with-markers`:Q7e(h.reason),stages:{base:c,ours:m,theirs:d}}),c1;case`clean`:case`merged`:{let r=h.kind===`clean`?d:h.newContent;return h.kind===`merged`&&h.dedupSkipped&&(yqe(),q(`reconcile`).warn({docName:n},`[reconcile] ${n} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`)),i1(e,t,n,r,i,void 0,a),h.kind===`merged`&&e.setReconciledBase(n,d),{reconciled:!0,baseBytes:Buffer.byteLength(c,`utf8`),diskBytes:Buffer.byteLength(d,`utf8`),mergeOutcome:h.kind}}}}const d1=q(`mermaid-validator`);let $7e=null;function e9e(e){let t=[],n=e.split(`
@@ -1 +1 @@
1
- import{Dt as e,Ka as t,Tt as n,Y as r,_c as i,ec as a,sc as o,v as s}from"./md-manager-BGnqyqi1-CMF2qMhD.mjs";import{$ as c,$a as l,$i as u,$n as d,$r as f,$t as p,A as m,Aa as h,Ai as g,An as _,Ao as v,Ar as y,At as b,B as x,Ba as S,Bi as C,Bn as w,Br as T,Bt as E,C as D,Ca as O,Ci as k,Cn as A,Co as j,Cr as M,Ct as N,D as P,Da as F,Di as I,Dn as L,Do as R,Dr as z,Ds as B,Dt as V,E as H,Ea as U,Ei as W,En as G,Eo as K,Er as q,Es as J,Et as Y,F as X,Fa as Z,Fi as Q,Fn as $,Fo as ee,Fr as te,Ft as ne,G as re,Ga as ie,Gi as ae,Gn as oe,Gr as se,Gt as ce,H as le,Ha as ue,Hi as de,Hn as fe,Hr as pe,Ht as me,I as he,Ia as ge,Ii as _e,In as ve,Io as ye,Ir as be,It as xe,J as Se,Ja as Ce,Ji as we,Jn as Te,Jr as Ee,Jt as De,K as Oe,Ka as ke,Ki as Ae,Kn as je,Kr as Me,Kt as Ne,L as Pe,La as Fe,Li as Ie,Ln as Le,Lo as Re,Lr as ze,Lt as Be,M as Ve,Ma as He,Mi as Ue,Mn as We,Mo as Ge,Mr as Ke,Mt as qe,N as Je,Na as Ye,Ni as Xe,Nn as Ze,No as Qe,Nr as $e,Nt as et,O as tt,Oa as nt,Oi as rt,On as it,Oo as at,Or as ot,Os as st,Ot as ct,P as lt,Pa as ut,Pi as dt,Pn as ft,Po as pt,Pr as mt,Pt as ht,Q as gt,Qa as _t,Qi as vt,Qn as yt,Qr as bt,Qt as xt,R as St,Ra as Ct,Ri as wt,Rn as Tt,Rr as Et,Rt as Dt,S as Ot,Sa as kt,Si as At,Sn as jt,So as Mt,Sr as Nt,Ss as Pt,St as Ft,T as It,Ta as Lt,Ti as Rt,Tn as zt,To as Bt,Tr as Vt,Ts as Ht,Tt as Ut,U as Wt,Ua as Gt,Ui as Kt,Un as qt,Ur as Jt,Ut as Yt,V as Xt,Va as Zt,Vi as Qt,Vn as $t,Vr as en,Vt as tn,W as nn,Wa as rn,Wi as an,Wn as on,Wr as sn,Wt as cn,X as ln,Xa as un,Xi as dn,Xn as fn,Xr as pn,Xt as mn,Y as hn,Ya as gn,Yi as _n,Yn as vn,Yr as yn,Yt as bn,Z as xn,Za as Sn,Zi as Cn,Zn as wn,Zr as Tn,Zt as En,_ as Dn,_a as On,_i as kn,_n as An,_o as jn,_r as Mn,_s as Nn,_t as Pn,a as Fn,aa as In,ai as Ln,an as Rn,ao as zn,ar as Bn,at as Vn,b as Hn,ba as Un,bi as Wn,bn as Gn,bo as Kn,br as qn,bs as Jn,bt as Yn,c as Xn,ca as Zn,ci as Qn,cn as $n,co as er,cr as tr,ct as nr,d as rr,da as ir,di as ar,dn as or,do as sr,dr as cr,dt as lr,ea as ur,ei as dr,en as fr,eo as pr,er as mr,et as hr,f as gr,fa as _r,fi as vr,fn as yr,fo as br,fr as xr,ft as Sr,g as Cr,ga as wr,gi as Tr,gn as Er,go as Dr,gr as Or,gs as kr,gt as Ar,h as jr,ha as Mr,hi as Nr,hn as Pr,ho as Fr,hr as Ir,hs as Lr,ht as Rr,i as zr,ia as Br,ii as Vr,in as Hr,io as Ur,ir as Wr,it as Gr,j as Kr,ja as qr,ji as Jr,jn as Yr,jo as Xr,jr as Zr,jt as Qr,k as $r,ka as ei,ki as ti,kn as ni,ko as ri,kr as ii,kt as ai,l as oi,la as si,li as ci,ln as li,lo as ui,lr as di,ls as fi,lt as pi,m as mi,ma as hi,mi as gi,mn as _i,mo as vi,mr as yi,ms as bi,mt as xi,n as Si,na as Ci,ni as wi,nn as Ti,no as Ei,nr as Di,nt as Oi,o as ki,oa as Ai,oi as ji,on as Mi,oo as Ni,or as Pi,ot as Fi,p as Ii,pa as Li,pi as Ri,pn as zi,po as Bi,pr as Vi,pt as Hi,q as Ui,qa as Wi,qi as Gi,qn as Ki,qr as qi,qt as Ji,r as Yi,ra as Xi,ri as Zi,rn as Qi,ro as $i,rr as ea,rt as ta,s as na,sa as ra,si as ia,sn as aa,so as oa,sr as sa,st as ca,t as la,ta as ua,ti as da,tn as fa,to as pa,tr as ma,tt as ha,u as ga,ua as _a,ui as va,un as ya,uo as ba,ur as xa,us as Sa,ut as Ca,v as wa,va as Ta,vi as Ea,vn as Da,vo as Oa,vr as ka,vs as Aa,vt as ja,w as Ma,wa as Na,wi as Pa,wn as Fa,wo as Ia,wr as La,wt as Ra,x as za,xa as Ba,xi as Va,xn as Ha,xo as Ua,xr as Wa,xs as Ga,xt as Ka,y as qa,ya as Ja,yi as Ya,yn as Xa,yo as Za,yr as Qa,ys as $a,yt as eo,z as to,za as no,zi as ro,zn as io,zr as ao,zt as oo}from"./dist-BlSdA1nb.mjs";export{la as AGENT_ID_MAX_LEN,Si as AGENT_ID_RE,Yi as AGENT_WRITE_ORIGIN,t as AUDIT_EMPTY_SCOPE_WARNING,zr as AcpPermissionStore,Fn as AcpRegistry,ki as AcpThreadManager,na as AgentFocusBroadcaster,Xn as AgentPresenceBroadcaster,oi as AgentSessionCapacityError,ga as AgentSessionManager,rr as AutoStartDisabledError,gr as BUNDLE_IDS,Ii as BUNDLE_SCOPE,mi as BUNDLE_SKILL_NAME,jr as BacklinkIndex,Cr as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Dn as CONCURRENT_REPLACE_WINDOW_MS,wa as CONFIG_FILENAME,qa as CONFLICT_MARKER_RE,Hn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,za as ConfigSchema,Ot as ConflictAuthority,D as DEFAULT_CHECKPOINT_RETENTION,Ma as DEFAULT_EMBEDDINGS_DIMENSIONS,It as DEFAULT_PACK_ID,H as DocumentDurabilityState,P as DocumentDurabilityStateError,tt as EMBEDDINGS_API_KEY_ENV,$r as EPHEMERAL_PROJECT_DIR_PREFIX,m as ExposureConsentError,Kr as FEATURED_AGENT_IDS,Ve as FILE_SYSTEM_WRITER,Je as FILE_WATCHER_ORIGIN,lt as FileEmbeddingsBackend,X as FilesystemRootProjectError,he as GIT_PREFLIGHT_FAIL_SPAN_NAME,Pe as GIT_UPSTREAM_WRITER,fi as GitDirAccessError,St as GitNotAvailableError,to as GitTooOldError,x as HOCUSPOCUS_AUTH_REJECTION_REASONS,Xt as HocuspocusAuthRejection,le as HocuspocusAuthTokenSchema,Wt as HomeProjectRootError,nn as INSTALLED_AGENTS_SCHEMES,re as JSON_SCHEMA_DIALECT_2020_12,B as LINEAGE_EPOCH_KEY,Oe as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ui as MANAGED_RENAME_ORIGIN,Se as MAX_ACP_THREADS,hn as MAX_AGENT_SESSIONS,ln as MCP_CONNECTION_ID_HEADER,a as MCP_SERVER_NAME,xn as MIN_EVICTABLE_IDLE_MS,gt as MIN_GIT_VERSION,c as MISSING_OK_CONFIG_MESSAGE,Sa as MalformedGitPointerError,hr as McpLogger,ha as MissingOkConfigError,Oi as OBSERVER_SYNC_ORIGIN,ta as OK_OKIGNORE_TEMPLATE,Gr as ONBOARDING_BUNDLE_IDS,Ht as ORPHAN_MODES,st as PROTOCOL_VERSION,bi as PinoLogger,Vn as ProcessLockCollisionError,Fi as ProjectGitInitError,ca as ROLLBACK_ORIGIN,nr as ROOT_GITIGNORE_TEMPLATE,pi as RUNTIME_VERSION,Ca as SERVICE_WRITER,lr as SKILL_INSTALL_EVENTS_FILENAME,s as SKILL_STATE_TARGETS,Sr as STARTER_FOLDER_FRONTMATTER_FILENAME,Hi as STARTER_PACKS,xi as STARTER_PACK_IDS,Rr as STATE_MANIFEST_FILENAME,Ar as STATE_SCHEMA_VERSION,Pn as SYMLINK_MERGE_MIN_GIT_LABEL,ja as SYMLINK_MERGE_MIN_GIT_VERSION,i as SYSTEM_DOC_NAME,eo as SeedPrerequisiteError,Yn as SeedRootDirError,Ka as ServerAuthorityCollisionError,Ft as ServerAuthorityRegistryError,N as ServerLockCollisionError,Ra as SingleFileNotAFileError,Ut as SingleFileNotFoundError,Y as SingleFileNotMarkdownError,V as SingleFileProjectOverrideError,ct as StateManifestError,ai as TagIndex,b as USER_GLOBAL_BUNDLE_IDS,Qr as UnsafeIncomingSymlinkError,qe as __getShowAllWalkStatsForTesting,et as __resetShowAllWalkStatsForTesting,ht as acpThreadStoreRoots,ne as acpThreadsDir,xe as acquireProcessLock,Be as acquireServerLock,Dt as applyAgentMarkdownWrite,oo as applyExternalChange,E as applySeed,tn as assertCheckoutSymlinksSafe,me as assertCompatibleStateManifest,Yt as assertGitAvailable,cn as assertIncomingSymlinksSafe,ce as assertMergeNameResolvesTo,Ne as assertNeverDiskEvent,Ji as assertRepoCheckoutSymlinksSafe,De as assertSafeProjectRoot,bn as attachAcpThreadSocket,mn as attachCollabClientCounter,En as attachIdleShutdown,xt as auditScopeNotFoundTitle,p as bindConflictAuthority,fr as bootServer,fa as buildAndOpenSkill,Ti as buildConfigYmlContent,Qi as buildExecResult,Hr as buildIngressPolicy,Rn as buildOkMcpStdioCommand,Mi as buildSkillZip,aa as buildStarterFolderFrontmatterYaml,$n as buildWipTree,li as bundleSkillMdPath,ya as canonicalProjectKey,or as canonicalizeForCompare,yr as classifyEvents,zi as classifyFsPath,_i as clearAllEmbeddingsKeys,Pr as coercePackId,Er as collectServerHostSnapshot,n as colorFromSeed,An as commitUpstreamImport,Da as commitWip,Xa as commitWipFromTree,Gn as compareSemver,Ha as composeEffectiveLinterConfig,jt as composeFrontmatterSchemasConfig,A as containsConflictMarkers,Fa as contentHash,zt as contributorCount,G as countShadowObjects,L as countStaleAgentWipRefs,it as countWipRefs,ni as createApiExtension,_ as createAssetServeMiddleware,Yr as createCollaborationHost,We as createContentFilter,Ze as createContentFilterAsync,ft as createEmbeddingsSecretStore,$ as createEphemeralProjectDir,ve as createExternalChangeHandler,Le as createFileLogger,Tt as createLiveDerivedIndexExtension,io as createMcpHttpHandler,w as createOsProbe,$t as createPersistenceExtension,fe as createProbeFailureReporter,qt as createServer,on as createServerObserverExtension,oe as createServerProbeResolver,je as createStreamingErrorWriter,Lr as createTestLogger,Ki as describeStoredEmbeddingsKey,Te as detectClaudeDesktopPresence,vn as detectGit,fn as detectProjectShape,wn as detectUserSkillHosts,yt as discoverLockDirs,d as discoverMarkdownlintConfig,mr as emitPreflightFailureSpan,ma as encodeDocName,Di as encodeFolderRoute,ea as encodeSkillRoute,Wr as ensureProjectGit,Bn as errorResponse,Pi as evictStaleTrackerEntries,sa as extractHeadings,tr as extractOkBinaryPath,di as extractWikiLinksFromMarkdown,xa as fallbackPaths,cr as findEnclosingGitRoot,xr as findEnclosingProjectRoot,Vi as findNativeMarkdownlintFile,yi as flushFileLogger,Ir as formatAuditBrokenLinkSuppressionLine,Or as formatAuthRejectionWire,Mn as formatContributorsFrom,ka as formatPackRationale,Qa as gcCheckpointRefs,qn as getCurrentMcpLogger,Wa as getIngressContext,Nt as getLocalDir,M as getLogFilePath,kr as getLogger,La as getLogsDir,Vt as getMachineId,q as getMeter,z as getMetrics,ot as getTracer,ii as handleCollabSocketError,y as handleSpawnCursor,Zr as hasForwardingHeaders,Ke as hasGcLogLatch,e as iconFromClientName,$e as incrementCollabSocketFilteredError,mt as incrementServerObserverFire,te as initContent,be as initShadowRepo,ze as initTelemetry,Et as initToleranceTelemetryWriter,ao as installJsonSchemaDialect,T as installPrettyZodErrors,Nn as installTestLoggers,en as installUserSkill,pe as isAllowedApiOrigin,Jt as isAllowedWorkspaceHostHeader,sn as isConfigDoc,se as isDefunctProcess,Me as isDocInConflict,qi as isFilesystemRoot,Ee as isHocuspocusAuthRejectionReason,yn as isHomeDir,pn as isHostAdmitted,Tn as isKnownPackId,bt as isLinkIndexExcludedDoc,f as isLockProcessRunning,dr as isLoopbackAddress,da as isManagedArtifactDoc,wi as isMintedThreadId,Zi as isOriginAdmitted,J as isOrphanMode,Vr as isPairedWriteOrigin,Ln as isPathWithinDir,ji as isPeerAdmitted,ia as isProcessAlive,Qn as isProjectRoot,ci as isReservedForUserTree,va as isSelfWrite,ar as isSkillInstallReportEnvOptOut,vr as isSystemDoc,Ri as isToleranceTelemetryEnabled,gi as isValidLockPid,Nr as lastKnownHash,Tr as listRescueCheckpoints,kn as listStarterPacks,Ea as loadCustomAgents,Ya as loadPrincipal,Wn as lockAdvertisesUi,Va as lockBaseUrl,At as lockFilePath,Aa as loggerFactory,k as loginShapedUserinfoUser,$a as logsCurrentPath,Jn as logsPreviousPath,Pa as makeLazyEmbeddingsKeyStore,Rt as markServerLockDraining,W as mountMcpAndApi,I as normalizeFsPath,rt as observeReadiness,ti as packageVersionMajorMinor,g as parseAuthRejectionWire,Jr as parseGitVersion,Ue as parseHocuspocusAuthToken,Xe as parseKeepaliveConnectionId,dt as pathToDocName,Q as planSeed,_e as prepareSingleFileOpen,Ie as processCommand,wt as processUsage,ro as readAgentBrowserTools,C as readAllTargets,Qt as readBundleDecision,de as readDeclaredGitHubHosts,Kt as readOriginCredentialHost,an as readOriginGitHubRepo,ae as readOwnNativeRules,Ae as readProcessLock,Gi as readProcessLockDetailed,we as readProcessState,_n as readProjectHeadState,dn as readProjectLocalSemanticConfig,Cn as readServerLock,vt as readServerPackageVersion,u as readSkillInstallStateSnapshot,ur as readStateManifest,ua as readTargetRecordedAt,Ci as readTargetVersion,Xi as reconcile,Br as recordContributor,In as recordSkillInstallEvent,Ai as redactShareSubprocessStderr,ra as registerAllTools,Zn as registerWrite,si as releaseProcessLock,_a as releaseServerLock,ir as removeLastKnownHash,_r as removeProjectSkillGitignoreBlock,Li as reportSkillInstall,hi as resetMetrics,Mr as resolveAuditScope,wr as resolveBuiltinSkillHosts,r as resolveBundleEnabled,On as resolveBundledSkillDir,Ta as resolveContentDir,Ja as resolveCursorBinaryDefault,Un as resolveCursorSpawnInvocation,Ba as resolveEffectiveLinterConfig,kt as resolveEmbeddingsCredential,O as resolveGitHubAccountFromUrl,Na as resolveGitHubAuthHost,Lt as resolveLockDir,U as resolveNativeConfigForDoc,F as resolveNativeMarkdownlintConfig,nt as resolvePack,ei as resolvePackageVersion,h as resolveSkillInstallReportSettings,qr as resolveUiInfo,He as restoreContributors,Ye as rewriteMarkdownLinksForDocumentRename,ut as rewriteWikiLinksForDocumentRename,Z as runAuthReposSubprocess,ge as runAuthStatusSubprocess,Fe as runCloneSubprocess,Ct as runDeviceFlowSubprocess,no as runWithMcpLogger,S as safeContentPath,Zt as safeSubdir,ue as safetyCheckpoint,Gt as sameGitHubLogin,rn as sanitizeClientName,ie as saveInMemoryCheckpoint,ke as saveVersion,Wi as scanLockProcesses,Ce as seedBasenameIndex,gn as seedEphemeralProjectDir,un as serializeError,Sn as setActiveSpanAttributes,_t as setupServerObservers,l as shadowGit,pr as shutdownTelemetry,Ga as spansCurrentPath,Pt as spansPreviousPath,pa as spawnDetached,Ei as splitMarkdownBlocks,$i as startWatcher,Ur as strategiesFor,zn as streamedChunkOf,Ni as streamingProblemEvent,oa as swapContributors,er as teardownToleranceTelemetryWriter,ui as toBroadcasterKey,ba as tracedAppendFileSync,sr as tracedLinkSync,br as tracedMkdir,Bi as tracedMkdirSync,vi as tracedRename,Fr as tracedRenameSync,Dr as tracedRmSync,jn as tracedRmdirSync,Oa as tracedUnlinkSync,Za as tracedWriteFile,Kn as tracedWriteFileSync,Ua as trustSystemCertificates,Mt as updateLastKnownHash,j as updateProcessLockPort,Ia as updateServerLockPort,Bt as validateAgentId,K as validateCloneInputs,R as validateSkillZip,at as waitForServerLockDrain,ri as withHiddenWindowsConsole,v as withSpan,Xr as withSpanSync,Ge as writeBundleDecision,Qe as writeMarkdownlintRule,pt as writeRootGitignoreForNewRepo,ee as writeStateManifest,ye as writeTargetVersion,Re as writeTracker};
1
+ import{Dt as e,Ka as t,Tt as n,Y as r,_c as i,ec as a,sc as o,v as s}from"./md-manager-BGnqyqi1-CMF2qMhD.mjs";import{$ as c,$a as l,$i as u,$n as d,$r as f,$t as p,A as m,Aa as h,Ai as g,An as _,Ao as v,Ar as y,At as b,B as x,Ba as S,Bi as C,Bn as w,Br as T,Bt as E,C as D,Ca as O,Ci as k,Cn as A,Co as j,Cr as M,Ct as N,D as P,Da as F,Di as I,Dn as L,Do as R,Dr as z,Ds as B,Dt as V,E as H,Ea as U,Ei as W,En as G,Eo as K,Er as q,Es as J,Et as Y,F as X,Fa as Z,Fi as Q,Fn as $,Fo as ee,Fr as te,Ft as ne,G as re,Ga as ie,Gi as ae,Gn as oe,Gr as se,Gt as ce,H as le,Ha as ue,Hi as de,Hn as fe,Hr as pe,Ht as me,I as he,Ia as ge,Ii as _e,In as ve,Io as ye,Ir as be,It as xe,J as Se,Ja as Ce,Ji as we,Jn as Te,Jr as Ee,Jt as De,K as Oe,Ka as ke,Ki as Ae,Kn as je,Kr as Me,Kt as Ne,L as Pe,La as Fe,Li as Ie,Ln as Le,Lo as Re,Lr as ze,Lt as Be,M as Ve,Ma as He,Mi as Ue,Mn as We,Mo as Ge,Mr as Ke,Mt as qe,N as Je,Na as Ye,Ni as Xe,Nn as Ze,No as Qe,Nr as $e,Nt as et,O as tt,Oa as nt,Oi as rt,On as it,Oo as at,Or as ot,Os as st,Ot as ct,P as lt,Pa as ut,Pi as dt,Pn as ft,Po as pt,Pr as mt,Pt as ht,Q as gt,Qa as _t,Qi as vt,Qn as yt,Qr as bt,Qt as xt,R as St,Ra as Ct,Ri as wt,Rn as Tt,Rr as Et,Rt as Dt,S as Ot,Sa as kt,Si as At,Sn as jt,So as Mt,Sr as Nt,Ss as Pt,St as Ft,T as It,Ta as Lt,Ti as Rt,Tn as zt,To as Bt,Tr as Vt,Ts as Ht,Tt as Ut,U as Wt,Ua as Gt,Ui as Kt,Un as qt,Ur as Jt,Ut as Yt,V as Xt,Va as Zt,Vi as Qt,Vn as $t,Vr as en,Vt as tn,W as nn,Wa as rn,Wi as an,Wn as on,Wr as sn,Wt as cn,X as ln,Xa as un,Xi as dn,Xn as fn,Xr as pn,Xt as mn,Y as hn,Ya as gn,Yi as _n,Yn as vn,Yr as yn,Yt as bn,Z as xn,Za as Sn,Zi as Cn,Zn as wn,Zr as Tn,Zt as En,_ as Dn,_a as On,_i as kn,_n as An,_o as jn,_r as Mn,_s as Nn,_t as Pn,a as Fn,aa as In,ai as Ln,an as Rn,ao as zn,ar as Bn,at as Vn,b as Hn,ba as Un,bi as Wn,bn as Gn,bo as Kn,br as qn,bs as Jn,bt as Yn,c as Xn,ca as Zn,ci as Qn,cn as $n,co as er,cr as tr,ct as nr,d as rr,da as ir,di as ar,dn as or,do as sr,dr as cr,dt as lr,ea as ur,ei as dr,en as fr,eo as pr,er as mr,et as hr,f as gr,fa as _r,fi as vr,fn as yr,fo as br,fr as xr,ft as Sr,g as Cr,ga as wr,gi as Tr,gn as Er,go as Dr,gr as Or,gs as kr,gt as Ar,h as jr,ha as Mr,hi as Nr,hn as Pr,ho as Fr,hr as Ir,hs as Lr,ht as Rr,i as zr,ia as Br,ii as Vr,in as Hr,io as Ur,ir as Wr,it as Gr,j as Kr,ja as qr,ji as Jr,jn as Yr,jo as Xr,jr as Zr,jt as Qr,k as $r,ka as ei,ki as ti,kn as ni,ko as ri,kr as ii,kt as ai,l as oi,la as si,li as ci,ln as li,lo as ui,lr as di,ls as fi,lt as pi,m as mi,ma as hi,mi as gi,mn as _i,mo as vi,mr as yi,ms as bi,mt as xi,n as Si,na as Ci,ni as wi,nn as Ti,no as Ei,nr as Di,nt as Oi,o as ki,oa as Ai,oi as ji,on as Mi,oo as Ni,or as Pi,ot as Fi,p as Ii,pa as Li,pi as Ri,pn as zi,po as Bi,pr as Vi,pt as Hi,q as Ui,qa as Wi,qi as Gi,qn as Ki,qr as qi,qt as Ji,r as Yi,ra as Xi,ri as Zi,rn as Qi,ro as $i,rr as ea,rt as ta,s as na,sa as ra,si as ia,sn as aa,so as oa,sr as sa,st as ca,t as la,ta as ua,ti as da,tn as fa,to as pa,tr as ma,tt as ha,u as ga,ua as _a,ui as va,un as ya,uo as ba,ur as xa,us as Sa,ut as Ca,v as wa,va as Ta,vi as Ea,vn as Da,vo as Oa,vr as ka,vs as Aa,vt as ja,w as Ma,wa as Na,wi as Pa,wn as Fa,wo as Ia,wr as La,wt as Ra,x as za,xa as Ba,xi as Va,xn as Ha,xo as Ua,xr as Wa,xs as Ga,xt as Ka,y as qa,ya as Ja,yi as Ya,yn as Xa,yo as Za,yr as Qa,ys as $a,yt as eo,z as to,za as no,zi as ro,zn as io,zr as ao,zt as oo}from"./dist-DEBeS2ZG.mjs";export{la as AGENT_ID_MAX_LEN,Si as AGENT_ID_RE,Yi as AGENT_WRITE_ORIGIN,t as AUDIT_EMPTY_SCOPE_WARNING,zr as AcpPermissionStore,Fn as AcpRegistry,ki as AcpThreadManager,na as AgentFocusBroadcaster,Xn as AgentPresenceBroadcaster,oi as AgentSessionCapacityError,ga as AgentSessionManager,rr as AutoStartDisabledError,gr as BUNDLE_IDS,Ii as BUNDLE_SCOPE,mi as BUNDLE_SKILL_NAME,jr as BacklinkIndex,Cr as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Dn as CONCURRENT_REPLACE_WINDOW_MS,wa as CONFIG_FILENAME,qa as CONFLICT_MARKER_RE,Hn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,za as ConfigSchema,Ot as ConflictAuthority,D as DEFAULT_CHECKPOINT_RETENTION,Ma as DEFAULT_EMBEDDINGS_DIMENSIONS,It as DEFAULT_PACK_ID,H as DocumentDurabilityState,P as DocumentDurabilityStateError,tt as EMBEDDINGS_API_KEY_ENV,$r as EPHEMERAL_PROJECT_DIR_PREFIX,m as ExposureConsentError,Kr as FEATURED_AGENT_IDS,Ve as FILE_SYSTEM_WRITER,Je as FILE_WATCHER_ORIGIN,lt as FileEmbeddingsBackend,X as FilesystemRootProjectError,he as GIT_PREFLIGHT_FAIL_SPAN_NAME,Pe as GIT_UPSTREAM_WRITER,fi as GitDirAccessError,St as GitNotAvailableError,to as GitTooOldError,x as HOCUSPOCUS_AUTH_REJECTION_REASONS,Xt as HocuspocusAuthRejection,le as HocuspocusAuthTokenSchema,Wt as HomeProjectRootError,nn as INSTALLED_AGENTS_SCHEMES,re as JSON_SCHEMA_DIALECT_2020_12,B as LINEAGE_EPOCH_KEY,Oe as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ui as MANAGED_RENAME_ORIGIN,Se as MAX_ACP_THREADS,hn as MAX_AGENT_SESSIONS,ln as MCP_CONNECTION_ID_HEADER,a as MCP_SERVER_NAME,xn as MIN_EVICTABLE_IDLE_MS,gt as MIN_GIT_VERSION,c as MISSING_OK_CONFIG_MESSAGE,Sa as MalformedGitPointerError,hr as McpLogger,ha as MissingOkConfigError,Oi as OBSERVER_SYNC_ORIGIN,ta as OK_OKIGNORE_TEMPLATE,Gr as ONBOARDING_BUNDLE_IDS,Ht as ORPHAN_MODES,st as PROTOCOL_VERSION,bi as PinoLogger,Vn as ProcessLockCollisionError,Fi as ProjectGitInitError,ca as ROLLBACK_ORIGIN,nr as ROOT_GITIGNORE_TEMPLATE,pi as RUNTIME_VERSION,Ca as SERVICE_WRITER,lr as SKILL_INSTALL_EVENTS_FILENAME,s as SKILL_STATE_TARGETS,Sr as STARTER_FOLDER_FRONTMATTER_FILENAME,Hi as STARTER_PACKS,xi as STARTER_PACK_IDS,Rr as STATE_MANIFEST_FILENAME,Ar as STATE_SCHEMA_VERSION,Pn as SYMLINK_MERGE_MIN_GIT_LABEL,ja as SYMLINK_MERGE_MIN_GIT_VERSION,i as SYSTEM_DOC_NAME,eo as SeedPrerequisiteError,Yn as SeedRootDirError,Ka as ServerAuthorityCollisionError,Ft as ServerAuthorityRegistryError,N as ServerLockCollisionError,Ra as SingleFileNotAFileError,Ut as SingleFileNotFoundError,Y as SingleFileNotMarkdownError,V as SingleFileProjectOverrideError,ct as StateManifestError,ai as TagIndex,b as USER_GLOBAL_BUNDLE_IDS,Qr as UnsafeIncomingSymlinkError,qe as __getShowAllWalkStatsForTesting,et as __resetShowAllWalkStatsForTesting,ht as acpThreadStoreRoots,ne as acpThreadsDir,xe as acquireProcessLock,Be as acquireServerLock,Dt as applyAgentMarkdownWrite,oo as applyExternalChange,E as applySeed,tn as assertCheckoutSymlinksSafe,me as assertCompatibleStateManifest,Yt as assertGitAvailable,cn as assertIncomingSymlinksSafe,ce as assertMergeNameResolvesTo,Ne as assertNeverDiskEvent,Ji as assertRepoCheckoutSymlinksSafe,De as assertSafeProjectRoot,bn as attachAcpThreadSocket,mn as attachCollabClientCounter,En as attachIdleShutdown,xt as auditScopeNotFoundTitle,p as bindConflictAuthority,fr as bootServer,fa as buildAndOpenSkill,Ti as buildConfigYmlContent,Qi as buildExecResult,Hr as buildIngressPolicy,Rn as buildOkMcpStdioCommand,Mi as buildSkillZip,aa as buildStarterFolderFrontmatterYaml,$n as buildWipTree,li as bundleSkillMdPath,ya as canonicalProjectKey,or as canonicalizeForCompare,yr as classifyEvents,zi as classifyFsPath,_i as clearAllEmbeddingsKeys,Pr as coercePackId,Er as collectServerHostSnapshot,n as colorFromSeed,An as commitUpstreamImport,Da as commitWip,Xa as commitWipFromTree,Gn as compareSemver,Ha as composeEffectiveLinterConfig,jt as composeFrontmatterSchemasConfig,A as containsConflictMarkers,Fa as contentHash,zt as contributorCount,G as countShadowObjects,L as countStaleAgentWipRefs,it as countWipRefs,ni as createApiExtension,_ as createAssetServeMiddleware,Yr as createCollaborationHost,We as createContentFilter,Ze as createContentFilterAsync,ft as createEmbeddingsSecretStore,$ as createEphemeralProjectDir,ve as createExternalChangeHandler,Le as createFileLogger,Tt as createLiveDerivedIndexExtension,io as createMcpHttpHandler,w as createOsProbe,$t as createPersistenceExtension,fe as createProbeFailureReporter,qt as createServer,on as createServerObserverExtension,oe as createServerProbeResolver,je as createStreamingErrorWriter,Lr as createTestLogger,Ki as describeStoredEmbeddingsKey,Te as detectClaudeDesktopPresence,vn as detectGit,fn as detectProjectShape,wn as detectUserSkillHosts,yt as discoverLockDirs,d as discoverMarkdownlintConfig,mr as emitPreflightFailureSpan,ma as encodeDocName,Di as encodeFolderRoute,ea as encodeSkillRoute,Wr as ensureProjectGit,Bn as errorResponse,Pi as evictStaleTrackerEntries,sa as extractHeadings,tr as extractOkBinaryPath,di as extractWikiLinksFromMarkdown,xa as fallbackPaths,cr as findEnclosingGitRoot,xr as findEnclosingProjectRoot,Vi as findNativeMarkdownlintFile,yi as flushFileLogger,Ir as formatAuditBrokenLinkSuppressionLine,Or as formatAuthRejectionWire,Mn as formatContributorsFrom,ka as formatPackRationale,Qa as gcCheckpointRefs,qn as getCurrentMcpLogger,Wa as getIngressContext,Nt as getLocalDir,M as getLogFilePath,kr as getLogger,La as getLogsDir,Vt as getMachineId,q as getMeter,z as getMetrics,ot as getTracer,ii as handleCollabSocketError,y as handleSpawnCursor,Zr as hasForwardingHeaders,Ke as hasGcLogLatch,e as iconFromClientName,$e as incrementCollabSocketFilteredError,mt as incrementServerObserverFire,te as initContent,be as initShadowRepo,ze as initTelemetry,Et as initToleranceTelemetryWriter,ao as installJsonSchemaDialect,T as installPrettyZodErrors,Nn as installTestLoggers,en as installUserSkill,pe as isAllowedApiOrigin,Jt as isAllowedWorkspaceHostHeader,sn as isConfigDoc,se as isDefunctProcess,Me as isDocInConflict,qi as isFilesystemRoot,Ee as isHocuspocusAuthRejectionReason,yn as isHomeDir,pn as isHostAdmitted,Tn as isKnownPackId,bt as isLinkIndexExcludedDoc,f as isLockProcessRunning,dr as isLoopbackAddress,da as isManagedArtifactDoc,wi as isMintedThreadId,Zi as isOriginAdmitted,J as isOrphanMode,Vr as isPairedWriteOrigin,Ln as isPathWithinDir,ji as isPeerAdmitted,ia as isProcessAlive,Qn as isProjectRoot,ci as isReservedForUserTree,va as isSelfWrite,ar as isSkillInstallReportEnvOptOut,vr as isSystemDoc,Ri as isToleranceTelemetryEnabled,gi as isValidLockPid,Nr as lastKnownHash,Tr as listRescueCheckpoints,kn as listStarterPacks,Ea as loadCustomAgents,Ya as loadPrincipal,Wn as lockAdvertisesUi,Va as lockBaseUrl,At as lockFilePath,Aa as loggerFactory,k as loginShapedUserinfoUser,$a as logsCurrentPath,Jn as logsPreviousPath,Pa as makeLazyEmbeddingsKeyStore,Rt as markServerLockDraining,W as mountMcpAndApi,I as normalizeFsPath,rt as observeReadiness,ti as packageVersionMajorMinor,g as parseAuthRejectionWire,Jr as parseGitVersion,Ue as parseHocuspocusAuthToken,Xe as parseKeepaliveConnectionId,dt as pathToDocName,Q as planSeed,_e as prepareSingleFileOpen,Ie as processCommand,wt as processUsage,ro as readAgentBrowserTools,C as readAllTargets,Qt as readBundleDecision,de as readDeclaredGitHubHosts,Kt as readOriginCredentialHost,an as readOriginGitHubRepo,ae as readOwnNativeRules,Ae as readProcessLock,Gi as readProcessLockDetailed,we as readProcessState,_n as readProjectHeadState,dn as readProjectLocalSemanticConfig,Cn as readServerLock,vt as readServerPackageVersion,u as readSkillInstallStateSnapshot,ur as readStateManifest,ua as readTargetRecordedAt,Ci as readTargetVersion,Xi as reconcile,Br as recordContributor,In as recordSkillInstallEvent,Ai as redactShareSubprocessStderr,ra as registerAllTools,Zn as registerWrite,si as releaseProcessLock,_a as releaseServerLock,ir as removeLastKnownHash,_r as removeProjectSkillGitignoreBlock,Li as reportSkillInstall,hi as resetMetrics,Mr as resolveAuditScope,wr as resolveBuiltinSkillHosts,r as resolveBundleEnabled,On as resolveBundledSkillDir,Ta as resolveContentDir,Ja as resolveCursorBinaryDefault,Un as resolveCursorSpawnInvocation,Ba as resolveEffectiveLinterConfig,kt as resolveEmbeddingsCredential,O as resolveGitHubAccountFromUrl,Na as resolveGitHubAuthHost,Lt as resolveLockDir,U as resolveNativeConfigForDoc,F as resolveNativeMarkdownlintConfig,nt as resolvePack,ei as resolvePackageVersion,h as resolveSkillInstallReportSettings,qr as resolveUiInfo,He as restoreContributors,Ye as rewriteMarkdownLinksForDocumentRename,ut as rewriteWikiLinksForDocumentRename,Z as runAuthReposSubprocess,ge as runAuthStatusSubprocess,Fe as runCloneSubprocess,Ct as runDeviceFlowSubprocess,no as runWithMcpLogger,S as safeContentPath,Zt as safeSubdir,ue as safetyCheckpoint,Gt as sameGitHubLogin,rn as sanitizeClientName,ie as saveInMemoryCheckpoint,ke as saveVersion,Wi as scanLockProcesses,Ce as seedBasenameIndex,gn as seedEphemeralProjectDir,un as serializeError,Sn as setActiveSpanAttributes,_t as setupServerObservers,l as shadowGit,pr as shutdownTelemetry,Ga as spansCurrentPath,Pt as spansPreviousPath,pa as spawnDetached,Ei as splitMarkdownBlocks,$i as startWatcher,Ur as strategiesFor,zn as streamedChunkOf,Ni as streamingProblemEvent,oa as swapContributors,er as teardownToleranceTelemetryWriter,ui as toBroadcasterKey,ba as tracedAppendFileSync,sr as tracedLinkSync,br as tracedMkdir,Bi as tracedMkdirSync,vi as tracedRename,Fr as tracedRenameSync,Dr as tracedRmSync,jn as tracedRmdirSync,Oa as tracedUnlinkSync,Za as tracedWriteFile,Kn as tracedWriteFileSync,Ua as trustSystemCertificates,Mt as updateLastKnownHash,j as updateProcessLockPort,Ia as updateServerLockPort,Bt as validateAgentId,K as validateCloneInputs,R as validateSkillZip,at as waitForServerLockDrain,ri as withHiddenWindowsConsole,v as withSpan,Xr as withSpanSync,Ge as writeBundleDecision,Qe as writeMarkdownlintRule,pt as writeRootGitignoreForNewRepo,ee as writeStateManifest,ye as writeTargetVersion,Re as writeTracker};
package/dist/index.mjs CHANGED
@@ -1542,6 +1542,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
1542
1542
  `);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(`
1543
1543
  `)?`
1544
1544
  `:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const zNe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function BNe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const VNe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function HNe(e){let t={contentDirSpellings:O9(e.contentDir)};for(let n of VNe)for(let r of P9(j(e.stagingDir,n)))BNe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(j(e.stagingDir,`state`))){let e=ae(n);n.endsWith(`.jsonl`)?j9(n,t):zNe.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 UNe(e){return j(e,...I9,z9)}function WNe(e){return j(e,...I9,B9)}function GNe(e){return j(e,...L9,V9)}function KNe(e){return j(e,...L9,H9)}function qNe(e){return j(e,...R9,U9)}function JNe(e){return j(e,...R9,W9)}const G9=1e3;async function YNe(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 XNe(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 ZNe(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 QNe(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(`
1545
- `)}\n`:null}catch{return null}}function $Ne(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],f8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function ePe(e){let t=j(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/`],f8({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 tPe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function nPe(){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,bs.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 rPe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return rPe(e.maxBytes)}function iPe(e){let t=J9($J(`project`,e)),n=J9($J(`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 aPe(e){return Me(`sha256`).update(e).digest(`hex`)}function oPe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const sPe=[`"doc.name"`,`"docName"`];function cPe(e){let t=S(e,`utf-8`),n=0;for(let e of sPe){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(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,t7(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=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const lPe=new Set([`.jsonl`]);function uPe(e){let t=e.lastIndexOf(`.`);return t!==-1&&lPe.has(e.slice(t))}const dPe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function fPe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&dPe.has(e.slice(t))}function pPe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!fPe(r))continue;let{redacted:i,patterns:a,lineCount:o}=DP(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 M(e,t).split(le).join(`/`)}async function mPe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??YNe,a=r.fetchAgentEffects??XNe,o=r.fetchWatcherRecent??ZNe,s=r.readShadowHead??$Ne,c=r.readCheckpointRefs??ePe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.86.8`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??tPe,h=r.isOtlpPushEnabled??nPe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(UNe(n),j(_,`telemetry`,z9)),Z9(WNe(n),j(_,`telemetry`,B9)),Z9(GNe(n),j(_,`logs`,V9)),Z9(KNe(n),j(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,NJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`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(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=QNe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(qNe(n),j(_,`state`,U9)),Z9(JNe(n),j(_,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,sd),j(_,`state`,sd)),Z9(j(b,cd),j(_,`state`,cd)),Z9(j(b,od),j(_,`state`,od));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
1545
+ `)}\n`:null}catch{return null}}function $Ne(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],f8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function ePe(e){let t=j(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/`],f8({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 tPe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function nPe(){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,bs.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 rPe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return rPe(e.maxBytes)}function iPe(e){let t=J9($J(`project`,e)),n=J9($J(`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 aPe(e){return Me(`sha256`).update(e).digest(`hex`)}function oPe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const sPe=[`"doc.name"`,`"docName"`];function cPe(e){let t=S(e,`utf-8`),n=0;for(let e of sPe){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(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,t7(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=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const lPe=new Set([`.jsonl`]);function uPe(e){let t=e.lastIndexOf(`.`);return t!==-1&&lPe.has(e.slice(t))}const dPe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function fPe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&dPe.has(e.slice(t))}function pPe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!fPe(r))continue;let{redacted:i,patterns:a,lineCount:o}=DP(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 M(e,t).split(le).join(`/`)}async function mPe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??YNe,a=r.fetchAgentEffects??XNe,o=r.fetchWatcherRecent??ZNe,s=r.readShadowHead??$Ne,c=r.readCheckpointRefs??ePe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.86.9`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??tPe,h=r.isOtlpPushEnabled??nPe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(UNe(n),j(_,`telemetry`,z9)),Z9(WNe(n),j(_,`telemetry`,B9)),Z9(GNe(n),j(_,`logs`,V9)),Z9(KNe(n),j(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,NJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`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(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=QNe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(qNe(n),j(_,`state`,U9)),Z9(JNe(n),j(_,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,sd),j(_,`state`,sd)),Z9(j(b,cd),j(_,`state`,cd)),Z9(j(b,od),j(_,`state`,od));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
1546
1546
  `:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:e7(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,i7),S7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&HNe({stagingDir:_,contentDir:t}),e.note&&re(j(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=pPe(_));for(let t of e.extraFiles??[]){let e=t.zipName??ae(t.sourcePath);if(!Z9(t.sourcePath,j(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=w7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=iPe(n),N=Q9(_),le=[],ue=0,de=0;for(let e of N){let t=$9(_,e),n=te(e).size,r=uPe(t)?oPe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=cPe(e))}let fe={applied:se};ce!==null&&(fe.secretScrub=ce);let P={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:aPe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:le};re(j(_,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=O9(t),me=N.some(e=>{try{let t=S(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:_,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function hPe(e){let{collected:t,outputPath:n}=e,r=k(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 WEe.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 gPe(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,bs.parse)(S(n,`utf-8`)),r=yY(t)?t.content:void 0,i=yY(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return N(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 N(e)}async function _Pe(e,t,n,r,i,a){let o=T7(t,e.logger),s=await mPe({contentDir:gPe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...EMe(o,e.userLogsDir??j(KJ(),`logs`)),...D7(e.cachesDir??j(_e(),`Library`,`Caches`))],userStateFiles:O7(e.bugReportsDir??C7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(k(e.outputPath),{recursive:!0}),await hPe({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function vPe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??D9,i=()=>nMe(e.diagnosticReportsDir??j(_e(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return _Pe(e,t,n,r,i(),await x7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await jMe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:D7(e.cachesDir??j(_e(),`Library`,`Caches`)),bugReportLedgerFiles:O7(e.bugReportsDir??C7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await x7(e.osTerminationEvidenceDeps):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{EY as ALL_EDITOR_IDS,DY as EDITOR_LABELS,rX as EDITOR_TARGETS,Zye as HOSTS_WITH_USER_SKILL_DIR,Wje as LAUNCH_CONFIG_NAME,xNe as PATH_SHIM_BEGIN,CNe as PATH_SHIM_BLOCK_RE,SNe as PATH_SHIM_END,m5 as ProjectPathSafetyError,Sje as addOkPathsToGitExclude,h5 as assertProjectPathSafe,zY as buildManagedServerEntry,uNe as buildMcpConfigDeclineEvent,dNe as buildMcpConfigMigrateEvent,Z5 as classifyExistingMcpEntry,vPe as collectReportBundle,ONe as createCliProbeResolver,aY as createTokenStore,CMe as defaultBugReportZipPath,Ke as detectGh,Ye as detectGhAccounts,Jje as detectInstalledEditors,JY as droppedManagedKeys,vbe as editorConfigPathDisplay,_be as editorEntryLocator,$Me as ensurePiBridge,cMe as findJetsamKillSync,k5 as formatTrackedRemediation,Tje as getExcludedOkPaths,D5 as getInstalledSkillProjectionPaths,Xye as getNativeTomlMcpEditor,E5 as getOkArtifactPaths,LY as isEntryUpToDate,BY as isOwnManagedEntry,vNe as loadConfig,Sye as makeLazyProbeTokenStore,C7 as okBugReportsDir,y9 as parseGitHubBlobUrl,yNe as parseGitHubShareUrl,b9 as parseGitHubTreeUrl,v9 as parseGitUrl,wNe as pathInstallMarkerPath,sje as previewContent,Yje as probeOwnManagedEditorMcpEntry,ZMe as probePiBridgeState,O5 as probeTrackedOkPaths,Y5 as readExistingMcpEntry,wje as readSharingMode,DP as redactContent,Cje as removeOkPathsFromGitExclude,oNe as removeOwnMcpEntry,vje as removeProjectSkill,ANe as removeUserGlobalSkillBundle,INe as removeUserSkill,fje as resolveProjectRoot,hNe as runStop,m9 as truncatePriorEntry,T9 as userGlobalSkillBundleTargets,FNe as userSkillPresentAnywhere,bNe as validateLocalFolderForShare,J5 as writeEditorMcpConfig,NNe as writeProjectAiIntegrations,x5 as writeProjectSkill,qje as writeUserMcpConfigs,PNe as writeUserSkill};
1547
1547
  //# sourceMappingURL=index.mjs.map