@inkeep/open-knowledge 0.88.0-beta.4 → 0.88.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-Cqoxvtnd.mjs +1 -0
- package/dist/{dist-CkWLD9k6.mjs → dist-6mRqHaPH.mjs} +1 -1
- package/dist/{dist-Gs3Faeeg.mjs → dist-cEMV5fgn.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-C0rtJLMt.mjs → init-CoefCaSm.mjs} +2 -2
- package/dist/init-D5P1EZ11.mjs +1 -0
- package/dist/{launch-json-removal-DlNTrdX0.mjs → launch-json-removal-BiKmyugG.mjs} +1 -1
- package/dist/{loader-DzqfET0v.mjs → loader-BiWSR3dj.mjs} +1 -1
- package/dist/loader-ZszRbrUC.mjs +1 -0
- package/dist/{open-browser-DmIGnAR_.mjs → open-browser-D1i95Ud7.mjs} +1 -1
- package/dist/{preview-5gP5qg7t.mjs → preview-CJB_jf6z.mjs} +1 -1
- package/dist/preview-wzCrdLuG.mjs +1 -0
- package/dist/public/assets/{AccountSection-pyWbuFmc.js → AccountSection-CLAysoUu.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-BzCNdm53.js → ActivityModeContent-BFLva-aI.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-ByAYJiuY.js → AddPropertiesButton-Df8GzxQM.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-aOO-fsyJ.js → AgentDiffPane-CkjdHqXl.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-CfxTJoHZ.js → AttachmentsSection-CdnT56ud.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-DZQ4BkYp.js → CodeMirrorPropInput-Cu6MHfhn.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-BdXHoyur.js → ContentRulesSection-Blqi7cZd.js} +1 -1
- package/dist/public/assets/{DocumentContext-f_UBvd4w.js → DocumentContext-DRHluqqS.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-DEm-TvNE.js → EditorModeToggle-CRBmAlro.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-FAkgGMIx.js → ExcalidrawDocEditor-CL9KvU2y.js} +1 -1
- package/dist/public/assets/FeedbackForm-Da0oPcpz.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-D0G8dXM_.js → ImportSkillDialog-dTN6VYKK.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-B3MJEO2P.js → LinkPreviewsSection-CjS2RaiF.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-VH1bWD9N.js → LintConfigEditor-DcTFFy7u.js} +1 -1
- package/dist/public/assets/{LintingSection-DxwVKi4j.js → LintingSection-CoeMghc-.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-ClFTnfdN.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-Dp9fraTI.js → ManagedArtifactProperties-gTdmM_LU.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-bmNuQCD6.js → MermaidDocEditor-wOrLIKcP.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-CgnCCHbA.js → NetworkAccessSection-CKEEYiU7.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-BveMZzwy.js → PropertyDisplayRow-DAjfj2IC.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-CiHvsXpf.js → PublishToGitHubDialog-jaZQVUoh.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-St76u0ee.js → SchemaConfigEditor-C8yLS6fx.js} +1 -1
- package/dist/public/assets/{SearchSection-CoxnlMu0.js → SearchSection-DjPDYJWk.js} +1 -1
- package/dist/public/assets/{SessionsHost-CgfT1hep.js → SessionsHost-DmYXxZZ6.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-t3iE3fLz.js → SettingsDialogBody-C1ciu0Ef.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-vRzY7Jv8.js → ShareReceiveMissDialog-C5_gwWJp.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-CtsbLqDT.js → SkillToolbarControls-BO6uEYyc.js} +1 -1
- package/dist/public/assets/{SourceEditor-CXnlzCx3.js → SourceEditor-Cza2d3-w.js} +1 -1
- package/dist/public/assets/{SyncSection-C-5iMrRu.js → SyncSection-DRpeJ3L1.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-CZP25yhb.js → SyncStatusBadge-CdicdQLN.js} +1 -1
- package/dist/public/assets/{TerminalSection-TWq8Mkh7.js → TerminalSection-B71tSEOA.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DjKQZ6e8.js → TerminalWindowApp-CA81dRDp.js} +1 -1
- package/dist/public/assets/{TextDocEditor-CLXQ0-BX.js → TextDocEditor-BpP8EOP8.js} +1 -1
- package/dist/public/assets/{ThreadView-Dsiuhy-G.js → ThreadView-BuEDX-dN.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-bl_YLWMz.js → TimelineDiffPane-COVO9Sul.js} +1 -1
- package/dist/public/assets/{client-version-S2pq-A2d.js → client-version-BMMGsbZv.js} +1 -1
- package/dist/public/assets/{comment-chips-BZPfQgcT.js → comment-chips-DjaMTlPp.js} +1 -1
- package/dist/public/assets/{config-provider-DJlrqCRv.js → config-provider-BCHjFvv6.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-D4PZBxZV.js → doc-undo-manager-CVm52oKR.js} +1 -1
- package/dist/public/assets/{index-CaVRqEFp.js → index-CHk56bMp.js} +7 -7
- package/dist/public/assets/{lint-plugins-DyoQe2qv.js → lint-plugins-rNV0QOjq.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-3l1VsraZ.js → pending-receive-nav-store-wHUEd2A8.js} +1 -1
- package/dist/public/assets/{preferred-session-events-BLRejZ_z.js → preferred-session-events-B2mWHLBY.js} +1 -1
- package/dist/public/assets/{progress-RA1uWm0H.js → progress-CeRpCdlQ.js} +1 -1
- package/dist/public/assets/{selection-context-0pM6ndc5.js → selection-context-C9mdbZ--.js} +1 -1
- package/dist/public/assets/{src-ptqVq5ku.js → src-yfrSguDD.js} +1 -1
- package/dist/public/assets/{telemetry-impl-qEuHQYiG.js → telemetry-impl-DiaERQBF.js} +1 -1
- package/dist/public/assets/{telemetry-startup-DrvSlOEH.js → telemetry-startup-Bvtft2eh.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-CX1Qs3dW.js → typing-burst-detector-BY09tzwq.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BUvrSJkx.js → use-activity-panel-Bi79r9jb.js} +1 -1
- package/dist/public/assets/{use-open-skill-BY5JNtzY.js → use-open-skill-Jjm4ZZZD.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-C6TjwbMf.js → use-terminal-enabled-Do98jWF3.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CsqNP2D3.js → use-timeline-entry-diff-DiYw2kxX.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/{registry-probes-lh9u_4Y8.mjs → registry-probes-D8GxfmkJ.mjs} +1 -1
- package/dist/{removal-file-path-dVFSEG9k.mjs → removal-file-path-KMM09nTv.mjs} +1 -1
- package/dist/{repair-launch-json-BAXUEwk6.mjs → repair-launch-json-CJba2_R0.mjs} +1 -1
- package/dist/{repair-mcp-configs--oBRB5Ge.mjs → repair-mcp-configs-B2Zf1DH7.mjs} +1 -1
- package/dist/{src-BPpE7LaD.mjs → src-CE3j3bJc.mjs} +1 -1
- package/dist/src-CrVMwhBP.mjs +1 -0
- package/dist/{start-Xcu0zXYB.mjs → start-Bu9LVxBr.mjs} +3 -3
- package/dist/start-fZp4epxx.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-BJbL6KLX.mjs +0 -1
- package/dist/init-SvoaMCoH.mjs +0 -1
- package/dist/loader-C45P_Nry.mjs +0 -1
- package/dist/preview-DsLcBlwe.mjs +0 -1
- package/dist/public/assets/FeedbackForm-B7HCZMAo.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-DyFXBJAT.js +0 -1
- package/dist/src-K7R3CxBI.mjs +0 -1
- package/dist/start-C42cSWsK.mjs +0 -1
|
@@ -916,7 +916,7 @@ ${e.terminator}`}function vqe(e){return`(${AV(e.body)})${kV(e.redirections)}`}fu
|
|
|
916
916
|
`).run(r,o),c.close(),s?.()}),l=!0,WK.delete(u))};return WK.add(u),u3e||(u3e=!0,process.prependOnceListener(`exit`,()=>{for(let e of WK)try{e()}catch(e){q(`server-authority`).warn({err:e},`Content ownership exit release failed`)}})),{scope:t,release:u}}var qK=class extends Error{constructor(){super(`This server does not own this content path. Open the project or file that owns it.`),this.name=`ContentScopeAdmissionError`}},JK=class extends Error{problemType;constructor(e){super(`The server is shutting down.`),this.name=`ServerMutationShuttingDownError`,this.problemType=e?`urn:ok:error:auth-failed`:`urn:ok:error:concurrent-operation`}};function h3e(e){return{writeFile:aW.writeFile,rename:async(t,n)=>{e(n),XU(t,n)}}}function YK(e){try{let{ancestor:t,missingSegments:n}=C2e(e);return W(t,...n)}catch(e){throw sG(e)===`ELOOP`?new EK(`symlink cycle in path`):e}}function g3e(e,t){return FU(`ok.boot.content-scope`,{attributes:{"content.scope.kind":t===void 0?`tree`:`file`}},n=>{let r=_3e(e,t);return n.setAttribute(`content.scope.exclusions`,r.kind===`tree`?r.excluded.length:0),r})}function _3e(e,t){let n=YK(e);if(t!==void 0)return{kind:`file`,path:YK(W(e,t))};let r=[],i=[n];for(;i.length>0;){let e=i.pop();if(e===void 0)break;try{for(let t of lc(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=H(e,t.name);try{zG(n)?r.push(YK(n)):i.push(n)}catch(e){let t=sG(e);if(t!==`ENOENT`&&t!==`ENOTDIR`&&t!==`EACCES`&&t!==`EPERM`)throw e;q(`server-content-policy`).warn({path:RU(n),code:t},`Unreadable nested-project marker remains in the parent authority scope`)}}}catch(t){let n=sG(t);if(n!==`ENOENT`&&n!==`ENOTDIR`&&n!==`EACCES`&&n!==`EPERM`)throw t;(n===`EACCES`||n===`EPERM`)&&q(`server-content-policy`).warn({path:RU(e),code:n},`Unreadable directory remains in the parent authority scope`)}}return{kind:`tree`,path:n,excluded:r}}function v3e(e,t){let n=YK(t);if(e.kind===`file`){if(!KK(e,n))throw new qK;return n}let r=e.excluded.find(e=>KK({kind:`tree`,path:e,excluded:[]},n));if(r!==void 0)throw new BG(r);if(!KK(e,n))throw new qK;return n}function y3e(e,t){let n=v3e(e,t);e.kind===`tree`&&HG(n,e.path)}function b3e(e,t){if(y3e(e,t),e.kind===`file`)throw new qK;let n=YK(t),r=e.excluded.find(e=>KK({kind:`tree`,path:n,excluded:[]},e));if(r!==void 0)throw new BG(r)}const XK=`x-request-id`,x3e=/^[A-Za-z0-9._-]{1,128}$/;function S3e(e){let t=e.headers[XK],n=Array.isArray(t)?t[0]:t;return n!==void 0&&x3e.test(n)?n:Pc()}const C3e=new WeakMap;function w3e(e,t){C3e.set(e,t)}function ZK(e){return C3e.get(e)}const QK=()=>q(`http`);let T3e=null;function $K(){return T3e||=NU().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),T3e}function X(e,t,n,r,i={}){t===500&&i.cause instanceof EK&&!(i.cause instanceof DK)&&(t=400,n=`urn:ok:error:path-escape`,r=`Path resolves outside the content directory or contains a symlink cycle.`,i={...i,detail:void 0}),i.cause instanceof JK&&(t=503,n=i.cause.problemType,r=i.cause.message),(i.cause instanceof BG||i.cause instanceof qK)&&(t=403,n=`urn:ok:error:path-escape`,r=`Path is outside this server’s content scope.`,i={...i,detail:i.cause.message});let a=i.instance??`urn:uuid:${Pc()}`;if(IU({"ok.error.instance":a}),e.headersSent||e.writableEnded||e.destroyed){QK().error({event:`api.error.double-write`,instance:a,requestId:ZK(e.req),type:n,status:t,handler:i.handler},`errorResponse called after headers already sent — suppressed`),$K().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let s={type:n,title:o(r),status:t,instance:a,detail:i.detail===void 0?void 0:o(i.detail)},c=Re.safeParse(s);if(!c.success){QK().error({event:`api.error.malformed-envelope`,requestId:ZK(e.req),issues:c.error.issues,body:s,handler:i.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`),$K().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}let l=i.extensions?{...i.extensions,...s}:s;$K().add(1,{type:n,...i.handler?{handler:i.handler}:{}});let u=i.logLevel??(t>=500?`error`:`warn`);QK()[u]({event:`api.error`,instance:a,requestId:ZK(e.req),type:n,status:t,handler:i.handler,detail:i.detail,err:i.cause,...i.extensions?{extensions:i.extensions}:{}},r);let d;try{d=JSON.stringify(l)}catch(n){QK().error({event:`api.error.unserializable-body`,requestId:ZK(e.req),bodyKeys:Object.keys(l),handler:i.handler,originalStatus:t,instance:a,err:n},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),$K().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(d)}function E3e(e,t,n,r={}){let i=r.instance??`urn:uuid:${Pc()}`,a={type:`error`,problem:{type:t,title:o(n),status:e,instance:i,detail:r.detail===void 0?void 0:o(r.detail)}},s=qn.safeParse(a);if(!s.success)return QK().error({event:`api.streaming.malformed-envelope`,issues:s.error.issues,body:a,handler:r.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`),$K().add(1,{type:`urn:ok:error:internal-server-error`,...r.handler?{handler:r.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:i}};$K().add(1,{type:t,...r.handler?{handler:r.handler}:{}});let c=e>=500?`error`:`warn`;return QK()[c]({event:`api.streaming.error`,instance:i,type:t,status:e,handler:r.handler,detail:r.detail,err:r.cause},n),a}function eq(e,t){return(n,r,i,a={})=>{if(e.writableEnded||e.destroyed){QK().error({event:`api.streaming.error.suppressed`,requestId:ZK(e.req),type:r,status:n,handler:t,detail:a.detail,err:a.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),$K().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let o=E3e(n,r,i,{handler:t,...a});try{e.write(`${JSON.stringify(o)}\n`)}catch(i){QK().error({event:`api.streaming.error.write-failed`,requestId:ZK(e.req),type:r,status:n,handler:t,err:a.cause,writeErr:i},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const tq=`urn:ok:error:concurrent-overwrite-refused`,D3e=`Concurrent overwrite refused.`,O3e=`Another writer changed this document recently. Wait a few seconds and retry.`,k3e=`${O3e} A write with position append or prepend is not refused.`;var nq=class extends Error{file;name=`ConcurrentOverwriteRefusedError`;constructor(e){super(`Concurrent overwrite refused for ${e}`),this.file=e}};function A3e(e,t){eZe(),q(`agent-write`).warn({event:`concurrent-overwrite-write-refused`,handler:t,"doc.name":HH(e.file)},`concurrent replace refused before mutation`)}function j3e(e,t,n){A3e(t,n),X(e,409,tq,D3e,{handler:n,detail:k3e,extensions:{file:t.file,retryAfterSeconds:3,...NG[`urn:ok:error:concurrent-overwrite-refused`]},extraHeaders:{"Retry-After":`3`}})}const rq=`/internal/acp/document-write`;async function M3e(e,t){let n=await e(`POST`,rq,{body:JSON.stringify({docName:t.docName,file:t.file,markdown:t.markdown,...N3e(t.file),agentId:t.agentId,agentName:t.agentName,clientName:t.clientName}),contentType:`application/json`});if(n===null)throw Error(`${rq} is not dispatchable in process`);return I3e(n.status,Yx(JSON.parse(n.bodyText)),t.file)}function N3e(e){return e.endsWith(`.mdx`)?{extension:`.mdx`}:e.endsWith(`.md`)?{extension:`.md`}:{}}function P3e(e){let t=Rr(e);if(t!==void 0)return{outcome:t.outcome,...t.saved===void 0?{}:{saved:t.saved},...t.nextStep===void 0?{}:{nextStep:t.nextStep}}}function F3e(e,t){let n=typeof t.title==`string`?t.title:`The write answered ${e}.`;return typeof t.detail==`string`?`${n} ${t.detail}`:n}function I3e(e,t,n){let r=P3e(t);if(e>=200&&e<300&&(r===void 0||r.outcome===`applied`||r.outcome===`merged-first`))return r===void 0?{}:{_meta:{openknowledge:{...r}}};throw t.type===`urn:ok:error:concurrent-overwrite-refused`?new WS(-32009,O3e,{type:tq,file:n,retryable:!0,retryAfterSeconds:3,...r}):new WS(-32010,F3e(e,t),{type:typeof t.type==`string`?t.type:`urn:ok:error:internal-server-error`,file:n,...r})}const L3e=/command not found|not recognized as an internal or external command/i,R3e=/permission denied/i,z3e=/cannot find module|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND/i,B3e=/out of memory|ENOMEM/i,V3e=new Set([`SIGTERM`,`SIGINT`,`SIGHUP`]);function H3e({exitCode:e,signal:t,tail:n}){if(t!==null)return t===`SIGKILL`?`killed`:V3e.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?``:Pwe(n);return B3e.test(r)?`out-of-memory`:L3e.test(r)?`command-not-found`:R3e.test(r)?`not-executable`:z3e.test(r)?`missing-module`:`unknown`}function U3e(e){return{exitCode:e.exitCode,signal:e.signal,cause:H3e(e)}}function W3e(e){return{reason:`exited`,exit:U3e(e),machineDetail:e.tail}}function G3e(e){return e===`connect`||e===`session-setup`}function K3e(e){return H(e,Bre)}function q3e(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),SW(`${t.join(`
|
|
917
917
|
`)}\n\n`)}const iq=new Map;function J3e(e,t){let n=K3e(e),r=q3e(t),i=(iq.get(n)??Promise.resolve()).then(async()=>{let e=await Ac(n).then(e=>e.size,()=>void 0);mo(e)===`w`?await HU(n,r):await UU(n,r)}),a=i.then(()=>void 0,()=>void 0);return iq.set(n,a),a.then(()=>{iq.get(n)===a&&iq.delete(n)}),i}const aq=`v24.18.0`,oq=`0.11.28`,Y3e=`https://nodejs.org/dist`,X3e=`https://github.com/astral-sh/uv/releases/download`,Z3e={node:45,uv:20};function Q3e(e){return e===`npx`?`node`:`uv`}function sq(e){return e===`node`?{kind:`node`,displayName:`Node.js`,provides:`npx`,version:aq,approxSizeMB:Z3e.node,sourceHost:`nodejs.org`}:{kind:`uv`,displayName:`uv`,provides:`uvx`,version:oq,approxSizeMB:Z3e.uv,sourceHost:`github.com/astral-sh`}}function cq(){return H(nS(),`runtimes`)}function lq(e){return e===`node`?aq:oq}function $3e(e){let t=process.platform===`win32`;return e===`node`?t?[`npx.cmd`,`npx.exe`]:[`npx`]:t?[`uvx.exe`]:[`uvx`]}function e6e(){let e=xc(),t=vc(),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-${aq}-${n}-${r}.${i?`zip`:`tar.gz`}`;return{archiveUrl:`${Y3e}/${aq}/${a}`,checksumUrl:`${Y3e}/${aq}/SHASUMS256.txt`,archiveName:a,isZip:i}}function t6e(){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`}[`${xc()}-${vc()}`];if(e===void 0)return null;let t=xc()===`win32`,n=`uv-${e}.${t?`zip`:`tar.gz`}`;return{archiveUrl:`${X3e}/${oq}/${n}`,checksumUrl:`${X3e}/${oq}/${n}.sha256`,archiveName:n,isZip:t}}function n6e(e){return e===`node`?e6e():t6e()}function r6e(e){return n6e(e)!==null}async function i6e(e){try{let t=await Ac(e);return!t.isFile()&&!t.isSymbolicLink()?!1:(process.platform===`win32`||await Cc(e,xae.X_OK),!0)}catch{return!1}}async function uq(e,t,n){let r;try{r=await Dc(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 uq(H(e,i.name),t,n-1);if(r!==null)return r}return null}function a6e(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 o6e(e,t=cq()){let n=H(t,e,yW(lq(e)));try{if(!(await Ac(n)).isDirectory())return null}catch{return null}let r=await uq(n,$3e(e),3);return r===null||!await i6e(r)?null:a6e(e,r,t)}var dq=class extends Error{constructor(e,t){super(e,t),this.name=`RuntimeInstallError`}};async function s6e(e,t,n=cq()){await OW(H(n,e),t,`[managed-runtime]`)}async function c6e(e,t,n=cq()){let r=H(n,e,yW(lq(e))),i=H(V(r),`.install-damaged-${yW(lq(e))}-${Pc()}`);try{await GU(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 WU(i,{recursive:!0,force:!0}).catch(()=>{}),!0}async function l6e(e,t,n={}){let r=n.root??cq(),i=H(r,e,yW(lq(e)));try{return await kW({versionDir:i,stagingLabel:yW(lq(e)),findInstalled:()=>o6e(e,r),prepare:async r=>{let i=n6e(e);if(i===null)throw new dq(`no ${e} build for ${xc()}-${vc()}`);let a=H(r,i.archiveName);t.info({kind:e,version:lq(e),url:i.archiveUrl},`[managed-runtime] downloading runtime`);let[o,s]=await Promise.all([B$e(i.archiveUrl,a,{signal:n.signal,onProgress:n.onProgress,fetchImpl:n.fetchImpl}),V$e(i.checksumUrl,{signal:n.signal,fetchImpl:n.fetchImpl})]),c=H$e(s,i.archiveName);if(c===null)throw new dq(`no published checksum for ${i.archiveName}`);if(o!==c)throw new dq(`checksum mismatch for ${i.archiveName}: got ${o}, expected ${c}`);let l=H(r,`extracted`);await KU(l,{recursive:!0}),await z$e(a,l,i.isZip);let u=await uq(l,$3e(e),3);if(u===null||!vW(l,u))throw new dq(`extracted ${e} archive has no usable launcher`);return l},log:t,logPrefix:`[managed-runtime]`,logContext:{kind:e,version:lq(e)},installedMessage:`runtime installed`,missingAfterCommitMessage:`installed ${e} runtime not found after extract`,beforeCommit:n.beforeCommit,commitLockTimeoutMs:n.commitLockTimeoutMs})}catch(t){throw t instanceof dq?t:new dq(`installing ${e} ${lq(e)} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}const u6e=`CODEX_CONFIG`;function d6e(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 f6e(e){let t=e.maxContextWindow,n=e.contextWindow;return t===null&&n===null?[]:t===null?[n]:n===null||n>=t?[t]:[n,t]}function p6e(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function m6e(e){if(e===void 0||e.trim()===``)return{};try{return p6e(JSON.parse(e))}catch{return{}}}function h6e(e,t){if(t===null||!Number.isFinite(t)||t<=0)return e;let n={...m6e(e[u6e]),model_context_window:Math.floor(t)};return{...e,[u6e]:JSON.stringify(n)}}function g6e(e){return(e.visibility??`list`)===`list`}const _6e={"codex-acp":`codex-config-env`,"claude-acp":`model-variant`};function fq(e){return _6e[e]??`none`}function v6e(e,t,n){if(n===null||fq(t)!==`codex-config-env`)return e;let r=h6e(e.env,n);return r===e.env?e:{...e,env:r}}function y6e(e){return fq(e.agentId)===`codex-config-env`?e.archived||e.turnActive||e.hasStartedWork?{kind:`needs-new-chat`}:{kind:`apply`}:{kind:`unsupported`}}function pq(e,t,n={}){YU(t,{recursive:!0});for(let r of lc(e)){let i=H(e,r);if(n.filter?.(i)===!1)continue;let a=H(t,r);mc(i).isDirectory()?pq(i,a,n):qU(a,K(i))}}const b6e=`open-knowledge`,x6e=`SKILL.md`,mq=new Set([`ENOENT`,`ENOTDIR`,`EISDIR`]);function S6e(e){return H(e,`agent-skill`,b6e)}function C6e(e,t){let n;try{n=K(t)}catch(e){let t=e.code;if(t!==void 0&&mq.has(t))return!1;throw e}return K(e).equals(n)}function w6e(e,t){let n=lc(e),r;try{r=new Set(lc(t))}catch(e){let t=e.code;if(t!==void 0&&mq.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(mc(n).isDirectory()){let e;try{e=mc(a).isDirectory()}catch(e){let t=e.code;if(t!==void 0&&mq.has(t))return!1;throw e}if(!e||!w6e(n,a))return!1}else if(!C6e(n,a))return!1}return!0}var T6e=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 E6e(e){let t;try{t=await wc(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(t.isSymbolicLink())throw new T6e(e)}async function D6e(e){let t=S6e(e.localDir),n=V(t),r=async()=>{await E6e(n),await E6e(t)};return kW({versionDir:t,stagingLabel:b6e,findInstalled:async()=>(await r(),w6e(e.sourceDir,t)?t:null),prepare:async t=>(pq(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 O6e(e,t=process.env){let n=(e.kind===`npx`||e.kind===`uvx`)&&Bs(e.cmd),r={};for(let[n,i]of Object.entries(e.env))n.toLowerCase()===`path`||!Ui(n)||i.includes(`\0`)||t[n]!==i&&(r[n]=i);return{executable:e.cmd,args:e.kind===`npx`?k1e(e.args):[...e.args],env:r,pathPrepend:n?[V(e.cmd)]:[]}}function k6e(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function A6e(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`)||Ui(n)&&(t[n]=r);return t}function j6e(e){return typeof e==`object`&&e?e:null}function M6e(e,t){return{executable:t.executable,args:[...t.args,...k6e(e.args)],env:{...t.env,...A6e(e.env)},pathPrepend:[...t.pathPrepend]}}function hq(e,t){return(e??[]).flatMap(e=>{let n=j6e(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 N6e(e,t,n){if(t===null)return null;for(let r of e??[]){let e=j6e(r);if(e!==null&&e.id===n&&e.type===`terminal`)return M6e(e,t)}return null}const P6e=2e3;function F6e(e){let t=0;for(;t<e.length&&(e[t]&192)==128;)t++;return e.subarray(t)}function I6e(e,t){let n=Buffer.from(e,`utf8`);return n.length<=t?e:F6e(n.subarray(n.length-t)).toString(`utf8`)}function gq(e){if(e.outputBytes<=e.byteLimit)return;let t=F6e(Buffer.from(e.output,`utf8`).subarray(e.outputBytes-e.byteLimit));e.output=t.toString(`utf8`),e.outputBytes=t.length,e.truncated=!0}var L6e=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=v1e(this.spawnEnv(n)),i=e.cwd==null?this.defaultCwd:Bs(e.cwd)?e.cwd:W(this.defaultCwd,e.cwd),a=process.platform===`win32`,o=a?qW(e.command,WW(r)):e.command,s=a&&/\.(cmd|bat)$/i.test(o),{cmd:c,args:l}=s?JW(o,e.args??[]):{cmd:o,args:e.args??[]},u=Ps(c,l,{cwd:i,env:r,stdio:[`ignore`,`pipe`,`pipe`],shell:!1,detached:!a,windowsHide:!0,windowsVerbatimArguments:s}),d=e.outputByteLimit,f={child:u,output:``,outputBytes:0,byteLimit:typeof d==`number`&&d>0?Math.floor(d):1048576,truncated:!1,exitStatus:null,exitWaiters:[],transcriptBytes:0,transcriptPaused:!1,pausedTail:``};this.terminals.set(t,f),this.safeEmit({kind:`terminal_created`,terminalId:t,command:e.command,args:e.args??[],ts:Date.now()});let p=e=>this.ingestChunk(t,f,e);u.stdout?.setEncoding(`utf8`),u.stdout?.on(`data`,p),u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,p);let m=!1;return u.on(`spawn`,()=>{m=!0}),u.on(`error`,e=>{if(m){this.log.warn({err:e,terminalId:t},`[acp-terminals] child error after spawn`);return}p(`${e.message}\n`),this.settleExit(t,f,{exitCode:127,signal:null})}),u.on(`close`,(e,n)=>{this.settleExit(t,f,{exitCode:e,signal:n})}),{terminalId:t}}output(e){let t=this.mustGet(e);return gq(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 QW(t.child,{graceMs:P6e})}async release(e){let t=this.terminals.get(e);t!==void 0&&(t.exitStatus===null&&await QW(t.child,{graceMs:P6e}),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=MW(e);return this.loginShellPath===null||PW(e)?t:zW(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?gq(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=I6e(t.pausedTail+n,16384)}}settleExit(e,t,n){if(t.exitStatus!==null)return;t.exitStatus=n,gq(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 _q=String.raw`(?![\p{L}\p{M}\p{N}_])`,R6e=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(`|`)})${_q}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),z6e=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/,B6e=/^[\s,:;.!?\-–—•|]+(?=\s|$)/;function V6e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function H6e(e){return(e.trim().split(`
|
|
918
918
|
`)[0]??``).trim()}function vq(e){let t=H6e(e);if(t.length<=48)return t;let n=Sa(t,47),r=n.lastIndexOf(` `);return`${(r>=24?n.slice(0,r):n).trimEnd()}…`}function U6e(e,t){let n=H6e(e),r=n.replace(z6e,``);if(t!==void 0&&t.trim()!==``){let e=V6e(t.trim()),n=String.raw`[,:;!.?\-–—•|]`,i=RegExp(`^(?:@${e}${_q}(?:\\s+|${n}+(?:\\s+|$)|$)|${e}${_q}\\s*${n}+(?:\\s+|$)|@?${e}${_q}$)`,`iu`);r=r.replace(i,``)}for(let e=0;e<6;e++){let e=r.replace(R6e,``);if(e===r)break;r=e}r=r.replace(B6e,``).trim();let i=r.split(/\s+/).filter(e=>e!==``).length;return!(r!==``&&(i>=2||r.length>=12))||r===n?vq(n):vq(r.charAt(0).toUpperCase()+r.slice(1))}const W6e=8,G6e=5e3,yq=3e5,bq=45e3,K6e=5e3,q6e=2e3,J6e=new Set([`ready`,`auth_required`,`authenticating`]),Y6e=`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 X6e(e){if(e===null)return Y6e;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`${Y6e}\n\n${t}`}const Z6e=new Set([`gemini`]);function Q6e(e){return e.source===`registry`&&Z6e.has(e.id)}function $6e(e,t,n){return n?.embeddedContext===!0?{type:`resource`,resource:{uri:qs(e).href,text:t,mimeType:`text/markdown`}}:{type:`text`,text:`\n\n--- OpenKnowledge skill: ${x6e} ---\n${t}\n--- End skill ---`}}var xq=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},Sq=class extends jW{refusal;constructor(e,t){super(`command-not-found`,t),this.name=`RuntimeConsentRefusedError`,this.refusal=e}},e8e=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},t8e=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function Cq(){return new xq(`not-ready`,`the thread was restarted during the sign-in`)}function n8e(e){return e.source===`registry`&&oXe[e.id]===`pi`}function r8e(e,t,n){let r=hi.resolve({host:e===void 0?void 0:{cliArgs:e},...n?.env===void 0?{}:{env:n.env}}).stdioServer([`mcp`,`--port`,String(t)]),{command:i,args:a}=r,o=Object.keys(r.env).length>0?{env:r.env}:{};if(i.includes(`/`)||i.includes(`\\`))return{command:i,args:a,...o};let s=(n?.resolveCommand??(e=>pW(e,NW())))(i);return s===null?(n?.log?.warn({command:i},`[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:i,args:a,...o}):{command:s,args:a,...o}}var i8e=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??(()=>DW(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]=x0e(e.globalDir,e.localDir);this.persistence=new C0e({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,o8e(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 xq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(await jH({site:`acp-thread`,agentId:n===null?x(t.id)??t.id:t.id,mode:`acp`,log:this.opts.log,snapshot:this.opts.hostSnapshot}),this.destroyed)throw new xq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`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,launchTicket:null,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};this.threads.set(r,a);let o=kq(a,e.prompt!==void 0&&e.prompt!==``||e.attachments!==void 0&&e.attachments.length>0?{content:e.prompt??``,attachments:e.attachments}:null);return this.emitStatus(a,`spawning`),this.startThread(a,o,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),Aq(a,o)&&this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await wH(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new xq(`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 xq(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new xq(`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??=D6e({localDir:this.opts.localDir,sourceDir:t??RH(`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}vW(e.cwd,r)||this.opts.log.info({...n,cwd:e.cwd,skillDir:r},`[acp-threads] skill staged above agent cwd`);let i=H(r,x6e);if(!Q6e(e.agentRef))return{skillPath:i,inlineText:null};try{return{skillPath:i,inlineText:await Ec(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,r=`reuse`,i,a=`available`){let o;if(n!==null)o=await this.ensureLaunchable(e,t,q1e(n),i);else{let s=await this.opts.registry.getAgent(e.agentRef.id);if(s===void 0)throw new xq(`unknown-agent`,`agent vanished`);try{o=await y1e(s,cXe(),this.opts.log,void 0,n=>this.ensureLaunchable(e,t,n,i),{reacquire:r===`reacquire`,install:!0,onAcquiring:()=>{Aq(e,t)&&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(r){if(r instanceof jW&&r.npxCacheEntry!==void 0&&a===`available`&&await this.clearStaleNpxCacheEntry(e,t,r.npxCacheEntry))return this.connectAgent(e,t,n,`reacquire`,i,`spent`);throw r}}if(o===null||!Aq(e,t))return null;let s=await this.resolveLoginShellPath().catch(()=>null);if(!Aq(e,t))return null;let c=await this.stageProjectSkillFor(e);if(!Aq(e,t))return null;e.projectSkill=c;let l=new L6e({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:s});e.terminalAuthBase=O6e(o),e.agentLaunchPath=WW(o.env),e.agentNpmCache=U0e(o.env),o=v6e(o,e.agentRef.id,e.launchSettings?.contextWindow??null),this.emitStatus(e,`spawning`);let u=o.kind===`npx`?YW(o):YW(o,e.cwd);e.child=u,e.terminals=l;let d=new Promise(e=>u.once(`close`,()=>e())),f,p=()=>u.exitCode===null&&u.signalCode===null&&u.stdout?.readableEnded!==!0&&u.stdout?.destroyed!==!0?Promise.resolve():(f??=new Promise(e=>{let t=setTimeout(e,1e3);t.unref(),d.then(()=>{clearTimeout(t),e()})}),f);e.drainStderr=p;let m=``,h=``,g=!0,_=CW(t=>{g&&(m=`${m}${t}\n`.slice(-16e3)),t.trim()!==``&&(e.stderrTail.push(t.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())},e=>{g&&(h=`${h}${e}\n`.slice(-16e3))}),v=o.kind,y=!1,b=()=>v===`npx`&&g&&a===`available`&&(IW(h)!==null||D1e(h)),x=()=>y||b()||!Aq(e,t);if(u.stderr?.setEncoding(`utf8`),u.stderr?.on(`data`,_.write),u.stderr?.on(`end`,_.end),u.stderr?.on(`data`,t=>{for(let n of t.split(`
|
|
919
|
-
`))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))}),u.on(`error`,t=>{x()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),u.on(`exit`,(t,n)=>{if(e.child!==u)return;let r=J6e.has(e.info.status);e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),l.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),jq(e).then(i=>{if(e.terminals!==l||Oq(e)||x())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?W3e({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`)})}),u.stdin===null||u.stdout===null)throw new xq(`spawn-failed`,`agent process has no stdio`);let S=ewe(Dae.toWeb(u.stdin),Mc.toWeb(u.stdout)),C=Mwe({name:`open-knowledge`}).onRequest(KS.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options,t.params._meta)).onRequest(KS.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(KS.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(KS.client.terminal.create,t=>(this.touchTurnActivity(e),l.create(t.params))).onRequest(KS.client.terminal.output,t=>(this.touchTurnActivity(e),l.output(t.params.terminalId))).onRequest(KS.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),l.waitForExit(t.params.terminalId))).onRequest(KS.client.terminal.kill,async t=>(this.touchTurnActivity(e),await l.kill(t.params.terminalId),{})).onRequest(KS.client.terminal.release,async t=>(this.touchTurnActivity(e),await l.release(t.params.terminalId),{})).onNotification(KS.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(S);e.conn=C;let w=async t=>{if(await p(),e.conn!==C||x()||(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)}`)};C.closed.then(()=>w(null),e=>w({err:e}));let T;try{T=await C.agent.request(KS.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:_W},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,...this.opts.terminalAuthAvailable===!0?{auth:{terminal:!0}}:{},session:{configOptions:{boolean:{}}}}})}catch(r){if(this.opts.log.warn({err:r,threadId:e.info.threadId},`[acp-threads] initialize failed`),o.kind===`npx`||o.kind===`uvx`){await p();let e=C1e(o,m,r);if(e!==null)throw e}let s=v===`npx`&&a===`available`?IW(h):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,t,s)||v===`npx`&&a===`available`&&D1e(h)&&await this.discardRefusedNpxLaunch(e,t,o))return y=!0,this.connectAgent(e,t,n,`reacquire`,i,`spent`);throw new xq(`spawn-failed`,`initialize failed: ${Tq(r)}`)}finally{g=!1,m=``,h=``}return Aq(e,t)?(e.lastInit=T,e.info.promptCapabilities=T.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:C,init:T,launch:o}):null}async discardRefusedNpxLaunch(e,t,n){return Aq(e,t)?(this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,package:A1e(n.args)},`[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch`),await this.discardFailedLaunch(e),Aq(e,t)):!1}async clearStaleNpxCacheEntry(e,t,n){let r={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:SW(n)},i=await this.removeStaleNpxCacheEntry(n,r);return i===`kept`?!1:Aq(e,t)?(this.opts.log.warn(r,i===`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),Aq(e,t)):(i===`removed`&&this.opts.log.warn(r,`[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched`),!1)}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 Ac(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 WU(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 QW(n,{graceMs:K6e})}async ensureLaunchable(e,t,n,r){let i;try{await HW(n),i=await this.withLoginShellPathIfEligible(n)}catch(a){if(!(a instanceof jW)||a.code!==`command-not-found`)throw a;let o=await this.retryWithLoginShellPath(n);if(o===null)return this.fallbackToManagedRuntime(e,t,n,a,void 0,r);i=o}return Aq(e,t)?this.ensureInterpreterRuns(e,t,i,r):null}async ensureInterpreterRuns(e,t,n,r){if(n.kind!==`npx`&&n.kind!==`uvx`)return n;let i=await this.probeInterpreterOnce(n);if(!Aq(e,t))return null;if(i===null)return n;if(i.kind===`incompatible`){let r=await this.withPreferredLoginShellPathIfEligible(n);if(!Aq(e,t))return null;if(WW(r.env)!==WW(n.env))try{await HW(r);let n=await this.probeInterpreterOnce(r);if(!Aq(e,t))return null;if(n===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`),r;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:r.cmd,kind:r.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof jW)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:i.kind,detail:i.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let a=i.kind===`incompatible`,o=new jW(`command-not-found`,a?p0e(n,i.detail):i0e(n,i.detail)),s=new jW(`command-not-found`,a?m0e(n,i.detail):u0e(n,o.message));return this.fallbackToManagedRuntime(e,t,n,o,{declined:o,expired:s},r)}async fallbackToManagedRuntime(e,t,n,r,i,a){if(n.kind!==`npx`&&n.kind!==`uvx`)throw r;let o=Q3e(n.kind);if(!r6e(o))throw r;let s=await this.provideManagedRuntime(e,t,o,i===void 0?`missing`:`broken`,a).catch(e=>{throw i!==void 0&&e instanceof Sq?e.refusal===`timeout`?i.expired:i.declined:e});if(s===null)return null;let c=J1e(n,s);await HW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;if(l.kind===`incompatible`)throw new jW(`install-failed`,o0e(l.detail));return this.repairManagedRuntime(e,t,n,o,l.detail,a)}async repairManagedRuntime(e,t,n,r,i,a){if(!Aq(e,t))return null;let o={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:r,detail:i};if(this.opts.log.warn(o,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await c6e(r,this.opts.log,this.opts.runtimeInstall?.root))throw new jW(`install-failed`,s0e(n,i));let s=await this.provideManagedRuntime(e,t,r,`damaged`,a).catch(e=>{throw e instanceof Sq?new jW(`command-not-found`,e.refusal===`timeout`?l0e(n):c0e(n)):e});if(s===null)return null;let c=J1e(n,s);await HW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;throw this.opts.log.error({...o,detail:l.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new jW(`install-failed`,l.kind===`incompatible`?o0e(l.detail):a0e(c,l.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,WW(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await d0e(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await f0e(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(WW(t.env)===WW(e.env))return null;try{await HW(t)}catch(t){if(!(t instanceof jW))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||GW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:Y1e(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||GW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:X1e(e,t)}async provideManagedRuntime(e,t,n,r,i){let a=this.opts.runtimeInstall?.root;await s6e(n,this.opts.log,a);let o=await o6e(n,a).catch(()=>null);if(o!==null)return o;if(!Aq(e,t))return null;let s=await this.requestRuntimeConsent(e,n,r,i);if(s===`closed`||!Aq(e,t))return null;if(s!==`granted`)throw new Sq(s,s===`timeout`?c8e(n):s8e(n));try{let r=await this.downloadRuntime(e,t,n);return Aq(e,t)?r:null}catch(e){let t=sq(n).displayName;throw new jW(`install-failed`,`couldn't install ${t}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=sq(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,n){this.emitStatus(e,`installing`);let r=0;return l6e(n,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:i=>{let a=Date.now();a-r<400||(r=a,Aq(e,t)&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:n,phase:`downloading`,receivedBytes:i.receivedBytes,totalBytes:i.totalBytes??void 0,ts:a}))}})}async buildMcpServers(e,t,n,r=yq){let i=[],a=null,o=!1,s;if(n8e(e.agentRef))s=await this.settlePiBridge(e,t,r)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)s=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&n.agentCapabilities?.mcpCapabilities?.http===!0)i.push({type:`http`,name:Jt(),url:`${e}/mcp`,headers:[{name:F$e,value:`1`}]}),s=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=NW();e==null?s=`none`:(i.push({name:Jt(),command:e.command,args:[...e.args],env:[{name:Xa,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[],...Object.entries(e.env??{}).map(([e,t])=>({name:e,value:t}))]}),s=`stdio-entry-env`)}}if(this.opts.agentBrowserTools?.()===!0&&Aq(e,t)){if(I0e(e.agentRef)){let n=await this.agentBrowserServer(e,t,r);typeof n==`string`?a=n:(i.push(n),o=!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 s===`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:s},`[acp-threads] OK MCP injection outcome`),{servers:i,hostedMarker:s,browserUnavailable:a,browserInjected:o}}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,n){let r={threadId:e.info.threadId,agentId:e.agentRef.id},i=this.opts.globalDir;if(i===null)return this.opts.log.warn(r,`[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 a=await this.resolveLoginShellPath().catch(()=>null);if(!Aq(e,t))return`failed`;let o=[],s=(this.opts.resolveBrowserNpx??H0e)([e.agentLaunchPath,a,NW()],void 0,t=>!(vW(this.opts.contentDir,t)||vW(e.cwd,t))&&Y0e(t)?!0:(o.push(t),!1));if(s===null)return this.opts.log.warn({...r,rejectedNpx:o},`[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser`),`no-node`;let c=e.agentNpmCache??null,l;try{l=q0e({npx:s,folders:await Z0e(i,e.info.threadId),npmCache:c})}catch(e){return this.opts.log.warn({...r,err:e},`[acp-threads] preparing the browser failed — the chat starts without a browser`),`failed`}if(l===null)return this.opts.log.warn({...r,npx:s.npx},`[acp-threads] the npx found cannot start the browser — the chat starts without a browser`),`no-node`;if(!Aq(e,t))return`failed`;let u=Math.min(this.browserInstallWaitMs,n),d,f=await Promise.race([this.installBrowserPackage(e,s,c),new Promise(e=>{d=setTimeout(()=>e(`still-installing`),u),d.unref?.()})]).finally(()=>clearTimeout(d));return f===`still-installing`?(this.opts.log.warn({...r,waitedMs:u},`[acp-threads] installing the browser is taking too long — the chat starts without a browser`),`failed`):f?(this.opts.log.info({...r,command:l.command,npx:s.npx},`[acp-threads] browser MCP injected`),l):`failed`}async installBrowserPackage(e,t,n,r=`cached`,i=`available`){let a={threadId:e.info.threadId,agentId:e.agentRef.id},o=this.opts.ensureBrowserPackage??F1e,s=W0e(t,n,r);try{return await o(s,D0e,this.opts.log,{reacquire:!0}),!0}catch(o){if(o instanceof jW&&o.npxCacheEntry!==void 0&&i===`available`){let i={...a,npxCacheEntry:SW(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=oXe[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,n){let r=this.opts.probePiAcpBridge,i=e.info.threadId;if(r===void 0)return this.opts.log.debug({threadId:i,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let a;try{a=await r(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:i},`[acp-threads] Pi bridge probe failed`),`unknown`}if(!Aq(e,t))return`unknown`;if(a.project===`unavailable`)return this.opts.log.warn({threadId:i,cwd:a.cwd,err:Error(a.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:a.bridgePath,detail:a.error,ts:Date.now()}),`unavailable`;if(a.bridgeLoadable)return this.opts.log.info({threadId:i,bridge:a.bridge,bridgePath:a.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(a.bridge===`foreign`||a.bridge===`unreadable`)return this.opts.log.warn({threadId:i,bridge:a.bridge,bridgePath:a.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:a.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:a.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:i},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let o=this.opts.ensurePiAcpBridge;if(o===void 0)return this.opts.log.warn({threadId:i},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let s=crypto.randomUUID(),c=await this.requestPiBridgeConsent(e,s,a,n);if(c===`declined`&&(e.piBridgeDeclined=!0),!Aq(e,t))return`unknown`;if(c!==`granted`)return this.opts.log.info({threadId:i,decision:c},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let l;try{l=await o(e.cwd,a.canonicalCwd)}catch(n){let r=n instanceof Error?n.message:String(n);return this.opts.log.warn({err:n,threadId:i},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,t,s,`bridge-failed`,a.bridgePath,{detail:r}),`unavailable`}if(l.ok)return this.opts.log.info({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),Aq(e,t)?(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:s,state:`ready`,bridgePath:l.bridgePath,bridge:l.bridge,trust:l.trust,ts:Date.now()}),`loadable`):`unknown`;let u=l.bridge===`written`||l.bridge===`refreshed`||l.bridge===`unchanged`,d=l.bridge===`refused-project-path`?`project-path-unavailable`:l.bridge===`refused-foreign`?`foreign-file`:l.bridge===`refused-unreadable`?`unreadable-file`:u?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath,err:l.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,t,s,d,l.bridgePath,{bridge:l.bridge,trust:l.trust,...l.error===void 0?{}:{detail:l.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i,a){Aq(e,t)&&this.appendEvent(e,{kind:`pi_bridge_status`,requestId:n,state:r,bridgePath:i,...a,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:n.canonicalCwd,otherExtensions:n.otherExtensions,ts:Date.now()}),new Promise(n=>{let i=setTimeout(()=>{e.pendingPiBridgeConsent.delete(t),this.appendEvent(e,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:`timeout`,ts:Date.now()}),n(`timeout`)},r);i.unref?.(),e.pendingPiBridgeConsent.set(t,{resolve:n,timer:i})})}respondPiBridgeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingPiBridgeConsent.get(t);if(i===void 0)return;r.pendingPiBridgeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async startThread(e,t,n,r,i=yq,a=`reuse`){let o;try{o=await this.connectAgent(e,t,r,a,i)}catch(n){let r=await d8e(n,e,Aq(e,t)||Oq(e));await this.failLaunch(e,t,r.agentMessage,r);return}if(o===null)return;let{conn:s,init:c,launch:l}=o;if(await this.openSession(e,t,s,c,n.settings,`park`,i)!==!0||!Aq(e,t))return;this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:l.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`);let u=t.initialPrompt;t.initialPrompt=null,u!==null&&this.sendPrompt(e.info.threadId,u.content,u.attachments)}async openSession(e,t,n,r,i,a=`park`,o=yq){e.info.availableCommands=null;let{servers:s,browserUnavailable:c,browserInjected:l}=await this.buildMcpServers(e,t,r,o);if(!Aq(e,t))return!1;e.browserInjected=l,this.noteBrowserUnavailable(e,c);try{let i=await n.agent.request(KS.agent.session.new,{cwd:e.cwd,mcpServers:s});if(!Aq(e,t))return!1;e.sessionId=i.sessionId,e.info.resumable=p8e(r),e.confirmedContextWindow=u8e(e),e.info.contextWindow=e.confirmedContextWindow,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),i.modes!==void 0&&i.modes!==null&&(e.info.modes=i.modes,this.emitInfo(e)),i.configOptions!==void 0&&i.configOptions!==null&&(e.info.configOptions=i.configOptions,this.emitInfo(e))}catch(n){let i=Tq(n);if(l8e(n)){let o=`sign in required: ${i}`,s={reason:`auth-required`,agentMessage:i,machineDetail:Nq(n,e),authMethods:hq(r.authMethods,e.terminalAuthBase)};return Aq(e,t)?a===`report`?`auth-required`:(this.emitStatus(e,`auth_required`,o,s),!1):(this.logSuppressedStatus(e,`auth_required`,o,s),!1)}let o=Aq(e,t)||Oq(e);return await this.failLaunch(e,t,`session setup failed: ${i}`,{reason:`session-setup`,agentMessage:i,machineDetail:Mq({primary:Eq(n),tail:o?await jq(e):void 0})}),!1}return!Aq(e,t)||i?.config!==void 0&&(await this.applyInitialConfig(e,t,n,i.config),!Aq(e,t))||i?.modeId!==void 0&&(await this.applyInitialMode(e,t,n,i.modeId),!Aq(e,t))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.closed)throw new xq(`not-ready`,`the thread is closing`);if(r.info.archived!==!0)throw new xq(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new xq(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`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 xq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let c=kq(r);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 l=t!==void 0&&t!==``||n!==void 0&&n.length>0;l&&(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 xq(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,c,s,`reuse`,bq);if(o===null)throw new xq(`not-ready`,`thread closed during resume`);let{conn:u,init:d}=o;r.info.resumable=p8e(d),r.confirmedContextWindow=u8e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:f,browserUnavailable:p,browserInjected:m}=await this.buildMcpServers(r,c,d,bq);if(!Aq(r,c))throw new xq(`not-ready`,`thread closed during resume`);r.browserInjected=m,this.noteBrowserUnavailable(r,p);let h=d.agentCapabilities,g=h?.sessionCapabilities?.resume!=null,_;if(g)_=await u.agent.request(KS.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:f});else if(h?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{_=await u.agent.request(KS.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:f}),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 xq(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);if(!Aq(r,c))throw new xq(`not-ready`,`thread closed during resume`);r.sessionId=a;let v=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),y=r.info.modes?.currentModeId,b=_.modes;b!=null&&(r.info.modes=b);let x=_.configOptions;if(x!=null&&(r.info.configOptions=x),await this.applyInitialConfig(r,c,u,v,x==null),!Aq(r,c)||y!==void 0&&(await this.applyInitialMode(r,c,u,y,b==null),!Aq(r,c)))throw new xq(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:g?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),l&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r,await d8e(t,r,!0)),t instanceof xq?t:t instanceof jW?new xq(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 xq(`resume-unsupported`,`couldn't resume the previous session: ${Tq(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 xq(`capacity`,`server is shutting down`);let n=this.mustGet(e);this.assertContextWindowChangeable(n,t);let{custom:r}=await this.resolveAgentInfo(n.agentRef);this.assertContextWindowChangeable(n,t);let i=n.launchSettings?.contextWindow,a=n.confirmedContextWindow??null;n.launchSettings={...n.launchSettings,contextWindow:Math.floor(t)},n.resumeInFlight=!0;let o=n.launchTicket?.initialPrompt??null,s=kq(n),c=!1;n.sessionBeforeRestart={sessionId:n.sessionId,resumable:n.info.resumable,contextWindow:n.info.contextWindow};try{if(await this.teardownFailedAgent(n),n.stderrTail=[],n.cancelRequested=!1,n.turnActive=!1,this.emitStatus(n,`spawning`),await this.startThread(n,s,{agent:n.agentRef,settings:n.launchSettings},r,bq),!Aq(n,s))throw new xq(`not-ready`,`thread closed during the context window change`);let t=this.getInfo(e)?.status;if(t===`ready`||t===`running`)return c=!0,o!==null&&this.dispatchPrompt(n,o.content,o.attachments,{echo:!0}),{...n.info};throw new xq(`spawn-failed`,Dq(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof xq)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new xq(`spawn-failed`,t)}finally{!c&&o!==null&&this.opts.log.info({threadId:e,agentId:n.agentRef.id},`[acp-threads] pending first message dropped: the context window change did not start the agent`),!c&&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}}assertContextWindowChangeable(e,t){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);if(e.closed)throw new xq(`not-ready`,`the thread is closing`);if(!Number.isFinite(t)||t<=0)throw new xq(`not-ready`,`a context window must be a positive number of tokens`);let n=y6e({agentId:e.agentRef.id,archived:e.info.archived===!0,turnActive:e.turnActive,hasStartedWork:this.hasStartedWork(e.info.threadId)});if(n.kind===`unsupported`)throw new xq(`not-ready`,`this agent takes its context window from the model`);if(n.kind===`needs-new-chat`)throw new xq(`not-ready`,`start a new chat to change the context window`);if(e.resumeInFlight)throw new xq(`not-ready`,`a restart is already in progress`)}async retryThread(e){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let t=this.mustGet(e);this.assertRetryable(t);let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);this.assertRetryable(t),t.resumeInFlight=!0;let i=kq(t);t.sessionBeforeRestart={sessionId:t.sessionId,resumable:t.info.resumable,contextWindow:t.info.contextWindow};try{p1e(),this.healthyInterpreters.clear(),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,i,{agent:t.agentRef,settings:t.launchSettings},r,bq,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new xq(`spawn-failed`,n)}if(!Aq(t,i))throw new xq(`not-ready`,`thread closed during retry`);let a=this.getInfo(e)?.status;if(a===`ready`||a===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new xq(`spawn-failed`,Dq(t)??`the agent failed to start`)}finally{this.threads.has(e)&&this.endRestart(t)&&this.emitInfo(t),t.resumeInFlight=!1}}assertRetryable(e){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);if(e.closed)throw new xq(`not-ready`,`the thread is closing`);if(e.info.archived===!0)throw new xq(`not-ready`,`the thread is archived — resume it instead`);if(e.info.status!==`error`&&e.info.status!==`auth_required`&&!e.authInFlight)throw new xq(`not-ready`,`this thread did not fail to start`);if(e.resumeInFlight)throw new xq(`not-ready`,`a retry is already in progress`)}terminalAuthLaunch(e,t){let n=this.mustGet(e),r=N6e(n.lastInit?.authMethods,n.terminalAuthBase,t);if(r===null)throw new xq(`not-ready`,`this agent offers no terminal sign-in by that name`);return r}async authenticateThread(e,t){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.closed)throw new xq(`not-ready`,`the thread is closing`);if(n.info.archived===!0)throw new xq(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new xq(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit,a=n.launchTicket;if(r===null||i===null||n.child===null||a===null)throw new xq(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new xq(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new xq(`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 Cq();let t=e instanceof e8e?`the sign-in didn't complete in time — try again`:Tq(e);throw n.child===null?new xq(`agent-exited`,t):(this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:Nq(e,n),authMethods:hq(i.authMethods,n.terminalAuthBase)}),new xq(`not-ready`,t))}if(Oq(n))throw new xq(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw Cq();let o=await this.openSession(n,a,r,i,n.launchSettings,`report`,bq);if(o===`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: ${Tq(t)}`,{reason:`auth-required`,agentMessage:Tq(t),machineDetail:Nq(t,n),authMethods:hq(i.authMethods,n.terminalAuthBase)}),t}}if(o!==!0)throw Oq(n)?new xq(`not-ready`,`thread closed during sign-in`):Aq(n,a)?new xq(`not-ready`,Dq(n)??`${n.info.agent.name} still couldn't start a conversation`):Cq();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 e8e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(KS.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(e.launchTicket=null,Oq(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 QW(n,{graceMs:q6e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(DH(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 xq(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new xq(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new xq(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new xq(`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:[f8e(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 xq(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new xq(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new xq(`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=[f8e(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=U6e(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 xq(`not-ready`,`the thread is closing`);let r=vq(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 xq(`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=`${X6e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=$6e(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;K$e(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 xq(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new t8e;return e.conn.agent.request(KS.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),!Oq(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`),Oq(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(l8e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${Tq(t)}`,{reason:`auth-required`,agentMessage:Tq(t),machineDetail:Nq(t,e),authMethods:hq(e.lastInit?.authMethods,e.terminalAuthBase)});return}let n=await jq(e);this.emitStatus(e,`error`,`prompt failed: ${Tq(t)}`,{reason:`prompt`,agentMessage:Tq(t),machineDetail:Mq({primary:Eq(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(KS.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 xq(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new xq(`not-ready`,`thread has no live agent session`);n.conn.agent.request(KS.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 xq(`not-ready`,`no such config option: ${t}`);if(!wq(e,n))throw new xq(`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 xq(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new xq(`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(KS.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,i=!1){let a=e.sessionId;if(a===null)return;let o=!1,s=new Set,c=t=>(e.info.configOptions??[]).find(e=>e.id===t),l=Object.keys(r).length+1,u=Object.entries(r);for(let d=0;u.length>0&&d<l;d+=1){let l=e=>c(e)?.category===`model`,f=!1,p=[...u].sort(([e],[t])=>Number(l(t))-Number(l(e)));for(let[r,l]of p){let u=c(r);if(u===void 0||(!i||d>0)&&u.currentValue===l||!wq(u,l))continue;let p=typeof l==`boolean`?{sessionId:a,configId:r,type:`boolean`,value:l}:{sessionId:a,configId:r,value:l};try{let i=await n.agent.request(KS.agent.session.setConfigOption,p);if(!Aq(e,t))return;e.info.configOptions=i.configOptions,s.delete(r),o=!0,f=!0}catch(t){s.add(r),this.opts.log.info({err:t,threadId:e.info.threadId,configId:r,pass:d},`[acp-threads] initial config apply attempt failed`)}if(!Aq(e,t))return}if(!f)break;u=Object.entries(r).filter(([e,t])=>c(e)?.currentValue!==t)}s.size>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:[...s],sessionStateUnknown:i},`[acp-threads] some remembered config options could not be applied to the new session`);let d=[],f=[];for(let[e,t]of Object.entries(r)){if(s.has(e))continue;let n=c(e);n===void 0?d.push(e):n.currentValue!==t&&f.push(e)}(d.length>0||f.length>0)&&this.opts.log.info({threadId:e.info.threadId,missingConfigIds:d,unmatchedConfigIds:f,sessionStateUnknown:i},`[acp-threads] some remembered config options did not come back in the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n,r,i=!1){let a=e.sessionId;if(a===null)return;let o=e.info.modes;if(o!=null&&o.availableModes.some(e=>e.id===r)){if(!i&&o.currentModeId===r)return;try{if(await n.agent.request(KS.agent.session.setMode,{sessionId:a,modeId:r}),!Aq(e,t))return;e.info.modes={...o,currentModeId:r},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let s=(e.info.configOptions??[]).find(e=>e.category===`mode`&&wq(e,r));if(s!==void 0&&!(!i&&s.currentValue===r))try{let i=await n.agent.request(KS.agent.session.setConfigOption,{sessionId:a,configId:s.id,value:r});if(!Aq(e,t))return;e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,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,n.launchTicket=null,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await QW(r,{graceMs:t?.killGraceMs??K6e})||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(DH(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(DH(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 xq(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new xq(`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 Q0e(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:q6e})))}async handlePermissionRequest(e,t,n,r){this.touchTurnActivity(e);let i=m8e(await g8e(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=B0e(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=eXe(o,n);return this.appendEvent(e,{kind:`permission_request`,requestId:c,toolCall:a,options:l,...MYe(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`)&&h8e(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:ZJe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await Ec(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await Ec(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
919
|
+
`))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))}),u.on(`error`,t=>{x()||this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),u.on(`exit`,(t,n)=>{if(e.child!==u)return;let r=J6e.has(e.info.status);e.child=null,this.failPendingPermissions(e),this.failPendingConsents(e),l.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),jq(e).then(i=>{if(e.terminals!==l||Oq(e)||x())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?W3e({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`)})}),u.stdin===null||u.stdout===null)throw new xq(`spawn-failed`,`agent process has no stdio`);let S=ewe(Dae.toWeb(u.stdin),Mc.toWeb(u.stdout)),C=Mwe({name:`open-knowledge`}).onRequest(KS.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options,t.params._meta)).onRequest(KS.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(KS.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(KS.client.terminal.create,t=>(this.touchTurnActivity(e),l.create(t.params))).onRequest(KS.client.terminal.output,t=>(this.touchTurnActivity(e),l.output(t.params.terminalId))).onRequest(KS.client.terminal.waitForExit,t=>(this.touchTurnActivity(e),l.waitForExit(t.params.terminalId))).onRequest(KS.client.terminal.kill,async t=>(this.touchTurnActivity(e),await l.kill(t.params.terminalId),{})).onRequest(KS.client.terminal.release,async t=>(this.touchTurnActivity(e),await l.release(t.params.terminalId),{})).onNotification(KS.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(S);e.conn=C;let w=async t=>{if(await p(),e.conn!==C||x()||(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)}`)};C.closed.then(()=>w(null),e=>w({err:e}));let T;try{T=await C.agent.request(KS.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:_W},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,...this.opts.terminalAuthAvailable===!0?{auth:{terminal:!0}}:{},session:{configOptions:{boolean:{}}}}})}catch(r){if(this.opts.log.warn({err:r,threadId:e.info.threadId},`[acp-threads] initialize failed`),o.kind===`npx`||o.kind===`uvx`){await p();let e=C1e(o,m,r);if(e!==null)throw e}let s=v===`npx`&&a===`available`?IW(h):null;if(s!==null&&await this.clearStaleNpxCacheEntry(e,t,s)||v===`npx`&&a===`available`&&D1e(h)&&await this.discardRefusedNpxLaunch(e,t,o))return y=!0,this.connectAgent(e,t,n,`reacquire`,i,`spent`);throw new xq(`spawn-failed`,`initialize failed: ${Tq(r)}`)}finally{g=!1,m=``,h=``}return Aq(e,t)?(e.lastInit=T,e.info.promptCapabilities=T.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:C,init:T,launch:o}):null}async discardRefusedNpxLaunch(e,t,n){return Aq(e,t)?(this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,package:A1e(n.args)},`[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch`),await this.discardFailedLaunch(e),Aq(e,t)):!1}async clearStaleNpxCacheEntry(e,t,n){let r={threadId:e.info.threadId,agentId:e.info.agent.id,npxCacheEntry:SW(n)},i=await this.removeStaleNpxCacheEntry(n,r);return i===`kept`?!1:Aq(e,t)?(this.opts.log.warn(r,i===`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),Aq(e,t)):(i===`removed`&&this.opts.log.warn(r,`[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched`),!1)}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 Ac(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 WU(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 QW(n,{graceMs:K6e})}async ensureLaunchable(e,t,n,r){let i;try{await HW(n),i=await this.withLoginShellPathIfEligible(n)}catch(a){if(!(a instanceof jW)||a.code!==`command-not-found`)throw a;let o=await this.retryWithLoginShellPath(n);if(o===null)return this.fallbackToManagedRuntime(e,t,n,a,void 0,r);i=o}return Aq(e,t)?this.ensureInterpreterRuns(e,t,i,r):null}async ensureInterpreterRuns(e,t,n,r){if(n.kind!==`npx`&&n.kind!==`uvx`)return n;let i=await this.probeInterpreterOnce(n);if(!Aq(e,t))return null;if(i===null)return n;if(i.kind===`incompatible`){let r=await this.withPreferredLoginShellPathIfEligible(n);if(!Aq(e,t))return null;if(WW(r.env)!==WW(n.env))try{await HW(r);let n=await this.probeInterpreterOnce(r);if(!Aq(e,t))return null;if(n===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`),r;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:r.cmd,kind:r.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof jW)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:i.kind,detail:i.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let a=i.kind===`incompatible`,o=new jW(`command-not-found`,a?p0e(n,i.detail):i0e(n,i.detail)),s=new jW(`command-not-found`,a?m0e(n,i.detail):u0e(n,o.message));return this.fallbackToManagedRuntime(e,t,n,o,{declined:o,expired:s},r)}async fallbackToManagedRuntime(e,t,n,r,i,a){if(n.kind!==`npx`&&n.kind!==`uvx`)throw r;let o=Q3e(n.kind);if(!r6e(o))throw r;let s=await this.provideManagedRuntime(e,t,o,i===void 0?`missing`:`broken`,a).catch(e=>{throw i!==void 0&&e instanceof Sq?e.refusal===`timeout`?i.expired:i.declined:e});if(s===null)return null;let c=J1e(n,s);await HW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;if(l.kind===`incompatible`)throw new jW(`install-failed`,o0e(l.detail));return this.repairManagedRuntime(e,t,n,o,l.detail,a)}async repairManagedRuntime(e,t,n,r,i,a){if(!Aq(e,t))return null;let o={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:r,detail:i};if(this.opts.log.warn(o,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await c6e(r,this.opts.log,this.opts.runtimeInstall?.root))throw new jW(`install-failed`,s0e(n,i));let s=await this.provideManagedRuntime(e,t,r,`damaged`,a).catch(e=>{throw e instanceof Sq?new jW(`command-not-found`,e.refusal===`timeout`?l0e(n):c0e(n)):e});if(s===null)return null;let c=J1e(n,s);await HW(c);let l=await this.probeInterpreterOnce(c);if(l===null)return c;throw this.opts.log.error({...o,detail:l.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new jW(`install-failed`,l.kind===`incompatible`?o0e(l.detail):a0e(c,l.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,WW(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await d0e(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await f0e(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(WW(t.env)===WW(e.env))return null;try{await HW(t)}catch(t){if(!(t instanceof jW))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||GW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:Y1e(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||GW(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:X1e(e,t)}async provideManagedRuntime(e,t,n,r,i){let a=this.opts.runtimeInstall?.root;await s6e(n,this.opts.log,a);let o=await o6e(n,a).catch(()=>null);if(o!==null)return o;if(!Aq(e,t))return null;let s=await this.requestRuntimeConsent(e,n,r,i);if(s===`closed`||!Aq(e,t))return null;if(s!==`granted`)throw new Sq(s,s===`timeout`?c8e(n):s8e(n));try{let r=await this.downloadRuntime(e,t,n);return Aq(e,t)?r:null}catch(e){let t=sq(n).displayName;throw new jW(`install-failed`,`couldn't install ${t}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n,r){let i=crypto.randomUUID(),a=sq(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,n){this.emitStatus(e,`installing`);let r=0;return l6e(n,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:i=>{let a=Date.now();a-r<400||(r=a,Aq(e,t)&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:n,phase:`downloading`,receivedBytes:i.receivedBytes,totalBytes:i.totalBytes??void 0,ts:a}))}})}async buildMcpServers(e,t,n,r=yq){let i=[],a=null,o=!1,s;if(n8e(e.agentRef))s=await this.settlePiBridge(e,t,r)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)s=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&n.agentCapabilities?.mcpCapabilities?.http===!0)i.push({type:`http`,name:Jt(),url:`${e}/mcp`,headers:[{name:F$e,value:`1`}]}),s=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=NW();e==null?s=`none`:(i.push({name:Jt(),command:e.command,args:[...e.args],env:[{name:Xa,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[],...Object.entries(e.env??{}).map(([e,t])=>({name:e,value:t}))]}),s=`stdio-entry-env`)}}if(this.opts.agentBrowserTools?.()===!0&&Aq(e,t)){if(I0e(e.agentRef)){let n=await this.agentBrowserServer(e,t,r);typeof n==`string`?a=n:(i.push(n),o=!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 s===`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:s},`[acp-threads] OK MCP injection outcome`),{servers:i,hostedMarker:s,browserUnavailable:a,browserInjected:o}}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,n){let r={threadId:e.info.threadId,agentId:e.agentRef.id},i=this.opts.globalDir;if(i===null)return this.opts.log.warn(r,`[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 a=await this.resolveLoginShellPath().catch(()=>null);if(!Aq(e,t))return`failed`;let o=[],s=(this.opts.resolveBrowserNpx??H0e)([e.agentLaunchPath,a,NW()],void 0,t=>!(vW(this.opts.contentDir,t)||vW(e.cwd,t))&&Y0e(t)?!0:(o.push(t),!1));if(s===null)return this.opts.log.warn({...r,rejectedNpx:o},`[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser`),`no-node`;let c=e.agentNpmCache??null,l;try{l=q0e({npx:s,folders:await Z0e(i,e.info.threadId),npmCache:c})}catch(e){return this.opts.log.warn({...r,err:e},`[acp-threads] preparing the browser failed — the chat starts without a browser`),`failed`}if(l===null)return this.opts.log.warn({...r,npx:s.npx},`[acp-threads] the npx found cannot start the browser — the chat starts without a browser`),`no-node`;if(!Aq(e,t))return`failed`;let u=Math.min(this.browserInstallWaitMs,n),d,f=await Promise.race([this.installBrowserPackage(e,s,c),new Promise(e=>{d=setTimeout(()=>e(`still-installing`),u),d.unref?.()})]).finally(()=>clearTimeout(d));return f===`still-installing`?(this.opts.log.warn({...r,waitedMs:u},`[acp-threads] installing the browser is taking too long — the chat starts without a browser`),`failed`):f?(this.opts.log.info({...r,command:l.command,npx:s.npx},`[acp-threads] browser MCP injected`),l):`failed`}async installBrowserPackage(e,t,n,r=`cached`,i=`available`){let a={threadId:e.info.threadId,agentId:e.agentRef.id},o=this.opts.ensureBrowserPackage??F1e,s=W0e(t,n,r);try{return await o(s,D0e,this.opts.log,{reacquire:!0}),!0}catch(o){if(o instanceof jW&&o.npxCacheEntry!==void 0&&i===`available`){let i={...a,npxCacheEntry:SW(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=oXe[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,n){let r=this.opts.probePiAcpBridge,i=e.info.threadId;if(r===void 0)return this.opts.log.debug({threadId:i,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let a;try{a=await r(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:i},`[acp-threads] Pi bridge probe failed`),`unknown`}if(!Aq(e,t))return`unknown`;if(a.project===`unavailable`)return this.opts.log.warn({threadId:i,cwd:a.cwd,err:Error(a.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:a.bridgePath,detail:a.error,ts:Date.now()}),`unavailable`;if(a.bridgeLoadable)return this.opts.log.info({threadId:i,bridge:a.bridge,bridgePath:a.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(a.bridge===`foreign`||a.bridge===`unreadable`)return this.opts.log.warn({threadId:i,bridge:a.bridge,bridgePath:a.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:a.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:a.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:i},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let o=this.opts.ensurePiAcpBridge;if(o===void 0)return this.opts.log.warn({threadId:i},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let s=crypto.randomUUID(),c=await this.requestPiBridgeConsent(e,s,a,n);if(c===`declined`&&(e.piBridgeDeclined=!0),!Aq(e,t))return`unknown`;if(c!==`granted`)return this.opts.log.info({threadId:i,decision:c},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let l;try{l=await o(e.cwd,a.canonicalCwd)}catch(n){let r=n instanceof Error?n.message:String(n);return this.opts.log.warn({err:n,threadId:i},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,t,s,`bridge-failed`,a.bridgePath,{detail:r}),`unavailable`}if(l.ok)return this.opts.log.info({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),Aq(e,t)?(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:s,state:`ready`,bridgePath:l.bridgePath,bridge:l.bridge,trust:l.trust,ts:Date.now()}),`loadable`):`unknown`;let u=l.bridge===`written`||l.bridge===`refreshed`||l.bridge===`unchanged`,d=l.bridge===`refused-project-path`?`project-path-unavailable`:l.bridge===`refused-foreign`?`foreign-file`:l.bridge===`refused-unreadable`?`unreadable-file`:u?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:i,bridge:l.bridge,trust:l.trust,bridgePath:l.bridgePath,err:l.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,t,s,d,l.bridgePath,{bridge:l.bridge,trust:l.trust,...l.error===void 0?{}:{detail:l.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i,a){Aq(e,t)&&this.appendEvent(e,{kind:`pi_bridge_status`,requestId:n,state:r,bridgePath:i,...a,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:n.canonicalCwd,otherExtensions:n.otherExtensions,ts:Date.now()}),new Promise(n=>{let i=setTimeout(()=>{e.pendingPiBridgeConsent.delete(t),this.appendEvent(e,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:`timeout`,ts:Date.now()}),n(`timeout`)},r);i.unref?.(),e.pendingPiBridgeConsent.set(t,{resolve:n,timer:i})})}respondPiBridgeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingPiBridgeConsent.get(t);if(i===void 0)return;r.pendingPiBridgeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`pi_bridge_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async startThread(e,t,n,r,i=yq,a=`reuse`){let o;try{o=await this.connectAgent(e,t,r,a,i)}catch(n){let r=await d8e(n,e,Aq(e,t)||Oq(e));await this.failLaunch(e,t,r.agentMessage,r);return}if(o===null)return;let{conn:s,init:c,launch:l}=o;if(await this.openSession(e,t,s,c,n.settings,`park`,i)!==!0||!Aq(e,t))return;this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:l.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`);let u=t.initialPrompt;t.initialPrompt=null,u!==null&&this.sendPrompt(e.info.threadId,u.content,u.attachments)}async openSession(e,t,n,r,i,a=`park`,o=yq){e.info.availableCommands=null;let{servers:s,browserUnavailable:c,browserInjected:l}=await this.buildMcpServers(e,t,r,o);if(!Aq(e,t))return!1;e.browserInjected=l,this.noteBrowserUnavailable(e,c);try{let i=await n.agent.request(KS.agent.session.new,{cwd:e.cwd,mcpServers:s});if(!Aq(e,t))return!1;e.sessionId=i.sessionId,e.info.resumable=p8e(r),e.confirmedContextWindow=u8e(e),e.info.contextWindow=e.confirmedContextWindow,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),i.modes!==void 0&&i.modes!==null&&(e.info.modes=i.modes,this.emitInfo(e)),i.configOptions!==void 0&&i.configOptions!==null&&(e.info.configOptions=i.configOptions,this.emitInfo(e))}catch(n){let i=Tq(n);if(l8e(n)){let o=`sign in required: ${i}`,s={reason:`auth-required`,agentMessage:i,machineDetail:Nq(n,e),authMethods:hq(r.authMethods,e.terminalAuthBase)};return Aq(e,t)?a===`report`?`auth-required`:(this.emitStatus(e,`auth_required`,o,s),!1):(this.logSuppressedStatus(e,`auth_required`,o,s),!1)}let o=Aq(e,t)||Oq(e);return await this.failLaunch(e,t,`session setup failed: ${i}`,{reason:`session-setup`,agentMessage:i,machineDetail:Mq({primary:Eq(n),tail:o?await jq(e):void 0})}),!1}return!Aq(e,t)||i?.config!==void 0&&(await this.applyInitialConfig(e,t,n,i.config),!Aq(e,t))||i?.modeId!==void 0&&(await this.applyInitialMode(e,t,n,i.modeId),!Aq(e,t))?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.closed)throw new xq(`not-ready`,`the thread is closing`);if(r.info.archived!==!0)throw new xq(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new xq(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`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 xq(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new xq(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let c=kq(r);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 l=t!==void 0&&t!==``||n!==void 0&&n.length>0;l&&(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 xq(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,c,s,`reuse`,bq);if(o===null)throw new xq(`not-ready`,`thread closed during resume`);let{conn:u,init:d}=o;r.info.resumable=p8e(d),r.confirmedContextWindow=u8e(r),r.info.contextWindow=r.confirmedContextWindow;let{servers:f,browserUnavailable:p,browserInjected:m}=await this.buildMcpServers(r,c,d,bq);if(!Aq(r,c))throw new xq(`not-ready`,`thread closed during resume`);r.browserInjected=m,this.noteBrowserUnavailable(r,p);let h=d.agentCapabilities,g=h?.sessionCapabilities?.resume!=null,_;if(g)_=await u.agent.request(KS.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:f});else if(h?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{_=await u.agent.request(KS.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:f}),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 xq(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);if(!Aq(r,c))throw new xq(`not-ready`,`thread closed during resume`);r.sessionId=a;let v=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),y=r.info.modes?.currentModeId,b=_.modes;b!=null&&(r.info.modes=b);let x=_.configOptions;if(x!=null&&(r.info.configOptions=x),await this.applyInitialConfig(r,c,u,v,x==null),!Aq(r,c)||y!==void 0&&(await this.applyInitialMode(r,c,u,y,b==null),!Aq(r,c)))throw new xq(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:g?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),l&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r,await d8e(t,r,!0)),t instanceof xq?t:t instanceof jW?new xq(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 xq(`resume-unsupported`,`couldn't resume the previous session: ${Tq(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 xq(`capacity`,`server is shutting down`);let n=this.mustGet(e);this.assertContextWindowChangeable(n,t);let{custom:r}=await this.resolveAgentInfo(n.agentRef);this.assertContextWindowChangeable(n,t);let i=n.launchSettings?.contextWindow,a=n.confirmedContextWindow??null;n.launchSettings={...n.launchSettings,contextWindow:Math.floor(t)},n.resumeInFlight=!0;let o=n.launchTicket?.initialPrompt??null,s=kq(n),c=!1;n.sessionBeforeRestart={sessionId:n.sessionId,resumable:n.info.resumable,contextWindow:n.info.contextWindow};try{if(await this.teardownFailedAgent(n),n.stderrTail=[],n.cancelRequested=!1,n.turnActive=!1,this.emitStatus(n,`spawning`),await this.startThread(n,s,{agent:n.agentRef,settings:n.launchSettings},r,bq),!Aq(n,s))throw new xq(`not-ready`,`thread closed during the context window change`);let t=this.getInfo(e)?.status;if(t===`ready`||t===`running`)return c=!0,o!==null&&this.dispatchPrompt(n,o.content,o.attachments,{echo:!0}),{...n.info};throw new xq(`spawn-failed`,Dq(n)??`the agent failed to start with that context window`)}catch(e){if(e instanceof xq)throw e;let t=e instanceof Error?e.message:String(e);throw this.emitStatus(n,`error`,t,{reason:`connect`,agentMessage:t}),new xq(`spawn-failed`,t)}finally{!c&&o!==null&&this.opts.log.info({threadId:e,agentId:n.agentRef.id},`[acp-threads] pending first message dropped: the context window change did not start the agent`),!c&&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}}assertContextWindowChangeable(e,t){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);if(e.closed)throw new xq(`not-ready`,`the thread is closing`);if(!Number.isFinite(t)||t<=0)throw new xq(`not-ready`,`a context window must be a positive number of tokens`);let n=y6e({agentId:e.agentRef.id,archived:e.info.archived===!0,turnActive:e.turnActive,hasStartedWork:this.hasStartedWork(e.info.threadId)});if(n.kind===`unsupported`)throw new xq(`not-ready`,`this agent takes its context window from the model`);if(n.kind===`needs-new-chat`)throw new xq(`not-ready`,`start a new chat to change the context window`);if(e.resumeInFlight)throw new xq(`not-ready`,`a restart is already in progress`)}async retryThread(e){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let t=this.mustGet(e);this.assertRetryable(t);let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);this.assertRetryable(t),t.resumeInFlight=!0;let i=kq(t);t.sessionBeforeRestart={sessionId:t.sessionId,resumable:t.info.resumable,contextWindow:t.info.contextWindow};try{p1e(),this.healthyInterpreters.clear(),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,i,{agent:t.agentRef,settings:t.launchSettings},r,bq,`reacquire`)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new xq(`spawn-failed`,n)}if(!Aq(t,i))throw new xq(`not-ready`,`thread closed during retry`);let a=this.getInfo(e)?.status;if(a===`ready`||a===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new xq(`spawn-failed`,Dq(t)??`the agent failed to start`)}finally{this.threads.has(e)&&this.endRestart(t)&&this.emitInfo(t),t.resumeInFlight=!1}}assertRetryable(e){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);if(e.closed)throw new xq(`not-ready`,`the thread is closing`);if(e.info.archived===!0)throw new xq(`not-ready`,`the thread is archived — resume it instead`);if(e.info.status!==`error`&&e.info.status!==`auth_required`&&!e.authInFlight)throw new xq(`not-ready`,`this thread did not fail to start`);if(e.resumeInFlight)throw new xq(`not-ready`,`a retry is already in progress`)}terminalAuthLaunch(e,t){let n=this.mustGet(e),r=N6e(n.lastInit?.authMethods,n.terminalAuthBase,t);if(r===null)throw new xq(`not-ready`,`this agent offers no terminal sign-in by that name`);return r}async authenticateThread(e,t){if(this.destroyed)throw new xq(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.closed)throw new xq(`not-ready`,`the thread is closing`);if(n.info.archived===!0)throw new xq(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new xq(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit,a=n.launchTicket;if(r===null||i===null||n.child===null||a===null)throw new xq(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new xq(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new xq(`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 Cq();let t=e instanceof e8e?`the sign-in didn't complete in time — try again`:Tq(e);throw n.child===null?new xq(`agent-exited`,t):(this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:Nq(e,n),authMethods:hq(i.authMethods,n.terminalAuthBase)}),new xq(`not-ready`,t))}if(Oq(n))throw new xq(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw Cq();let o=await this.openSession(n,a,r,i,n.launchSettings,`report`,bq);if(o===`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: ${Tq(t)}`,{reason:`auth-required`,agentMessage:Tq(t),machineDetail:Nq(t,n),authMethods:hq(i.authMethods,n.terminalAuthBase)}),t}}if(o!==!0)throw Oq(n)?new xq(`not-ready`,`thread closed during sign-in`):Aq(n,a)?new xq(`not-ready`,Dq(n)??`${n.info.agent.name} still couldn't start a conversation`):Cq();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 e8e),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(KS.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e,t){if(e.launchTicket=null,Oq(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 QW(n,{graceMs:q6e}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(DH(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 xq(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new xq(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new xq(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new xq(`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:[f8e(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 xq(`not-ready`,`the thread is archived — resume it first`);if(e.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(e.authInFlight)throw new xq(`not-ready`,`the thread is still signing in`);if(e.sessionId===null||e.conn===null)throw new xq(`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=[f8e(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=U6e(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 xq(`not-ready`,`the thread is closing`);let r=vq(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 xq(`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=`${X6e(n===null?null:{skillPath:n.skillPath,inline:r})}\n\n${t}`,n!==null&&(n.inlineText!==null&&(a=$6e(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;K$e(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 xq(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new t8e;return e.conn.agent.request(KS.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),!Oq(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`),Oq(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(l8e(t)){this.emitStatus(e,`auth_required`,`sign in required: ${Tq(t)}`,{reason:`auth-required`,agentMessage:Tq(t),machineDetail:Nq(t,e),authMethods:hq(e.lastInit?.authMethods,e.terminalAuthBase)});return}let n=await jq(e);this.emitStatus(e,`error`,`prompt failed: ${Tq(t)}`,{reason:`prompt`,agentMessage:Tq(t),machineDetail:Mq({primary:Eq(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(KS.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 xq(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new xq(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new xq(`not-ready`,`thread has no live agent session`);n.conn.agent.request(KS.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 xq(`not-ready`,`no such config option: ${t}`);if(!wq(e,n))throw new xq(`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 xq(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new xq(`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(KS.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,i=!1){let a=e.sessionId;if(a===null)return;let o=!1,s=new Set,c=t=>(e.info.configOptions??[]).find(e=>e.id===t),l=Object.keys(r).length+1,u=Object.entries(r);for(let d=0;u.length>0&&d<l;d+=1){let l=e=>c(e)?.category===`model`,f=!1,p=[...u].sort(([e],[t])=>Number(l(t))-Number(l(e)));for(let[r,l]of p){let u=c(r);if(u===void 0||(!i||d>0)&&u.currentValue===l||!wq(u,l))continue;let p=typeof l==`boolean`?{sessionId:a,configId:r,type:`boolean`,value:l}:{sessionId:a,configId:r,value:l};try{let i=await n.agent.request(KS.agent.session.setConfigOption,p);if(!Aq(e,t))return;e.info.configOptions=i.configOptions,s.delete(r),o=!0,f=!0}catch(t){s.add(r),this.opts.log.info({err:t,threadId:e.info.threadId,configId:r,pass:d},`[acp-threads] initial config apply attempt failed`)}if(!Aq(e,t))return}if(!f)break;u=Object.entries(r).filter(([e,t])=>c(e)?.currentValue!==t)}s.size>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:[...s],sessionStateUnknown:i},`[acp-threads] some remembered config options could not be applied to the new session`);let d=[],f=[];for(let[e,t]of Object.entries(r)){if(s.has(e))continue;let n=c(e);n===void 0?d.push(e):n.currentValue!==t&&f.push(e)}(d.length>0||f.length>0)&&this.opts.log.info({threadId:e.info.threadId,missingConfigIds:d,unmatchedConfigIds:f,sessionStateUnknown:i},`[acp-threads] some remembered config options did not come back in the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n,r,i=!1){let a=e.sessionId;if(a===null)return;let o=e.info.modes;if(o!=null&&o.availableModes.some(e=>e.id===r)){if(!i&&o.currentModeId===r)return;try{if(await n.agent.request(KS.agent.session.setMode,{sessionId:a,modeId:r}),!Aq(e,t))return;e.info.modes={...o,currentModeId:r},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let s=(e.info.configOptions??[]).find(e=>e.category===`mode`&&wq(e,r));if(s!==void 0&&!(!i&&s.currentValue===r))try{let i=await n.agent.request(KS.agent.session.setConfigOption,{sessionId:a,configId:s.id,value:r});if(!Aq(e,t))return;e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:r,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,n.launchTicket=null,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await QW(r,{graceMs:t?.killGraceMs??K6e})||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(DH(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(DH(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){await this.forgetThread(n),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 xq(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new xq(`not-ready`,`a resume is in progress`);await this.forgetThread(t),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async forgetThread(e){let t=e.info.threadId;this.threads.delete(t),e.subscribers.clear(),e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),this.clearStall(e),await this.persistence.whenIdle(t),await this.persistence.delete(t),this.opts.globalDir!==null&&await Q0e(this.opts.globalDir,t).catch(e=>{this.opts.log.warn({err:e,threadId:t},`[acp-threads] removing browser folders failed`)})}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:q6e})))}async handlePermissionRequest(e,t,n,r){this.touchTurnActivity(e);let i=m8e(await g8e(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=B0e(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=eXe(o,n);return this.appendEvent(e,{kind:`permission_request`,requestId:c,toolCall:a,options:l,...MYe(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`)&&h8e(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:ZJe(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await Ec(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await Ec(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
920
920
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
921
921
|
`)}return{content:i}}async handleFsWrite(e,t,n){this.touchTurnActivity(e);let r=await this.confinePath(t);if(r.docName!==null){if(this.opts.localApi===void 0)throw Error(`document writes are not available here: ${t}`);let i=await M3e(this.opts.localApi,{docName:r.docName,file:r.rel,markdown:n,agentId:e.agentSessionId,agentName:e.info.agent.name,clientName:e.info.agent.id});return this.setPresence(e,r.docName),i}if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:i,tracedWriteFile:a}=await Promise.resolve().then(()=>LU);return await i(V(r.abs),{recursive:!0}),await a(r.abs,n),{}}confinePath(e){return a8e(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new xq(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&tYe(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>G6e){let t=e.events.length-G6e;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(Oq(e)){this.logSuppressedStatus(e,t,n,r);return}this.recordTerminalStatus(e,t,n,r)}logSuppressedStatus(e,t,n,r){(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:SW(n),reason:r?.reason,machineDetail:r?.machineDetail===void 0?void 0:SW(r.machineDetail)},Oq(e)?`[acp-threads] status suppressed after thread close`:`[acp-threads] status suppressed for a superseded launch`)}recordTerminalStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e),this.clearStall(e)),e.launchTicket!==null&&e.launchTicket.initialPrompt!==null&&(t===`exited`||t===`error`||t===`auth_required`)&&(e.launchTicket.initialPrompt=null,this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,status:t},`[acp-threads] pending first message dropped: the launch settled without starting a turn`)),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&&G3e(r.reason)&&J3e(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 failLaunch(e,t,n,r){if(!Aq(e,t)){this.logSuppressedStatus(e,`error`,n,r);return}this.emitStatus(e,`error`,n,r),Aq(e,t)&&await this.teardownFailedAgent(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:(Oq(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=Jn(e.info.agent.id),i=so[r]??ze(e.agentSessionId);n.setPresence(DH(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 a8e(e,t,n){let r=await Oc(e),i=Vs(Bs(t)?t:W(r,t)),a=i,o=``;for(;;)try{let e=await Oc(a),i=o===``?e:H(e,o),s=U(r,i);if(s===``||s.startsWith(`..`)||Bs(s))throw Error(`path escapes the content directory: ${t}`);let c=s.split(Ws).join(`/`),l=/\.(md|mdx)$/.exec(c),u=l===null?yU(c)||bU(c)||xU(c)?c:null:c.slice(0,-l[0].length);return{abs:i,rel:c,docName:u!==null&&!gU(u)&&!_U(u)&&!n(c)?u:null}}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 o8e(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,launchTicket:null,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 wq(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 s8e(e){let t=sq(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 c8e(e){let t=sq(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 l8e(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 Tq(e){return e instanceof Error?e.message:String(e)}function Eq(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return SW(JSON.stringify(t)).slice(0,300)}catch{return}}function u8e(e){return fq(e.agentRef.id)===`codex-config-env`?e.launchSettings?.contextWindow??null:null}function Dq(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 d8e(e,t,n){return{reason:`connect`,agentMessage:e instanceof jW||e instanceof xq?e.message:String(e),machineDetail:Mq({primary:e instanceof jW?e.machineDetail:void 0,tail:n?await jq(t):void 0})}}function f8e(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 Oq(e){return e.closed||e.info.archived===!0}function kq(e,t=null){let n={initialPrompt:t};return e.launchTicket=n,n}function Aq(e,t){return e.launchTicket===t}async function jq(e){let t=e.stderrTail;await e.drainStderr?.();let n=SW(t.join(`
|
|
922
922
|
`)).slice(-16e3);return n===``?void 0:n}function Mq({primary:e,tail:t}){if(!e)return t?.slice(-16e3)||void 0;if(!t)return e.slice(0,xW);let n=Math.min(t.length,1024),r=xW-n-1,i=e.length>r?`${e.slice(0,r-1)}…`:e,a=xW-i.length-1;return`${i}\n${t.slice(-a)}`}function Nq(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
package/dist/index.mjs
CHANGED
|
@@ -1550,6 +1550,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1550
1550
|
`);O(e,o)}function M9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
|
|
1551
1551
|
`)?`
|
|
1552
1552
|
`:``;O(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDirSpellings);r!==n&&O(e,r)}}function N9(e,t){let n=C(e,`utf-8`),r=k9(n,t.contentDirSpellings);r!==n&&O(e,r)}function P9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const $Fe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function eIe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const tIe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function nIe(e){let t={contentDirSpellings:O9(e.contentDir)};for(let n of tIe)for(let r of P9(j(e.stagingDir,n)))eIe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(j(e.stagingDir,`state`))){let e=oe(n);n.endsWith(`.jsonl`)?j9(n,t):$Fe.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 rIe(e){return j(e,...I9,z9)}function iIe(e){return j(e,...I9,B9)}function aIe(e){return j(e,...L9,V9)}function oIe(e){return j(e,...L9,H9)}function sIe(e){return j(e,...R9,U9)}function cIe(e){return j(e,...R9,W9)}const G9=1e3;async function lIe(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 uIe(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 dIe(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 fIe(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(`
|
|
1553
|
-
`)}\n`:null}catch{return null}}function pIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function mIe(e){let t=j(e,`.git`,`ok`);if(!_(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/`],z6({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 hIe(){return{nodeVersion:process.version,platform:be(),arch:he()}}function gIe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!_(e))return{};let t;try{t=(0,js.parse)(C(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 _Ie(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return _Ie(e.maxBytes)}function vIe(e){let t=J9(bJ(`project`,e)),n=J9(bJ(`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 yIe(e){return Ee(`sha256`).update(e).digest(`hex`)}function bIe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const xIe=[`"doc.name"`,`"docName"`];function SIe(e){let t=C(e,`utf-8`),n=0;for(let e of xIe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!_(e))return!1;try{return y(k(t),{recursive:!0}),e.endsWith(`.ips`)?O(t,Y5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=T(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 CIe=new Set([`.jsonl`]);function wIe(e){let t=e.lastIndexOf(`.`);return t!==-1&&CIe.has(e.slice(t))}const TIe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function EIe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&TIe.has(e.slice(t))}function DIe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!EIe(r))continue;let{redacted:i,patterns:a,lineCount:o}=vP(C(n,`utf-8`));a.length!==0&&(O(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 N(e,t).split(ue).join(`/`)}async function OIe(e){let t=le(e.contentDir),n=le(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??lIe,a=r.fetchAgentEffects??uIe,o=r.fetchWatcherRecent??dIe,s=r.readShadowHead??pIe,c=r.readCheckpointRefs??mIe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.88.0-beta.
|
|
1553
|
+
`)}\n`:null}catch{return null}}function pIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function mIe(e){let t=j(e,`.git`,`ok`);if(!_(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/`],z6({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 hIe(){return{nodeVersion:process.version,platform:be(),arch:he()}}function gIe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!_(e))return{};let t;try{t=(0,js.parse)(C(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 _Ie(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return _Ie(e.maxBytes)}function vIe(e){let t=J9(bJ(`project`,e)),n=J9(bJ(`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 yIe(e){return Ee(`sha256`).update(e).digest(`hex`)}function bIe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const xIe=[`"doc.name"`,`"docName"`];function SIe(e){let t=C(e,`utf-8`),n=0;for(let e of xIe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!_(e))return!1;try{return y(k(t),{recursive:!0}),e.endsWith(`.ips`)?O(t,Y5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=T(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 CIe=new Set([`.jsonl`]);function wIe(e){let t=e.lastIndexOf(`.`);return t!==-1&&CIe.has(e.slice(t))}const TIe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function EIe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&TIe.has(e.slice(t))}function DIe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!EIe(r))continue;let{redacted:i,patterns:a,lineCount:o}=vP(C(n,`utf-8`));a.length!==0&&(O(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 N(e,t).split(ue).join(`/`)}async function OIe(e){let t=le(e.contentDir),n=le(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??lIe,a=r.fetchAgentEffects??uIe,o=r.fetchWatcherRecent??dIe,s=r.readShadowHead??pIe,c=r.readCheckpointRefs??mIe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.88.0-beta.5`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??hIe,m=r.isOtlpPushEnabled??gIe,g=b(j(Se(),`ok-bundle-`));try{y(j(g,`telemetry`),{recursive:!0}),y(j(g,`logs`),{recursive:!0}),y(j(g,`state`),{recursive:!0}),Z9(rIe(n),j(g,`telemetry`,z9)),Z9(iIe(n),j(g,`telemetry`,B9)),Z9(aIe(n),j(g,`logs`,V9)),Z9(oIe(n),j(g,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(g,`logs`,oe(t)));for(let t of e.userStateFiles??[])Z9(t,j(g,eJ,oe(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(g,`diagnostic-reports`,oe(t)))&&(v+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){Z9(x,j(g,`state`,`server.lock`));try{let e=C(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`:(O(j(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&O(j(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=fIe(n);e!==null&&O(j(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&O(j(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&O(j(g,`state`,`checkpoint-refs.txt`),D),Z9(sIe(n),j(g,`state`,U9)),Z9(cIe(n),j(g,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(g,`state`,`last-spawn-error.log`)),Z9(j(b,Gd),j(g,`state`,Gd)),Z9(j(b,Kd),j(g,`state`,Kd)),Z9(j(b,Wd),j(g,`state`,Wd));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};O(j(g,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let k=S===`running`?`running
|
|
1554
1554
|
`:`not-running (${w})\n`;O(j(g,`state`,`server-status.txt`),k);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:J5(e.diagnosticReports,v);if(O(j(g,`state`,`diagnostic-reports-status.txt`),`${A}\n`),O(j(g,Q5),y7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=j(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&nIe({stagingDir:g,contentDir:t}),e.note&&O(j(g,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=DIe(g));for(let t of e.extraFiles??[]){let e=t.zipName??oe(t.sourcePath);if(!Z9(t.sourcePath,j(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=x7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=vIe(n),N=Q9(g),le=[],ue=0,de=0;for(let e of N){let t=$9(g,e),n=re(e).size,r=wIe(t)?bIe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=SIe(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:yIe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:m()},redaction:fe,serverStatus:S,files:le};O(j(g,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=O9(t),me=N.some(e=>{try{let t=C(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:v,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:g,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,te(g,{recursive:!0,force:!0}))}}}catch(e){throw te(g,{recursive:!0,force:!0}),e}}async function kIe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new kTe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(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 AIe(e,t){let n=j(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,js.parse)(C(n,`utf-8`)),r=BJ(t)?t.content:void 0,i=BJ(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return le(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 le(e)}async function jIe(e,t,n,r,i,a){let o=S7(t,e.logger),s=await OIe({contentDir:AIe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...kPe(o,e.userLogsDir??j(pJ(),`logs`)),...w7(e.cachesDir??j(ve(),`Library`,`Caches`))],userStateFiles:T7(e.bugReportsDir??b7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(k(e.outputPath),{recursive:!0}),await kIe({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 MIe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??D9,i=()=>tPe(e.diagnosticReportsDir??j(ve(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return jIe(e,t,n,r,i(),await v7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await PPe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:w7(e.cachesDir??j(ve(),`Library`,`Caches`)),bugReportLedgerFiles:T7(e.bugReportsDir??b7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await v7(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{YJ as ALL_EDITOR_IDS,XJ as EDITOR_LABELS,AY as EDITOR_TARGETS,Exe as HOSTS_WITH_USER_SKILL_DIR,UNe as LAUNCH_CONFIG_NAME,FFe as PATH_SHIM_BEGIN,LFe as PATH_SHIM_BLOCK_RE,IFe as PATH_SHIM_END,l5 as ProjectPathSafetyError,bNe as addOkPathsToGitExclude,u5 as assertProjectPathSafe,dY as buildManagedServerEntry,_Fe as buildMcpConfigDeclineEvent,vFe as buildMcpConfigMigrateEvent,xY as canonicalEntryFor,G5 as classifyExistingMcpEntry,MIe as collectReportBundle,HFe as createCliProbeResolver,EJ as createTokenStore,EPe as defaultBugReportZipPath,qe as detectGh,Xe as detectGhAccounts,qNe as detectInstalledEditors,bY as droppedManagedKeys,qxe as editorConfigPathDisplay,Kxe as editorEntryLocator,oFe as ensurePiBridge,sPe as findJetsamKillSync,C5 as formatTrackedRemediation,CNe as getExcludedOkPaths,x5 as getInstalledSkillProjectionPaths,Txe as getNativeTomlMcpEditor,b5 as getOkArtifactPaths,lY as isEntryUpToDate,fY as isOwnManagedEntry,MFe as loadConfig,$be as makeLazyProbeTokenStore,b7 as okBugReportsDir,y9 as parseGitHubBlobUrl,NFe as parseGitHubShareUrl,b9 as parseGitHubTreeUrl,v9 as parseGitUrl,RFe as pathInstallMarkerPath,aNe as previewContent,JNe as probeOwnManagedEditorMcpEntry,iFe as probePiBridgeState,S5 as probeTrackedOkPaths,U5 as readExistingMcpEntry,SNe as readSharingMode,vP as redactContent,RPe as registerWindowsProcessStartReader,xNe as removeOkPathsFromGitExclude,pFe as removeOwnMcpEntry,gNe as removeProjectSkill,WFe as removeUserGlobalSkillBundle,XFe as removeUserSkill,uNe as resolveProjectRoot,EFe as runStop,f9 as truncatePriorEntry,T9 as userGlobalSkillBundleTargets,YFe as userSkillPresentAnywhere,PFe as validateLocalFolderForShare,H5 as writeEditorMcpConfig,qFe as writeProjectAiIntegrations,h5 as writeProjectSkill,KNe as writeUserMcpConfigs,JFe as writeUserSkill};
|
|
1555
1555
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$f as r,Ac as i,Af as a,Bf as o,Cf as s,Df as c,Ef as l,Ff as u,Gf as d,If as f,K as p,Kf as m,Md as h,Qf as g,Rf as _,Sf as v,V as y,Wf as b,Xa as x,Ya as S,_ as ee,a as C,fd as te,jf as ne,kd as re,ol as ie,qf as ae,tt as oe,wf as se,z as ce,zf as w}from"./md-manager-BGnqyqi1-B15iekH4.mjs";import{B as le,Br as ue,Cs as de,Da as fe,Ea as pe,F as me,Kr as he,Nt as ge,Qr as _e,R as ve,W as ye,Wa as be,Wo as xe,Yo as Se,Zi as Ce,_i as we,at as Te,cs as Ee,ct as De,ei as Oe,hn as ke,hs as T,ja as Ae,ks as je,lr as Me,ls as Ne,m as Pe,mi as Fe,nr as Ie,os as Le,qo as Re,ss as E,us as ze,z as Be}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$f as r,Ac as i,Af as a,Bf as o,Cf as s,Df as c,Ef as l,Ff as u,Gf as d,If as f,K as p,Kf as m,Md as h,Qf as g,Rf as _,Sf as v,V as y,Wf as b,Xa as x,Ya as S,_ as ee,a as C,fd as te,jf as ne,kd as re,ol as ie,qf as ae,tt as oe,wf as se,z as ce,zf as w}from"./md-manager-BGnqyqi1-B15iekH4.mjs";import{B as le,Br as ue,Cs as de,Da as fe,Ea as pe,F as me,Kr as he,Nt as ge,Qr as _e,R as ve,W as ye,Wa as be,Wo as xe,Yo as Se,Zi as Ce,_i as we,at as Te,cs as Ee,ct as De,ei as Oe,hn as ke,hs as T,ja as Ae,ks as je,lr as Me,ls as Ne,m as Pe,mi as Fe,nr as Ie,os as Le,qo as Re,ss as E,us as ze,z as Be}from"./dist-cEMV5fgn.mjs";import{i as Ve,n as D,o as O,r as He,s as k,t as A}from"./colors-r_owlCuY.mjs";import{t as j}from"./is-object-BGze3w87.mjs";import{t as Ue}from"./constants-Cqoxvtnd.mjs";import{t as We}from"./preview-CJB_jf6z.mjs";import{createRequire as Ge}from"node:module";import{execFileSync as Ke}from"node:child_process";import qe,{basename as Je,dirname as M,isAbsolute as Ye,join as N,posix as Xe,relative as P,resolve as F,sep as I,win32 as Ze}from"node:path";import L from"node:process";import{fileURLToPath as Qe}from"node:url";import{copyFileSync as $e,existsSync as R,lstatSync as et,mkdirSync as tt,readFileSync as z,readdirSync as nt,readlinkSync as rt,realpathSync as it,rmSync as at,statSync as ot,writeFileSync as st}from"node:fs";import{homedir as B}from"node:os";import{inspect as ct,stripVTControlCharacters as lt,styleText as V}from"node:util";import*as ut from"node:readline";import{AsyncLocalStorage as dt,AsyncResource as ft}from"node:async_hooks";var pt=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),mt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),ht=n((e=>{let{humanReadableArgName:t}=mt();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
2
2
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
3
3
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),gt=n((e=>{let{InvalidArgumentError:t}=pt();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&T(e,g,{mode:Ka(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const zo=e=>e!==`project`,Bo=e=>e!==`user`;async function Vo(){let e=await to({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Ho(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Vo)():`both`}async function Uo(e){return oo({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:`OK config stays on this machine only; teammates do not see it. Safe escape hatch via \`${b()} config-sharing share\`.`}]})}async function Wo(e){if(e.sharing!==void 0)return e.sharing;let t=ma(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Uo)(t):t}var Go=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}},Ko=class extends Error{constructor(e){super(`A dev MCP entry is written to project config only, never to user-level editor config, so --scope ${e} is not supported with --dev-mcp or OK_CHANNEL=dev. Re-run with --scope project or without --scope.`),this.name=`DevMcpScopeError`}};const qo=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${_} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;function Jo(e){if(e===void 0||e===!0)return new Set(Te);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(ge.filter(e=>t.includes(e)))}function Yo(e,t,n){let r=F(n,e),i;try{i=ot(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Go(`--content-dir path does not exist: ${r}`):new Go(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Go(`--content-dir must be a directory: ${r}`);let a=Xo(t),o=Xo(r),s=P(a,o);if(s.startsWith(`..`)||Ye(s))throw new Go(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Xo(e){try{return it(e)}catch{return e}}const Zo=`open-knowledge-ui`;function Qo(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return R(r)}catch{return!1}}function $o(e,t,n){try{let r=F(M(e.configPath(t,n))),i=F(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+I)}catch{return!1}}function es(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!R(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||$o(e,t,r);if(!i&&c&&!Qo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Aa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return ns(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||tt(M(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{de(`${o}.lock`,()=>{let t=yo(o).writePath;if(s||tt(M(t),{recursive:!0}),e.format===`toml`){let r=Fo(oi(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=Ro(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=Po(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const ts={pi:uo};function ns(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=ts[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{tt(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{de(`${t}.lock`,()=>{let e=null;try{e=z(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}T(t,c,e===null?void 0:{mode:Ka(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function rs(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!R(n)))return{editorId:e.id,label:e.label,path:n}}async function is(e){let t=sa(e.editors).filter(e=>e.scope===`global`);if(g())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:qo}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>es(t,``,n,e.home))}function as(e,t,n,r){let i=ss(e,t,n,r);return i.kind===`present`?i.entry:null}function os(e,t,n,r){let i=No(e,t,r);if(!j(i))return{kind:`no-entry`};let a=i[n];return j(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function ss(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!R(i))return{kind:`absent`};try{if(ot(i).size>Do)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:Ha(e)}}let a;try{a=z(i,`utf-8`)}catch(e){return{kind:`decline`,reason:Ha(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:lo(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=oi().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return os(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,qr.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:os(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=So(a);return s?Co(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:os(E(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function cs(e={}){let t=F(e.cwd??process.cwd()),n=mo(t,{homeDir:e.home}),r=n.projectRoot;if(Oe(r,e.home??B()))throw new ye(r);if(_e(r))throw new me(r);let i=!R(N(r,`.ok`)),a=n.gitRootPromoted?P(r,t):void 0,o=e.contentDir===void 0?n.defaultContentDir:Yo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&o===`.`&&process.stderr.write(`${k(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${a}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`${b()} init --content-dir .\`, or set content.dir: ${a} in .ok/config.yml.\n`);let s={mode:e.devMcp?`dev`:`published`},c=e.devMcp===!0||g();if(c&&e.mcp!==!1&&e.scope&&e.scope!==`project`)throw new Ko(e.scope);let l=await Me(r),u;try{u=ue(r,{contentDir:o})}catch(t){let i=$.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:l.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let d=u.created.includes(Ue),f=!1;if(l.didInit)try{f=Se(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{pe(r)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${r}: ${e instanceof Error?e.message:String(e)}`)}let p=await Ho({scope:c?`project`:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),m=e.editors??ms(r,e.home),h=e.editors??m,_=sa(m),v=sa(h),y=e.mcp===!1||p===null,S=Array.from(new Map([..._,...y?[]:v].map(e=>[e.id,e])).values()),ee=_.filter(t=>Qo(t,r,e.home)),C=[],te=[],ne=new Set;for(let t of S){if(y){let n=``;try{n=t.configPath(r,e.home)}catch{}C.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(zo(p)&&_.includes(t)&&t.scope===`global`&&C.push(es(t,r,s,e.home)),Bo(p)&&v.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=es(t,r,s,e.home,n);C.push(i),(i.action===`written`||i.action===`overwritten`)&&ne.add(n)}}let re=new Set;for(let t of v){let n=t.projectSkillPath?.(r);!n||re.has(n)||(re.add(n),te.push(Ba(t,r,{home:e.home})))}let ie=za(r,v.map(e=>e.id));ie&&te.push(ie);let ae=te.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(ae.length>0){let t=e.home??B();fe({source:x,skills:[Pe.project],agents:ae,scope:r},{home:t,enabled:be(t).enabled})}let oe=!y&&p!==null&&Bo(p)?v.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,se=y?[]:ee.map(e=>rs(e,r)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ce=e.installUserSkill??he,w=e.home??B(),le=Jo(e.skills),de=typeof e.skills!=`string`,ve=!1,xe=!1,Te=!1,Ee=!1,De=!1,ke=!1,T=!1,Ae=[];for(let t of ge){if(!le.has(t))continue;if(ve=!0,de){let e=await Ce(w,Pe[t]).then(e=>({ok:!0,value:e}),()=>({ok:!1}));if(!e.ok){Ae.push({bundleId:t,result:`decision-read-failed`}),T=!0;continue}if(e.value===!1){Ae.push({bundleId:t,result:`opted-out`}),ke=!0;continue}}await Re(w,Pe[t],!0).catch(()=>{});let n=await ce({home:e.home,bundleId:t,force:!0});Ae.push({bundleId:t,result:n}),n===`installed`?xe=!0:n===`failed`?Te=!0:n===`no-hosts`?De=!0:Ee=!0}let je=Te?`failed`:T?`decision-read-failed`:xe?`installed`:ve&&Ee?`skip-current`:ve&&De?`no-hosts`:ke?`opted-out`:`declined`,Ne=xe?Ie(w).map(e=>e.editorId):[],Fe=be(w).enabled&&!we(),Le=y?`skipped-flag`:`skipped-missing`,E=C.find(e=>e.editorId===`claude`)??C[0]??{action:Le,configPath:$.claude.configPath(r,e.home)},ze=await ls({projectRoot:r,desiredMode:await Wo({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:u.created,contentUpdated:u.updated,contentSkipped:u.skipped,editors:C,projectSkills:te,legacyProjectConfigs:se,skillInstall:je,skillBundles:Ae,skillsRequested:e.skills,skillHosts:Ne,skillInstallsCounted:Fe,didGitInit:l.didInit,rootGitignoreCreated:f,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDir:d?o:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:E.action,mcpPath:E.configPath,mcpError:`error`in E?E.error:void 0,projectScopeUnsupportedLabels:oe,sharing:ze}}async function ls(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=ma(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=ua(t);if(n===`local-only`){let e=fa(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:us(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=pa(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:us(t,o,`remove`)}function us(e,t,n){let r=ma(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function ds(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function fs(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let s=N(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(A(`Content scaffolded at ${s}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(A(`Content already present at ${s}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(A(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(A(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(A(`MCP server configuration:`));for(let r of e.editors){let e=r.configPath.startsWith(t)?P(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),i=r.serverName===m()?``:` (${r.serverName})`,a=r.configScope===`project`?` (project)`:``,o=`${r.label}${a}`,s=` `.repeat(Math.max(1,20-o.length)),c=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${o}${s}${e} ${O(`registered`)}${i}${c}`);break;case`overwritten`:n.push(` ${o}${s}${e} ${O(`updated`)}${i}${c}`);break;case`skipped-missing`:n.push(` ${o}${s}${e} config root missing; skipped`);break;case`failed`:n.push(` ${o}${s}${e} ${He(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${o}${s}${e} left unchanged (${ds(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}let r=w.dev.mcpServerName;e.editors.some(e=>e.serverName===r&&(e.action===`written`||e.action===`overwritten`))&&n.push(` The ${r} entry runs this checkout on this machine only; keep it out of commits.`)}if(e.projectSkills.length>0){n.push(``),n.push(A(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?P(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${O(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${O(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${He(`FAILED`)}: ${r.error}`)}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${P(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall===`declined`)n.push(``),n.push(A(`User-global skills:`)),typeof e.skillsRequested==`string`?(n.push(` ${D(`none installed — --skills "${e.skillsRequested}" names no known skill bundle (known: ${ge.join(`, `)})`)}`),n.push(` ${D(`No user-global skill was installed or removed.`)}`)):(n.push(` ${D(`none installed — skipped for this run (--no-skills)`)}`),n.push(` ${D(`No user-global skill was installed or removed; any already on this`)}`),n.push(` ${D(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${D(` ${b()} init`)}`),n.push(` ${D(`--no-skills covers user-global skills only, not project-local skills.`)}`));else if(e.skillInstall){n.push(``),n.push(A(`User-global skills:`));let t=e.skillBundles??[],r=Math.max(0,...t.map(e=>Pe[e.bundleId].length));for(let i of t){let t=Pe[i.bundleId].padEnd(r);switch(i.result){case`installed`:{let r=(e.skillHosts??[]).map(e=>X[e]??e),i=r.length>0?r.join(`, `):`the shared ~/.agents store`;n.push(` ${t} ${O(`installed for ${i}`)}`);break}case`skip-current`:n.push(` ${t} ${O(`already installed at current version`)}`);break;case`no-hosts`:n.push(` ${t} ${D(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${k(`${t} install failed`)}`);break;case`opted-out`:n.push(` ${t} ${D(`not installed — turned off on this machine; reinstall with ${b()} init --skills ${i.bundleId} or Settings → Skills Studio`)}`);break;case`decision-read-failed`:n.push(` ${k(`${t} not installed — could not read whether it is turned off on this machine; rerun ${b()} init once ${ie(ee)} is readable`)}`);break;default:i.result}}e.skillInstallsCounted&&t.some(e=>e.result===`installed`)&&(n.push(` ${D(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${D(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`)),t.some(e=>e.result===`failed`)&&n.push(` ${k(`Retry with: ${b()} repair-skills`)}`)}e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(k(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(k(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`${b()} init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(` To scope to just that sub-folder, re-run \`${b()} init --content-dir .\` from there, or set`),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(We(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(..._s(e.sharing,t));let c=e=>[`${e}- ${Ve(`${b()} seed --list-packs`)} — browse the starter packs`,`${e}- ${Ve(`${b()} seed`)} — scaffold an empty repo`];if(r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${O(`✓`)} ${A(`Next steps:`)}`),n.push(` 1. Open your editor (${Ve(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`);let i=3;e.contentScaffoldFailed||(n.push(` ${i++}. (Optional) scaffold the starter knowledge-base structure:`),n.push(...c(` `))),n.push(` ${i}. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}else e.contentScaffoldFailed||(n.push(``),n.push(`${A(`Next steps:`)} (optional) scaffold the starter knowledge-base structure:`),n.push(...c(` `)));return n.join(`
|
|
691
691
|
`)}function ps(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function ms(e,t){let n=[];for(let r of ci)r!==`claude-desktop`&&Qo($[r],e,t)&&n.push(r);return n}function hs(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ct(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function gs(){return new Et(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry (node + packages/cli/dist/cli.mjs, debug logging) in project config only, as the dev channel unless OK_CHANNEL is set`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new Ot(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new Ot(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new Ot(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd();e.devMcp&&ae(process.env);let n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?hs():null;try{let r;try{r=await cs({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Go||e instanceof Ko||e instanceof ye||e instanceof me){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof ve||e instanceof Be||e instanceof le){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof De){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-ZszRbrUC.mjs`),{resolveContentDir:s}=await import(`./dist-6mRqHaPH.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-wzCrdLuG.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(ps(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${fs(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function _s(e,t){let n=[];switch(e.kind){case`applied`:return n.push(A(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${O(`local-only`)} — appended ${e.appended.length} path(s) to ${A(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${O(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${O(`local-only`)} — already excluded; nothing to do.`):n.push(` ${O(`local-only`)}`):e.action===`removed`?n.push(` ${O(`shared`)} — removed OK paths from ${A(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${O(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(k(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${Ve(`${b()} config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(k(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${Ve(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${Ve(`${b()} config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(k(`Sharing mode unavailable: ${e.reason}.`));return n}}export{Z as $,Ga as A,Da as B,yo as C,Rt as Ct,oo as D,co as E,Ot as Et,Na as F,ua as G,ba as H,Aa as I,pa as J,ga as K,ja as L,Ua as M,Ha as N,to as O,ka as P,li as Q,Va as R,$o as S,U as St,uo as T,wt as Tt,ha as U,fa as V,da as W,X,ci as Y,$ as Z,Wo as _,gr as _t,ls as a,Ei as at,es as b,fn as bt,ms as c,Gi as ct,gs as d,si as dt,Vi as et,Qo as f,oi as ft,Yo as g,Qr as gt,Ho as h,Yr as ht,ts as i,Ci as it,qa as j,Ka as k,fs as l,na as lt,Jo as m,Xr as mt,Ko as n,Hi as nt,ps as o,Wi as ot,as as p,Y as pt,ma as q,Zo as r,Ui as rt,ss as s,Q as st,Go as t,Bi as tt,_s as u,Ai as ut,cs as v,ar as vt,mo as w,Et as wt,is as x,dn as xt,jo as y,hn as yt,Ba as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-cEMV5fgn.mjs";import{v as e}from"./init-CoefCaSm.mjs";export{e as runInit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hs as e,ss as t,us as n}from"./dist-
|
|
1
|
+
import{hs as e,ss as t,us as n}from"./dist-cEMV5fgn.mjs";import{N as r,j as i,k as a}from"./init-CoefCaSm.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-KMM09nTv.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:r(e)}}let g=[],_=n(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=t(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=i(h,[`configurations`,y]);return x?(e(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Jc as e,Kc as t,bl as n,fd as r,gl as i,k as a,ml as o}from"./md-manager-BGnqyqi1-B15iekH4.mjs";import{x as s,xs as c,ys as l}from"./dist-
|
|
1
|
+
import{Jc as e,Kc as t,bl as n,fd as r,gl as i,k as a,ml as o}from"./md-manager-BGnqyqi1-B15iekH4.mjs";import{x as s,xs as c,ys as l}from"./dist-cEMV5fgn.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-Cqoxvtnd.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=r();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=i({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(r){let i=r??process.cwd(),u=[],p=[],m=[],h=[],g=c(`user`,i),_=l({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(e,t=!1)=>{let r=v(e);if(r.diagnostic!==void 0&&p.push(r.diagnostic),r.value===null)return{};let i=o({value:r.value,file:r.path,source:r.source,doc:r.doc});p.push(...i),u.push(e);let s=i.length>0?n(r.value):r.value;return t&&h.push(...a({value:s,file:r.path,source:r.source,doc:r.doc})),s},x=f(i,`.ok`,d),S=b(x,!0),C=b(c(`project-local`,i)),w=t(_.value,S,C),T=s.safeParse(w);if(!T.success){let t=v(x),n={code:`SCHEMA_INVALID`,issues:y(T.error.issues,t)};throw Error(e(n))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-BiWSR3dj.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Wo as e}from"./dist-
|
|
1
|
+
import{Wo as e}from"./dist-cEMV5fgn.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|