@inkeep/open-knowledge 0.62.0-beta.8 → 0.62.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-harness-probe-DS_1snlG.mjs → acp-harness-probe-DBIIsKVz.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/constants-BXtZdqBu.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/init-CDqryhay.mjs +1 -0
- package/dist/{init-D53VmdHm.mjs → init-PW1PHv2x.mjs} +3 -3
- package/dist/{launch-json-removal-DwjhIdI7.mjs → launch-json-removal-tcEB2vFa.mjs} +2 -2
- package/dist/loader-67m9WNnP.mjs +1 -0
- package/dist/{loader-nsH_hdbs.mjs → loader-Cg2a3fTX.mjs} +2 -2
- package/dist/{open-browser-CqoTUuyv.mjs → open-browser-D60Dz1iI.mjs} +2 -2
- package/dist/{preview-83eThwUX.mjs → preview-B4X8PAmW.mjs} +2 -2
- package/dist/preview-Cy3j_ZSG.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-DkTQxKSH.js → ActivityModeContent-BcZPTskd.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-q59j25HN.js → AgentDiffPane-DmBwcSrx.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-D0vkBW6L.js → CodeMirrorPropInput-DbtfdWI7.js} +1 -1
- package/dist/public/assets/{DocumentContext-nI82_Ey9.js → DocumentContext-Ck50-yde.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CWgtrWJu.js → EditorModeToggle-BBqYa6JE.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-DNw1ACIK.js → EnableSyncConfirmDialog-D2kjMUuG.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-D9RIMLLE.js → ExcalidrawDocEditor-CQUp82Jf.js} +1 -1
- package/dist/public/assets/FeedbackForm-CblDDg9E.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-DxlQ_a05.js → ImportSkillDialog-CIkAZSMV.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-C7ui8Eo-.js → LintConfigEditor-CF-I70Tv.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CSBBIAdm.js → ManagedArtifactProperties-46boJs1z.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DU2HSHDi.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-8nUao94a.js → MermaidDocEditor-BLQH-UZz.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-Byp1IIUE.js → PropertyDisplayRow-BJv0H_wf.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-BwwZgItz.js → SchemaConfigEditor-D9J8kIWE.js} +1 -1
- package/dist/public/assets/{SessionsHost-Bm3gL2DW.js → SessionsHost-R7rO_QKQ.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-BmMhT_2k.js → SettingsDialogBody-D1rWqQm5.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-Coy5-oRH.js → ShareReceiveMissDialog-DDQTZofi.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-CJzrDX6L.js → SkillInstallMenu-_2qgOJI6.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-zTTB_G6l.js → SkillToolbarControls-DtoRnxUD.js} +1 -1
- package/dist/public/assets/{SourceEditor-D-u3wvTQ.js → SourceEditor-D5lTf5Bh.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BXC4QUF2.js → TerminalWindowApp-Bmrytq1a.js} +1 -1
- package/dist/public/assets/{TextDocEditor-BLCKy42N.js → TextDocEditor-BDZveBXD.js} +1 -1
- package/dist/public/assets/{ThreadView-BRSCN73i.js → ThreadView-CLySobaJ.js} +2 -2
- package/dist/public/assets/{TimelineDiffPane-BKVxf8dW.js → TimelineDiffPane-C3r1D2TM.js} +1 -1
- package/dist/public/assets/{agent-diff-store-9VJa6-5g.js → agent-diff-store-DGEPOw_2.js} +1 -1
- package/dist/public/assets/{auth-state-cache-BGdHT3yJ.js → auth-state-cache-heN4B8MW.js} +1 -1
- package/dist/public/assets/{comment-chips-BWksZgYB.js → comment-chips-Bd_Ee8gr.js} +1 -1
- package/dist/public/assets/{config-provider-D2BCGlLV.js → config-provider-DLTxAd1q.js} +3 -3
- package/dist/public/assets/i18n-DEuWk-9U.js +1 -0
- package/dist/public/assets/{index-UY97Q8v-.js → index-CFSlZP6h.js} +7 -7
- package/dist/public/assets/messages-B3aWVD-S.js +1 -0
- package/dist/public/assets/messages-B83G3ljc.js +1 -0
- package/dist/public/assets/messages-Be7jCLyD.js +1 -0
- package/dist/public/assets/messages-C7toDQ-d.js +1 -0
- package/dist/public/assets/messages-CNajBoag.js +1 -0
- package/dist/public/assets/messages-COqXyjq1.js +1 -0
- package/dist/public/assets/messages-DDVnELoa.js +1 -0
- package/dist/public/assets/messages-DJHXPwV_.js +1 -0
- package/dist/public/assets/messages-DRZl5lAj.js +1 -0
- package/dist/public/assets/messages-JkhxpD-b.js +1 -0
- package/dist/public/assets/messages-gSHTuU7C.js +1 -0
- package/dist/public/assets/messages-w63SLKlk.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-B5aLXTYw.js → pending-receive-nav-store-UxCZZqPo.js} +1 -1
- package/dist/public/assets/{progress-DDXDWJkv.js → progress-CopfQaC8.js} +1 -1
- package/dist/public/assets/{selection-context-BcabMCnT.js → selection-context-DGXxWyI6.js} +1 -1
- package/dist/public/assets/{skill-actions-dNZISPM-.js → skill-actions-BPZhgTVv.js} +1 -1
- package/dist/public/assets/{src-D3LmPlv1.js → src-7pHDfMXy.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-9a9I_C3E.js → typing-burst-detector-C7BoCgKx.js} +1 -1
- package/dist/public/assets/{uninstall-CDEBm9fT.js → uninstall-Dcb_Lsmn.js} +1 -1
- package/dist/public/assets/{use-activity-panel-xYBxx5c3.js → use-activity-panel-BBVDhVwA.js} +1 -1
- package/dist/public/assets/{use-open-skill-CtcxRltp.js → use-open-skill-DJbuKFkN.js} +1 -1
- package/dist/public/assets/{use-popular-skills-C8nnGJxp.js → use-popular-skills-B4f2Q6xQ.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-PblA9Ksh.js → use-terminal-enabled-CT_mZgaI.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-BbdgaWhQ.js → use-timeline-entry-diff-CVCEa59v.js} +1 -1
- package/dist/public/index.html +21 -21
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-CtwUv4CE.mjs → repair-launch-json-MRFbgFDR.mjs} +2 -2
- package/dist/{repair-mcp-configs-CSIhiWby.mjs → repair-mcp-configs-YzmkgoIk.mjs} +2 -2
- package/dist/{repair-skills-D26UpUq7.mjs → repair-skills-C5NbMYuU.mjs} +2 -2
- package/dist/repair-skills-DycFH6DB.mjs +1 -0
- package/dist/{resolve-project-root-C94rZ_5O.mjs → resolve-project-root-XuKmxBzQ.mjs} +2 -2
- package/dist/{skill-teardown-CbmpKJso.mjs → skill-teardown-Dp8qru7m.mjs} +2 -2
- package/dist/{src-BHDHmhMl.mjs → src-32lVY8sD.mjs} +2 -2
- package/dist/src-BTKQ464e.mjs +1 -0
- package/dist/{src-BqEF6smt.mjs → src-DQ3dkBL8.mjs} +1 -1
- package/dist/{src-8l-H1eWN.mjs → src-H5bQHekD.mjs} +2 -2
- package/dist/start-B6aZOT-d.mjs +1 -0
- package/dist/{start-CC_nXyuU.mjs → start-d7sxUrTf.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-M3x5gx4s.mjs +0 -2
- package/dist/init-Bk8FhVWX.mjs +0 -1
- package/dist/loader-CMYX8gbo.mjs +0 -1
- package/dist/preview-p5ZsiV5H.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DtFjotdd.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-RWJ-WT5I.js +0 -1
- package/dist/public/assets/i18n-UJBgk95d.js +0 -1
- package/dist/public/assets/messages-B7csyV27.js +0 -1
- package/dist/public/assets/messages-BcR8jLMO.js +0 -1
- package/dist/public/assets/messages-Bg0RMNN1.js +0 -1
- package/dist/public/assets/messages-Bg1eGvm2.js +0 -1
- package/dist/public/assets/messages-CZE1y4NZ.js +0 -1
- package/dist/public/assets/messages-C_pdrnaV.js +0 -1
- package/dist/public/assets/messages-C_ximtJ3.js +0 -1
- package/dist/public/assets/messages-CmkoIyvq.js +0 -1
- package/dist/public/assets/messages-DDcoa_2T.js +0 -1
- package/dist/public/assets/messages-DeIEbqwd.js +0 -1
- package/dist/public/assets/messages-Dv8wA9Ym.js +0 -1
- package/dist/public/assets/messages-S7GnIPsZ.js +0 -1
- package/dist/repair-skills-BxzzWVm-.mjs +0 -1
- package/dist/src-CohGVfRj.mjs +0 -1
- package/dist/start-BjZWHsvR.mjs +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./launch-json-removal-
|
|
2
|
-
//# sourceMappingURL=repair-launch-json-
|
|
1
|
+
import{t as e}from"./launch-json-removal-tcEB2vFa.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=e(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
|
|
2
|
+
//# sourceMappingURL=repair-launch-json-MRFbgFDR.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bs as e}from"./src-tR2kRwXj.mjs";import{a as t,m as n,s as r}from"./resolve-project-root-
|
|
2
|
-
//# sourceMappingURL=repair-mcp-configs-
|
|
1
|
+
import{bs as e}from"./src-tR2kRwXj.mjs";import{a as t,m as n,s as r}from"./resolve-project-root-XuKmxBzQ.mjs";import{d as i,v as a}from"./init-PW1PHv2x.mjs";import{t as o}from"./mcp-migrate-event-9DFnNzHa.mjs";import{homedir as s}from"node:os";function c(e){let n=e.logger??d,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return n({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=r[o],s=l(()=>t.configPath(``,i));if(s!==null&&a.push(u({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:n})),t.projectConfigPath){let r=t.projectConfigPath,i=l(()=>r(e.projectDir));i!==null&&a.push(u({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:n}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function l(e){try{return e()}catch{return null}}function u(t){let r={scope:t.scope,editorId:t.editorId,configPath:t.configPath},s=i(t.target,t.cwd,t.home,t.configPathOverride);if(s===null)return{...r,outcome:`no-entry`};if(t.editorId===`pi`){if(n(s))return{...r,outcome:`canonical`}}else{let n=e(s);if(n.kind===`recognized`&&n.disposition===`keep`)return{...r,outcome:`canonical`};if(n.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-declined`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:n.reason}),{...r,outcome:`declined`,reason:n.reason}}t.logger(o({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:s}));let c=a(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride);if(c.action===`failed`){let e=c.error??`unknown write failure`;return t.logger({event:`mcp-config-repair-write-failed`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,error:e}),{...r,outcome:`write-failed`,error:e}}return c.action===`declined`?(t.logger({event:`mcp-config-repair-declined`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:c.declineReason}),{...r,outcome:`declined`}):{...r,outcome:`repaired`}}function d(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{c as repairMcpConfigs};
|
|
2
|
+
//# sourceMappingURL=repair-mcp-configs-YzmkgoIk.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as e,zs as t}from"./src-tR2kRwXj.mjs";import{ar as n,cr as r,gn as i,hr as a,ir as o,lr as s,pr as c,ur as l,xr as u,yr as d}from"./src-BHDHmhMl.mjs";import{c as f,n as p,s as m,x as h}from"./resolve-project-root-C94rZ_5O.mjs";import{n as g,s as _,t as v}from"./colors-DSyAT9Cz.mjs";import{n as y,r as b,t as x}from"./skill-teardown-CbmpKJso.mjs";import{basename as S,dirname as C,join as w,relative as T,resolve as E}from"node:path";import{existsSync as D,mkdirSync as O,readFileSync as k,readdirSync as A,rmSync as j,statSync as M,writeFileSync as N}from"node:fs";import{homedir as P}from"node:os";import{createInterface as F}from"node:readline/promises";const I={existsSync:e=>D(e),isDirectory:e=>{try{return M(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>A(e),readFileSync:e=>k(e),writeFileSync:(e,t)=>{N(e,t)},mkdirSync:(e,t)=>{O(e,t)},rmSync:(e,t)=>{j(e,t)}},L={resolveProjectBundledSkillDir:()=>a(`project`,{checkDesktop:!1}),resolveUserBundledSkillDir:e=>a(e,{checkDesktop:!1}),readBundledVersion:()=>n(),readRecordedVersion:e=>r(e,`cli-hosts`),writeRecordedVersion:(e,t)=>l(e,`cli-hosts`,t,`cli-start`),recordEvent:e=>c(e),readBundleDecision:(e,t)=>o(e,t),writeBundleDecision:(e,t,n)=>s(e,t,n),removeBundleFromDisk:(e,t)=>b(e,t)};function R(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function z(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(C(t),{recursive:!0}),B(e,t,n)}function B(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=w(e,r),a=w(t,r);n.isDirectory(i)?B(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function V(e,n,r){return r.existsSync(w(e,`.agents`,`skills`,n))||t.some(t=>r.existsSync(w(e,t.skillsRoot,n)))}function H(e,n,r,i,a,o){let s=[],c=w(e,`.agents`,`skills`,n);if(V(e,n,i)){i.existsSync(c)&&s.push({kind:`central`,path:c,outcome:`skipped-present`});for(let r of t){let t=w(e,r.skillsRoot,n);if(t!==c){if(!i.existsSync(w(e,r.hostDir))){s.push({kind:`host`,editorId:r.editorId,hostDir:r.hostDir,path:t,outcome:`skipped-host-absent`});continue}i.existsSync(t)&&s.push({kind:`host`,editorId:r.editorId,hostDir:r.hostDir,path:t,outcome:`skipped-present`})}}return{entries:s,anyWritten:!1,anyDestinationSucceeded:!0}}let l=i.existsSync(w(e,`.agents`));if(l&&i.existsSync(c))s.push({kind:`central`,path:c,outcome:`skipped-present`});else if(l)try{z(r,c,i),s.push({kind:`central`,path:c,outcome:`written`}),a({event:`user-skill-reclaim-central-written`,scope:`user`,path:c,preexisting:!1,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);s.push({kind:`central`,path:c,outcome:`failed`,error:t}),a({event:`user-skill-reclaim-central-failed`,scope:`user`,path:c,error:t})}for(let l of t){let t=w(e,l.hostDir),u=w(e,l.skillsRoot,n);if(u===c){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-collapsed-with-central`});continue}if(!i.existsSync(t)){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-host-absent`});continue}if(i.existsSync(u)){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-present`});continue}try{z(r,u,i),s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`written`}),a({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:l.editorId,hostDir:l.hostDir,path:u,preexisting:!1,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`failed`,error:t}),a({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:l.editorId,hostDir:l.hostDir,path:u,error:t})}}return{entries:s,anyWritten:s.some(e=>e.outcome===`written`),anyDestinationSucceeded:s.some(e=>e.outcome===`written`||e.outcome===`skipped-present`)}}function U(e,t){if(!e)return!1;try{return t.existsSync(e)?t.readFileSync(e).toString(`utf8`).includes(`# ok-mcp-`):!1}catch{return!1}}function W(e,t,n,r){if(!e||!t)return!1;let a;try{a=e.configPath(n,r)}catch{return!1}let o=e=>w(i(C(e)),S(e));return o(t)===o(a)}function G(e,t,n,r,i){let a;try{a=n.resolveProjectBundledSkillDir()}catch(e){return i({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let o=[];for(let n of f){let s=w(e,n.hostDir,`skills`,`open-knowledge`),c=w(s,`SKILL.md`);if(r.existsSync(c)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`present`});continue}let l=m[n.editorId],u=l?.projectConfigPath?.(e);if(W(l,u,e,t)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`skipped-global-collision`}),i({event:`project-skill-reclaim-skipped-global-collision`,scope:`project`,editorId:n.editorId,path:s});continue}if(!U(u,r)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`no-token`}),i({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:n.editorId,path:s});continue}try{p(s,e),z(a,s,r),o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`created`}),i({event:`project-skill-reclaim-created`,scope:`project`,editorId:n.editorId,path:s})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`failed`,error:t}),i({event:`project-skill-reclaim-failed`,scope:`project`,editorId:n.editorId,path:s,error:t})}}return{outcome:`done`,entries:o}}async function K(t,n,r,i){let a=e=>{n.recordEvent(e).catch(()=>{})},o=()=>new Date().toISOString(),s;try{s=await n.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let c;try{c=await n.readRecordedVersion(t)}catch(e){i({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),c=null}let l=[],f=null;for(let e of u)try{l.push({id:e,sourceDir:n.resolveUserBundledSkillDir(e)})}catch(e){f=e instanceof Error?e.message:String(e)}if(l.length===0)return i({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:f??`no user-global bundles`}),a({ts:o(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,reason:`bundle-missing:${f}`}),{outcome:`skipped`,reason:`bundle-missing`};let p=[];for(let a of l){let o=d[a.id],s=V(t,o,r),c=await n.readBundleDecision(t,o).catch(()=>null);if(!e(c,{installedOnDisk:s})){if(s)try{n.removeBundleFromDisk(t,a.id),i({event:`user-skill-reclaim-bundle-declined-removed`,scope:`user`,bundle:a.id})}catch(e){i({event:`user-skill-reclaim-bundle-remove-failed`,scope:`user`,bundle:a.id,error:e instanceof Error?e.message:String(e)})}continue}if(c===null&&s)try{await n.writeBundleDecision(t,o,!0)}catch(e){i({event:`user-skill-reclaim-grandfather-write-failed`,scope:`user`,bundle:a.id,error:e instanceof Error?e.message:String(e)})}p.push(a)}if(p.length===0)return{outcome:`skipped`,reason:`all-bundles-declined`};let m=p.every(e=>V(t,d[e.id],r));if(c!==null&&c===s&&m)return i({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:s}),{outcome:`skipped`,reason:`version-current`};let h=[],g=l.length===u.length,_=[];for(let{id:e,sourceDir:n}of p){let a=H(t,d[e],n,r,i,s);h.push(...a.entries),_.push({id:e,anyWritten:a.anyWritten,landed:a.anyDestinationSucceeded,centralFailed:a.entries.some(e=>e.kind===`central`&&e.outcome===`failed`),hostFailed:a.entries.some(e=>e.kind===`host`&&e.outcome===`failed`)})}let v=_.some(e=>e.centralFailed),y=_.every(e=>e.landed);if(g&&y&&!v){let e=null;try{await n.writeRecordedVersion(t,s),i({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:s})}catch(t){e=t instanceof Error?t.message:String(t),i({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:s,error:e})}for(let{id:t,anyWritten:n}of _)a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:t,outcome:e===null?n?`installed`:`skip-current`:`failed`,version:s,...e===null?{}:{reason:`state-write-failed:${e}`}})}else{g||a({ts:o(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,version:s,reason:`bundle-unresolved`});for(let{id:e,centralFailed:t,hostFailed:n}of _)!t&&!n||a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:e,outcome:`failed`,version:s,reason:n?`all-writes-failed`:`central-write-failed`})}return{outcome:`done`,version:s,entries:h}}async function q(e){let t=e.logger??R,n=e.fs??I,r=e.home??P(),i={...L,...e.deps};if(e.reclaimDisableEnv===`1`)return t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`};let a=G(e.projectDir,r,i,n,t),o=await K(r,i,n,t),s=y(r),c=[],l=!1,u=!1;if(s.skillDirs.length>0||s.emptyDirs.length>0)if(e.confirmLegacyCleanup&&await e.confirmLegacyCleanup(s)){try{c=x(r,s)}catch(e){u=!0,t({event:`legacy-fanout-cleanup-refused`,scope:`user`,error:e instanceof Error?e.message:String(e)})}for(let e of c)t({event:`legacy-fanout-path-removed`,scope:`user`,path:e})}else l=!0,t({event:`legacy-fanout-cleanup-declined`,scope:`user`});return{status:`done`,project:a,user:o,legacySwept:c,legacyCleanupDeclined:l,legacyCleanupFailed:u}}function J(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`&&e.user.reason!==`all-bundles-declined`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function Y(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`present`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length,o=e.project.entries.filter(e=>e.outcome===`skipped-global-collision`).length;t.push(` Project: ${n} present, ${r} created, ${i} no-token, ${a} failed.`),o>0&&t.push(` Skipped ${o} host(s) whose project config path is their user-global config (not a project directory).`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-present`).length,i=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,a=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} present, ${i} skipped, ${a} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return e.legacySwept.length>0?t.push(` Cleanup: removed ${e.legacySwept.length} path(s) from a pre-0.42 install.`):e.legacyCleanupFailed?t.push(` Cleanup: failed — see logs; pre-0.42 directories left in place.`):e.legacyCleanupDeclined&&t.push(` Cleanup: declined — pre-0.42 directories left in place.`),t.join(`
|
|
1
|
+
import{q as e,zs as t}from"./src-tR2kRwXj.mjs";import{ar as n,cr as r,gn as i,hr as a,ir as o,lr as s,pr as c,ur as l,xr as u,yr as d}from"./src-32lVY8sD.mjs";import{c as f,n as p,s as m,x as h}from"./resolve-project-root-XuKmxBzQ.mjs";import{n as g,s as _,t as v}from"./colors-DSyAT9Cz.mjs";import{n as y,r as b,t as x}from"./skill-teardown-Dp8qru7m.mjs";import{basename as S,dirname as C,join as w,relative as T,resolve as E}from"node:path";import{existsSync as D,mkdirSync as O,readFileSync as k,readdirSync as A,rmSync as j,statSync as M,writeFileSync as N}from"node:fs";import{homedir as P}from"node:os";import{createInterface as F}from"node:readline/promises";const I={existsSync:e=>D(e),isDirectory:e=>{try{return M(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>A(e),readFileSync:e=>k(e),writeFileSync:(e,t)=>{N(e,t)},mkdirSync:(e,t)=>{O(e,t)},rmSync:(e,t)=>{j(e,t)}},L={resolveProjectBundledSkillDir:()=>a(`project`,{checkDesktop:!1}),resolveUserBundledSkillDir:e=>a(e,{checkDesktop:!1}),readBundledVersion:()=>n(),readRecordedVersion:e=>r(e,`cli-hosts`),writeRecordedVersion:(e,t)=>l(e,`cli-hosts`,t,`cli-start`),recordEvent:e=>c(e),readBundleDecision:(e,t)=>o(e,t),writeBundleDecision:(e,t,n)=>s(e,t,n),removeBundleFromDisk:(e,t)=>b(e,t)};function R(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function z(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(C(t),{recursive:!0}),B(e,t,n)}function B(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=w(e,r),a=w(t,r);n.isDirectory(i)?B(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function V(e,n,r){return r.existsSync(w(e,`.agents`,`skills`,n))||t.some(t=>r.existsSync(w(e,t.skillsRoot,n)))}function H(e,n,r,i,a,o){let s=[],c=w(e,`.agents`,`skills`,n);if(V(e,n,i)){i.existsSync(c)&&s.push({kind:`central`,path:c,outcome:`skipped-present`});for(let r of t){let t=w(e,r.skillsRoot,n);if(t!==c){if(!i.existsSync(w(e,r.hostDir))){s.push({kind:`host`,editorId:r.editorId,hostDir:r.hostDir,path:t,outcome:`skipped-host-absent`});continue}i.existsSync(t)&&s.push({kind:`host`,editorId:r.editorId,hostDir:r.hostDir,path:t,outcome:`skipped-present`})}}return{entries:s,anyWritten:!1,anyDestinationSucceeded:!0}}let l=i.existsSync(w(e,`.agents`));if(l&&i.existsSync(c))s.push({kind:`central`,path:c,outcome:`skipped-present`});else if(l)try{z(r,c,i),s.push({kind:`central`,path:c,outcome:`written`}),a({event:`user-skill-reclaim-central-written`,scope:`user`,path:c,preexisting:!1,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);s.push({kind:`central`,path:c,outcome:`failed`,error:t}),a({event:`user-skill-reclaim-central-failed`,scope:`user`,path:c,error:t})}for(let l of t){let t=w(e,l.hostDir),u=w(e,l.skillsRoot,n);if(u===c){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-collapsed-with-central`});continue}if(!i.existsSync(t)){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-host-absent`});continue}if(i.existsSync(u)){s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`skipped-present`});continue}try{z(r,u,i),s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`written`}),a({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:l.editorId,hostDir:l.hostDir,path:u,preexisting:!1,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);s.push({kind:`host`,editorId:l.editorId,hostDir:l.hostDir,path:u,outcome:`failed`,error:t}),a({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:l.editorId,hostDir:l.hostDir,path:u,error:t})}}return{entries:s,anyWritten:s.some(e=>e.outcome===`written`),anyDestinationSucceeded:s.some(e=>e.outcome===`written`||e.outcome===`skipped-present`)}}function U(e,t){if(!e)return!1;try{return t.existsSync(e)?t.readFileSync(e).toString(`utf8`).includes(`# ok-mcp-`):!1}catch{return!1}}function W(e,t,n,r){if(!e||!t)return!1;let a;try{a=e.configPath(n,r)}catch{return!1}let o=e=>w(i(C(e)),S(e));return o(t)===o(a)}function G(e,t,n,r,i){let a;try{a=n.resolveProjectBundledSkillDir()}catch(e){return i({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let o=[];for(let n of f){let s=w(e,n.hostDir,`skills`,`open-knowledge`),c=w(s,`SKILL.md`);if(r.existsSync(c)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`present`});continue}let l=m[n.editorId],u=l?.projectConfigPath?.(e);if(W(l,u,e,t)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`skipped-global-collision`}),i({event:`project-skill-reclaim-skipped-global-collision`,scope:`project`,editorId:n.editorId,path:s});continue}if(!U(u,r)){o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`no-token`}),i({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:n.editorId,path:s});continue}try{p(s,e),z(a,s,r),o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`created`}),i({event:`project-skill-reclaim-created`,scope:`project`,editorId:n.editorId,path:s})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({editorId:n.editorId,hostDir:n.hostDir,path:s,outcome:`failed`,error:t}),i({event:`project-skill-reclaim-failed`,scope:`project`,editorId:n.editorId,path:s,error:t})}}return{outcome:`done`,entries:o}}async function K(t,n,r,i){let a=e=>{n.recordEvent(e).catch(()=>{})},o=()=>new Date().toISOString(),s;try{s=await n.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let c;try{c=await n.readRecordedVersion(t)}catch(e){i({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),c=null}let l=[],f=null;for(let e of u)try{l.push({id:e,sourceDir:n.resolveUserBundledSkillDir(e)})}catch(e){f=e instanceof Error?e.message:String(e)}if(l.length===0)return i({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:f??`no user-global bundles`}),a({ts:o(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,reason:`bundle-missing:${f}`}),{outcome:`skipped`,reason:`bundle-missing`};let p=[];for(let a of l){let o=d[a.id],s=V(t,o,r),c=await n.readBundleDecision(t,o).catch(()=>null);if(!e(c,{installedOnDisk:s})){if(s)try{n.removeBundleFromDisk(t,a.id),i({event:`user-skill-reclaim-bundle-declined-removed`,scope:`user`,bundle:a.id})}catch(e){i({event:`user-skill-reclaim-bundle-remove-failed`,scope:`user`,bundle:a.id,error:e instanceof Error?e.message:String(e)})}continue}if(c===null&&s)try{await n.writeBundleDecision(t,o,!0)}catch(e){i({event:`user-skill-reclaim-grandfather-write-failed`,scope:`user`,bundle:a.id,error:e instanceof Error?e.message:String(e)})}p.push(a)}if(p.length===0)return{outcome:`skipped`,reason:`all-bundles-declined`};let m=p.every(e=>V(t,d[e.id],r));if(c!==null&&c===s&&m)return i({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:s}),{outcome:`skipped`,reason:`version-current`};let h=[],g=l.length===u.length,_=[];for(let{id:e,sourceDir:n}of p){let a=H(t,d[e],n,r,i,s);h.push(...a.entries),_.push({id:e,anyWritten:a.anyWritten,landed:a.anyDestinationSucceeded,centralFailed:a.entries.some(e=>e.kind===`central`&&e.outcome===`failed`),hostFailed:a.entries.some(e=>e.kind===`host`&&e.outcome===`failed`)})}let v=_.some(e=>e.centralFailed),y=_.every(e=>e.landed);if(g&&y&&!v){let e=null;try{await n.writeRecordedVersion(t,s),i({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:s})}catch(t){e=t instanceof Error?t.message:String(t),i({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:s,error:e})}for(let{id:t,anyWritten:n}of _)a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:t,outcome:e===null?n?`installed`:`skip-current`:`failed`,version:s,...e===null?{}:{reason:`state-write-failed:${e}`}})}else{g||a({ts:o(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,version:s,reason:`bundle-unresolved`});for(let{id:e,centralFailed:t,hostFailed:n}of _)!t&&!n||a({ts:o(),surface:`cli-start`,target:`cli-hosts`,bundle:e,outcome:`failed`,version:s,reason:n?`all-writes-failed`:`central-write-failed`})}return{outcome:`done`,version:s,entries:h}}async function q(e){let t=e.logger??R,n=e.fs??I,r=e.home??P(),i={...L,...e.deps};if(e.reclaimDisableEnv===`1`)return t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`};let a=G(e.projectDir,r,i,n,t),o=await K(r,i,n,t),s=y(r),c=[],l=!1,u=!1;if(s.skillDirs.length>0||s.emptyDirs.length>0)if(e.confirmLegacyCleanup&&await e.confirmLegacyCleanup(s)){try{c=x(r,s)}catch(e){u=!0,t({event:`legacy-fanout-cleanup-refused`,scope:`user`,error:e instanceof Error?e.message:String(e)})}for(let e of c)t({event:`legacy-fanout-path-removed`,scope:`user`,path:e})}else l=!0,t({event:`legacy-fanout-cleanup-declined`,scope:`user`});return{status:`done`,project:a,user:o,legacySwept:c,legacyCleanupDeclined:l,legacyCleanupFailed:u}}function J(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`&&e.user.reason!==`all-bundles-declined`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function Y(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`present`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length,o=e.project.entries.filter(e=>e.outcome===`skipped-global-collision`).length;t.push(` Project: ${n} present, ${r} created, ${i} no-token, ${a} failed.`),o>0&&t.push(` Skipped ${o} host(s) whose project config path is their user-global config (not a project directory).`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-present`).length,i=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,a=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} present, ${i} skipped, ${a} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return e.legacySwept.length>0?t.push(` Cleanup: removed ${e.legacySwept.length} path(s) from a pre-0.42 install.`):e.legacyCleanupFailed?t.push(` Cleanup: failed — see logs; pre-0.42 directories left in place.`):e.legacyCleanupDeclined&&t.push(` Cleanup: declined — pre-0.42 directories left in place.`),t.join(`
|
|
2
2
|
`)}function X(){return new h(`repair-skills`).description("Refresh bundled SKILL.md files for installed AI editors (project-local + user-global). Runs automatically during `ok start`; this command forces an explicit sweep.").option(`-y, --yes`,`Skip the confirmation prompt for removing directories left by a pre-0.42 install.`).action(async e=>{let t=await q({projectDir:E(process.cwd()),reclaimDisableEnv:process.env.OK_RECLAIM_DISABLE??null,confirmLegacyCleanup:t=>Z(t,{yes:e.yes===!0})});process.stdout.write(`${Y(t)}\n`),process.exitCode=J(t)})}async function Z(e,t){let n=P(),r=e=>`~/${T(n,e)}`,i=t.input??process.stdin,a=[``,v(`A previous version of OpenKnowledge installed its skill into agent tools you may never have used.`),g(`(Versions before 0.42 wrote to every host a third-party installer knew about — see issue #820.)`)];if(e.skillDirs.length>0&&a.push(``,`${v(`Remove OpenKnowledge skills:`)} ${e.skillDirs.length}`,...e.skillDirs.map(e=>` ${r(e)}`)),e.emptyDirs.length>0){let t=e.skillDirs.length>0?`Then remove these, which hold nothing else once the above are gone:`:`Remove these empty directories, left behind by that install:`;a.push(``,`${v(t)} ${e.emptyDirs.length}`,...e.emptyDirs.map(e=>` ${r(e)}`))}if(a.push(``,g(`Nothing outside these paths is touched. A directory that still holds anything is kept.`)),process.stdout.write(`${a.join(`
|
|
3
3
|
`)}\n`),t.yes)return!0;if(!i.isTTY)return process.stdout.write(`${_("Not a terminal — skipping cleanup. Re-run with `ok repair-skills --yes` to remove these.")}\n`),!1;let o=F({input:i,output:process.stdout});try{let e=(await o.question(`\n${v(`Remove them?`)} ${g(`[y/N] `)}`)).trim().toLowerCase();return e===`y`||e===`yes`}finally{o.close()}}export{X as n,q as t};
|
|
4
|
-
//# sourceMappingURL=repair-skills-
|
|
4
|
+
//# sourceMappingURL=repair-skills-C5NbMYuU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./repair-skills-C5NbMYuU.mjs";export{e as repairSkills};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{As as r,Ps as i,Rs as a,ks as o,xs as s}from"./src-tR2kRwXj.mjs";import{Ir as c,Pi as l,gn as u,hr as d,kn as f}from"./src-
|
|
1
|
+
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{As as r,Ps as i,Rs as a,ks as o,xs as s}from"./src-tR2kRwXj.mjs";import{Ir as c,Pi as l,gn as u,hr as d,kn as f}from"./src-32lVY8sD.mjs";import{execFileSync as p}from"node:child_process";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as x,win32 as S}from"node:path";import{cpSync as ee,existsSync as C,lstatSync as te,mkdirSync as ne,readFileSync as re,realpathSync as w,rmSync as ie,statSync as ae}from"node:fs";import{homedir as T}from"node:os";var E=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})),D=n((e=>{let{InvalidArgumentError:t}=E();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;break}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})),O=n((e=>{let{humanReadableArgName:t}=D();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})),k=n((e=>{let{InvalidArgumentError:t}=E();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?!1: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}
|
|
@@ -53,4 +53,4 @@ foreach ($d in $dirs) {
|
|
|
53
53
|
}
|
|
54
54
|
[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
|
|
55
55
|
exit 127`,I=`// ok-pi-bridge`,L=`${I}-v1`,be=`ok-pi-managed-extension`;function xe(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(L)}return!1}function R(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=b(e);if(m(t)===`cli.mjs`&&m(h(t))===`dist`)return t;let n=t.split(x),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return _(i.length===0?x:i.join(x),`packages`,`cli`,`dist`,`cli.mjs`)}function z(e={}){return e.mode===`dev`?{command:M,args:[R(),`mcp`],env:{...N}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,F]}:{command:`/bin/sh`,args:[`-l`,`-c`,P]}}function Se(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[M,R(),`mcp`],environment:{...N}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,F]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,P]}}function Ce(e){if(typeof e!=`object`||!e)return!1;let t=e;return B(t,z({mode:`published`,platformName:`darwin`}))||B(t,z({mode:`published`,platformName:`win32`}))}function B(e,t){return Object.keys(e).length===Object.keys(t).length?we(e,t):!1}function we(e,t){if(e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function V(e,t){let n=e=>typeof e==`string`&&e.includes(`# ok-mcp`);return t===`/bin/sh`?e[0]===`-l`&&e[1]===`-c`&&n(e[2]):t===`powershell`?e[0]===`-NoProfile`&&e[1]===`-NonInteractive`&&e[2]===`-Command`&&n(e[3]):!1}function Te(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.enabled===!1||typeof t.command!=`string`||!Array.isArray(t.args)?!1:V(t.args,t.command)}function Ee(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.type!==`local`||t.enabled===!1||!Array.isArray(t.command))return!1;let[n,...r]=t.command;return typeof n==`string`&&V(r,n)}function H(e){return e===`win32`?S:v}function De(e={}){let t=e.platformName??process.platform,n=e.home??T(),r=e.env??process.env,i=H(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA||i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME||i.join(n,`.config`)}function Oe(e={}){let t=e.platformName??process.platform,n=e.home??T();return H(t).join(n,`.claude.json`)}function U(e={}){let t=e.platformName??process.platform,n=e.home??T(),r=e.env??process.env;if(t===`darwin`)return v.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??S.join(n,`AppData`,`Roaming`);return S.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function W(e={}){let t=e.platformName??process.platform,n=e.home??T();return H(t).join(n,`.cursor`,`mcp.json`)}function ke(e={}){let t=e.platformName??process.platform,n=e.home??T();return(e.env??process.env).CODEX_HOME??H(t).join(n,`.codex`)}function G(e={}){return H(e.platformName??process.platform).join(ke(e),`config.toml`)}function K(e={}){let t=e.platformName??process.platform,n=e.home??T(),r=(e.env??process.env).COPILOT_HOME??H(t).join(n,`.copilot`);return H(t).join(r,`mcp-config.json`)}function Ae(e={}){let t=e.platformName??process.platform,n=e.home??T(),r=e.env??process.env,i=H(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function q(e={}){return H(e.platformName??process.platform).join(Ae(e),`opencode.json`)}function je(e={}){let t=e.platformName??process.platform,n=e.home??T();return H(t).join(n,`.openclaw`,`openclaw.json`)}function Me(e={}){let t=e.platformName??process.platform,n=e.home??T();return H(t).join(n,`.hermes`,`config.yaml`)}function J(e={}){let t=e.platformName??process.platform,n=e.home??T();return(e.env??process.env).PI_CODING_AGENT_DIR??H(t).join(n,`.pi`,`agent`)}function Ne(e={}){let t=e.platformName??process.platform,n=e.home??T();return H(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function Pe(e,t){let n=H(t),r=n.join(e,`.lmstudio`,`mcp.json`),i=n.join(e,`.cache`,`lm-studio`,`mcp.json`);return t===`darwin`?[i,r]:[r,i]}function Y(e={}){let t=e.platformName??process.platform,n=Pe(e.home??T(),t);return n.find(e=>C(e))||n.find(e=>C(h(e)))||n[0]}const X={claude:{id:`claude`,label:j.claude,configPath:(e,t)=>Oe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>_(t??T(),`.claude`),projectConfigPath:e=>_(e,`.mcp.json`),projectSkillPath:e=>_(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:j[`claude-desktop`],configPath:(e,t)=>U({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>h(U({home:t}))},cursor:{id:`cursor`,label:j.cursor,configPath:(e,t)=>W({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>h(W({home:t})),projectConfigPath:e=>_(e,`.cursor`,`mcp.json`),projectSkillPath:e=>_(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:j.codex,configPath:(e,t)=>G({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>h(G({home:t})),projectConfigPath:e=>_(e,`.codex`,`config.toml`),projectSkillPath:e=>_(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},copilot:{id:`copilot`,label:j.copilot,configPath:(e,t)=>K({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>h(K({home:t})),projectSkillPath:e=>_(e,`.github`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:j.opencode,configPath:(e,t)=>q({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>s,buildEntry:(e,t)=>Se(t),scope:`global`,detectPath:(e,t)=>h(q({home:t})),projectConfigPath:e=>_(e,`opencode.json`),projectSkillPath:e=>_(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:j.openclaw,configPath:(e,t)=>je({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>_(t??T(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:j.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>J({home:t}),projectConfigPath:e=>_(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>_(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:j.antigravity,configPath:(e,t)=>Ne({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>_(t??T(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:j[`lm-studio`],configPath:(e,t)=>Y({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>h(Y({home:t})),offerOnlyWhenDetected:!0},hermes:{id:`hermes`,label:j.hermes,configPath:(e,t)=>Me({home:t}),format:`yaml`,topLevelKey:`mcp_servers`,serverName:()=>s,buildEntry:(e,t)=>z(t),scope:`global`,detectPath:(e,t)=>_(t??T(),`.hermes`),offerOnlyWhenDetected:!0}};function Fe(e){let t=e.filter(e=>!Object.hasOwn(X,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${A.join(`, `)}`);return e.map(e=>X[e])}function Z(e,t){let n;try{n=te(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);Q(e,t)}function Ie(e,t){Q(e,t)}function Q(e,t){let n;try{n=w(t)}catch{n=b(t)}let r=h(e);for(;r.length>1&&r!==x;){let t;try{t=w(r)}catch(e){if(e.code===`ENOENT`){r=h(r);continue}throw e}let i=y(n,t);if(i===``||!i.startsWith(`..`)&&!g(i))return;throw Error(`Refusing to write at ${e}: ancestor ${r} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Le(e,t,n){try{if(ae(n).size>10485760)return!1}catch{return!1}let r;try{r=re(n,`utf-8`)}catch{return!1}let i=[],a=c(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!$(a))return!1;let o=a[e.topLevelKey];if(!$(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;return $(s)?$(s[e.serverName(t)]):!1}function Re(e,t,n={}){if(!a.includes(e.id))return!0;try{return Le(e,t,e.configPath(t,n.home))}catch{return!1}}function ze(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!Re(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=d(`project`,{checkDesktop:!0}),i=h(r);Z(i,t);let a=C(r)?`overwritten`:`written`;return ie(i,{recursive:!0,force:!0}),ne(h(i),{recursive:!0}),ee(n,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function Be(e,t){let n=y(u(t),u(e));return n.length>0&&!n.startsWith(`..`)&&!g(n)}const Ve=e=>{try{let t=p(`git`,[`rev-parse`,`--show-toplevel`],l({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function He(e,t={}){let n=t.homeDir??T(),r=t.gitTopLevel??Ve,i=b(e),a;try{a=w(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(f(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=h(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&Be(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}export{_e as C,pe as S,H as _,A as a,J as b,ye as c,be as d,z as f,Ee as g,Ce as h,ze as i,I as l,xe as m,Z as n,j as o,Te as p,Ie as r,X as s,He as t,L as u,De as v,he as x,Fe as y};
|
|
56
|
-
//# sourceMappingURL=resolve-project-root-
|
|
56
|
+
//# sourceMappingURL=resolve-project-root-XuKmxBzQ.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{zs as e}from"./src-tR2kRwXj.mjs";import{xr as t,yr as n}from"./src-
|
|
2
|
-
//# sourceMappingURL=skill-teardown-
|
|
1
|
+
import{zs as e}from"./src-tR2kRwXj.mjs";import{xr as t,yr as n}from"./src-32lVY8sD.mjs";import{dirname as r,isAbsolute as i,join as a,relative as o,resolve as s,sep as c}from"node:path";import{existsSync as l,lstatSync as u,readdirSync as d,rmSync as f,rmdirSync as p}from"node:fs";const m=[{hostDir:`.adal`,pruneRoot:`.adal`},{hostDir:`.aider-desk`,pruneRoot:`.aider-desk`},{hostDir:`.astrbot/data`,pruneRoot:`.astrbot`},{hostDir:`.augment`,pruneRoot:`.augment`},{hostDir:`.autohand`,pruneRoot:`.autohand`},{hostDir:`.bob`,pruneRoot:`.bob`},{hostDir:`.codeartsdoer`,pruneRoot:`.codeartsdoer`},{hostDir:`.codebuddy`,pruneRoot:`.codebuddy`},{hostDir:`.codeium/windsurf`,pruneRoot:`.codeium`},{hostDir:`.codemaker`,pruneRoot:`.codemaker`},{hostDir:`.codestudio`,pruneRoot:`.codestudio`},{hostDir:`.commandcode`,pruneRoot:`.commandcode`},{hostDir:`.config/crush`,pruneRoot:`.config/crush`},{hostDir:`.config/devin`,pruneRoot:`.config/devin`},{hostDir:`.config/goose`,pruneRoot:`.config/goose`},{hostDir:`.config/kimchi/harness`,pruneRoot:`.config/kimchi`},{hostDir:`.continue`,pruneRoot:`.continue`},{hostDir:`.factory`,pruneRoot:`.factory`},{hostDir:`.forge`,pruneRoot:`.forge`},{hostDir:`.grok`,pruneRoot:`.grok`},{hostDir:`.iflow`,pruneRoot:`.iflow`},{hostDir:`.inferencesh`,pruneRoot:`.inferencesh`},{hostDir:`.jazz`,pruneRoot:`.jazz`},{hostDir:`.junie`,pruneRoot:`.junie`},{hostDir:`.kilocode`,pruneRoot:`.kilocode`},{hostDir:`.kiro`,pruneRoot:`.kiro`},{hostDir:`.kode`,pruneRoot:`.kode`},{hostDir:`.lingma`,pruneRoot:`.lingma`},{hostDir:`.mcpjam`,pruneRoot:`.mcpjam`},{hostDir:`.moxby`,pruneRoot:`.moxby`},{hostDir:`.mux`,pruneRoot:`.mux`},{hostDir:`.neovate`,pruneRoot:`.neovate`},{hostDir:`.ona`,pruneRoot:`.ona`},{hostDir:`.openhands`,pruneRoot:`.openhands`},{hostDir:`.pochi`,pruneRoot:`.pochi`},{hostDir:`.qoder`,pruneRoot:`.qoder`},{hostDir:`.qoder-cn`,pruneRoot:`.qoder-cn`},{hostDir:`.qwen`,pruneRoot:`.qwen`},{hostDir:`.reasonix`,pruneRoot:`.reasonix`},{hostDir:`.roo`,pruneRoot:`.roo`},{hostDir:`.rovodev`,pruneRoot:`.rovodev`},{hostDir:`.snowflake/cortex`,pruneRoot:`.snowflake`},{hostDir:`.tabnine/agent`,pruneRoot:`.tabnine`},{hostDir:`.terramind`,pruneRoot:`.terramind`},{hostDir:`.tinycloud`,pruneRoot:`.tinycloud`},{hostDir:`.trae`,pruneRoot:`.trae`},{hostDir:`.trae-cn`,pruneRoot:`.trae-cn`},{hostDir:`.vibe`,pruneRoot:`.vibe`},{hostDir:`.zcode`,pruneRoot:`.zcode`},{hostDir:`.zencoder`,pruneRoot:`.zencoder`}],h=[...t.map(e=>n[e]),`open-knowledge`];function g(e){if(!i(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=s(e);if(t===c||r(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function _(e,t){let n=o(e,t);if(n.startsWith(`..`)||i(n))return!1;let r=e;for(let e of n.split(c)){r=a(r,e);try{if(!u(r).isDirectory())return!1}catch{return!1}}return!0}function v(e,t){try{return d(e).every(n=>t.has(a(e,n)))}catch{return!1}}function y(e){let t=g(e),n=[],i=[],o=new Set;for(let e of m){let s=a(t,e.hostDir,`skills`);if(!_(t,s))continue;let u=h.map(e=>a(s,e)).filter(e=>l(e));n.push(...u);for(let e of u)o.add(e);let d=a(t,e.pruneRoot),f=s;for(;v(f,o)&&(i.push(f),o.add(f),f!==d);){let e=r(f);if(e===f||e===t||!e.startsWith(t+c))break;f=e}}return{skillDirs:n,emptyDirs:i}}function b(e){try{if(!u(e).isDirectory())return!1;let t=d(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function x(e){let t=new Set,n=new Set;for(let i of m){let o=a(e,i.hostDir,`skills`);for(let e of h)t.add(a(o,e));let s=a(e,i.pruneRoot),l=o;for(;n.add(l),l!==s;){let t=r(l);if(t===l||t===e||!t.startsWith(e+c))break;l=t}}return{skillDirs:t,emptyDirs:n}}function S(e,t){let n=g(e),r=x(n),i=[...t.skillDirs.filter(e=>!r.skillDirs.has(e)),...t.emptyDirs.filter(e=>!r.emptyDirs.has(e))];if(i.length>0)throw Error(`refusing skill cleanup — ${i.length} path(s) outside the known legacy set: ${i.join(`, `)}`);let a=[];for(let e of t.skillDirs)if(_(n,e)&&b(e))try{f(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(_(n,e))try{p(e),a.push(e)}catch{}return a}function C(r){let i=g(r),o=[];for(let r of t){let t=n[r];o.push({path:a(i,`.agents`,`skills`,t),bundleId:r,scope:`central`});for(let n of e)o.push({path:a(i,n.skillsRoot,t),bundleId:r,scope:`host`,hostDir:n.hostDir})}return o}function w(e,t){let n=[];for(let r of C(e))if(r.bundleId===t)try{f(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}export{C as i,y as n,w as r,S as t};
|
|
2
|
+
//# sourceMappingURL=skill-teardown-Dp8qru7m.mjs.map
|
|
@@ -26,7 +26,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,A as i,At
|
|
|
26
26
|
`)}\n`;this.enqueue(e,async()=>{if(!this.appendBroken.has(e))try{await ic(this.eventsPath(e),n)}catch(t){this.appendBroken.add(e),this.log.error({err:t,threadId:e},`[acp-persist] event append failed; thread continues memory-only`)}})}queueMetaWrite(e,t){this.pinHome(e);let n=`${JSON.stringify(t,null,1)}\n`;this.enqueue(e,async()=>{let t=this.metaPath(e),r=`${t}.tmp`;try{await Hs(r,n),await sc(r,t)}catch(t){this.log.warn({err:t,threadId:e},`[acp-persist] meta write failed`);try{await qs(r,{force:!0})}catch{}}})}whenIdle(e){return this.writeQueues.get(e)??Promise.resolve()}async scan(){let e=[],t=new Set,n=this.cwd===null?null:await xD(this.cwd);return await this.scanDir(this.primaryThreadsDir,n,e,t),this.legacyThreadsDir!==null&&this.legacyThreadsDir!==this.primaryThreadsDir&&await this.scanDir(this.legacyThreadsDir,null,e,t),e}async scanDir(e,t,n,r){let i;try{i=await md(e)}catch(t){t.code!==`ENOENT`&&this.log.warn({err:t,dir:e},`[acp-persist] could not read a threads dir`);return}for(let a of i){if(!a.endsWith(`.meta.json`))continue;let i=F(e,a),o;try{o=JSON.parse(await pd(i,`utf8`))}catch(e){this.log.warn({err:e,path:i},`[acp-persist] skipping unreadable thread meta`);continue}if(o.version!==1||typeof o.info!=`object`||o.info===null||typeof o.info.threadId!=`string`||typeof o.cwd!=`string`||typeof o.agentRef!=`object`||o.agentRef===null){this.log.warn({path:i},`[acp-persist] skipping unreadable thread meta`);continue}let s=o,c=s.info.threadId;r.has(c)||t!==null&&await xD(s.cwd)!==t||(r.add(c),this.homeByThread.has(c)||this.homeByThread.set(c,e),n.push(s))}}async resolveEventLog(e){let t=this.eventsPath(e);if(!z(t))return{count:0,midTurn:!1};let n=0,r=!1;return await this.forEachCompleteLine(t,e=>(n+=1,e.startsWith(`{"kind":"turn_started"`)?r=!0:e.startsWith(`{"kind":"turn_ended"`)&&(r=!1),!0)),{count:n,midTurn:r}}async readEvents(e,t,n,r){let i=this.eventsPath(e);if(t>=n||!z(i))return;let a=0,o=[],s=t,c=()=>{o.length!==0&&(r(s,o),s+=o.length,o=[])};await this.forEachCompleteLine(i,e=>a>=n?!1:(a>=t&&(o.push(bD(e)),o.length>=512&&c()),a+=1,!0)),c()}async delete(e){this.appendBroken.delete(e),this.writeQueues.delete(e);let t=[this.eventsPath(e),this.metaPath(e)],n=await Promise.allSettled(t.map(e=>qs(e,{force:!0})));this.homeByThread.delete(e);for(let[r,i]of n.entries())i.status===`rejected`&&this.log.warn({err:i.reason,threadId:e,path:t[r]},`[acp-persist] thread file removal failed`)}async forEachCompleteLine(e,t){let n=Uu(e,{encoding:`utf8`}),r=null;n.on(`error`,e=>{r=e});let i=Ote({input:n,crlfDelay:1/0}),a=!1,o=null,s=!1;try{for await(let e of i){if(o!==null&&!t(o)){s=!0;break}o=e}s||(a=await yD(e),o!==null&&a&&t(o))}finally{i.close(),n.destroy()}if(r!==null)throw r}};async function yD(e){let{open:t}=await import(`node:fs/promises`),n=await t(e,`r`);try{let{size:e}=await n.stat();if(e===0)return!1;let t=Buffer.alloc(1);return await n.read(t,0,1,e-1),t[0]===10}finally{await n.close()}}function bD(e){try{return JSON.parse(e)}catch{return{kind:`agent_stderr`,line:`[unreadable log entry]`,ts:0}}}async function xD(e){try{return await hd(e)}catch{return L(e)}}const SD=RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b(?:[\\s,:;!.\\-–—]+|$)`,`i`),CD=/^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/;function wD(e){return(e.trim().split(`
|
|
27
27
|
`)[0]??``).trim()}function TD(e){let t=wD(e);if(t.length<=48)return t;let n=t.slice(0,47),r=n.lastIndexOf(` `);return`${(r>=48/2?n.slice(0,r):n).trimEnd()}…`}function ED(e){let t=wD(e),n=t.replace(CD,``);for(let e=0;e<6;e++){let e=n.replace(SD,``);if(e===n)break;n=e}n=n.trim();let r=n.split(/\s+/).filter(e=>e!==``).length;return!(n!==``&&(r>=2||n.length>=12))||n===t?TD(t):TD(n.charAt(0).toUpperCase()+n.slice(1))}const DD=8,OD=5e3,kD=300*1e3,AD=45e3,jD=5e3,MD=2e3;var ND=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadOpError`,this.code=e}},PD=class extends Error{constructor(){super(`authenticate timed out`),this.name=`AuthenticateTimeoutError`}},FD=class extends Error{constructor(){super(`prompt build cancelled before dispatch`),this.name=`PromptCancelledBeforeDispatchError`}};function ID(){return new ND(`not-ready`,`the thread was restarted during the sign-in`)}function LD(e){return e.source===`registry`&&pf[e.id]===`pi`}function RD(e,t,n){let[r=`open-knowledge`,...i]=e&&e.length>0?e:[`open-knowledge`],a=[...i,`mcp`,`--port`,String(t)];if(r.includes(`/`)||r.includes(`\\`))return{command:r,args:a};let o=(n?.resolveCommand??(e=>Yw(e,nE())))(r);return o===null?(n?.log?.warn({command:r},`[acp-threads] OK MCP stdio command did not resolve on PATH — injecting the bare name, which fails for harnesses that spawn MCP children under a minimal PATH`),{command:r,args:a}):{command:o,args:a}}var zD=class{opts;threads=new Map;reapTimer;maxThreads;idleReapMs;steerStallMs;authenticateTimeoutMs;unwatchedTurnCancelMs;unwatchedTurnKillMs;persistence;resolveLoginShellPath;healthyInterpreters=new Set;destroyed=!1;initialized=!1;constructor(e){this.opts=e,this.resolveLoginShellPath=e.resolveLoginShellPath??(()=>KT(e.log)()),this.maxThreads=e.maxThreads??8,this.idleReapMs=e.idleReapMs??36e5,this.steerStallMs=e.steerStallMs??1e4,this.authenticateTimeoutMs=e.authenticateTimeoutMs??3e5,this.unwatchedTurnCancelMs=e.unwatchedTurnCancelMs??6e5,this.unwatchedTurnKillMs=e.unwatchedTurnKillMs??12e5,this.persistence=new vD({primaryDir:e.globalDir??e.localDir,legacyDir:e.globalDir===null?null:e.localDir,cwd:e.globalDir===null?null:e.contentDir,log:e.log}),this.reapTimer=setInterval(()=>this.reapIdleThreads(),3e5),this.reapTimer.unref?.()}async init(){if(this.initialized)return;this.initialized=!0,this.resolveLoginShellPath().catch(()=>{}),await this.persistence.init();let e=await this.persistence.scan();for(let t of e){let e=t.info.threadId;this.threads.has(e)||this.threads.set(e,VD(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),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()=>{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})(),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 ND(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);let{info:t,custom:n}=await this.resolveAgentInfo(e.agent);if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`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:`installing`,createdAt:i,lastActivityAt:i,promptCapabilities:null,modes:null,configOptions:null,availableCommands:null,lastSeq:-1,archived:!1},docName:e.docName,agentRef:{source:e.agent.source,id:e.agent.id},launchSettings:e.settings,cwd:this.opts.contentDir,child:null,conn:null,lastInit:null,sessionId:null,agentSessionId:`acp-${r}`,events:[],baseSeq:0,logResolved:!0,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:i,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!1,titleHint:e.titleHint,envNotePending:!1};return this.threads.set(r,a),this.emitStatus(a,`installing`),this.startThread(a,e,n).catch(e=>{this.opts.log.error({err:e,threadId:r},`[acp-threads] thread start failed`),this.emitStatus(a,`error`,e instanceof Error?e.message:String(e))}),{...a.info}}async resolveAgentInfo(e){if(e.source===`custom`){let t=(await Sf(this.opts.localDir,this.opts.log)).find(t=>t.id===e.id);if(t===void 0)throw new ND(`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 ND(`install-failed`,`agent registry unavailable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw new ND(`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 connectAgent(e,t){let n;if(t!==null)n=oE(t);else{let t=await this.opts.registry.getAgent(e.agentRef.id);if(t===void 0)throw new ND(`unknown-agent`,`agent vanished`);n=await aE(t,gf(),this.opts.log)}if(e.closed)return null;let r=await this.ensureLaunchable(e,n);if(r===null||(n=r,e.closed))return null;let i=await this.resolveLoginShellPath().catch(()=>null);if(e.closed)return null;let a=new gD({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log,loginShellPath:i});this.emitStatus(e,`spawning`);let o=RE(n,e.cwd);if(e.child=o,e.terminals=a,o.stderr?.setEncoding(`utf8`),o.stderr?.on(`data`,t=>{for(let n of t.split(`
|
|
28
28
|
`))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift(),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)))}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
|
|
29
|
-
`);this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:JD(e)},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new ND(`spawn-failed`,`agent process has no stdio`);let s=lie(bte.toWeb(o.stdin),_d.toWeb(o.stdout)),c=jie({name:`open-knowledge`}).onRequest(eh.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(eh.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(eh.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(eh.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(eh.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(eh.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(eh.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(eh.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(eh.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(eh.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:Pc},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new ND(`spawn-failed`,`initialize failed: ${GD(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){let n;try{await yE(t),n=await this.withLoginShellPathIfEligible(t)}catch(r){if(!(r instanceof QT)||r.code!==`command-not-found`)throw r;let i=await this.retryWithLoginShellPath(t);if(i===null)return this.fallbackToManagedRuntime(e,t,r);n=i}return e.closed?null:this.ensureInterpreterRuns(e,n)}async ensureInterpreterRuns(e,t){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let n=await this.probeInterpreterOnce(t);if(e.closed)return null;if(n===null)return t;if(n.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(e.closed)return null;if(AE(n.env)!==AE(t.env))try{await yE(n);let t=await this.probeInterpreterOnce(n);if(e.closed)return null;if(t===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),n;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:t.kind,detail:t.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof QT)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let r=new QT(`command-not-found`,n.kind===`incompatible`?kE(t,n.detail):xE(t,n.detail));return this.fallbackToManagedRuntime(e,t,r,r)}async fallbackToManagedRuntime(e,t,n,r){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=JE(t.kind);if(!rD(i))throw n;let a=await this.provideManagedRuntime(e,i,r===void 0?`missing`:`broken`).catch(e=>{throw r!==void 0&&e instanceof QT&&e.code===`command-not-found`?r:e});if(a===null)return null;let o=sE(t,a);await yE(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;if(s.kind===`incompatible`)throw new QT(`install-failed`,CE(s.detail));return this.repairManagedRuntime(e,t,i,s.detail)}async repairManagedRuntime(e,t,n,r){let i={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(i,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await uD(n,this.opts.log,this.opts.runtimeInstall?.root))throw new QT(`install-failed`,wE(t,r));let a=await this.provideManagedRuntime(e,n,`damaged`).catch(e=>{throw e instanceof QT&&e.code===`command-not-found`?new QT(`command-not-found`,TE(t)):e});if(a===null)return null;let o=sE(t,a);await yE(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;throw this.opts.log.error({...i,detail:s.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new QT(`install-failed`,s.kind===`incompatible`?CE(s.detail):SE(o,s.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,AE(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await DE(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await OE(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(AE(t.env)===AE(e.env))return null;try{await yE(t)}catch(t){if(!(t instanceof QT))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||jE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:cE(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||jE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:lE(e,t)}async provideManagedRuntime(e,t,n){let r=this.opts.runtimeInstall?.root;await lD(t,this.opts.log,r);let i=await sD(t,r).catch(()=>null);if(i!==null)return i;let a=await this.requestRuntimeConsent(e,t,n);if(a===`closed`||e.closed)return null;if(a!==`granted`)throw new QT(`command-not-found`,UD(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=YE(t).displayName;throw new QT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n){let r=crypto.randomUUID(),i=YE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:r,runtime:t,displayName:i.displayName,provides:i.provides,version:i.version,approxSizeMB:i.approxSizeMB,sourceHost:i.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(r),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:r,decision:`timeout`,ts:Date.now()}),t(`timeout`)},kD);n.unref?.(),e.pendingRuntimeConsent.set(r,{resolve:t,timer:n})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return dD(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t,n=kD){let r=[],i;if(LD(e.agentRef))i=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)i=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:`open-knowledge`,url:`${e}/mcp`,headers:[{name:lT,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=nE();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:_r,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),i=`stdio-entry-env`)}}return i===`none`?this.opts.log.warn({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] no OK MCP transport available for this agent — it starts without OK tools`):this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,hostedMarker:i},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:i}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=pf[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async settlePiBridge(e,t){let n=this.opts.probePiAcpBridge,r=e.info.threadId;if(n===void 0)return this.opts.log.debug({threadId:r,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let i;try{i=await n(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:r},`[acp-threads] Pi bridge probe failed`),`unknown`}if(e.closed)return`unknown`;if(i.bridgeLoadable)return this.opts.log.info({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(i.bridge===`foreign`||i.bridge===`unreadable`)return this.opts.log.warn({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:i.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:i.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:r},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let a=this.opts.ensurePiAcpBridge;if(a===void 0)return this.opts.log.warn({threadId:r},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let o=crypto.randomUUID(),s=await this.requestPiBridgeConsent(e,o,i,t);if(s===`declined`&&(e.piBridgeDeclined=!0),e.closed)return`unknown`;if(s!==`granted`)return this.opts.log.info({threadId:r,decision:s},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let c;try{c=await a(e.cwd)}catch(t){let n=t instanceof Error?t.message:String(t);return this.opts.log.warn({err:t,threadId:r},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,o,`bridge-failed`,i.bridgePath,{detail:n}),`unavailable`}if(c.ok)return this.opts.log.info({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),e.closed?`unknown`:(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:o,state:`ready`,bridgePath:c.bridgePath,bridge:c.bridge,trust:c.trust,ts:Date.now()}),`loadable`);let l=c.bridge===`written`||c.bridge===`refreshed`||c.bridge===`unchanged`,u=c.bridge===`refused-foreign`?`foreign-file`:c.bridge===`refused-unreadable`?`unreadable-file`:l?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath,err:c.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,o,u,c.bridgePath,{bridge:c.bridge,trust:c.trust,...c.error===void 0?{}:{detail:c.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i){e.closed||this.appendEvent(e,{kind:`pi_bridge_status`,requestId:t,state:n,bridgePath:r,...i,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:e.cwd,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=kD){let i;try{i=await this.connectAgent(e,n)}catch(t){let n=t instanceof QT||t instanceof ND?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:JD(e)}),await this.teardownFailedAgent(e);return}if(i===null)return;let{conn:a,init:o,launch:s}=i;await this.openSession(e,a,o,t.settings,`park`,r)===!0&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:s.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),(t.prompt!==void 0&&t.prompt!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`,a=kD){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let n=await t.agent.request(eh.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=n.sessionId,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){if(WD(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,e),authMethods:ZD(n.authMethods)})}else this.emitStatus(e,`error`,`session setup failed: ${GD(t)}`,{reason:`session-setup`,agentMessage:GD(t),machineDetail:YD(KD(t),JD(e))}),await this.teardownFailedAgent(e);return!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new ND(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new ND(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`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 ND(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`installing`);try{if(a===null)throw new ND(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s);if(o===null)throw new ND(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o,{servers:d}=await this.buildMcpServers(r,u,AD),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(eh.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(eh.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw new ND(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=m.modes;h!=null&&(r.info.modes=h);let g=m.configOptions;return g!=null&&(r.info.configOptions=g),this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r),t instanceof ND?t:t instanceof QT?new ND(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 ND(`resume-unsupported`,`couldn't resume the previous session: ${GD(t)}`))}}finally{r.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new ND(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new ND(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new ND(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{qT(),this.healthyInterpreters.clear();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r,AD)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new ND(`spawn-failed`,n)}if(t.closed)throw new ND(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new ND(`spawn-failed`,qD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new ND(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new ND(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new ND(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new ND(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw ID();let t=e instanceof PD?`the sign-in didn't complete in time — try again`:GD(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:XD(e,n),authMethods:ZD(i.authMethods)}),new ND(`not-ready`,t)}if(n.closed)throw new ND(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw ID();let a=await this.openSession(n,r,i,n.launchSettings,`report`,AD);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,n),authMethods:ZD(i.authMethods)}),t}}if(a!==!0)throw new ND(`not-ready`,qD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new PD),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(eh.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingConsents(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await HE(t,{graceMs:MD}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(xh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),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 ND(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new ND(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new ND(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new ND(`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);if(r.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new ND(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new ND(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);if(!r.turnActive){this.dispatchPrompt(r,t,n,{echo:!0});return}this.clearSteer(r);let i={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.steer=i,r.info.lastActivityAt=Date.now(),this.emitInfo(r);let a=setTimeout(()=>this.demoteStalledSteer(r),this.steerStallMs);a.unref?.(),r.steerStallTimer=a,this.cancelTurn(r,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;if(t===void 0||e.closed||!e.turnActive)return;e.info.steer=void 0;let n={id:crypto.randomUUID(),content:t.content,ts:t.ts};t.attachments!==void 0&&t.attachments.length>0&&(n.attachments=t.attachments),e.info.queue=[n,...e.info.queue??[]],this.emitInfo(e)}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(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=ED(n),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 ND(`not-ready`,`the thread is closing`);let r=TD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,i=`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.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let a=e.sessionId;hT(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 ND(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new FD;return e.conn.agent.request(eh.agent.session.prompt,{sessionId:a,prompt:[...t.blocks]})}).then(t=>{if(e.turnActive=!1,!e.closed){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(t=>{if(e.turnActive=!1,!e.closed){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(WD(t)){this.emitStatus(e,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,e),authMethods:ZD(e.lastInit?.authMethods)});return}this.emitStatus(e,`error`,`prompt failed: ${GD(t)}`,{reason:`prompt`,agentMessage:GD(t),machineDetail:YD(KD(t),JD(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(eh.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.conn===null||n.sessionId===null)throw new ND(`not-ready`,`thread has no live agent session`);n.conn.agent.request(eh.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.conn===null||r.sessionId===null)throw new ND(`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(eh.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){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!HD(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(eh.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(eh.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&HD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(eh.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await HE(r,{graceMs:t?.killGraceMs??jD})||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(xh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(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 ND(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new ND(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:MD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:bT(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await pd(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await pd(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
29
|
+
`);this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:JD(e)},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new ND(`spawn-failed`,`agent process has no stdio`);let s=lie(bte.toWeb(o.stdin),_d.toWeb(o.stdout)),c=jie({name:`open-knowledge`}).onRequest(eh.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(eh.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(eh.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(eh.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(eh.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(eh.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(eh.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(eh.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(eh.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(eh.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:Pc},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new ND(`spawn-failed`,`initialize failed: ${GD(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){let n;try{await yE(t),n=await this.withLoginShellPathIfEligible(t)}catch(r){if(!(r instanceof QT)||r.code!==`command-not-found`)throw r;let i=await this.retryWithLoginShellPath(t);if(i===null)return this.fallbackToManagedRuntime(e,t,r);n=i}return e.closed?null:this.ensureInterpreterRuns(e,n)}async ensureInterpreterRuns(e,t){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let n=await this.probeInterpreterOnce(t);if(e.closed)return null;if(n===null)return t;if(n.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(e.closed)return null;if(AE(n.env)!==AE(t.env))try{await yE(n);let t=await this.probeInterpreterOnce(n);if(e.closed)return null;if(t===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),n;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:t.kind,detail:t.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof QT)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let r=new QT(`command-not-found`,n.kind===`incompatible`?kE(t,n.detail):xE(t,n.detail));return this.fallbackToManagedRuntime(e,t,r,r)}async fallbackToManagedRuntime(e,t,n,r){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=JE(t.kind);if(!rD(i))throw n;let a=await this.provideManagedRuntime(e,i,r===void 0?`missing`:`broken`).catch(e=>{throw r!==void 0&&e instanceof QT&&e.code===`command-not-found`?r:e});if(a===null)return null;let o=sE(t,a);await yE(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;if(s.kind===`incompatible`)throw new QT(`install-failed`,CE(s.detail));return this.repairManagedRuntime(e,t,i,s.detail)}async repairManagedRuntime(e,t,n,r){let i={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(i,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await uD(n,this.opts.log,this.opts.runtimeInstall?.root))throw new QT(`install-failed`,wE(t,r));let a=await this.provideManagedRuntime(e,n,`damaged`).catch(e=>{throw e instanceof QT&&e.code===`command-not-found`?new QT(`command-not-found`,TE(t)):e});if(a===null)return null;let o=sE(t,a);await yE(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;throw this.opts.log.error({...i,detail:s.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new QT(`install-failed`,s.kind===`incompatible`?CE(s.detail):SE(o,s.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,AE(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await DE(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await OE(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(AE(t.env)===AE(e.env))return null;try{await yE(t)}catch(t){if(!(t instanceof QT))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||jE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:cE(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||jE(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:lE(e,t)}async provideManagedRuntime(e,t,n){let r=this.opts.runtimeInstall?.root;await lD(t,this.opts.log,r);let i=await sD(t,r).catch(()=>null);if(i!==null)return i;let a=await this.requestRuntimeConsent(e,t,n);if(a===`closed`||e.closed)return null;if(a!==`granted`)throw new QT(`command-not-found`,UD(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=YE(t).displayName;throw new QT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n){let r=crypto.randomUUID(),i=YE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:r,runtime:t,displayName:i.displayName,provides:i.provides,version:i.version,approxSizeMB:i.approxSizeMB,sourceHost:i.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(r),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:r,decision:`timeout`,ts:Date.now()}),t(`timeout`)},kD);n.unref?.(),e.pendingRuntimeConsent.set(r,{resolve:t,timer:n})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return dD(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t,n=kD){let r=[],i;if(LD(e.agentRef))i=await this.settlePiBridge(e,n)===`unavailable`?`none`:`unknown`;else if(await this.harnessAlreadyHasOkMcp(e)!==null)i=`unknown`;else{let e=this.opts.getServerUrl?.();if(e!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)r.push({type:`http`,name:`open-knowledge`,url:`${e}/mcp`,headers:[{name:lT,value:`1`}]}),i=`http-header`;else{let e=this.opts.getMcpStdioCommand?.(),t=nE();e==null?i=`none`:(r.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:_r,value:`1`},...t!==void 0&&t!==``?[{name:`PATH`,value:t}]:[]]}),i=`stdio-entry-env`)}}return i===`none`?this.opts.log.warn({threadId:e.info.threadId,agentId:e.agentRef.id},`[acp-threads] no OK MCP transport available for this agent — it starts without OK tools`):this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,hostedMarker:i},`[acp-threads] OK MCP injection outcome`),{servers:r,hostedMarker:i}}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=pf[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async settlePiBridge(e,t){let n=this.opts.probePiAcpBridge,r=e.info.threadId;if(n===void 0)return this.opts.log.debug({threadId:r,agentId:e.agentRef.id},`[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired`),`unknown`;let i;try{i=await n(e.cwd)}catch(e){return this.opts.log.warn({err:e,threadId:r},`[acp-threads] Pi bridge probe failed`),`unknown`}if(e.closed)return`unknown`;if(i.bridgeLoadable)return this.opts.log.info({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] Pi already loads the OK bridge extension for this project`),`loadable`;if(i.bridge===`foreign`||i.bridge===`unreadable`)return this.opts.log.warn({threadId:r,bridge:i.bridge,bridgePath:i.bridgePath},`[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools`),this.emitPiBridgeStatus(e,{kind:`pi_bridge_status`,state:i.bridge===`foreign`?`foreign-file`:`unreadable-file`,bridgePath:i.bridgePath,ts:Date.now()}),`unavailable`;if(e.piBridgeDeclined)return this.opts.log.debug({threadId:r},`[acp-threads] Pi bridge prompt already declined for this thread — not re-asking`),`unavailable`;let a=this.opts.ensurePiAcpBridge;if(a===void 0)return this.opts.log.warn({threadId:r},`[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting`),`unavailable`;let o=crypto.randomUUID(),s=await this.requestPiBridgeConsent(e,o,i,t);if(s===`declined`&&(e.piBridgeDeclined=!0),e.closed)return`unknown`;if(s!==`granted`)return this.opts.log.info({threadId:r,decision:s},`[acp-threads] Pi bridge not provisioned — the thread continues without OK tools`),`unavailable`;let c;try{c=await a(e.cwd)}catch(t){let n=t instanceof Error?t.message:String(t);return this.opts.log.warn({err:t,threadId:r},`[acp-threads] Pi bridge provisioning threw`),this.appendPiBridgeFailure(e,o,`bridge-failed`,i.bridgePath,{detail:n}),`unavailable`}if(c.ok)return this.opts.log.info({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath},`[acp-threads] provisioned the Pi bridge extension for this project`),e.closed?`unknown`:(this.appendEvent(e,{kind:`pi_bridge_status`,requestId:o,state:`ready`,bridgePath:c.bridgePath,bridge:c.bridge,trust:c.trust,ts:Date.now()}),`loadable`);let l=c.bridge===`written`||c.bridge===`refreshed`||c.bridge===`unchanged`,u=c.bridge===`refused-foreign`?`foreign-file`:c.bridge===`refused-unreadable`?`unreadable-file`:l?`trust-failed`:`bridge-failed`;return this.opts.log.warn({threadId:r,bridge:c.bridge,trust:c.trust,bridgePath:c.bridgePath,err:c.error},`[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools`),this.appendPiBridgeFailure(e,o,u,c.bridgePath,{bridge:c.bridge,trust:c.trust,...c.error===void 0?{}:{detail:c.error}}),`unavailable`}appendPiBridgeFailure(e,t,n,r,i){e.closed||this.appendEvent(e,{kind:`pi_bridge_status`,requestId:t,state:n,bridgePath:r,...i,ts:Date.now()})}emitPiBridgeStatus(e,t){e.lastPiBridgeStatus!==t.state&&(e.lastPiBridgeStatus=t.state,this.appendEvent(e,t))}requestPiBridgeConsent(e,t,n,r){return this.appendEvent(e,{kind:`pi_bridge_consent_request`,requestId:t,agentName:e.info.agent.name,bridgePath:n.bridgePath,cwd:e.cwd,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=kD){let i;try{i=await this.connectAgent(e,n)}catch(t){let n=t instanceof QT||t instanceof ND?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:JD(e)}),await this.teardownFailedAgent(e);return}if(i===null)return;let{conn:a,init:o,launch:s}=i;await this.openSession(e,a,o,t.settings,`park`,r)===!0&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:s.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),(t.prompt!==void 0&&t.prompt!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`,a=kD){e.info.availableCommands=null;let{servers:o}=await this.buildMcpServers(e,n,a);try{let n=await t.agent.request(eh.agent.session.new,{cwd:e.cwd,mcpServers:o});e.sessionId=n.sessionId,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){if(WD(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,e),authMethods:ZD(n.authMethods)})}else this.emitStatus(e,`error`,`session setup failed: ${GD(t)}`,{reason:`session-setup`,agentMessage:GD(t),machineDetail:YD(KD(t),JD(e))}),await this.teardownFailedAgent(e);return!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new ND(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new ND(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`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 ND(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new ND(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`installing`);try{if(a===null)throw new ND(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s);if(o===null)throw new ND(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o,{servers:d}=await this.buildMcpServers(r,u,AD),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(eh.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(eh.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw new ND(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=Object.fromEntries((r.info.configOptions??[]).map(e=>[e.id,e.currentValue])),g=r.info.modes?.currentModeId,_=m.modes;_!=null&&(r.info.modes=_);let v=m.configOptions;if(v!=null&&(r.info.configOptions=v),await this.applyInitialConfig(r,l,h,v==null),r.closed||g!==void 0&&(await this.applyInitialMode(r,l,g,_==null),r.closed))throw new ND(`not-ready`,`thread closed during resume`);return this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r),t instanceof ND?t:t instanceof QT?new ND(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 ND(`resume-unsupported`,`couldn't resume the previous session: ${GD(t)}`))}}finally{r.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new ND(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new ND(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new ND(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{qT(),this.healthyInterpreters.clear();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r,AD)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new ND(`spawn-failed`,n)}if(t.closed)throw new ND(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new ND(`spawn-failed`,qD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new ND(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new ND(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new ND(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new ND(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new ND(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw ID();let t=e instanceof PD?`the sign-in didn't complete in time — try again`:GD(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:XD(e,n),authMethods:ZD(i.authMethods)}),new ND(`not-ready`,t)}if(n.closed)throw new ND(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw ID();let a=await this.openSession(n,r,i,n.launchSettings,`report`,AD);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,n),authMethods:ZD(i.authMethods)}),t}}if(a!==!0)throw new ND(`not-ready`,qD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new PD),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(eh.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingConsents(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await HE(t,{graceMs:MD}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(xh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),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 ND(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new ND(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new ND(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new ND(`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);if(r.info.archived===!0)throw new ND(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new ND(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new ND(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);if(!r.turnActive){this.dispatchPrompt(r,t,n,{echo:!0});return}this.clearSteer(r);let i={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.steer=i,r.info.lastActivityAt=Date.now(),this.emitInfo(r);let a=setTimeout(()=>this.demoteStalledSteer(r),this.steerStallMs);a.unref?.(),r.steerStallTimer=a,this.cancelTurn(r,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;if(t===void 0||e.closed||!e.turnActive)return;e.info.steer=void 0;let n={id:crypto.randomUUID(),content:t.content,ts:t.ts};t.attachments!==void 0&&t.attachments.length>0&&(n.attachments=t.attachments),e.info.queue=[n,...e.info.queue??[]],this.emitInfo(e)}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(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=ED(n),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 ND(`not-ready`,`the thread is closing`);let r=TD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new ND(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,i=`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.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let a=e.sessionId;hT(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 ND(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new FD;return e.conn.agent.request(eh.agent.session.prompt,{sessionId:a,prompt:[...t.blocks]})}).then(t=>{if(e.turnActive=!1,!e.closed){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(t=>{if(e.turnActive=!1,!e.closed){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(WD(t)){this.emitStatus(e,`auth_required`,`sign in required: ${GD(t)}`,{reason:`auth-required`,agentMessage:GD(t),machineDetail:XD(t,e),authMethods:ZD(e.lastInit?.authMethods)});return}this.emitStatus(e,`error`,`prompt failed: ${GD(t)}`,{reason:`prompt`,agentMessage:GD(t),machineDetail:YD(KD(t),JD(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(eh.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 ND(`not-ready`,`no such mode: ${t}`);n.info.modes={...e,currentModeId:t},this.emitInfo(n);return}if(n.resumeInFlight)throw new ND(`not-ready`,`the thread is still resuming`);if(n.conn===null||n.sessionId===null)throw new ND(`not-ready`,`thread has no live agent session`);n.conn.agent.request(eh.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 ND(`not-ready`,`no such config option: ${t}`);if(!HD(e,n))throw new ND(`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 ND(`not-ready`,`the thread is still resuming`);if(r.conn===null||r.sessionId===null)throw new ND(`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(eh.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n,r=!1){let i=e.sessionId;if(i===null)return;let a=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,o=Object.keys(n).sort((e,t)=>Number(a(t))-Number(a(e))),s=!1,c=[];for(let a of o){let o=n[a];if(o===void 0)continue;let l=(e.info.configOptions??[]).find(e=>e.id===a);if(l===void 0||!r&&l.currentValue===o||!HD(l,o))continue;let u=typeof o==`boolean`?{sessionId:i,configId:a,type:`boolean`,value:o}:{sessionId:i,configId:a,value:o};try{let n=await t.agent.request(eh.agent.session.setConfigOption,u);e.info.configOptions=n.configOptions,s=!0}catch(t){c.push(a),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:a},`[acp-threads] initial config apply failed`)}if(e.closed)return}c.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:c,sessionStateUnknown:r},`[acp-threads] some remembered config options could not be applied to the new session`),s&&this.emitInfo(e)}async applyInitialMode(e,t,n,r=!1){let i=e.sessionId;if(i===null)return;let a=e.info.modes;if(a!=null&&a.availableModes.some(e=>e.id===n)){if(!r&&a.currentModeId===n)return;try{await t.agent.request(eh.agent.session.setMode,{sessionId:i,modeId:n}),e.info.modes={...a,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let o=(e.info.configOptions??[]).find(e=>e.category===`mode`&&HD(e,n));if(o!==void 0&&!(!r&&o.currentValue===n))try{let r=await t.agent.request(eh.agent.session.setConfigOption,{sessionId:i,configId:o.id,value:n});e.info.configOptions=r.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingConsents(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await HE(r,{graceMs:t?.killGraceMs??jD})||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(xh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(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 ND(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new ND(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:MD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:bT(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await pd(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await pd(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
30
30
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
31
31
|
`)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=ww(t.dc.document);Cw(t.dc.document,n,`replace`,i,void 0,xw(t));let a=Ri(r,ww(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-DjggEXdh.mjs`);await e(P(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return BD(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new ND(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&TT(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>OD){let t=e.events.length-OD;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){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await HE(t,{graceMs:jD})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,...i}=e.info;return{version:1,info:i,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}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=ds(e.info.agent.id),i=ui[r]??_s(e.agentSessionId);n.setPresence(xh(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 BD(e,t,n){let r=await hd(e),i=ju(Au(t)?t:L(r,t)),a=i,o=``;for(;;)try{let e=await hd(a),i=o===``?e:F(e,o),s=I(r,i);if(s===``||s.startsWith(`..`)||Au(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(R).join(`/`),t=s.split(R).join(`/`);!iS(e)&&!aS(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(R).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=P(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):F(a.slice(t.length+1),o),a=t}}function VD(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0,signInOutput:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,pendingPiBridgeConsent:new Map,piBridgeDeclined:!1,lastPiBridgeStatus:null,stderrTail:[],authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function HD(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 UD(e){let t=YE(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 WD(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 GD(e){return e instanceof Error?e.message:String(e)}function KD(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function qD(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}}function JD(e){let t=e.stderrTail.join(`
|
|
32
32
|
`);return t===``?void 0:t}function YD(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
|
|
@@ -2026,4 +2026,4 @@ native-divergence-injected
|
|
|
2026
2026
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await M.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(ee(!1),await M.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await Ix(be.current,t,e.oldHead,e.newHead,i);ex(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=QM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Jx(e),a=Ce.documents.get(i);if(!a)continue;let o=zt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=QM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Jx(e));i&&Vt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=ZF(r);b.debug({resetAmbientCredentials:f,originKind:YF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=Oc(h,{resetAmbient:f}),g=re();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{$t=new lPe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||M.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=be.current;n&&await Rx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await Rx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Ns({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:Ee(t.error),configPath:Qs(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Je(`files`),ye.announceReadyViews();let _=BL();_!==void 0&&VL(`readyMs`,_),oe()}return an().then(()=>{Qe=!0,He(),dt()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:j,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:nn,ready:We,generatedIndexSweepReady:st,degraded:rn,lockDir:de,get syncEngine(){return $t},getLinkPreviewsEnabled:k,resolveEmbed:me,acpRegistry:fe,acpPermissions:A}}function l9(e){return e/1048576}function hPe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:l9(e.rss),heapTotalMb:l9(e.heapTotal),heapUsedMb:l9(e.heapUsed),externalMb:l9(e.external),arrayBuffersMb:l9(e.arrayBuffers)}}}let u9=null,d9=null,f9=null;const p9=1e6;let m9=null,h9=null;Bs(()=>{u9=null,d9=null,f9=null,m9?.disable(),m9=null,h9=null});function gPe(){if(u9)return;let e=dc().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=hPe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),u9=e}function _Pe(){if(!d9){let e=dc().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!m9){m9=Dte({resolution:20}),m9.enable();return}e.observe(m9.percentile(50)/p9,{stat:`p50`}),e.observe(m9.percentile(99)/p9,{stat:`p99`}),m9.reset()}),d9=e}if(!f9){let e=dc().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=h9;if(h9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),f9=e}}const g9=N(`skill-migrate`);function _9(e){return[{host:`agents`,root:Pi},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=YO.indexOf(e.host),r=YO.indexOf(t.host);return(n===-1?YO.length:n)-(r===-1?YO.length:r)||e.host.localeCompare(t.host)})}const vPe=_9(Mn),yPe=_9(Bn);function bPe(e,t){return z(L(e,st(t)))}function xPe(e,t){$s(P(t),{recursive:!0});try{Ks(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;nc(e,t,{recursive:!0}),rc(e,{recursive:!0,force:!0})}}function SPe(e,t,n){let r=YI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function v9(e,t){let n;try{n=V(L(e,`.ok`,`skills`))}catch{n=L(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!V(L(e,t.dir)).startsWith(n+R)}catch{return!0}}).map(e=>e.name))}async function y9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??vPe,a={migrated:[],skipped:[]};if(!z(n))return a;let o;try{o=Zu(n)}catch{return a}let s=I(t,n).split(R).join(`/`),c=new Set;for(let[e,n]of Object.entries($Y(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!oo.test(e)||uI.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=L(n,e);if(!z(F(o,`SKILL.md`)))continue;let s=RO(o)?.contentHash;if(s===void 0)continue;let l=V(o),u=i.map(({host:n,root:r})=>{let i=L(t,r);return{host:n,root:r,path:F(i,e),escapes:rL(t,i),state:SPe(F(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>bPe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?rc(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&rc(d.path,{recursive:!0,force:!0}),xPe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(rc(e.path,{recursive:!0,force:!0}),nc(d.path,e.path,{recursive:!0}));await MN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),g9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),g9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const b9=N(`skill-reconcile`),CPe=uI;function x9(){let e=[];for(let t of Rt){let n=Mn[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Pi,editor:null}),e}function wPe(e,t){let n=I(e,L(t));return Au(n)?L(t):n}function S9(e){let{frontmatter:t,body:n}=eo(e),r={};if(t!==``)try{let e=(0,_k.parse)(Fo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function TPe(e,t){let n=S9(e),r=S9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function C9(e,t){let n=w9(e),r=w9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=F(e,o),c=F(t,o);if(i+=nd(s).size+nd(c).size,i>1048576)return!1;let l=B(s),u=B(c);if(!l.equals(u)&&(o!==`SKILL.md`||!TPe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function w9(e,t=``){let n=[];for(let r of Zu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...w9(F(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function T9(e,t,n){rc(t,{recursive:!0,force:!0}),$s(e,{recursive:!0}),Ys(wPe(e,n),t,`dir`)}function E9(e,t){try{let n=Qu(e);return L(Au(n)?n:L(P(e),n))===L(t)}catch{return!1}}function EPe(e,t){try{let n=Qu(e),r=Au(n)?L(n):L(P(e),n);if(!z(r))return!1;let i=I(L(t),r);return i!==``&&(i.startsWith(`..`)||Au(i))}catch(t){return b9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const DPe=[...Rt,`agents`];function OPe(e){for(let t of DPe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function kPe(e){let{projectDir:t,skillsRoot:n}=e;if(!z(n))return;let r;try{r=Zu(n)}catch{return}let i=x9();for(let e of r){let r=OPe(e);if(r===null)continue;let a=L(n,e),o=L(n,r);if(z(o))try{let n=Gu(a);if(n.isSymbolicLink()||!n.isDirectory()||!z(F(a,`SKILL.md`))||!z(F(o,`SKILL.md`))||!C9(o,a))continue;for(let{rel:n}of i){let r=L(t,n);if(rL(t,r))continue;let i=F(r,e);E9(i,a)&&T9(r,i,o)}rc(a,{recursive:!0,force:!0}),b9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){b9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function APe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of x9()){let o=L(t,e);if(!z(o)||rL(t,o))continue;let s;try{s=Zu(o)}catch(e){b9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(CPe.has(e))continue;let t=F(o,e),s=L(n,e),c=z(s);try{let l=Gu(t);if(l.isSymbolicLink()){if(E9(t,s)&&c)continue;if(EPe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(T9(o,t,s),r.healed.push({name:e,editor:i})):(rc(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!oo.test(e)){b9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&C9(t,s)){T9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){b9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=kN(t);for(let[r,a]of i){let i=L(n,r);if(!z(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await jN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??QI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){b9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{kPe({projectDir:t,skillsRoot:n})}catch(e){b9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let D9=null,O9=!1;function k9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function A9(e){if(!k9())return;let t=Yk(e);D9=new vc({currentPath:L(t,`tolerance-telemetry.jsonl`),previousPath:L(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),zt(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};D9?.append(`${JSON.stringify(t)}\n`).catch(e=>{O9||(O9=!0,N(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function j9(){zt(null),await D9?.drain(),D9=null,O9=!1}ks();const jPe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],MPe=[`cache`,`tmp`];function NPe(e){let t=L(e,ye);if(!(()=>{if(!z(t))return!0;try{return Zu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of jPe)z(L(e,t))&&n.push(t);for(let t of MPe){let r=L(e,t);try{z(r)&&nd(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function PPe(e){let t=Rd(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const M9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function FPe(e){sge();let t=e.projectDir??e.contentDir,n=zye({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}mc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}uc({localSink:n?.telemetry}),A9(t),gPe(),_Pe();let{kind:r,gitdir:i}=PPe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=tc(i));let o=Lye(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Vs(`ok.boot`,{attributes:a},async()=>IPe(e)),l=()=>{if(s)try{let e=Ds.extract(As.active(),{traceparent:s});return As.with(e,c)}catch(e){N(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function IPe(e){let t=e.skipAutoInit??!1,n=e.log??N(`boot`),r=e.serverRuntime??{...ma(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((Ba(r)||!mo(i))&&!r.allowExternal)throw new WB(`refusing to start: the server would bind a non-loopback address (${(mo(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=qB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock--BI6Lqjj.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=L(p,`.ok`);if(!z(L(m,`config.yml`)))throw new i8(z(m)?`config`:`okdir`,p);let h=L(m,`.gitignore`);z(h)||N(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??Uw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof Bw||e instanceof Vw){let t=e instanceof Vw?e.detected:``,r=e instanceof Vw?`too_old`:`not_available`;yK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await lc(),await Promise.race([j9(),new Promise(e=>setTimeout(e,M9))]),e}let _=NPe(m);_.length>0&&N(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ye}/.`);let v=c9({contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=()=>`http://${te}:${re}`,D=e.ephemeral?void 0:Z6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ie(),localApi:v.localApi,log:n}),O=c();O.headersTimeout=3e4,O.requestTimeout=6e4;let k=e.serveContentAssets===!1?void 0:xZ({contentFilter:v.contentFilter,contentSirv:PZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:be,assetExtensions:ne,blocklistExtensions:Ne,ingressPolicy:a}),ae=e.reactShellDistDir?PZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new zD({contentDir:e.contentDir,localDir:C,globalDir:L(od(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ie(),getMcpStdioCommand:()=>RD(e.localOpCliArgs,re,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=n8({httpServer:O,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:D,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:k,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=zZ({httpServer:O,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await N9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],A=async()=>{await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await pe(O,e.port??0,fe??`127.0.0.1`)}catch(e){throw await A(),e}let me=O.address(),he=typeof me==`object`&&me?me.port:e.port??0,ge=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=O.headersTimeout,t.requestTimeout=O.requestTimeout;for(let e of O.listeners(`request`))t.on(`request`,e);for(let e of O.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:ge.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ge,O])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await A(),t}ge.push(t)}let _e=BL();_e!==void 0&&VL(`httpListenMs`,_e);let ve=O.address(),j=typeof ve==`object`&&ve?ve.port:e.port??0;re=j,d(C,j,ie());let M=!1,xe=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${M9}ms`))},M9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(M)return;M=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await xe(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of ge)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>ce.shutdown()),D!==void 0&&await t(`mcpHttpHandler.close`,()=>D.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),await t(`shutdownTelemetry`,()=>lc()),await t(`teardownToleranceTelemetry`,()=>j9()),await t(`flushLogFileSinks`,()=>mc.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await y9({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`),inPlaceNames:v9(e.contentDir,DL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=od(),t=await y9({projectDir:e,skillsRoot:L(e,`.ok`,`skills`),hostRoots:yPe,inPlaceNames:v9(e,OL(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await APe({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:le,lockDir:C,contentDir:e.contentDir,port:j,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:qAe(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function N9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new IZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=zd(n),t=e?F(e,`MERGE_HEAD`):null;if(!t||!z(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=wc({baseDir:n,timeout:{block:5e3}});s=new Set(await Zb(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=Jx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const LPe=Ie;function RPe(e={}){let t=e.home??od(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(F(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(F(r.APPDATA??F(t,`AppData`,`Roaming`),`Claude`)):!1}var P9=t(_c(),1);const F9=F(od(),`.ok`,`logs`),zPe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function BPe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function VPe(e){Ku(e,{recursive:!0})}function I9(){return new Date().toISOString().slice(0,10)}function HPe(e){try{if(nd(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{$u(n,r)}catch{}}try{rd(`${e}.3`)}catch{}}function UPe(e){try{let t=Date.now(),n=10080*60*1e3,r=Zu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=nd(F(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{rd(F(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{rd(F(e,t.name)),a-=t.size}catch{}}}catch{}}function WPe(e){VPe(F9);let t=I9(),n=e.filePath??F(F9,`${e.name}.${t}.log`);HPe(n),(e._setTimeout??setTimeout)(()=>UPe(F9),5e3).unref();let r=P9.default.destination({dest:n,append:!0,sync:!0});return(0,P9.default)({level:BPe(),name:e.name,redact:{paths:zPe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:P9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function GPe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[P9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function KPe(e){return F(F9,`${e}.${I9()}.log`)}function qPe(){return F9}function JPe(e){let t=L(e),n=0;for(;n<30;){let e=!1;try{e=z(L(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=P(t);if(r===t)return null;t=r,n+=1}return null}const L9=Dd(Su),R9=N(`project-git`);var z9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function YPe(e,t){try{return await L9(e,[`var`,`GIT_COMMITTER_IDENT`],Lw({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function XPe(e,t){try{let{stdout:n}=await L9(e,[`for-each-ref`,`--count=1`,`refs/`],Lw({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return R9.warn({path:t,stderr:B9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function ZPe(e){let t=L(e,`packed-refs`);if(z(t))try{if(B(t,`utf-8`).split(`
|
|
2027
2027
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return Zu(L(e,`refs/heads`)).length>0}catch{return!1}}function B9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function V9(e,t){if(await XPe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await YPe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await L9(e,i,Lw({cwd:t,encoding:`utf-8`})),r||R9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){R9.warn({path:t,stderr:B9(e)},`could not create initial commit`)}}async function QPe(e,t){try{let{stdout:n}=await L9(e,[`rev-parse`,`--is-inside-work-tree`],Lw({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function $Pe(e){let t=L(e);zW(t);let n=L(t,`.git`),r=L(n,`HEAD`),i=!1,a=!1;if(z(n)){if(!nd(n).isDirectory())return{didInit:!1};if(z(r)){if(ZPe(n))return{didInit:!1};a=!0}else R9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=Uw()}catch(e){throw e instanceof Bw||e instanceof Vw?(yK(e),R9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof Vw?`too_old`:`not_available`,detectedVersion:e instanceof Vw?e.detected:``},e instanceof Vw?`git binary too old`:`git binary not found`)):R9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await V9(s,t),{didInit:!1};if(!i&&await QPe(s,t))return{didInit:!1};let c=``;try{c=(await L9(s,[`init`,`--initial-branch=main`,t],Lw({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new z9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!z(r))throw new z9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await V9(s,t),i?(R9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(R9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const H9=N(`project-skill-git`),U9=/^[0-9a-f]{40}$/,W9=sn.map(e=>e.replace(/\/$/,``));async function eFe(e){let t=zd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(iFe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Tc(e,{credentialConfig:[]});if((await G9(n)).length===0)return{kind:`nothing-tracked`};try{return await Cc(async()=>{let t=await tFe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await nFe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await G9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Tc(e,{gitIndexFile:F(ld(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`),credentialConfig:[]});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await rFe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await PB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ac(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${On}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!U9.test(f))return H9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return H9.info({branch:t,err:K9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){H9.info({err:K9(e)},`real-index reset after untrack failed (cosmetic)`)}return H9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:K9(e)}}}async function G9(e){let t=[];for(let n of W9){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function tFe(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function nFe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return U9.test(t)?t:null}catch{return null}}async function rFe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return U9.test(n)?n:null}catch{return null}}function iFe(e){return z(F(e,`MERGE_HEAD`))||z(F(e,`rebase-merge`))||z(F(e,`rebase-apply`))||z(F(e,`CHERRY_PICK_HEAD`))||z(F(e,`REVERT_HEAD`))}function K9(e){return e instanceof Error?e.message:String(e)}async function aFe(e,t){let n;try{n=xu(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=P(n),r=0;r<32;r+=1){let n=F(t,`package.json`);if(z(n))try{let t=JSON.parse(await pd(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=P(t);if(r===t)return;t=r}}const oFe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function q9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of oFe)t=t.replace(e,n);return t}function J9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:q9(e.message)??``,stack:q9(e.stack),code:e.code,cause:e.cause===void 0?void 0:J9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:q9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:q9(String(r.message??``))??``,stack:q9(r.stack),code:r.code,cause:r.cause===void 0?void 0:J9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Y9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},X9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},Z9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function sFe(e){if(!Kx(e))throw new Z9(e);let t;try{t=V(L(e))}catch(t){throw t.code===`ENOENT`?new Y9(e):t}if(!nd(t).isFile())throw new X9(e);let n=P(t),r=vB(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Jx(I(cFe(e),t).split(R).join(`/`)),canonicalFilePath:t}}let i=Du(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Jx(i)}}function cFe(e){return L(e,Is({absPath:Qs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}const Q9=`ok-ephemeral-`;function $9(e,t){let n=L(e,`.ok`);return Ku(n,{recursive:!0}),id(L(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),id(L(n,`.gitignore`),`local/
|
|
2028
2028
|
`,`utf-8`),e}function lFe(e){return $9(qu(L(ld(),Q9)),e)}export{$0 as $,Vx as $i,qI as $n,aM as $r,CK as $t,O7 as A,Bd as Aa,sT as Ai,Ez as An,VP as Ar,BX as At,zMe as B,Cw as Bi,Xz as Bn,fN as Br,Ige as Bt,k9 as C,xf as Ca,RD as Ci,ZB as Cn,XF as Cr,DZ as Ct,D7 as D,Ud as Da,Vw as Di,IB as Dn,XP as Dr,CZ as Dt,s9 as E,df as Ea,Bw as Ei,LB as En,YP as Er,kZ as Et,_7 as F,_w as Fi,Yz as Fn,zP as Fr,WX as Ft,i8 as G,G as Gi,dz as Gn,lN as Gr,Fge as Gt,K5 as H,KC as Hi,_z as Hn,hN as Hr,NJ as Ht,t7 as I,Nw as Ii,Wz as In,FP as Ir,Uge as It,$6 as J,aS as Ji,cz as Jn,eN as Jr,AJ as Jt,n8 as K,xS as Ki,pz as Kn,iN as Kr,PJ as Kt,ZMe as L,Iw as Li,jz as Ln,IP as Lr,RJ as Lt,M7 as M,Xw as Mi,Nz as Mn,HP as Mr,uye as Mt,E7 as N,Gw as Ni,Mz as Nn,BP as Nr,bZ as Nt,A7 as O,Hd as Oa,Rw as Oi,vB as On,qP as Or,xZ as Ot,b7 as P,Lw as Pi,$z as Pn,RP as Pr,vZ as Pt,Q0 as Q,iS as Qi,JI as Qn,cM as Qr,yJ as Qt,r7 as R,jw as Ri,Zz as Rn,lP as Rr,IJ as Rt,A9 as S,bh as Sa,DD as Si,XB as Sn,uhe as Sr,wZ as St,c9 as T,Sf as Ta,uT as Ti,RB as Tn,JP as Tr,Tye as Tt,U5 as U,hw as Ui,vz as Un,pN as Ur,DJ as Ut,Y5 as V,GC as Vi,kz as Vn,dN as Vr,Pge as Vt,r8 as W,SS as Wi,uz as Wn,mN as Wr,OJ as Wt,J6 as X,oS as Xi,RR as Xn,zM as Xr,kJ as Xt,Z6 as Y,dS as Yi,$R as Yn,BM as Yr,MJ as Yt,R6 as Z,uS as Zi,kR as Zn,lM as Zr,vJ as Zt,qPe as _,ax as _a,mk as _i,RW as _n,fI as _r,T$ as _t,lFe as a,Dx as aa,Jj as ai,dK as an,BI as ar,B0 as at,FPe as b,yh as ba,QD as bi,tV as bn,lhe as br,TZ as bt,J9 as c,Tx as ca,Bj as ci,YW as cn,II as cr,fCe as ct,z9 as d,zx as da,Ij as di,XW as dn,CI as dr,N0 as dt,Mx as ea,rfe as ei,xK as en,Rhe as er,e2 as et,$Pe as f,Ux as fa,Rj as fi,HW as fn,xI as fr,$1 as ft,KPe as g,fx as ga,Xk as gi,LW as gn,yI as gr,S$ as gt,GPe as h,mx as ha,Jk as hi,zW as hn,_I as hr,kbe as ht,Z9 as i,Ix as ia,Wde as ii,mK as in,zI as ir,G0 as it,j7 as j,Md as ja,Hw as ji,Qz as jn,UP as jr,lye as jt,N7 as k,cf as ka,Uw as ki,_B as kn,Wpe as kr,VX as kt,aFe as l,Bx as la,wde as li,WW as ln,whe as lr,P0 as lt,WPe as m,gx as ma,Yk as mi,IW as mn,bI as mr,s$ as mt,X9 as n,Px as na,nfe as ni,yK as nn,WI as nr,CCe as nt,sFe as o,jx as oa,tM as oi,BW as on,VI as or,uCe as ot,JPe as p,Cx as pa,Lj as pi,ZW as pn,SI as pr,k$ as pt,t8 as q,mS as qi,fz as qn,sN as qr,jJ as qt,Y9 as r,kx as ra,tfe as ri,hK as rn,HI as rr,K0 as rt,$9 as s,Hx as sa,Ede as si,JW as sn,LI as sr,dCe as st,Q9 as t,Nx as ta,efe as ti,vK as tn,Mhe as tr,a2 as tt,eFe as u,Rx as ua,zj as ui,$W as un,RI as ur,j0 as ut,RPe as v,Fse as va,nO as vi,WB as vn,pI as vr,zZ as vt,j9 as w,ff as wa,cT as wi,JB as wn,lF as wr,EZ as wt,N9 as x,xh as xa,zD as xi,HB as xn,mI as xr,OZ as xt,LPe as y,Fie as ya,eO as yi,qB as yn,lI as yr,AZ as yt,n7 as z,Mw as zi,hB as zn,Tpe as zr,CJ as zt};
|
|
2029
|
-
//# sourceMappingURL=src-
|
|
2029
|
+
//# sourceMappingURL=src-32lVY8sD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./src-tR2kRwXj.mjs";import"./resolve-project-root-XuKmxBzQ.mjs";import"./src-H5bQHekD.mjs";import"./acp-harness-probe-DBIIsKVz.mjs";import"./init-PW1PHv2x.mjs";import{n as e}from"./loader-Cg2a3fTX.mjs";import"./skill-teardown-Dp8qru7m.mjs";import"./preview-B4X8PAmW.mjs";import"./mcp-migrate-event-9DFnNzHa.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ac as e,Hs as t,Ts as n,U as r,Ws as i,ec as a,q as o,ws as s,x as c,xs as l,y as u}from"./src-tR2kRwXj.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Ai as _,An as v,Ar as y,At as b,B as x,Bi as S,Bn as C,Br as w,Bt as T,C as E,Ca as D,Ci as O,Cn as k,Cr as A,Ct as j,D as M,Da as N,Di as P,Dn as F,Dr as I,Dt as L,E as R,Ea as z,Ei as B,En as V,Er as H,Et as U,F as W,Fi as G,Fn as K,Ft as q,G as J,Gi as Y,Gn as X,Gr as Z,Gt as Q,H as $,Hi as ee,Hn as te,Hr as ne,Ht as re,I as ie,Ii as ae,In as oe,It as se,J as ce,Ji as le,Jn as ue,Jr as de,Jt as fe,K as pe,Ki as me,Kn as he,Kr as ge,Kt as _e,L as ve,Li as ye,Ln as be,Lt as xe,M as Se,Mi as Ce,Mn as we,Mr as Te,Mt as Ee,N as De,Ni as Oe,Nn as ke,Nt as Ae,O as je,Oa as Me,Oi as Ne,On as Pe,Or as Fe,Ot as Ie,P as Le,Pi as Re,Pn as ze,Pt as Be,Q as Ve,Qi as He,Qn as Ue,Qr as We,Qt as Ge,R as Ke,Ri as qe,Rn as Je,Rr as Ye,Rt as Xe,S as Ze,Sa as Qe,Si as $e,Sn as et,Sr as tt,St as nt,T as rt,Ta as it,Ti as at,Tn as ot,Tr as st,Tt as ct,U as lt,Ui as ut,Un as dt,Ur as ft,Ut as pt,V as mt,Vi as ht,Vn as gt,Vr as _t,Vt as vt,W as yt,Wi as bt,Wn as xt,Wr as St,Wt as Ct,X as wt,Xi as Tt,Xn as Et,Xr as Dt,Xt as Ot,Y as kt,Yi as At,Yn as jt,Yr as Mt,Yt as Nt,Z as Pt,Zi as Ft,Zn as It,Zr as Lt,Zt as Rt,_ as zt,_a as Bt,_n as Vt,_r as Ht,a as Ut,aa as Wt,ai as Gt,an as Kt,ar as qt,at as Jt,b as Yt,ba as Xt,bi as Zt,bn as Qt,br as $t,bt as en,c as tn,ca as nn,ci as rn,cn as an,cr as on,ct as sn,d as cn,da as ln,di as un,dn,dr as fn,dt as pn,ea as mn,ei as hn,en as gn,er as _n,et as vn,f as yn,fa as bn,fi as xn,fn as Sn,fr as Cn,g as wn,ga as Tn,gi as En,gn as Dn,gr as On,h as kn,ha as An,hi as jn,hn as Mn,hr as Nn,i as Pn,ia as Fn,ii as In,in as Ln,ir as Rn,it as zn,j as Bn,ji as Vn,jn as Hn,jr as Un,jt as Wn,k as Gn,ki as Kn,kn as qn,kr as Jn,kt as Yn,l as Xn,la as Zn,li as Qn,ln as $n,lr as er,lt as tr,m as nr,ma as rr,mi as ir,mn as ar,mr as or,n as sr,na as cr,ni as lr,nn as ur,nr as dr,nt as fr,o as pr,oa as mr,oi as hr,on as gr,or as _r,ot as vr,p as yr,pa as br,pi as xr,pn as Sr,pr as Cr,q as wr,qi as Tr,qn as Er,qr as Dr,qt as Or,r as kr,ra as Ar,ri as jr,rn as Mr,rr as Nr,rt as Pr,s as Fr,sa as Ir,si as Lr,sn as Rr,sr as zr,st as Br,t as Vr,ta as Hr,ti as Ur,tn as Wr,tr as Gr,tt as Kr,u as qr,ua as Jr,ui as Yr,un as Xr,ur as Zr,ut as Qr,v as $r,va as ei,vi as ti,vn as ni,vr as ri,vt as ii,w as ai,wa as oi,wi as si,wn as ci,wr as li,wt as ui,x as di,xa as fi,xi as pi,xn as mi,xr as hi,xt as gi,y as _i,ya as vi,yi,yn as bi,yr as xi,yt as Si,z as Ci,zi as wi,zn as Ti,zr as Ei,zt as Di}from"./src-BHDHmhMl.mjs";import{C as Oi,E as ki,T as Ai,_ as ji,b as Mi,c as Ni,d as Pi,g as Fi,i as Ii,l as Li,m as Ri,n as zi,p as Bi,s as Vi,t as Hi,u as Ui,v as Wi,w as Gi,x as Ki,y as qi}from"./fs-traced-2B_-YK-g.mjs";import{a as Ji,d as Yi,f as Xi,i as Zi,l as Qi,n as $i,r as ea,t as ta,u as na}from"./logger-Dq-cRhcP.mjs";import{C as ra,S as ia,_ as aa,a as oa,b as sa,c as ca,d as la,f as ua,g as da,h as fa,i as pa,l as ma,m as ha,n as ga,o as _a,p as va,r as ya,s as ba,t as xa,u as Sa,x as Ca}from"./server-lock-Dngwkd_U.mjs";export{vi as AGENT_ID_MAX_LEN,Xt as AGENT_ID_RE,G as AGENT_WRITE_ORIGIN,z as AcpPermissionStore,D as AcpRegistry,pi as AcpThreadManager,yi as AgentFocusBroadcaster,ti as AgentPresenceBroadcaster,ae as AgentSessionCapacityError,ye as AgentSessionManager,Si as AutoStartDisabledError,Ht as BUNDLE_IDS,ri as BUNDLE_SCOPE,xi as BUNDLE_SKILL_NAME,Et as BacklinkIndex,Tr as CC1Broadcaster,i as CC1_CONTRACT_VERSION,gr as CONFIG_FILENAME,xt as CONFLICT_MARKER_RE,w as CURSOR_BUNDLE_PATHS_BY_PLATFORM,_i as ConfigSchema,f as DEFAULT_CHECKPOINT_RETENTION,In as DEFAULT_EMBEDDINGS_DIMENSIONS,Di as DEFAULT_PACK_ID,lt as DocumentDurabilityState,Gt as EMBEDDINGS_API_KEY_ENV,Vr as EPHEMERAL_PROJECT_DIR_PREFIX,ni as ExposureConsentError,oi as FEATURED_AGENT_IDS,mn as FILE_SYSTEM_WRITER,ue as FILE_WATCHER_ORIGIN,We as FileEmbeddingsBackend,Wr as GIT_PREFLIGHT_FAIL_SPAN_NAME,Hr as GIT_UPSTREAM_WRITER,N as GitDirAccessError,B as GitNotAvailableError,P as GitTooOldError,en as HOCUSPOCUS_AUTH_REJECTION_REASONS,gi as HocuspocusAuthRejection,nt as HocuspocusAuthTokenSchema,ar as HomeProjectRootError,ge as INSTALLED_AGENTS_SCHEMES,Qr as JSON_SCHEMA_DIALECT_2020_12,t as LINEAGE_EPOCH_KEY,x as LIVE_DERIVED_INDEX_DEBOUNCE_MS,T as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,$e as MAX_ACP_THREADS,qe as MAX_AGENT_SESSIONS,si as MCP_CONNECTION_ID_HEADER,l as MCP_SERVER_NAME,wi as MIN_EVICTABLE_IDLE_MS,Ne as MIN_GIT_VERSION,yt as MISSING_OK_CONFIG_MESSAGE,Me as MalformedGitPointerError,fr as McpLogger,J as MissingOkConfigError,ht as OBSERVER_SYNC_ORIGIN,Rr as OK_OKIGNORE_TEMPLATE,$t as ONBOARDING_BUNDLE_IDS,s as ORPHAN_MODES,e as PROTOCOL_VERSION,ta as PinoLogger,ma as ProcessLockCollisionError,cn as ProjectGitInitError,b as ROLLBACK_ORIGIN,an as ROOT_GITIGNORE_TEMPLATE,sa as RUNTIME_VERSION,cr as SERVICE_WRITER,Cn as SKILL_INSTALL_EVENTS_FILE_REL,r as SKILL_STATE_TARGETS,vt as STARTER_FOLDERS,re as STARTER_FOLDER_FRONTMATTER_FILENAME,pt as STARTER_PACKS,Ct as STARTER_PACK_IDS,Q as STARTER_TEMPLATES,M as STATE_MANIFEST_FILENAME,Ca as STATE_SCHEMA_VERSION,a as SYSTEM_DOC_NAME,Rt as SeedPrerequisiteError,Ge as SeedRootDirError,xa as ServerLockCollisionError,sr as SingleFileNotAFileError,kr as SingleFileNotFoundError,Pn as SingleFileNotMarkdownError,je as StateManifestError,jt as TagIndex,hi as USER_GLOBAL_BUNDLE_IDS,Wn as __getShowAllWalkStatsForTesting,Ee as __resetShowAllWalkStatsForTesting,Sa as acquireProcessLock,ga as acquireServerLock,S as applyAgentMarkdownWrite,te as applyExternalChange,Xe as applySeed,Gn as assertCompatibleStateManifest,Kn as assertGitAvailable,v as assertNeverDiskEvent,Mn as assertNotHomeProjectRoot,Zt as attachAcpThreadSocket,ii as attachIdleShutdown,Yt as bootServer,Ue as buildAndOpenSkill,$n as buildConfigYmlContent,Pt as buildExecResult,bi as buildIngressPolicy,O as buildOkMcpStdioCommand,or as buildSkillZip,_e as buildStarterFolderFrontmatterYaml,Ar as buildWipTree,tt as bundleSkillMdPath,m as canonicalProjectKey,Dn as canonicalizeForCompare,Hn as classifyEvents,Hi as classifyFsPath,hn as clearAllEmbeddingsKeys,Lr as clearContributors,Or as coercePackId,u as colorFromSeed,Fn as commitUpstreamImport,Wt as commitWip,mr as commitWipFromTree,_ as compareSemver,st as composeEffectiveLinterConfig,H as composeFrontmatterSchemasConfig,X as containsConflictMarkers,we as contentHash,rn as contributorCount,ie as countShadowObjects,ve as countStaleAgentWipRefs,Ke as countWipRefs,Ae as createApiExtension,Ie as createAssetServeMiddleware,wr as createCollaborationHost,Ye as createContentFilter,Ei as createContentFilterAsync,Ur as createEmbeddingsSecretStore,Ut as createEphemeralProjectDir,dt as createExternalChangeHandler,nr as createFileLogger,mt as createLiveDerivedIndexExtension,kt as createMcpHttpHandler,Dr as createOsProbe,W as createPersistenceExtension,rt as createServer,De as createServerObserverExtension,bt as createStreamingErrorWriter,$i as createTestLogger,lr as describeStoredEmbeddingsKey,$r as detectClaudeDesktopPresence,Vn as detectGit,g as detectProjectShape,p as detectUserSkillHosts,Jt as discoverLockDirs,Jn as discoverMarkdownlintConfig,ur as emitPreflightFailureSpan,Ve as encodeDocName,d as encodeFolderRoute,vn as encodeSkillRoute,yn as ensureProjectGit,Xr as ensureProjectSkillGitignore,Y as errorResponse,ke as evictStaleTrackerEntries,Be as extractHeadings,vr as extractOkBinaryPath,It as extractWikiLinksFromMarkdown,Ce as fallbackPaths,yr as findEnclosingGitRoot,Pe as findEnclosingProjectRoot,y as findNativeMarkdownlintFile,kn as flushFileLogger,j as formatAuthRejectionWire,Qn as formatContributors,Yr as formatContributorsFrom,se as formatPackRationale,Ir as gcCheckpointRefs,Pr as getCurrentMcpLogger,Qt as getIngressContext,ir as getLocalDir,wn as getLogFilePath,ea as getLogger,zt as getLogsDir,aa as getMachineId,qi as getMeter,rr as getMetrics,Mi as getTracer,An as handleCollabSocketError,_t as handleSpawnCursor,mi as hasForwardingHeaders,Ci as hasGcLogLatch,c as iconFromClientName,Tn as incrementCollabSocketFilteredError,Bt as incrementServerObserverFire,dn as initContent,nn as initShadowRepo,Ki as initTelemetry,Ze as initToleranceTelemetryWriter,pn as installJsonSchemaDialect,tr as installPrettyZodErrors,Zi as installTestLoggers,_n as installUserSkill,F as isAllowedApiOrigin,ot as isAllowedWorkspaceHostHeader,le as isConfigDoc,ui as isHocuspocusAuthRejectionReason,Vt as isHomeDir,et as isHostAdmitted,fe as isKnownPackId,At as isLinkIndexExcludedDoc,V as isLoopbackAddress,Tt as isManagedArtifactDoc,k as isOriginAdmitted,n as isOrphanMode,ee as isPairedWriteOrigin,ne as isPathWithinDir,ci as isPeerAdmitted,ia as isProcessAlive,qn as isProjectRoot,Ft as isReservedForUserTree,ze as isSelfWrite,He as isSystemDoc,E as isToleranceTelemetryEnabled,ra as isValidLockPid,K as lastKnownHash,Zn as listRescueCheckpoints,Nt as listStarterPacks,it as loadCustomAgents,Le as loadPrincipal,ya as lockAdvertisesUi,la as lockBaseUrl,ua as lockFilePath,Ji as loggerFactory,Qi as logsCurrentPath,na as logsPreviousPath,jr as makeLazyEmbeddingsKeyStore,pa as markServerLockDraining,pe as mountMcpAndApi,zi as normalizeFsPath,A as originGitHubHost,Sn as packageVersionMajorMinor,ct as parseAuthRejectionWire,Oe as parseGitVersion,U as parseHocuspocusAuthToken,ce as parseKeepaliveConnectionId,oe as pathToDocName,xe as planSeed,pr as prepareSingleFileOpen,Br as processCommand,sn as processUsage,Nr as readAllTargets,Rn as readBundleDecision,Un as readOwnNativeRules,va as readProcessLock,ha as readProcessLockDetailed,$ as readProjectHeadState,Lt as readProjectLocalSemanticConfig,oa as readServerLock,qt as readServerPackageVersion,_r as readSkillInstallStateSnapshot,Bn as readStateManifest,zr as readTargetRecordedAt,on as readTargetVersion,he as reconcile,un as recordContributor,Cr as recordSkillInstallEvent,wt as registerAllTools,be as registerWrite,fa as releaseProcessLock,_a as releaseServerLock,Je as removeLastKnownHash,dr as reportSkillInstall,ei as resetMetrics,Gr as resolveBuiltinSkillHosts,o as resolveBundleEnabled,Nn as resolveBundledSkillDir,jn as resolveContentDir,ft as resolveCursorBinaryDefault,St as resolveCursorSpawnInvocation,I as resolveEffectiveLinterConfig,hr as resolveEmbeddingsCredential,En as resolveLockDir,Fe as resolveNativeConfigForDoc,Te as resolveNativeMarkdownlintConfig,Ot as resolvePack,Xn as resolvePackageVersion,fn as resolveSkillInstallReportSettings,Kr as resolveUiInfo,xn as restoreContributors,di as restoreLifecycleFromConflictsJson,Mt as rewriteMarkdownLinksForDocumentRename,Dt as rewriteWikiLinksForDocumentRename,Mr as runAuthReposSubprocess,Ln as runAuthStatusSubprocess,h as runCloneSubprocess,Kt as runDeviceFlowSubprocess,zn as runWithMcpLogger,de as safeContentPath,q as safeSubdir,Jr as safetyCheckpoint,at as sanitizeClientName,ln as saveInMemoryCheckpoint,bn as saveVersion,L as seedBasenameIndex,Fr as seedEphemeralProjectDir,tn as serializeError,Oi as setActiveSpanAttributes,ut as setupServerObservers,br as shadowGit,Gi as shutdownTelemetry,Yi as spansCurrentPath,Xi as spansPreviousPath,Z as spawnDetached,Er as splitMarkdownBlocks,Ti as startWatcher,me as streamingProblemEvent,xr as swapContributors,ai as teardownToleranceTelemetryWriter,fi as toBroadcasterKey,Ii as tracedAppendFileSync,Vi as tracedLinkSync,Ni as tracedMkdir,Li as tracedMkdirSync,Ui as tracedRename,Pi as tracedRenameSync,Bi as tracedRmSync,Ri as tracedRmdirSync,Fi as tracedUnlinkSync,ji as tracedWriteFile,Wi as tracedWriteFileSync,R as trustSystemCertificates,qr as untrackTrackedProjectSkillProjection,C as updateLastKnownHash,da as updateProcessLockPort,ba as updateServerLockPort,Qe as validateAgentId,gn as validateCloneInputs,On as validateSkillZip,ca as waitForServerLockDrain,Re as withHiddenWindowsConsole,Ai as withSpan,ki as withSpanSync,er as writeBundleDecision,li as writeMarkdownlintRule,Sr as writeRootGitignoreForNewRepo,Se as writeStateManifest,Zr as writeTargetVersion,gt as writeTracker};
|
|
1
|
+
import{Ac as e,Hs as t,Ts as n,U as r,Ws as i,ec as a,q as o,ws as s,x as c,xs as l,y as u}from"./src-tR2kRwXj.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Ai as _,An as v,Ar as y,At as b,B as x,Bi as S,Bn as C,Br as w,Bt as T,C as E,Ca as D,Ci as O,Cn as k,Cr as A,Ct as j,D as M,Da as N,Di as P,Dn as F,Dr as I,Dt as L,E as R,Ea as z,Ei as B,En as V,Er as H,Et as U,F as W,Fi as G,Fn as K,Ft as q,G as J,Gi as Y,Gn as X,Gr as Z,Gt as Q,H as $,Hi as ee,Hn as te,Hr as ne,Ht as re,I as ie,Ii as ae,In as oe,It as se,J as ce,Ji as le,Jn as ue,Jr as de,Jt as fe,K as pe,Ki as me,Kn as he,Kr as ge,Kt as _e,L as ve,Li as ye,Ln as be,Lt as xe,M as Se,Mi as Ce,Mn as we,Mr as Te,Mt as Ee,N as De,Ni as Oe,Nn as ke,Nt as Ae,O as je,Oa as Me,Oi as Ne,On as Pe,Or as Fe,Ot as Ie,P as Le,Pi as Re,Pn as ze,Pt as Be,Q as Ve,Qi as He,Qn as Ue,Qr as We,Qt as Ge,R as Ke,Ri as qe,Rn as Je,Rr as Ye,Rt as Xe,S as Ze,Sa as Qe,Si as $e,Sn as et,Sr as tt,St as nt,T as rt,Ta as it,Ti as at,Tn as ot,Tr as st,Tt as ct,U as lt,Ui as ut,Un as dt,Ur as ft,Ut as pt,V as mt,Vi as ht,Vn as gt,Vr as _t,Vt as vt,W as yt,Wi as bt,Wn as xt,Wr as St,Wt as Ct,X as wt,Xi as Tt,Xn as Et,Xr as Dt,Xt as Ot,Y as kt,Yi as At,Yn as jt,Yr as Mt,Yt as Nt,Z as Pt,Zi as Ft,Zn as It,Zr as Lt,Zt as Rt,_ as zt,_a as Bt,_n as Vt,_r as Ht,a as Ut,aa as Wt,ai as Gt,an as Kt,ar as qt,at as Jt,b as Yt,ba as Xt,bi as Zt,bn as Qt,br as $t,bt as en,c as tn,ca as nn,ci as rn,cn as an,cr as on,ct as sn,d as cn,da as ln,di as un,dn,dr as fn,dt as pn,ea as mn,ei as hn,en as gn,er as _n,et as vn,f as yn,fa as bn,fi as xn,fn as Sn,fr as Cn,g as wn,ga as Tn,gi as En,gn as Dn,gr as On,h as kn,ha as An,hi as jn,hn as Mn,hr as Nn,i as Pn,ia as Fn,ii as In,in as Ln,ir as Rn,it as zn,j as Bn,ji as Vn,jn as Hn,jr as Un,jt as Wn,k as Gn,ki as Kn,kn as qn,kr as Jn,kt as Yn,l as Xn,la as Zn,li as Qn,ln as $n,lr as er,lt as tr,m as nr,ma as rr,mi as ir,mn as ar,mr as or,n as sr,na as cr,ni as lr,nn as ur,nr as dr,nt as fr,o as pr,oa as mr,oi as hr,on as gr,or as _r,ot as vr,p as yr,pa as br,pi as xr,pn as Sr,pr as Cr,q as wr,qi as Tr,qn as Er,qr as Dr,qt as Or,r as kr,ra as Ar,ri as jr,rn as Mr,rr as Nr,rt as Pr,s as Fr,sa as Ir,si as Lr,sn as Rr,sr as zr,st as Br,t as Vr,ta as Hr,ti as Ur,tn as Wr,tr as Gr,tt as Kr,u as qr,ua as Jr,ui as Yr,un as Xr,ur as Zr,ut as Qr,v as $r,va as ei,vi as ti,vn as ni,vr as ri,vt as ii,w as ai,wa as oi,wi as si,wn as ci,wr as li,wt as ui,x as di,xa as fi,xi as pi,xn as mi,xr as hi,xt as gi,y as _i,ya as vi,yi,yn as bi,yr as xi,yt as Si,z as Ci,zi as wi,zn as Ti,zr as Ei,zt as Di}from"./src-32lVY8sD.mjs";import{C as Oi,E as ki,T as Ai,_ as ji,b as Mi,c as Ni,d as Pi,g as Fi,i as Ii,l as Li,m as Ri,n as zi,p as Bi,s as Vi,t as Hi,u as Ui,v as Wi,w as Gi,x as Ki,y as qi}from"./fs-traced-2B_-YK-g.mjs";import{a as Ji,d as Yi,f as Xi,i as Zi,l as Qi,n as $i,r as ea,t as ta,u as na}from"./logger-Dq-cRhcP.mjs";import{C as ra,S as ia,_ as aa,a as oa,b as sa,c as ca,d as la,f as ua,g as da,h as fa,i as pa,l as ma,m as ha,n as ga,o as _a,p as va,r as ya,s as ba,t as xa,u as Sa,x as Ca}from"./server-lock-Dngwkd_U.mjs";export{vi as AGENT_ID_MAX_LEN,Xt as AGENT_ID_RE,G as AGENT_WRITE_ORIGIN,z as AcpPermissionStore,D as AcpRegistry,pi as AcpThreadManager,yi as AgentFocusBroadcaster,ti as AgentPresenceBroadcaster,ae as AgentSessionCapacityError,ye as AgentSessionManager,Si as AutoStartDisabledError,Ht as BUNDLE_IDS,ri as BUNDLE_SCOPE,xi as BUNDLE_SKILL_NAME,Et as BacklinkIndex,Tr as CC1Broadcaster,i as CC1_CONTRACT_VERSION,gr as CONFIG_FILENAME,xt as CONFLICT_MARKER_RE,w as CURSOR_BUNDLE_PATHS_BY_PLATFORM,_i as ConfigSchema,f as DEFAULT_CHECKPOINT_RETENTION,In as DEFAULT_EMBEDDINGS_DIMENSIONS,Di as DEFAULT_PACK_ID,lt as DocumentDurabilityState,Gt as EMBEDDINGS_API_KEY_ENV,Vr as EPHEMERAL_PROJECT_DIR_PREFIX,ni as ExposureConsentError,oi as FEATURED_AGENT_IDS,mn as FILE_SYSTEM_WRITER,ue as FILE_WATCHER_ORIGIN,We as FileEmbeddingsBackend,Wr as GIT_PREFLIGHT_FAIL_SPAN_NAME,Hr as GIT_UPSTREAM_WRITER,N as GitDirAccessError,B as GitNotAvailableError,P as GitTooOldError,en as HOCUSPOCUS_AUTH_REJECTION_REASONS,gi as HocuspocusAuthRejection,nt as HocuspocusAuthTokenSchema,ar as HomeProjectRootError,ge as INSTALLED_AGENTS_SCHEMES,Qr as JSON_SCHEMA_DIALECT_2020_12,t as LINEAGE_EPOCH_KEY,x as LIVE_DERIVED_INDEX_DEBOUNCE_MS,T as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,$e as MAX_ACP_THREADS,qe as MAX_AGENT_SESSIONS,si as MCP_CONNECTION_ID_HEADER,l as MCP_SERVER_NAME,wi as MIN_EVICTABLE_IDLE_MS,Ne as MIN_GIT_VERSION,yt as MISSING_OK_CONFIG_MESSAGE,Me as MalformedGitPointerError,fr as McpLogger,J as MissingOkConfigError,ht as OBSERVER_SYNC_ORIGIN,Rr as OK_OKIGNORE_TEMPLATE,$t as ONBOARDING_BUNDLE_IDS,s as ORPHAN_MODES,e as PROTOCOL_VERSION,ta as PinoLogger,ma as ProcessLockCollisionError,cn as ProjectGitInitError,b as ROLLBACK_ORIGIN,an as ROOT_GITIGNORE_TEMPLATE,sa as RUNTIME_VERSION,cr as SERVICE_WRITER,Cn as SKILL_INSTALL_EVENTS_FILE_REL,r as SKILL_STATE_TARGETS,vt as STARTER_FOLDERS,re as STARTER_FOLDER_FRONTMATTER_FILENAME,pt as STARTER_PACKS,Ct as STARTER_PACK_IDS,Q as STARTER_TEMPLATES,M as STATE_MANIFEST_FILENAME,Ca as STATE_SCHEMA_VERSION,a as SYSTEM_DOC_NAME,Rt as SeedPrerequisiteError,Ge as SeedRootDirError,xa as ServerLockCollisionError,sr as SingleFileNotAFileError,kr as SingleFileNotFoundError,Pn as SingleFileNotMarkdownError,je as StateManifestError,jt as TagIndex,hi as USER_GLOBAL_BUNDLE_IDS,Wn as __getShowAllWalkStatsForTesting,Ee as __resetShowAllWalkStatsForTesting,Sa as acquireProcessLock,ga as acquireServerLock,S as applyAgentMarkdownWrite,te as applyExternalChange,Xe as applySeed,Gn as assertCompatibleStateManifest,Kn as assertGitAvailable,v as assertNeverDiskEvent,Mn as assertNotHomeProjectRoot,Zt as attachAcpThreadSocket,ii as attachIdleShutdown,Yt as bootServer,Ue as buildAndOpenSkill,$n as buildConfigYmlContent,Pt as buildExecResult,bi as buildIngressPolicy,O as buildOkMcpStdioCommand,or as buildSkillZip,_e as buildStarterFolderFrontmatterYaml,Ar as buildWipTree,tt as bundleSkillMdPath,m as canonicalProjectKey,Dn as canonicalizeForCompare,Hn as classifyEvents,Hi as classifyFsPath,hn as clearAllEmbeddingsKeys,Lr as clearContributors,Or as coercePackId,u as colorFromSeed,Fn as commitUpstreamImport,Wt as commitWip,mr as commitWipFromTree,_ as compareSemver,st as composeEffectiveLinterConfig,H as composeFrontmatterSchemasConfig,X as containsConflictMarkers,we as contentHash,rn as contributorCount,ie as countShadowObjects,ve as countStaleAgentWipRefs,Ke as countWipRefs,Ae as createApiExtension,Ie as createAssetServeMiddleware,wr as createCollaborationHost,Ye as createContentFilter,Ei as createContentFilterAsync,Ur as createEmbeddingsSecretStore,Ut as createEphemeralProjectDir,dt as createExternalChangeHandler,nr as createFileLogger,mt as createLiveDerivedIndexExtension,kt as createMcpHttpHandler,Dr as createOsProbe,W as createPersistenceExtension,rt as createServer,De as createServerObserverExtension,bt as createStreamingErrorWriter,$i as createTestLogger,lr as describeStoredEmbeddingsKey,$r as detectClaudeDesktopPresence,Vn as detectGit,g as detectProjectShape,p as detectUserSkillHosts,Jt as discoverLockDirs,Jn as discoverMarkdownlintConfig,ur as emitPreflightFailureSpan,Ve as encodeDocName,d as encodeFolderRoute,vn as encodeSkillRoute,yn as ensureProjectGit,Xr as ensureProjectSkillGitignore,Y as errorResponse,ke as evictStaleTrackerEntries,Be as extractHeadings,vr as extractOkBinaryPath,It as extractWikiLinksFromMarkdown,Ce as fallbackPaths,yr as findEnclosingGitRoot,Pe as findEnclosingProjectRoot,y as findNativeMarkdownlintFile,kn as flushFileLogger,j as formatAuthRejectionWire,Qn as formatContributors,Yr as formatContributorsFrom,se as formatPackRationale,Ir as gcCheckpointRefs,Pr as getCurrentMcpLogger,Qt as getIngressContext,ir as getLocalDir,wn as getLogFilePath,ea as getLogger,zt as getLogsDir,aa as getMachineId,qi as getMeter,rr as getMetrics,Mi as getTracer,An as handleCollabSocketError,_t as handleSpawnCursor,mi as hasForwardingHeaders,Ci as hasGcLogLatch,c as iconFromClientName,Tn as incrementCollabSocketFilteredError,Bt as incrementServerObserverFire,dn as initContent,nn as initShadowRepo,Ki as initTelemetry,Ze as initToleranceTelemetryWriter,pn as installJsonSchemaDialect,tr as installPrettyZodErrors,Zi as installTestLoggers,_n as installUserSkill,F as isAllowedApiOrigin,ot as isAllowedWorkspaceHostHeader,le as isConfigDoc,ui as isHocuspocusAuthRejectionReason,Vt as isHomeDir,et as isHostAdmitted,fe as isKnownPackId,At as isLinkIndexExcludedDoc,V as isLoopbackAddress,Tt as isManagedArtifactDoc,k as isOriginAdmitted,n as isOrphanMode,ee as isPairedWriteOrigin,ne as isPathWithinDir,ci as isPeerAdmitted,ia as isProcessAlive,qn as isProjectRoot,Ft as isReservedForUserTree,ze as isSelfWrite,He as isSystemDoc,E as isToleranceTelemetryEnabled,ra as isValidLockPid,K as lastKnownHash,Zn as listRescueCheckpoints,Nt as listStarterPacks,it as loadCustomAgents,Le as loadPrincipal,ya as lockAdvertisesUi,la as lockBaseUrl,ua as lockFilePath,Ji as loggerFactory,Qi as logsCurrentPath,na as logsPreviousPath,jr as makeLazyEmbeddingsKeyStore,pa as markServerLockDraining,pe as mountMcpAndApi,zi as normalizeFsPath,A as originGitHubHost,Sn as packageVersionMajorMinor,ct as parseAuthRejectionWire,Oe as parseGitVersion,U as parseHocuspocusAuthToken,ce as parseKeepaliveConnectionId,oe as pathToDocName,xe as planSeed,pr as prepareSingleFileOpen,Br as processCommand,sn as processUsage,Nr as readAllTargets,Rn as readBundleDecision,Un as readOwnNativeRules,va as readProcessLock,ha as readProcessLockDetailed,$ as readProjectHeadState,Lt as readProjectLocalSemanticConfig,oa as readServerLock,qt as readServerPackageVersion,_r as readSkillInstallStateSnapshot,Bn as readStateManifest,zr as readTargetRecordedAt,on as readTargetVersion,he as reconcile,un as recordContributor,Cr as recordSkillInstallEvent,wt as registerAllTools,be as registerWrite,fa as releaseProcessLock,_a as releaseServerLock,Je as removeLastKnownHash,dr as reportSkillInstall,ei as resetMetrics,Gr as resolveBuiltinSkillHosts,o as resolveBundleEnabled,Nn as resolveBundledSkillDir,jn as resolveContentDir,ft as resolveCursorBinaryDefault,St as resolveCursorSpawnInvocation,I as resolveEffectiveLinterConfig,hr as resolveEmbeddingsCredential,En as resolveLockDir,Fe as resolveNativeConfigForDoc,Te as resolveNativeMarkdownlintConfig,Ot as resolvePack,Xn as resolvePackageVersion,fn as resolveSkillInstallReportSettings,Kr as resolveUiInfo,xn as restoreContributors,di as restoreLifecycleFromConflictsJson,Mt as rewriteMarkdownLinksForDocumentRename,Dt as rewriteWikiLinksForDocumentRename,Mr as runAuthReposSubprocess,Ln as runAuthStatusSubprocess,h as runCloneSubprocess,Kt as runDeviceFlowSubprocess,zn as runWithMcpLogger,de as safeContentPath,q as safeSubdir,Jr as safetyCheckpoint,at as sanitizeClientName,ln as saveInMemoryCheckpoint,bn as saveVersion,L as seedBasenameIndex,Fr as seedEphemeralProjectDir,tn as serializeError,Oi as setActiveSpanAttributes,ut as setupServerObservers,br as shadowGit,Gi as shutdownTelemetry,Yi as spansCurrentPath,Xi as spansPreviousPath,Z as spawnDetached,Er as splitMarkdownBlocks,Ti as startWatcher,me as streamingProblemEvent,xr as swapContributors,ai as teardownToleranceTelemetryWriter,fi as toBroadcasterKey,Ii as tracedAppendFileSync,Vi as tracedLinkSync,Ni as tracedMkdir,Li as tracedMkdirSync,Ui as tracedRename,Pi as tracedRenameSync,Bi as tracedRmSync,Ri as tracedRmdirSync,Fi as tracedUnlinkSync,ji as tracedWriteFile,Wi as tracedWriteFileSync,R as trustSystemCertificates,qr as untrackTrackedProjectSkillProjection,C as updateLastKnownHash,da as updateProcessLockPort,ba as updateServerLockPort,Qe as validateAgentId,gn as validateCloneInputs,On as validateSkillZip,ca as waitForServerLockDrain,Re as withHiddenWindowsConsole,Ai as withSpan,ki as withSpanSync,er as writeBundleDecision,li as writeMarkdownlintRule,Sr as writeRootGitignoreForNewRepo,Se as writeStateManifest,Zr as writeTargetVersion,gt as writeTracker};
|