@inkeep/open-knowledge 0.77.3-beta.0 → 0.77.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/cli.mjs +69 -69
  2. package/dist/constants-DNRGYFcv.mjs +1 -0
  3. package/dist/dist-Bm7UNIQ7.mjs +1 -0
  4. package/dist/dist-C9m6GTCy.mjs +2103 -0
  5. package/dist/index.mjs +54 -54
  6. package/dist/init-Bg4JHPO2.mjs +1 -0
  7. package/dist/{init-CKYTbt0W.mjs → init-CpdZzBDJ.mjs} +53 -53
  8. package/dist/{launch-json-removal-D-iOTea0.mjs → launch-json-removal-3Kw3p1DL.mjs} +1 -1
  9. package/dist/{loader-BspmmwZ3.mjs → loader-BO9PdE8J.mjs} +1 -1
  10. package/dist/loader-DDZR7HUh.mjs +1 -0
  11. package/dist/{open-browser-wd9wHZQk.mjs → open-browser-OpHQJzqy.mjs} +1 -1
  12. package/dist/{preview-x22R2FIa.mjs → preview-C6kwN66_.mjs} +1 -1
  13. package/dist/preview-CgaqfV0J.mjs +1 -0
  14. package/dist/public/assets/{ActivityModeContent-Cly7TccG.js → ActivityModeContent-DdY8HTgG.js} +1 -1
  15. package/dist/public/assets/{AddPropertiesButton--JEPTOvf.js → AddPropertiesButton-0Xd1Eu9N.js} +1 -1
  16. package/dist/public/assets/{AgentDiffPane-C05mlqQF.js → AgentDiffPane-D9BeRll7.js} +1 -1
  17. package/dist/public/assets/{CodeMirrorPropInput-Cw8s-22X.js → CodeMirrorPropInput-LHxWux_5.js} +1 -1
  18. package/dist/public/assets/{DocumentContext-pOoj0L3z.js → DocumentContext-BcpTXGhp.js} +20 -20
  19. package/dist/public/assets/{EditorModeToggle-pQMXkMMZ.js → EditorModeToggle-CmsUYN94.js} +1 -1
  20. package/dist/public/assets/{EnableSyncConfirmDialog-DoyYDBEl.js → EnableSyncConfirmDialog-Dfdu_Nrw.js} +1 -1
  21. package/dist/public/assets/{ExcalidrawDocEditor-ffN6BfT4.js → ExcalidrawDocEditor-wbIes0GF.js} +1 -1
  22. package/dist/public/assets/FeedbackForm-D0R5beAy.js +1 -0
  23. package/dist/public/assets/{ImportSkillDialog-79N3HVSR.js → ImportSkillDialog-Df6e1Zex.js} +1 -1
  24. package/dist/public/assets/{LintConfigEditor-oDeUmMk8.js → LintConfigEditor-CP23Nvdf.js} +1 -1
  25. package/dist/public/assets/ManagedArtifactProperties-BtLBSRfJ.js +1 -0
  26. package/dist/public/assets/{ManagedArtifactProperties-sDCU-QIV.js → ManagedArtifactProperties-ByKieWvV.js} +1 -1
  27. package/dist/public/assets/{MermaidDocEditor-ClC2hTNx.js → MermaidDocEditor-CVgKXaSH.js} +1 -1
  28. package/dist/public/assets/{PropertyDisplayRow-DO3TjykM.js → PropertyDisplayRow-tBkU-Lni.js} +1 -1
  29. package/dist/public/assets/{SchemaConfigEditor-ge9v9BYH.js → SchemaConfigEditor-BTaf9gfi.js} +1 -1
  30. package/dist/public/assets/{SessionsHost-C_WHwAlk.js → SessionsHost-Dt4bClHN.js} +2 -2
  31. package/dist/public/assets/{SettingsDialogBody-n3q1Zt-W.js → SettingsDialogBody-DvFMIJLV.js} +1 -1
  32. package/dist/public/assets/{ShareReceiveMissDialog-DDudI7yb.js → ShareReceiveMissDialog-_wZZOKaV.js} +1 -1
  33. package/dist/public/assets/{SkillToolbarControls-7yMg0eYh.js → SkillToolbarControls-CCX-xNkB.js} +1 -1
  34. package/dist/public/assets/{SourceEditor-c8AlNUTm.js → SourceEditor-CumXR9rC.js} +1 -1
  35. package/dist/public/assets/{TerminalWindowApp-OIuWzuXx.js → TerminalWindowApp-qKgNA2Mo.js} +1 -1
  36. package/dist/public/assets/{TextDocEditor-C7zzGKHk.js → TextDocEditor-C_4DuXUe.js} +1 -1
  37. package/dist/public/assets/ThreadView-CkCVG6GY.js +19 -0
  38. package/dist/public/assets/{TimelineDiffPane-DtH-4ov1.js → TimelineDiffPane-IIntnl90.js} +1 -1
  39. package/dist/public/assets/{auth-state-cache-Y11OYoWi.js → auth-state-cache-47bMYGu6.js} +1 -1
  40. package/dist/public/assets/{client-version-aCv0VgEY.js → client-version-CMlRvumK.js} +1 -1
  41. package/dist/public/assets/{comment-chips-DtQTmBfB.js → comment-chips--gePul0Q.js} +1 -1
  42. package/dist/public/assets/{config-provider-C0wt7q8N.js → config-provider-Ds6NR4Rq.js} +2 -2
  43. package/dist/public/assets/{doc-undo-manager-BUGYO5Zm.js → doc-undo-manager-C5FvKTwy.js} +1 -1
  44. package/dist/public/assets/globals-7nCZAq2S.css +1 -0
  45. package/dist/public/assets/index-Jn2H_fk4.js +2205 -0
  46. package/dist/public/assets/messages-BOXmu7oy.js +1 -0
  47. package/dist/public/assets/messages-CDlxreKG.js +1 -0
  48. package/dist/public/assets/messages-CTsKlH-I.js +1 -0
  49. package/dist/public/assets/messages-Cb1azu09.js +1 -0
  50. package/dist/public/assets/messages-DEgGnv3K.js +1 -0
  51. package/dist/public/assets/messages-DM-o9LgS.js +1 -0
  52. package/dist/public/assets/messages-DmneIICn.js +1 -0
  53. package/dist/public/assets/messages-NfJP_ITl.js +1 -0
  54. package/dist/public/assets/messages-QY2C_OhH.js +1 -0
  55. package/dist/public/assets/messages-Sj555HCR.js +1 -0
  56. package/dist/public/assets/messages-SsdPqRfS.js +1 -0
  57. package/dist/public/assets/messages-VB-J1YNH.js +1 -0
  58. package/dist/public/assets/{pending-receive-nav-store-FqubZyQH.js → pending-receive-nav-store-xn97DjE2.js} +1 -1
  59. package/dist/public/assets/progress-BEblkRt2.js +9 -0
  60. package/dist/public/assets/{selection-context-TaUPJhlD.js → selection-context-CwPJWRQX.js} +1 -1
  61. package/dist/public/assets/{src-BwGoIT9x.js → src-BHR4rO2P.js} +1 -1
  62. package/dist/public/assets/{telemetry-impl-C--W3DEz.js → telemetry-impl-D2ZNvJ3W.js} +1 -1
  63. package/dist/public/assets/{telemetry-startup-ZWh0ycV4.js → telemetry-startup-BJpsbP-K.js} +1 -1
  64. package/dist/public/assets/{typing-burst-detector-BOe-EKEk.js → typing-burst-detector-CFtumduA.js} +1 -1
  65. package/dist/public/assets/{uninstall-BmvLrb2W.js → uninstall-CfFU-wU5.js} +1 -1
  66. package/dist/public/assets/{use-activity-panel-B-o3YWja.js → use-activity-panel-weoh1mQb.js} +1 -1
  67. package/dist/public/assets/{use-apply-config-language-BG3V72CW.js → use-apply-config-language-bYtZlXJh.js} +2 -2
  68. package/dist/public/assets/{use-open-skill-Dm0N-Dns.js → use-open-skill-fZdlm00W.js} +1 -1
  69. package/dist/public/assets/{use-terminal-enabled-CzdRO277.js → use-terminal-enabled-DgH7ywtp.js} +1 -1
  70. package/dist/public/assets/{use-timeline-entry-diff-CP8w27Xm.js → use-timeline-entry-diff-L8m5Fb9K.js} +1 -1
  71. package/dist/public/index.html +21 -21
  72. package/dist/public/uninstall.html +5 -5
  73. package/dist/registry-probes-IEdtS87H.mjs +17 -0
  74. package/dist/{removal-file-path-BQW3S4Ju.mjs → removal-file-path-aJs30iAd.mjs} +1 -1
  75. package/dist/{repair-launch-json-DLnFd_5Q.mjs → repair-launch-json-M4NXtsH6.mjs} +1 -1
  76. package/dist/{repair-mcp-configs-CHc-dBF7.mjs → repair-mcp-configs-CZuGtwXO.mjs} +1 -1
  77. package/dist/src-Bhe2iRrK.mjs +1 -0
  78. package/dist/{src-BffXZT9n.mjs → src-DLjYEvaT.mjs} +5 -5
  79. package/dist/start-KRLPepwq.mjs +1 -0
  80. package/dist/start-My-4sl0s.mjs +5 -0
  81. package/package.json +4 -4
  82. package/dist/constants-D7J4gc4g.mjs +0 -1
  83. package/dist/dist-B5vmOfkB.mjs +0 -2104
  84. package/dist/dist-D2OjImAs.mjs +0 -1
  85. package/dist/init-DwM___GH.mjs +0 -1
  86. package/dist/loader-BSZ72fep.mjs +0 -1
  87. package/dist/preview-bORFsdTj.mjs +0 -1
  88. package/dist/public/assets/FeedbackForm-xlcaKjwM.js +0 -1
  89. package/dist/public/assets/ManagedArtifactProperties-shklLNBZ.js +0 -1
  90. package/dist/public/assets/ThreadView-Bb-sBP_7.js +0 -19
  91. package/dist/public/assets/globals-DQTCRH6J.css +0 -1
  92. package/dist/public/assets/index-CnK-r_hO.js +0 -2205
  93. package/dist/public/assets/messages-2ku_y04q.js +0 -1
  94. package/dist/public/assets/messages-BIC-T4p1.js +0 -1
  95. package/dist/public/assets/messages-CFtpRqY7.js +0 -1
  96. package/dist/public/assets/messages-CWvvXCad.js +0 -1
  97. package/dist/public/assets/messages-CX_L3Z7h.js +0 -1
  98. package/dist/public/assets/messages-Cz3qUVx6.js +0 -1
  99. package/dist/public/assets/messages-DjwO0PQ1.js +0 -1
  100. package/dist/public/assets/messages-DlwadW8k.js +0 -1
  101. package/dist/public/assets/messages-Dnf3Bx2V.js +0 -1
  102. package/dist/public/assets/messages-DyCycqYY.js +0 -1
  103. package/dist/public/assets/messages-Jgk0JmYN.js +0 -1
  104. package/dist/public/assets/messages-f6M5jM7z.js +0 -1
  105. package/dist/public/assets/progress-DSNQd9Lx.js +0 -9
  106. package/dist/registry-probes-DVxZlHaB.mjs +0 -17
  107. package/dist/src-Drm-nOBa.mjs +0 -1
  108. package/dist/start-57Lfh4P3.mjs +0 -1
  109. package/dist/start-C_Ifx8Di.mjs +0 -5
  110. /package/dist/public/assets/{globals-D_vtSey-.js → globals-D1RUz7O8.js} +0 -0
package/dist/index.mjs CHANGED
@@ -812,22 +812,22 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
812
812
  \r
813
813
  `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));_Ee(),F6(),I6(),R6(),yEe(),bc();const bEe=new Set;function z6(e){bEe.add(e)}function xEe(){return vc.getTracer(`open-knowledge-server`)}async function SEe(e,t,n){return xEe().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:dc.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}EX(`loss-capture`),B({ts:I(),schemaVersion:I(),seq:I(),event:F(),docName:F(),writerId:F().nullable(),site:F().optional(),direction:F().optional(),lostLen:I().optional(),digest:F().optional(),checkpointSha:F().optional(),which:F().optional(),witnessAvailable:L().optional(),connections:I().optional()}),EX(`checkpoint-chain`);function B6(e){try{return E.native(e)}catch{return e}}`${Wu.map(e=>`${e}/`).join(`
814
814
  `)}${Bu.join(`
815
- `)}`;function CEe(e){try{return process.kill(e,0),`signalable`}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`?`foreign`:`absent`}}function V6(e){return CEe(e)!==`absent`}function wEe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}EX(`shadow-lock`),EX(`shadow-op-gate`),EX(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const TEe=Hu.map(e=>`.ok/${e}/`),EEe=Bu.map(e=>`.ok/${e}`),H6=[...TEe.map(e=>`**/${e}`),...EEe.map(e=>`**/${e}`),Dbe];`${H6.join(`
816
- `)}`,H6.flatMap(e=>[`-x`,e]),DY.fileSystem,DY.gitUpstream,DY.service,DY.generator,EX(`bridge-loss-detector`),EX(`checkpoint`);function U6(e){let t=he(e).toLowerCase();return fR.includes(t)}function DEe(e){let t=e.toLowerCase();for(let n of fR)if(t.endsWith(n))return e.slice(0,-n.length);return e}function OEe(e){return e===`__system__`}const kEe=new Set(Jre);function AEe(e){return kEe.has(e)}function jEe(e){return Yre(e)}function MEe(e){return OEe(e)||AEe(e)||jEe(e)}function W6(e){return{...e,windowsHide:!0}}function G6(e){try{return te(be(e,`.ok/config.yml`)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function K6(e){return e.replace(/\\/g,`/`)}const q6=EX(`content-filter`);Re(o);const J6=[`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`],Y6=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,...J6,`Library`,`Applications`,`.Trash`]),NEe=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,...J6]),X6=new Set([`worktrees`,`local`]);function Z6(e){let t=eu(e);if(!tu(t))throw Error(`Invalid attachment folder path`);if(t===`./`)return{kind:`sibling`};if(t===`/`||t===`.`)return{kind:`content-root`};let n=t.startsWith(`./`),r=(n?t.slice(2):t).split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return r===``?n?{kind:`sibling`}:{kind:`content-root`}:{kind:n?`doc-relative`:`fixed`,path:r}}function PEe(e){throw Error(`[AttachmentFolderShape] unhandled variant: ${JSON.stringify(e)}`)}function FEe(e,t,n){let r=he(e).slice(1).toLowerCase();if(!Yc.has(r)||t.kind===`sibling`)return!1;let i=e.lastIndexOf(`/`),a=i===-1?``:e.slice(0,i);if(t.kind===`content-root`)return a===``;if(t.kind===`fixed`)return a===t.path||a.startsWith(`${t.path}/`);if(t.kind===`doc-relative`){let e=a===``?[]:a.split(`/`),r=t.path.split(`/`);for(let t=0;t<=e.length-r.length;t++)if(r.every((n,r)=>e[t+r]===n)&&n(e.slice(0,t).join(`/`)))return!0;return!1}return PEe(t)}function Q6(e,t){let n=e.split(`/`);for(let e=0;e<n.length;e++){let r=n[e],i=r.toLowerCase()===`.ok`?`.ok`:r;if(NEe.has(i)&&!(t&&i===`.ok`&&!X6.has((n[e+1]??``).toLowerCase())))return!0}return!1}function $6(e){return e.startsWith(`${ls}/`)}function IEe(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}const e8=new Set([`.ok`,...J6]),LEe=new Set([...Y6].filter(e=>!e8.has(e))),REe=[`.git`,`node_modules`,`.ok/local`,`.ok/worktrees`].flatMap(e=>[e,`${e}/**`,`**/${e}`,`**/${e}/**`]);function zEe(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);return t.includes(`..`)?!1:t.some(e=>LEe.has(e))?!0:t.some((e,n)=>e.toLowerCase()===`.ok`&&X6.has((t[n+1]??``).toLowerCase()))}const BEe=[`.gitignore`,`.ok`,`.ok/config.yml`,`.ok/.gitignore`,`.ok/schemas/frontmatter.json`,`.ok/templates/example.md`,`.ok/skills/example/SKILL.md`,`docs/.ok`,`docs/.ok/frontmatter.yml`,`docs/.ok/templates/example.md`,...J6.flatMap(e=>[e,`${e}/skills/example/SKILL.md`])];function VEe(e){let t=e.trim();if(!t||t.startsWith(`!`)||t.startsWith(`#`))return!1;let n=t.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);if(n.includes(`..`))return!0;if(zEe(t))return!1;if(n.some(e=>e8.has(e)))return!0;try{let e=(0,n4.default)().add(t);return BEe.some(t=>e.ignores(t))}catch{return!0}}function HEe(e){let t=e.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!VEe(e));return[...new Set([...t,...REe])]}function t8(e,t){for(let n=0;n<t;n++)if(Y6.has(e[n])||e[n].toLowerCase()===`.ok`)return!0;return!1}function n8(e){let t=e.split(`/`),n=t.length;return n<3||t[n-3]!==`.ok`||t[n-2]!==`templates`||he(t[n-1])!==`.md`?!1:!t8(t,n-3)}function r8(e){let t=e.split(`/`),n=t.length;return t[n-1]===`.ok`?!t8(t,n-1):n>=2&&t[n-1]===`templates`&&t[n-2]===`.ok`&&!t8(t,n-2)}function UEe(e){let t=e.split(`/`),n=t.length;return t[0]===`.ok`&&(n===2&&(t[1]===`config.yml`||t[1]===`.gitignore`)||n===3&&t[1]===`schemas`&&t[2].toLowerCase().endsWith(`.json`))||n8(e)?!0:n>=2&&t[n-1]===`frontmatter.yml`&&t[n-2]===`.ok`&&!t8(t,n-2)}function WEe(e){return e===`.ok`||e===`.ok/schemas`||r8(e)}function GEe(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}function i8(e,t){if(t.size===0)return!1;for(let n of t)if(e.startsWith(`${n}/`))return!0;return!1}function KEe(e,t){if(t.size===0)return!1;for(let n of t)if(n===e||n.startsWith(`${e}/`)||e.startsWith(`${n}/`))return!0;return!1}const qEe=new Set([`.ds_store`,`.localized`,`thumbs.db`,`desktop.ini`,`.directory`]);function a8(e){return qEe.has(e.slice(e.lastIndexOf(`/`)+1).toLowerCase())}const JEe=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function o8(e){for(let t of e.split(`/`))if(JEe.has(t.toLowerCase()))return!0;return!1}const YEe=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),XEe=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function s8(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||YEe.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of XEe)if(t.endsWith(e))return!0;return!1}function ZEe(e,t){return t===e||t.startsWith(`${e}/`)}function QEe(e,t,n){let r=n===void 0,i=new Map;function a(e){let t=i.get(e);if(t!==void 0)return t;let n;try{n=G6(e)}catch{return!1}return i.set(e,n),n}return{isInside(n,i){if(!r||n===``)return!1;let o=i?.pathBase===`project`?e:t;for(let e of n.split(`/`))if(o=N(o,e),a(o))return!0;return!1},reset(){i.clear()}}}const c8=[`.gitignore`,`.okignore`];function $Ee(e,t){let n=eDe(e);if(n===null)return[];let r=[];l8(N(n,`info`,`exclude`),t,r,`info/exclude`);let i=tDe(e);return i&&l8(i,t,r,`global excludesfile`),r}function eDe(e){let t=l(`git`,[`rev-parse`,`--git-common-dir`],W6({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||!t.stdout?null:be(e,t.stdout.trim())}function tDe(e){let t=l(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],W6({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return nDe()}function nDe(){let e=process.env.XDG_CONFIG_HOME?.trim(),t=e&&e.length>0?e:N(k(),`.config`);return N(t,`git`,`ignore`)}function l8(e,t,n,r){if(g(e))try{let r=S(e,`utf-8`);t.value+=r.length,n.push(...d8(r))}catch(t){q6.warn({path:e,err:t},`Failed to read ${r} at ${e}`)}}function rDe(e){let{projectDir:t,contentDir:n,onAfterRebuild:r,singleDocRelPath:i}=e,a=e.inPlaceSkillDirs??new Set,o=Z6(e.attachmentFolderPath??`./`),s=e.skillRootPaths??new Set,c=QEe(t,n,i),l=K6(ye(t,n)),u=l.startsWith(`..`),d,f,p,m,h=0,_=0,v=0;function y(){let e=(0,n4.default)(),r=(0,n4.default)();e.add(`.git`);let i=[],a=0,o=0;for(let n of c8){let o=N(t,n);if(g(o))try{let t=S(o,`utf-8`);a+=t.length;let s=d8(t);i.push(...s),e.add(s),n===`.okignore`&&r.add(s)}catch(e){q6.warn({path:o,err:e},`Failed to read ${n} at ${o}`)}}if(l&&!u)for(let t of c8){let i=N(n,t);if(g(i))try{let n=S(i,`utf-8`);a+=n.length,o++;let s=d8(n).map(e=>f8(e,l));e.add(s),t===`.okignore`&&r.add(s)}catch(e){q6.warn({path:i,err:e},`Failed to read ${t} at ${i}`)}}let s={value:a};o+=p8(n,t,e,r,s),a=s.value;let c=$Ee(t,s);a=s.value,c.length>0&&(i.push(...c),e.add(c));let y=HEe(i);return d=e,f=r,p=i,m=y,h=i.length,_=o,v=a,{patternCount:h,nestedFileCount:_,bytes:v}}y();let b=new Map;function x(e,t){if(u&&t?.pathBase!==`project`)return!1;let n=t?.pathBase===`project`||!l?e:`${l}/${e}`;return!n.startsWith(`..`)&&d.ignores(n)}function C(e,t){return t.pathBase===`project`||!l?e:`${l}/${e}`}function w(e){if(u)return!1;let t=l?`${l}/${e}`:e;return f.ignores(t)}let T=()=>{i===void 0&&u8(n,``,x,b)};T();function E(e){return MEe(DEe(e))}function D(e){for(let t of e.split(`/`))if(Y6.has(t))return!0;return!u&&x(e)}let O=null,ee=null;return{isExcluded(e,t){if(E(e)||s8(e)||o8(e)||c.isInside(e,t?.syncScope)||!t?.bypassFilters&&GEe(e,s)&&!i8(e,a))return!0;if(!t?.bypassFilters&&($6(e)||i8(e,a)&&!x(e))){if(i!==void 0)return e!==i;if(U6(e))return!1;let t=he(e).slice(1).toLowerCase();return!Yc.has(t)}if(!t?.bypassFilters&&n8(e)||!t?.bypassFilters&&t?.syncScope!==void 0&&UEe(C(e,t.syncScope))&&!x(e,t.syncScope))return i!==void 0&&e!==i;if(Q6(e,t?.showOk)||a8(e))return!0;if(i!==void 0)return e!==i;if(t?.bypassFilters)return t.respectOkignore===!0&&w(e);if(D(e))return!0;if(U6(e)||FEe(e,o,e=>(b.get(e)??0)>0))return!1;let n=he(e).slice(1).toLowerCase();if(Yc.has(n)){let t=M(e),n=t===`.`?``:t;if((b.get(n)??0)>0)return!1}return!0},isDirExcluded(e,t){if(o8(e)||c.isInside(e,t?.syncScope))return!0;if(!t?.bypassFilters&&(IEe(e)||r8(e)||t?.syncScope!==void 0&&WEe(C(e,t.syncScope))||KEe(e,a)))return!1;if(Q6(e,t?.showOk))return!0;if(i!==void 0)return!ZEe(e,i);if(t?.bypassFilters)return t.respectOkignore===!0&&(w(e)||w(`${e}/`));for(let t of e.split(`/`))if(Y6.has(t))return!0;return u?!1:x(e,t?.syncScope)||x(`${e}/`,t?.syncScope)},isPathIgnored(e,t){return E(e)||s8(e)||o8(e)?!0:$6(e)||i8(e,a)&&!x(e)||n8(e)?!1:Q6(e)||a8(e)?!0:!t?.bypassFilters&&D(e)},getWatcherIgnoreGlobs(){return m},incrementMdDir(e){let t=e===`.`?``:e;b.set(t,(b.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=b.get(t)??0;n<=1?b.delete(t):b.set(t,n-1)},rebuildDirCount(){let e=new Map(b);b.clear();try{T()}catch(t){for(let[t,n]of e)b.set(t,n);q6.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},setAttachmentFolderPath(e){o=Z6(e)},refreshInPlaceSkillDirs(){if(e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs()}catch(e){q6.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}},inPlaceSkillDirsFingerprint(){return[...a].sort().join(`
815
+ `)}`;function V6(e){try{return process.kill(e,0),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`)}}function CEe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}EX(`shadow-lock`),EX(`shadow-op-gate`),EX(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const wEe=Hu.map(e=>`.ok/${e}/`),TEe=Bu.map(e=>`.ok/${e}`),H6=[...wEe.map(e=>`**/${e}`),...TEe.map(e=>`**/${e}`),Dbe];`${H6.join(`
816
+ `)}`,H6.flatMap(e=>[`-x`,e]),DY.fileSystem,DY.gitUpstream,DY.service,DY.generator,EX(`bridge-loss-detector`),EX(`checkpoint`);function U6(e){let t=he(e).toLowerCase();return fR.includes(t)}function EEe(e){let t=e.toLowerCase();for(let n of fR)if(t.endsWith(n))return e.slice(0,-n.length);return e}function DEe(e){return e===`__system__`}const OEe=new Set(Jre);function kEe(e){return OEe.has(e)}function AEe(e){return Yre(e)}function jEe(e){return DEe(e)||kEe(e)||AEe(e)}function W6(e){return{...e,windowsHide:!0}}function G6(e){try{return te(be(e,`.ok/config.yml`)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function K6(e){return e.replace(/\\/g,`/`)}const q6=EX(`content-filter`);Re(o);const J6=[`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`],Y6=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,...J6,`Library`,`Applications`,`.Trash`]),MEe=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,...J6]),X6=new Set([`worktrees`,`local`]);function Z6(e){let t=eu(e);if(!tu(t))throw Error(`Invalid attachment folder path`);if(t===`./`)return{kind:`sibling`};if(t===`/`||t===`.`)return{kind:`content-root`};let n=t.startsWith(`./`),r=(n?t.slice(2):t).split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return r===``?n?{kind:`sibling`}:{kind:`content-root`}:{kind:n?`doc-relative`:`fixed`,path:r}}function NEe(e){throw Error(`[AttachmentFolderShape] unhandled variant: ${JSON.stringify(e)}`)}function PEe(e,t,n){let r=he(e).slice(1).toLowerCase();if(!Yc.has(r)||t.kind===`sibling`)return!1;let i=e.lastIndexOf(`/`),a=i===-1?``:e.slice(0,i);if(t.kind===`content-root`)return a===``;if(t.kind===`fixed`)return a===t.path||a.startsWith(`${t.path}/`);if(t.kind===`doc-relative`){let e=a===``?[]:a.split(`/`),r=t.path.split(`/`);for(let t=0;t<=e.length-r.length;t++)if(r.every((n,r)=>e[t+r]===n)&&n(e.slice(0,t).join(`/`)))return!0;return!1}return NEe(t)}function Q6(e,t){let n=e.split(`/`);for(let e=0;e<n.length;e++){let r=n[e],i=r.toLowerCase()===`.ok`?`.ok`:r;if(MEe.has(i)&&!(t&&i===`.ok`&&!X6.has((n[e+1]??``).toLowerCase())))return!0}return!1}function $6(e){return e.startsWith(`${ls}/`)}function FEe(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}const e8=new Set([`.ok`,...J6]),IEe=new Set([...Y6].filter(e=>!e8.has(e))),LEe=[`.git`,`node_modules`,`.ok/local`,`.ok/worktrees`].flatMap(e=>[e,`${e}/**`,`**/${e}`,`**/${e}/**`]);function REe(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);return t.includes(`..`)?!1:t.some(e=>IEe.has(e))?!0:t.some((e,n)=>e.toLowerCase()===`.ok`&&X6.has((t[n+1]??``).toLowerCase()))}const zEe=[`.gitignore`,`.ok`,`.ok/config.yml`,`.ok/.gitignore`,`.ok/schemas/frontmatter.json`,`.ok/templates/example.md`,`.ok/skills/example/SKILL.md`,`docs/.ok`,`docs/.ok/frontmatter.yml`,`docs/.ok/templates/example.md`,...J6.flatMap(e=>[e,`${e}/skills/example/SKILL.md`])];function BEe(e){let t=e.trim();if(!t||t.startsWith(`!`)||t.startsWith(`#`))return!1;let n=t.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`);if(n.includes(`..`))return!0;if(REe(t))return!1;if(n.some(e=>e8.has(e)))return!0;try{let e=(0,n4.default)().add(t);return zEe.some(t=>e.ignores(t))}catch{return!0}}function VEe(e){let t=e.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!BEe(e));return[...new Set([...t,...LEe])]}function t8(e,t){for(let n=0;n<t;n++)if(Y6.has(e[n])||e[n].toLowerCase()===`.ok`)return!0;return!1}function n8(e){let t=e.split(`/`),n=t.length;return n<3||t[n-3]!==`.ok`||t[n-2]!==`templates`||he(t[n-1])!==`.md`?!1:!t8(t,n-3)}function r8(e){let t=e.split(`/`),n=t.length;return t[n-1]===`.ok`?!t8(t,n-1):n>=2&&t[n-1]===`templates`&&t[n-2]===`.ok`&&!t8(t,n-2)}function HEe(e){let t=e.split(`/`),n=t.length;return t[0]===`.ok`&&(n===2&&(t[1]===`config.yml`||t[1]===`.gitignore`)||n===3&&t[1]===`schemas`&&t[2].toLowerCase().endsWith(`.json`))||n8(e)?!0:n>=2&&t[n-1]===`frontmatter.yml`&&t[n-2]===`.ok`&&!t8(t,n-2)}function UEe(e){return e===`.ok`||e===`.ok/schemas`||r8(e)}function WEe(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}function i8(e,t){if(t.size===0)return!1;for(let n of t)if(e.startsWith(`${n}/`))return!0;return!1}function GEe(e,t){if(t.size===0)return!1;for(let n of t)if(n===e||n.startsWith(`${e}/`)||e.startsWith(`${n}/`))return!0;return!1}const KEe=new Set([`.ds_store`,`.localized`,`thumbs.db`,`desktop.ini`,`.directory`]);function a8(e){return KEe.has(e.slice(e.lastIndexOf(`/`)+1).toLowerCase())}const qEe=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function o8(e){for(let t of e.split(`/`))if(qEe.has(t.toLowerCase()))return!0;return!1}const JEe=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),YEe=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function s8(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||JEe.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of YEe)if(t.endsWith(e))return!0;return!1}function XEe(e,t){return t===e||t.startsWith(`${e}/`)}function ZEe(e,t,n){let r=n===void 0,i=new Map;function a(e){let t=i.get(e);if(t!==void 0)return t;let n;try{n=G6(e)}catch{return!1}return i.set(e,n),n}return{isInside(n,i){if(!r||n===``)return!1;let o=i?.pathBase===`project`?e:t;for(let e of n.split(`/`))if(o=N(o,e),a(o))return!0;return!1},reset(){i.clear()}}}const c8=[`.gitignore`,`.okignore`];function QEe(e,t){let n=$Ee(e);if(n===null)return[];let r=[];l8(N(n,`info`,`exclude`),t,r,`info/exclude`);let i=eDe(e);return i&&l8(i,t,r,`global excludesfile`),r}function $Ee(e){let t=l(`git`,[`rev-parse`,`--git-common-dir`],W6({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||!t.stdout?null:be(e,t.stdout.trim())}function eDe(e){let t=l(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],W6({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return tDe()}function tDe(){let e=process.env.XDG_CONFIG_HOME?.trim(),t=e&&e.length>0?e:N(k(),`.config`);return N(t,`git`,`ignore`)}function l8(e,t,n,r){if(g(e))try{let r=S(e,`utf-8`);t.value+=r.length,n.push(...d8(r))}catch(t){q6.warn({path:e,err:t},`Failed to read ${r} at ${e}`)}}function nDe(e){let{projectDir:t,contentDir:n,onAfterRebuild:r,singleDocRelPath:i}=e,a=e.inPlaceSkillDirs??new Set,o=Z6(e.attachmentFolderPath??`./`),s=e.skillRootPaths??new Set,c=ZEe(t,n,i),l=K6(ye(t,n)),u=l.startsWith(`..`),d,f,p,m,h=0,_=0,v=0;function y(){let e=(0,n4.default)(),r=(0,n4.default)();e.add(`.git`);let i=[],a=0,o=0;for(let n of c8){let o=N(t,n);if(g(o))try{let t=S(o,`utf-8`);a+=t.length;let s=d8(t);i.push(...s),e.add(s),n===`.okignore`&&r.add(s)}catch(e){q6.warn({path:o,err:e},`Failed to read ${n} at ${o}`)}}if(l&&!u)for(let t of c8){let i=N(n,t);if(g(i))try{let n=S(i,`utf-8`);a+=n.length,o++;let s=d8(n).map(e=>f8(e,l));e.add(s),t===`.okignore`&&r.add(s)}catch(e){q6.warn({path:i,err:e},`Failed to read ${t} at ${i}`)}}let s={value:a};o+=p8(n,t,e,r,s),a=s.value;let c=QEe(t,s);a=s.value,c.length>0&&(i.push(...c),e.add(c));let y=VEe(i);return d=e,f=r,p=i,m=y,h=i.length,_=o,v=a,{patternCount:h,nestedFileCount:_,bytes:v}}y();let b=new Map;function x(e,t){if(u&&t?.pathBase!==`project`)return!1;let n=t?.pathBase===`project`||!l?e:`${l}/${e}`;return!n.startsWith(`..`)&&d.ignores(n)}function C(e,t){return t.pathBase===`project`||!l?e:`${l}/${e}`}function w(e){if(u)return!1;let t=l?`${l}/${e}`:e;return f.ignores(t)}let T=()=>{i===void 0&&u8(n,``,x,b)};T();function E(e){return jEe(EEe(e))}function D(e){for(let t of e.split(`/`))if(Y6.has(t))return!0;return!u&&x(e)}let O=null,ee=null;return{isExcluded(e,t){if(E(e)||s8(e)||o8(e)||c.isInside(e,t?.syncScope)||!t?.bypassFilters&&WEe(e,s)&&!i8(e,a))return!0;if(!t?.bypassFilters&&($6(e)||i8(e,a)&&!x(e))){if(i!==void 0)return e!==i;if(U6(e))return!1;let t=he(e).slice(1).toLowerCase();return!Yc.has(t)}if(!t?.bypassFilters&&n8(e)||!t?.bypassFilters&&t?.syncScope!==void 0&&HEe(C(e,t.syncScope))&&!x(e,t.syncScope))return i!==void 0&&e!==i;if(Q6(e,t?.showOk)||a8(e))return!0;if(i!==void 0)return e!==i;if(t?.bypassFilters)return t.respectOkignore===!0&&w(e);if(D(e))return!0;if(U6(e)||PEe(e,o,e=>(b.get(e)??0)>0))return!1;let n=he(e).slice(1).toLowerCase();if(Yc.has(n)){let t=M(e),n=t===`.`?``:t;if((b.get(n)??0)>0)return!1}return!0},isDirExcluded(e,t){if(o8(e)||c.isInside(e,t?.syncScope))return!0;if(!t?.bypassFilters&&(FEe(e)||r8(e)||t?.syncScope!==void 0&&UEe(C(e,t.syncScope))||GEe(e,a)))return!1;if(Q6(e,t?.showOk))return!0;if(i!==void 0)return!XEe(e,i);if(t?.bypassFilters)return t.respectOkignore===!0&&(w(e)||w(`${e}/`));for(let t of e.split(`/`))if(Y6.has(t))return!0;return u?!1:x(e,t?.syncScope)||x(`${e}/`,t?.syncScope)},isPathIgnored(e,t){return E(e)||s8(e)||o8(e)?!0:$6(e)||i8(e,a)&&!x(e)||n8(e)?!1:Q6(e)||a8(e)?!0:!t?.bypassFilters&&D(e)},getWatcherIgnoreGlobs(){return m},incrementMdDir(e){let t=e===`.`?``:e;b.set(t,(b.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=b.get(t)??0;n<=1?b.delete(t):b.set(t,n-1)},rebuildDirCount(){let e=new Map(b);b.clear();try{T()}catch(t){for(let[t,n]of e)b.set(t,n);q6.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},setAttachmentFolderPath(e){o=Z6(e)},refreshInPlaceSkillDirs(){if(e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs()}catch(e){q6.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}},inPlaceSkillDirsFingerprint(){return[...a].sort().join(`
817
817
  `)},peekFreshInPlaceSkillDirsFingerprint(){if(!e.rescanInPlaceSkillDirs)return[...a].sort().join(`
818
818
  `);try{return[...e.rescanInPlaceSkillDirs()].sort().join(`
819
819
  `)}catch{return[...a].sort().join(`
820
- `)}},async rebuildIgnorePatterns(){let t=e=>(O=e().finally(()=>{O=null}),O),o=async()=>{if(c.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs()}catch(e){q6.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}let t=d,o=f,s=p,l=m,u=h,g=_,S=v,C=Date.now();return SEe(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=y();b.clear(),i===void 0&&await iDe(n,x,b);let a=Date.now()-C;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),q6.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){q6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a}}catch(e){d=t,f=o,p=s,m=l,h=u,_=g,v=S,b.clear();try{T()}catch(e){q6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let n=e instanceof Error?e.message:String(e);return q6.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return O===null?t(o):(ee===null&&(ee=O.catch(()=>null).then(()=>(ee=null,t(o)))),ee)}}}async function iDe(e,t,n){let r=[{dir:e,relPath:``}],i=0;for(;r.length>0;){let{dir:e,relPath:a}=r.pop();i+=1,i>=50&&(i=0,await new Promise(e=>setImmediate(e)));let o;try{o=w(e,{withFileTypes:!0})}catch(t){q6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);continue}for(let i of o){let o=a?`${a}/${i.name}`:i.name;if(i.isDirectory()){if(Y6.has(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:N(e,i.name),relPath:o})}else i.isFile()&&U6(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function u8(e,t,n,r){let i;try{i=w(e,{withFileTypes:!0})}catch(t){q6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(Y6.has(a.name)||n(i)||n(`${i}/`))continue;u8(N(e,a.name),i,n,r)}else a.isFile()&&U6(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function d8(e){return e.split(`
821
- `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function f8(e,t){let n=e.startsWith(`!`),r=n?e.slice(1):e,i=r.startsWith(`/`)?r.slice(1):r,a=i.endsWith(`/`)?i.slice(0,-1):i,o=r.startsWith(`/`)||a.includes(`/`)?`${t}/${i}`:`${t}/**/${i}`;return n?`!${o}`:o}function p8(e,t,n,r,i){let a;try{a=w(e,{withFileTypes:!0})}catch(t){return q6.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||Y6.has(s.name))continue;let a=N(e,s.name),c=K6(ye(t,a));if(!c.startsWith(`..`)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of c8){let t=N(a,e);if(g(t))try{let a=S(t,`utf-8`);i.value+=a.length;let s=d8(a).map(e=>f8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){q6.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=p8(a,t,n,r,i)}}return o}RegExp(`<(${KJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const aDe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,oDe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,m8=String.raw`([^\]\n]*)`,h8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,g8=e=>RegExp(`(!?)${aDe}`,e),_8=(e,t)=>RegExp(`(!?)\\[${e}\\]${oDe}`,t);g8(`y`),g8(`g`),_8(m8,`y`),_8(h8,`y`),_8(m8,`g`),_8(h8,`g`);const sDe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(sDe,`y`),EX(`file-watcher`),EX(`conflict-authority`),EX(`parse-pool`),Math.max(1,Math.min(4,oe()-1)),z6(()=>{}),EX(`bridge-watchdog`),z6(()=>{}),EX(`server-observers`),EX(`server-observers`),EX(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)cDe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function cDe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}function lDe(){try{let e=M(we(import.meta.url)),t=be(e,`..`,`package.json`),n=JSON.parse(S(t,`utf-8`));if(typeof n.version==`string`&&n.version.length>0)return n.version}catch{}return`0.0.0-unknown`}lDe();const v8=B({name:F(),version:F().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});V([z(v8),H(F(),v8).transform(e=>Object.values(e))]).pipe(ore([v8])),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`);const y8={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(y8));const uDe=Object.keys(y8),dDe={discovery:`user`,project:`project`,"write-skill":`user`},b8=uDe.filter(e=>dDe[e]===`user`);new Set(b8.map(e=>y8[e])),Re(x),EX(`agent-registry-apply`),EX(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),pR.cursor,pR.codex,pR[`claude-desktop`],z6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),EX(`external-change-attribution`),EX(`mermaid-validator`),EX(`rename-log`),EX(`history`),EX(`backlinks`);const x8=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function S8(e,t={}){let n=t.platform??process.platform,r=t.checkDesktop??!1,i=t.home??k(),a=[],o=process.env.NODE_ENV===`test`;r&&n===`darwin`&&(o||a.push(N(`/Applications`,x8,e)),(!o||t.home!==void 0)&&a.push(N(i,`Applications`,x8,e))),a.push(we(new URL(`../dist/assets/skills/${e}`,import.meta.url))),a.push(we(new URL(`../assets/skills/${e}`,import.meta.url))),a.push(we(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of a)if(g(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${a.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}function C8(e){return pn.filter(t=>g(N(e,t.hostDir)))}function w8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}w8(cn,us),[...w8(ln,us)].sort((e,t)=>{let n=r4.indexOf(e.editor),r=r4.indexOf(t.editor);return(n===-1?r4.length:n)-(r===-1?r4.length:r)||e.editor.localeCompare(t.editor)}),EX(`installed-skills-marker`),EX(`skill-import`),EX(`tag-index`),EX(`derived-document-index`),new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};const T8={start:I().int().nonnegative().optional(),end:I().int().nonnegative().optional(),quote:F().min(1).optional(),prefix:F().max(1e3).optional(),suffix:F().max(1e3).optional()};B({docName:F().min(1),...T8,propertyKey:F().min(1).optional(),propertyPath:z(V([F(),I().int().nonnegative()])).optional(),body:F(),queue:L().optional(),summary:F().optional()});const E8=Fne();no(`action`,[B({action:W(`edit`),id:E8,body:F(),summary:F().optional()}),B({action:W(`resolve`),id:E8,summary:F().optional()}),B({action:W(`reopen`),id:E8,summary:F().optional()}),B({action:W(`replace`),id:E8,...T8,summary:F().optional()}),B({action:W(`queue`),id:E8,summary:F().optional()}),B({action:W(`unqueue`),id:E8,summary:F().optional()}),B({action:W(`dispatch-prepare`),id:E8,summary:F().optional()}),B({action:W(`dispatch-complete`),id:E8,summary:F().optional()}),B({action:W(`dispatch-prepare-batch`),ids:z(E8).min(1).max(200),summary:F().optional()}),B({action:W(`dispatch-complete-batch`),ids:z(E8).min(1).max(200),summary:F().optional()})]),EX(`embeddings`),EX(`embeddings`);function fDe(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}fDe(Wl),EX(`embeddings`),EX(`embeddings`);const pDe=/^[A-Za-z0-9-]{8,64}$/;let D8=null;function mDe(e){return N(e??k(),`.ok`,`machine-id`)}function hDe(e){if(e===void 0&&D8!==null)return D8;let t=mDe(e),n=null;try{let e=S(t,`utf-8`).trim();pDe.test(e)&&(n=e)}catch{}if(n===null){n=Pe();try{v(M(t),{recursive:!0}),re(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){EX(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(D8=n),n}EX(`process-lock`);function gDe(e,t){return be(e,`${t}.lock`)}function _De(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function vDe(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=_De(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}EX(`asset-references`),EX(`file-ops`),EX(`upload-streaming`);const O8="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).";F().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),F().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),F().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),F().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),F().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const yDe=B({value:F(),truncatedFrom:I().optional(),hint:F().optional()}).describe(`Normalized change-note summary, when one was recorded.`),bDe=z(H(F(),R()));H(F(),R()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),z(LJ).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.'),zJ.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),yDe.optional(),z(FJ).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),z(B({name:F(),description:F().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const xDe=F().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function k8(e){return{text:xDe,...e}}function SDe(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}SDe(`the server`);function CDe(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}CDe(`the server`),EX(`git-checkout`),EX(`git-worktree-status`),EX(`git-context`),EX(`managed-artifact-persistence`),EX(`timeline`),EX(`suggest-links`),EX(`clone-flow`),Re(o),y8.project,Object.fromEntries(Object.entries(ds).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
820
+ `)}},async rebuildIgnorePatterns(){let t=e=>(O=e().finally(()=>{O=null}),O),o=async()=>{if(c.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs()}catch(e){q6.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}let t=d,o=f,s=p,l=m,u=h,g=_,S=v,C=Date.now();return SEe(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=y();b.clear(),i===void 0&&await rDe(n,x,b);let a=Date.now()-C;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),q6.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){q6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a}}catch(e){d=t,f=o,p=s,m=l,h=u,_=g,v=S,b.clear();try{T()}catch(e){q6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let n=e instanceof Error?e.message:String(e);return q6.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return O===null?t(o):(ee===null&&(ee=O.catch(()=>null).then(()=>(ee=null,t(o)))),ee)}}}async function rDe(e,t,n){let r=[{dir:e,relPath:``}],i=0;for(;r.length>0;){let{dir:e,relPath:a}=r.pop();i+=1,i>=50&&(i=0,await new Promise(e=>setImmediate(e)));let o;try{o=w(e,{withFileTypes:!0})}catch(t){q6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);continue}for(let i of o){let o=a?`${a}/${i.name}`:i.name;if(i.isDirectory()){if(Y6.has(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:N(e,i.name),relPath:o})}else i.isFile()&&U6(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function u8(e,t,n,r){let i;try{i=w(e,{withFileTypes:!0})}catch(t){q6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(Y6.has(a.name)||n(i)||n(`${i}/`))continue;u8(N(e,a.name),i,n,r)}else a.isFile()&&U6(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function d8(e){return e.split(`
821
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function f8(e,t){let n=e.startsWith(`!`),r=n?e.slice(1):e,i=r.startsWith(`/`)?r.slice(1):r,a=i.endsWith(`/`)?i.slice(0,-1):i,o=r.startsWith(`/`)||a.includes(`/`)?`${t}/${i}`:`${t}/**/${i}`;return n?`!${o}`:o}function p8(e,t,n,r,i){let a;try{a=w(e,{withFileTypes:!0})}catch(t){return q6.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||Y6.has(s.name))continue;let a=N(e,s.name),c=K6(ye(t,a));if(!c.startsWith(`..`)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of c8){let t=N(a,e);if(g(t))try{let a=S(t,`utf-8`);i.value+=a.length;let s=d8(a).map(e=>f8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){q6.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=p8(a,t,n,r,i)}}return o}RegExp(`<(${KJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const iDe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,aDe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,m8=String.raw`([^\]\n]*)`,h8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,g8=e=>RegExp(`(!?)${iDe}`,e),_8=(e,t)=>RegExp(`(!?)\\[${e}\\]${aDe}`,t);g8(`y`),g8(`g`),_8(m8,`y`),_8(h8,`y`),_8(m8,`g`),_8(h8,`g`);const oDe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(oDe,`y`),EX(`file-watcher`),EX(`conflict-authority`),EX(`parse-pool`),Math.max(1,Math.min(4,oe()-1)),z6(()=>{}),EX(`bridge-watchdog`),z6(()=>{}),EX(`server-observers`),EX(`server-observers`),EX(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)sDe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function sDe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}function cDe(){try{let e=M(we(import.meta.url)),t=be(e,`..`,`package.json`),n=JSON.parse(S(t,`utf-8`));if(typeof n.version==`string`&&n.version.length>0)return n.version}catch{}return`0.0.0-unknown`}cDe();const v8=B({name:F(),version:F().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});V([z(v8),H(F(),v8).transform(e=>Object.values(e))]).pipe(ore([v8])),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`);const y8={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(y8));const lDe=Object.keys(y8),uDe={discovery:`user`,project:`project`,"write-skill":`user`},b8=lDe.filter(e=>uDe[e]===`user`);new Set(b8.map(e=>y8[e])),Re(x),EX(`agent-registry-apply`),EX(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),pR.cursor,pR.codex,pR[`claude-desktop`],z6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),EX(`external-change-attribution`),EX(`mermaid-validator`),EX(`rename-log`),EX(`history`),EX(`backlinks`);const x8=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function S8(e,t={}){let n=t.platform??process.platform,r=t.checkDesktop??!1,i=t.home??k(),a=[],o=process.env.NODE_ENV===`test`;r&&n===`darwin`&&(o||a.push(N(`/Applications`,x8,e)),(!o||t.home!==void 0)&&a.push(N(i,`Applications`,x8,e))),a.push(we(new URL(`../dist/assets/skills/${e}`,import.meta.url))),a.push(we(new URL(`../assets/skills/${e}`,import.meta.url))),a.push(we(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of a)if(g(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${a.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}function C8(e){return pn.filter(t=>g(N(e,t.hostDir)))}function w8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}w8(cn,us),[...w8(ln,us)].sort((e,t)=>{let n=r4.indexOf(e.editor),r=r4.indexOf(t.editor);return(n===-1?r4.length:n)-(r===-1?r4.length:r)||e.editor.localeCompare(t.editor)}),EX(`installed-skills-marker`),EX(`skill-import`),EX(`tag-index`),EX(`derived-document-index`),new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};const T8={start:I().int().nonnegative().optional(),end:I().int().nonnegative().optional(),quote:F().min(1).optional(),prefix:F().max(1e3).optional(),suffix:F().max(1e3).optional()};B({docName:F().min(1),...T8,propertyKey:F().min(1).optional(),propertyPath:z(V([F(),I().int().nonnegative()])).optional(),body:F(),queue:L().optional(),summary:F().optional()});const E8=Fne();no(`action`,[B({action:W(`edit`),id:E8,body:F(),summary:F().optional()}),B({action:W(`resolve`),id:E8,summary:F().optional()}),B({action:W(`reopen`),id:E8,summary:F().optional()}),B({action:W(`replace`),id:E8,...T8,summary:F().optional()}),B({action:W(`queue`),id:E8,summary:F().optional()}),B({action:W(`unqueue`),id:E8,summary:F().optional()}),B({action:W(`dispatch-prepare`),id:E8,summary:F().optional()}),B({action:W(`dispatch-complete`),id:E8,summary:F().optional()}),B({action:W(`dispatch-prepare-batch`),ids:z(E8).min(1).max(200),summary:F().optional()}),B({action:W(`dispatch-complete-batch`),ids:z(E8).min(1).max(200),summary:F().optional()})]),EX(`embeddings`),EX(`embeddings`);function dDe(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}dDe(Wl),EX(`embeddings`),EX(`embeddings`);const fDe=/^[A-Za-z0-9-]{8,64}$/;let D8=null;function pDe(e){return N(e??k(),`.ok`,`machine-id`)}function mDe(e){if(e===void 0&&D8!==null)return D8;let t=pDe(e),n=null;try{let e=S(t,`utf-8`).trim();fDe.test(e)&&(n=e)}catch{}if(n===null){n=Pe();try{v(M(t),{recursive:!0}),re(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){EX(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(D8=n),n}EX(`process-lock`);function hDe(e,t){return be(e,`${t}.lock`)}function gDe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function _De(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=gDe(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}EX(`asset-references`),EX(`file-ops`),EX(`upload-streaming`);const O8="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).";F().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),F().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),F().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),F().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),F().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const vDe=B({value:F(),truncatedFrom:I().optional(),hint:F().optional()}).describe(`Normalized change-note summary, when one was recorded.`),yDe=z(H(F(),R()));H(F(),R()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),z(LJ).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.'),zJ.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),vDe.optional(),z(FJ).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),z(B({name:F(),description:F().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const bDe=F().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function k8(e){return{text:bDe,...e}}function xDe(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}xDe(`the server`);function SDe(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}SDe(`the server`),EX(`git-checkout`),EX(`git-worktree-status`),EX(`git-context`),EX(`managed-artifact-persistence`),EX(`timeline`),EX(`suggest-links`),EX(`clone-flow`),Re(o),y8.project,Object.fromEntries(Object.entries(ds).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
822
822
  `),EX(`skills-leaderboard`),EX(`handoff-dispatch`),B({target:U(Object.keys({"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}})),url:F().min(1).max(4096),workspacePath:F().optional()}),B({}).loose(),EX(`link-preview.guarded-fetch`),EX(`link-preview.cache`),EX(`saved-themes`),B({enabled:L(),active:L(),git:B({state:U([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:U([`open-knowledge`,`existing`]).optional()}),applied:L().optional(),reason:U([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),B({enabled:L()}).strict(),EX(`managed-rename`),Object.assign(Swe,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`}),EX(`search`),EX(`skill-install`),EX(`api`),B({principalId:F().optional(),tabSessionId:F().optional(),expectedServerInstanceId:F().optional(),expectedBranch:F().optional(),expectedDocLineageEpoch:F().optional(),clientProtocolVersion:I().optional(),clientRuntimeVersion:F().optional(),clientKind:F().optional()}).loose(),new Ve,z6(()=>{}),[...Phe],[`[Requires: Hocuspocus server] Unified validation audit: every content problem — markdown-lint violations AND broken internal links — in one read-only call, grouped by the file to fix.`,``,"- No args → audit every in-scope `.md`/`.mdx` doc; pass `path` to scope to a folder or a single file.","- The result reports `ran`, the source families selected for this run. Project audit can report `markdownlint`, `frontmatter`, `okf`, and `links`. A family absent from `ran` was not checked. `okf` covers both document and project-tree OKF checks here.","- A selected family stays in `ran` if it degrades, with the reason in `warnings`. A partial degradation may still have contributed findings.","- To CHECK whether links resolve, use this tool: each broken link is reported under the SOURCE doc that contains it, at the offending line. (The `links` tool is the navigation/graph reader — backlinks, forward links, orphans, hubs — not the validation surface.)",'- Broken links written INSIDE a lowercase-stemmed `log.md`/`log.mdx` are omitted at any depth while the project\'s default-on `validation.suppressLogLinkAdvisories` setting is enabled. When findings are withheld, `brokenLinkSuppression: { reason: "reserved-log-policy", count: N }` makes the filtered result explicit without exposing paths or hrefs. A log is an append-only history whose entries deliberately reference pages that moved or were never written, so repairing them would rewrite that history. `LOG.md` is an ordinary doc and keeps its findings, and `links({ kind: "dead" })` reads the raw state unconditionally.',``,"Each diagnostic carries a `source` naming the validator ('markdownlint' rule violations; 'links' broken internal links), a `code` (e.g. MD010, dead-link), `message`, a 0-based LSP `range` (for links: line exact, column approximate), and `severity` ('error' | 'warning' — broken links default to warnings; the project's `validation.links` setting can raise them to errors or hide them). Only files with at least one problem are listed, plus `fileCount`/`errorCount`/`warningCount` totals. Output (text and structured) is capped at 10 files × 10 diagnostics per file and project-wide at 10 warnings, with explicit '… and N more' indicators and `omittedWarningCount` when warnings are dropped; the counts always reflect the full scan — re-run with `path` scoped to a folder or file to see what was omitted.",``,"Read-only: nothing is modified. Auto-fix fixable lint findings with `lint({ document, fix: true })`; broken links need content edits via `edit`/`write`."].join(`
823
823
  `),[`[Requires: Hocuspocus server] Save a project-wide checkpoint of every document — a single restore point you can return to.`,``,`**Parameters:**`,'- `summary` — Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Appears as the checkpoint subject in `history`. Avoid secrets or PII — persisted to git history.',``,"Returns `{ version }` — the 40-char checkpoint SHA. Find checkpoints later via `history`; restore a single doc with `restore_version({ document, version })`."].join(`
824
824
  `),[`[Operates on disk; no running OK server required] Read the effective merged OpenKnowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)",``,"This tool is a pure READ. Folder-level skill topology (link / unlink / add-root) moved to the `install` tool's `skillFolders` argument, so this one keeps its read-only annotation and stays auto-approvable.",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
825
825
  `),F().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),F().optional().describe(O8),k8({value:R().describe(`Resolved config value at the requested path (or full config).`),exists:L().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:F().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)}),["[Requires: Hocuspocus server] Read tracked conflicts. Dispatches on `kind`:",``,'- `kind: "list"` enumerates every file currently tracked as conflicted. Returns `{ list: [{ file, detectedAt, conflict, reason?, conflictKind?, docName }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` fetches the three stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }`. `ours` is the live Y.Text when the doc is loaded server-side and marker-free, else the stage pinned when the conflict was detected; for `reason: "stale-external-write"` it is the protected acknowledged content and `theirs` the rejected older save. On a `reconcile` conflict, `resolve_conflict` with `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers. To keep exactly the bytes reviewed here, send them back as `content`. Returns 404 (`urn:ok:error:no-conflict-tracked`) when no conflict is tracked for that `file`; re-read the list before retrying.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"`conflict` names where the conflict came from: `merge-native` (a git merge left unmerged stages), `working-tree` (a pull-only overlay collision pinned to an origin blob), or `reconcile` (OK's own merge of editor and disk, including local stale-save protection); `reason` refines a `reconcile` conflict, and the compatibility `conflictKind` field is `stale-external-write` for that reason and `git` otherwise. `resolutionOptions` lists the strategies that apply to THIS conflict: a `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and `refused-too-large` offers only `mine`, `theirs`, and `delete`.",``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
826
- `);const wDe=[`lock`],TDe=V([is,Xa()]),EDe=V([F(),I(),L(),z(R()),H(F(),R()),Xa()]);H(F(),EDe).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))TDe.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),U([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),U(fR).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`."),U(cs).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`),new Set(lY),["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `skill` — `{ name }` deletes a whole SKILL; `{ name, files: ["references/x.md"] }` deletes specific bundle files (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
826
+ `);const CDe=[`lock`],wDe=V([is,Xa()]),TDe=V([F(),I(),L(),z(R()),H(F(),R()),Xa()]);H(F(),TDe).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))wDe.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),U([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),U(fR).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`."),U(cs).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`),new Set(lY),["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `skill` — `{ name }` deletes a whole SKILL; `{ name, files: ["references/x.md"] }` deletes specific bundle files (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
827
827
  `),`${["Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, `template`, or `skill`. Within each: a body edit (`find` + `replace`) OR a metadata patch — not both in one call.",``,"- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.","- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).",'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',"- `skill` — Edit a SKILL: `{ name, ... }`; body `find`/`replace`/`occurrence?` OR a `description` change (a skill's only metadata leaf). Every recorded copy re-syncs from the source, so there is nothing to re-install.","- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, `template`, or `skill` edit. Avoid secrets or PII — persisted to git history.",``,'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).'].join(`
828
- `)}${JJ()}`;const DDe=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];[...new Set([`-name`,`-iname`,`-path`,`-ipath`,`-regex`,`-iregex`,`-lname`,`-ilname`])],new Set(DDe),EX(`mcp:exec`),["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.",``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, subshells, writes, and ALL redirection are rejected, `<` too (read via `cat a.md`, not `< a.md`). For several things use separate exec calls or multiple paths (`cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
828
+ `)}${JJ()}`;const EDe=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];[...new Set([`-name`,`-iname`,`-path`,`-ipath`,`-regex`,`-iregex`,`-lname`,`-ilname`])],new Set(EDe),EX(`mcp:exec`),["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.",``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, subshells, writes, and ALL redirection are rejected, `<` too (read via `cat a.md`, not `< a.md`). For several things use separate exec calls or multiple paths (`cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
829
829
  `),["Resolve the browser-reachable preview URL for an OpenKnowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.",``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,"This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Claude Code Desktop opens its in-app Browser pane with `preview_start({url})` then `navigate({url})` to move; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.",``,"If you are running INSIDE an OpenKnowledge surface — the desktop app’s built-in terminal or its in-app agent panel — the response leads with an `ok open …` steer and returns it as `okOpenCommand`. Run that instead: the user is already looking at the app, so a localhost URL in your reply is noise at best and a dead link at worst. Never paste `url` into your answer in that case.",``,"Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.",``,"To open a single markdown file that may live OUTSIDE any Open Knowledge project (a loose file, or a doc in a different git worktree), pass `file` with an absolute path: the tool finds the running session whose content directory contains it and returns that session’s URL, then navigate your in-app browser there. `document`/`folder` are for a doc in the current project; `file` is the out-of-project form.",``,`**Parameters:**`,"- `document` (optional) — Extension-less doc path in the current project (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.","- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.","- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
830
- `),F().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),F().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),B({name:F().min(1).regex(zge,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(cs).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),F().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),F().optional().describe(O8),k8({url:F().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:F().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:L().describe(`Whether a UI is running for the project.`),autoOpen:L().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:F().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact `ok open …` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")}),B({version:F().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:F().describe(`ISO timestamp of the entry.`),author:F().describe(`Author display name.`),authorEmail:F().describe(`Author email.`),kind:U([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:F().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:bDe.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:R().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `skill` — Skill NAME to query version history for (the skill folder's attributed versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
830
+ `),F().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),F().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),B({name:F().min(1).regex(zge,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(cs).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),F().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),F().optional().describe(O8),k8({url:F().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:F().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:L().describe(`Whether a UI is running for the project.`),autoOpen:L().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:F().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact `ok open …` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")}),B({version:F().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:F().describe(`ISO timestamp of the entry.`),author:F().describe(`Author display name.`),authorEmail:F().describe(`Author email.`),kind:U([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:F().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:yDe.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:R().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `skill` — Skill NAME to query version history for (the skill folder's attributed versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
831
831
  `),[...lY,...gY],[`[Requires: Hocuspocus server] Import a skill into this project as versioned content.`,``,"Fetches an agentskills.io / skills.sh skill-dir from a `source` and writes it into the vendor-neutral `.agents/skills/<name>/` hub — where it gains history, search, attribution, and cross-harness projection (via `install`) for free. Provenance (source, commit, content hash, publisher) is recorded in `.ok/skills-lock.json`. Scripts are imported as content and are NEVER executed. `add` says where it goes — an import always places the skill somewhere, so `install` afterwards is only for changing WHERE it lives (add/remove/convert/source).",``,`**Parameters:**`,"- `source` — paste the full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), or pass `owner/repo[/subpath]` (GitHub), a git URL, or a local / `file://` path.","- `skill` — Pick ONE skill when the source bundles several.","- `scope` — `project` (default, versioned + shared) or `global` (user-global, unversioned).",``,"On a name collision with an existing skill the import lands under `<name>-imported` (never overwrites). An identical re-import (same content hash) is a no-op."].join(`
832
832
  `),new Set(gY),['[Requires: Hocuspocus server] Manage WHERE a skill is available. A skill is ONE real folder (its SOURCE — the skill itself) plus managed copies/symlinks at other locations. `add`/`remove` change the other locations; `mode` flips copies↔symlinks; `source` moves the real folder. There is NO "uninstall everywhere" and no draft state — a skill with no extra locations still lives (and loads) at its source folder; to make a skill stop existing, use `delete`.',``,"Location ids: editor host ids (`claude` | `cursor` | `codex` | `copilot` | `opencode` | `pi`), `agents` (the vendor-neutral `.agents/skills` hub), or a base-relative custom root path containing `/` (e.g. `.team/skills`; home-relative at global scope). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never fanned into your agent context).",``,`**Parameters:**`,'- `name` — Skill name — the skill\'s identity AND its bundle-dir name, wherever the skill lives (e.g. `.agents/skills/<name>/`). Lowercase letters, digits, hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase). Example: "trip-log".',"- `add` — Locations to ADD the skill to (everything else untouched). Editor ids fan out a copy/symlink; a custom root path places the bundle there. Omitting both `add` and `remove` installs into the project-configured editors.","- `remove` — Locations to REMOVE it from (lossless only: a hand-edited fork is refused, never deleted). Works however the agent gets the skill: removing an editor that reads it through a folder alias (its skills folder symlinked into a shared root) automatically unfollows that folder from the root MINUS this skill — the editor keeps its other skills. The SOURCE cannot be removed — its folder is the skill; move it with `source` or use `delete`.",'- `mode` — `"link"`: a live symlink to the source. `"copy"`: an independent folder, auto-refreshed from the source until hand-edited (a hand-edit forks that copy). Applies ONLY to the locations this call names — the ones in `add`, or the ones in `convert` — and sets no skill-wide default. Omit it on `add` and the new location takes the form the skill already uses. Requires `add` or `convert` — passing `mode` alone is refused rather than silently ignored.',"- `convert` — Existing locations to change the FORM of, leaving membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.","- `source` — Move the skill's REAL folder to this location; the old source becomes a symlink to it. Run alone (not with add/remove).","- `scope` — `project` (default, shared via git) or `global` (user-level, every project on this machine).",``,"- `skillFolders` — Folder-level topology instead of one skill (the Settings → Folders surface). Run alone; `name` is not used with it. One action per call:",' - `{ action: "link", scope, root, target }` — merge the skills folder `root` into `target` and replace `root` with a symlink, so its agent reads everything placed in `target`. Same-content entries drop; a DIFFERENT skill in both folders aborts with a conflict list; an interrupted merge is resumable by re-running. `target` is required — nothing is ever assumed.',' - `{ action: "unlink", scope, root, exclude? }` — turn a linked folder back into a real directory holding one per-skill symlink per skill it sees (lossless, reversible). `exclude: ["<skill>"]` leaves named skills out — "this agent should not get that skill": the folder keeps everything else but stops following the root.',' - `{ action: "add-root", scope, root }` — declare a NEW custom skills root (base-relative, e.g. ".team/skills"); it becomes a folder row and an install/link target immediately.',``,"Copies auto-refresh when the source changes — you do NOT need to re-run install after editing a skill. After `delete({skill})` every location is removed with the source."].join(`
833
833
  `),["[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.",``,'- `backlinks` / `forward` / `suggest` — operate on one page; require `document`. `suggest` finds prose mentions of the page not yet wrapped in link syntax. Each mention returns an `excerpt` (a normalized, `…`-trimmed snippet for context — NOT an edit-ready literal) plus an `offset`. To wrap one: re-read the doc (`exec("cat …")`), find the real mention text, and `edit` it into a `[[wiki-link]]`.',"- `dead` — missing internal link targets corpus-wide; optional `sourceDocuments` filter (OR semantics). This is the raw graph read: unlike `audit`, it still lists unresolved links whose source is a skill document or a lowercase-stemmed `log.md`/`log.mdx` — read those to audit deliberately, never as a repair queue, and never rewrite a log's existing entries to clear one.","- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.","- `hubs` — most-linked pages; optional `limit` (default 20)."].join(`
@@ -837,10 +837,10 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
837
837
  `),z(F().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),F().optional().describe(O8),k8({version:W(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:z(B({id:F(),displayName:F(),description:F(),authoring:U([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:F().describe(`Copy-ready source for the authoring form.`),guidance:F().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:z(B({id:F(),title:F(),description:F(),snippet:F().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:z(B({name:F().describe("CSS custom-property name, e.g. `--chart-1`."),light:F(),dark:F()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:z(H(F(),R())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:z(F()).optional().describe("Requested `components` ids that did not match any canonical.")}),['[Requires: Hocuspocus server] Resolve a tracked conflict by writing the chosen content to disk. Only the strategies listed in `resolutionOptions` on `conflicts({ kind: "content" })` apply.',``,`Strategy:`,"- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.","- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.","- `content` — writes the exact provided `content` bytes (e.g. a per-hunk merged result, the live Y.Text shown in the DiffView, or an explicit empty string). Use `delete` to remove the file.",'- `delete` — runs `git rm <file>`, which stages the removal rather than committing it on its own. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',``,"Those git mechanics are the `merge-native` kind (a git merge left unmerged stages); its merge is committed once it was the last tracked `merge-native` conflict, and other kinds do not hold that commit back. On a `working-tree` conflict (a pull-only overlay collision pinned to an origin blob) nothing is committed: `mine` keeps the overlay verbatim, `theirs` restores the pinned origin blob. On a `reconcile` conflict (OK's own merge of editor and disk) the chosen bytes land on disk and in the loaded document with no git command, and `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk stage captured at detection — for `reason: \"stale-external-write\"`, the current local content and the rejected older save. `resolutionOptions` drops `theirs` when a `reconcile` conflict's `theirs` side is raw marker text (`reason` of `disk-markers` or `refused-conflict-markers`), and drops `content` for `refused-too-large`.",``,'Returns 200 on success. 404 (`urn:ok:error:no-conflict-tracked`) means no conflict is tracked for that path — it may have been resolved by another session, or the path may be stale; re-read `conflicts({ kind: "list" })` rather than inferring that your resolution was saved. 422 (`urn:ok:error:unresolved-conflict-markers`) carries a `refusal` field telling two cases apart: `markers-in-content` means the `content` you sent still contains a `<<<<<<< … >>>>>>>` block — a permanent rejection of those bytes, so resolve every region before retrying rather than re-sending; `strategy-not-offered` means your strategy is not among the `resolutionOptions` the same body echoes — pick one from that list. 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',``,"**DESTRUCTIVE:** this modifies the working tree, and a `merge-native` resolve also creates a git commit once it was the last tracked `merge-native` conflict.",``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).","- `strategy` — One of `mine` | `theirs` | `content` | `delete`, narrowed by the conflict's `resolutionOptions`.",'- `content` — Required when `strategy === "content"`; an empty string keeps an empty file. Ignored otherwise.'].join(`
838
838
  `),k8({ok:L(),file:F()}),["[Requires: Hocuspocus server] Restore a DOCUMENT (CRDT, append-only) or a SKILL (fs-direct) to a historical version. Pass EXACTLY ONE of `document` or `skill`.",``,`**Parameters:**`,"- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped). Append-only via the CRDT layer; all connected editors see the change live.","- `skill` — The skill NAME to restore (PROJECT-scope skills only — global skills are unversioned). Rewrites the skill folder to the target version (fs-direct); every recorded copy re-syncs from it, so there is nothing to re-install.","- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).","- `summary` — Optional one-line summary (≤80 chars). Avoid secrets or PII — persisted to git history.",``,'A response may include `structuredContent.warnings` (kind `content-divergence`) when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.'].join(`
839
839
  `),EX(`mcp:search`),["[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).",``,"NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only).",``,'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
840
- `),F().describe(`Search query — title, path, or body terms.`),U([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),z(U([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),I().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),L().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),F().optional().describe(O8);const ODe=B({kind:U([`page`,`folder`,`file`]),path:F(),docName:F(),title:F().nullable(),score:I(),signals:B({lexical:I(),fullText:I(),recency:I(),vector:I().optional()}),snippet:F().optional(),previewUrl:F().nullable(),previewUrlSource:U(wDe).optional()});k8({cwd:F(),query:F(),intent:F(),resultCount:I().int(),results:z(ODe),elapsedMs:I().nullable(),semantic:xY.optional(),ready:W(!1).optional()}),["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin."].join(`
841
- `),k8({ok:L().describe(`Success discriminator.`),shareUrl:F().optional().describe(`Marketing share URL (success only).`),sharedUrl:F().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:F().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:U([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:tB.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:U([...eB.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:F().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:F().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:F().optional().describe(`Internal: preview-URL provenance.`)});const A8="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",kDe=B({id:F().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:F().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:U([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.`),audience:z(F()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:L().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});B({name:F().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:U([`project`,`global`]).describe(A8),description:F().optional().describe(`The skill's one-line description (when present).`),installed:L().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:z(F()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:z(kDe).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:U([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:z(F()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const ADe=B({path:F().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:U([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});B({name:F().describe(`Skill name (its identity).`),scope:U([`project`,`global`]).describe(A8),description:F().describe(`The skill's one-line description (empty if none).`),body:F().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:z(ADe).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),B({path:F().describe(`Skill-relative path read.`),kind:U([`reference`,`script`]).describe("`reference` or `script`."),text:F().describe(`Full text of the bundle file.`)}),B({name:F().describe("Skill name to pass as `skill` to `import`."),source:F().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:F().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:I().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:F().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.",``,"OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Four modes:**`,"- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.","- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
840
+ `),F().describe(`Search query — title, path, or body terms.`),U([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),z(U([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),I().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),L().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),F().optional().describe(O8);const DDe=B({kind:U([`page`,`folder`,`file`]),path:F(),docName:F(),title:F().nullable(),score:I(),signals:B({lexical:I(),fullText:I(),recency:I(),vector:I().optional()}),snippet:F().optional(),previewUrl:F().nullable(),previewUrlSource:U(CDe).optional()});k8({cwd:F(),query:F(),intent:F(),resultCount:I().int(),results:z(DDe),elapsedMs:I().nullable(),semantic:xY.optional(),ready:W(!1).optional()}),["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin."].join(`
841
+ `),k8({ok:L().describe(`Success discriminator.`),shareUrl:F().optional().describe(`Marketing share URL (success only).`),sharedUrl:F().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:F().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:U([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:tB.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:U([...eB.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:F().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:F().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:F().optional().describe(`Internal: preview-URL provenance.`)});const A8="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",ODe=B({id:F().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:F().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:U([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.`),audience:z(F()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:L().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});B({name:F().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:U([`project`,`global`]).describe(A8),description:F().optional().describe(`The skill's one-line description (when present).`),installed:L().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:z(F()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:z(ODe).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:U([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:z(F()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const kDe=B({path:F().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:U([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});B({name:F().describe(`Skill name (its identity).`),scope:U([`project`,`global`]).describe(A8),description:F().describe(`The skill's one-line description (empty if none).`),body:F().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:z(kDe).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),B({path:F().describe(`Skill-relative path read.`),kind:U([`reference`,`script`]).describe("`reference` or `script`."),text:F().describe(`Full text of the bundle file.`)}),B({name:F().describe("Skill name to pass as `skill` to `import`."),source:F().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:F().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:I().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:F().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.",``,"OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Four modes:**`,"- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.","- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
842
842
  `),`${["Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).",``,'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. A replace is refused when another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. Peers are told apart per MCP connection. Writers sharing one connection are not refused against each other; there is no `agentId` to send. The MCP connection records you as a peer, while your own recent write does not arm the refusal against your follow-up `replace`. A recent change from a connected editor refuses a `replace` too. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.','- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.','- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.','- `skill` — Create or overwrite an agent SKILL: reusable agent guidance you author in OK and `install` into your editors. A NEW skill lands at the project\'s default skill home (e.g. `.agents/skills/<name>/`); an existing one is edited at its real folder. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.','- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',"- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.","- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.",``,"Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit)."].join(`
843
- `)}${Jhe()}`,EX(`config-persistence`),EX(`generated-index-git-attributes`),EX(`head-watcher`),EX(`shadow-gc`),EX(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),EX(`mermaid-persistence`),EX(`persistence`),EX(`persistence-staleness`),EX(`recovered-file-target`),EX(`removed-docs-journal`),EX(`server-observers`),EX(`github-permissions`),EX(`github-account`),EX(`sync-engine`),Re(o),new Set(Xge);const j8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`];new Set(j8),[...j8],(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let M8=null;z6(()=>{M8?.disable(),M8=null}),EX(`skill-migrate`);function N8(e){return[{host:`agents`,root:us},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=r4.indexOf(e.host),r=r4.indexOf(t.host);return(n===-1?r4.length:n)-(r===-1?r4.length:r)||e.host.localeCompare(t.host)})}N8(cn),N8(ln),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const jDe=nu;qY(),N(k(),`.ok`,`logs`),Re(o),EX(`project-git`);
843
+ `)}${Jhe()}`,EX(`config-persistence`),EX(`generated-index-git-attributes`),EX(`head-watcher`),EX(`shadow-gc`),EX(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),EX(`mermaid-persistence`),EX(`persistence`),EX(`persistence-staleness`),EX(`recovered-file-target`),EX(`removed-docs-journal`),EX(`server-observers`),EX(`github-permissions`),EX(`github-account`),EX(`sync-engine`),Re(o),new Set(Xge);const j8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`];new Set(j8),[...j8],(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let M8=null;z6(()=>{M8?.disable(),M8=null}),EX(`skill-migrate`);function N8(e){return[{host:`agents`,root:us},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=r4.indexOf(e.host),r=r4.indexOf(t.host);return(n===-1?r4.length:n)-(r===-1?r4.length:r)||e.host.localeCompare(t.host)})}N8(cn),N8(ln),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const ADe=nu;qY(),N(k(),`.ok`,`logs`),Re(o),EX(`project-git`);
844
844
  /*!
845
845
  * Copyright (c) Squirrel Chat et al., All rights reserved.
846
846
  * SPDX-License-Identifier: BSD-3-Clause
@@ -868,7 +868,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
868
868
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
869
869
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
870
870
  */
871
- let MDe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var NDe=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(MDe);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
871
+ let jDe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var MDe=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(jDe);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
872
872
  /*!
873
873
  * Copyright (c) Squirrel Chat et al., All rights reserved.
874
874
  * SPDX-License-Identifier: BSD-3-Clause
@@ -896,9 +896,9 @@ let MDe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+
896
896
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
897
897
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
898
898
  */
899
- function PDe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function FDe(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
899
+ function NDe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function PDe(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
900
900
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
901
- `))}return i}var P8=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=PDe(t.toml,t.ptr),i=FDe(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
901
+ `))}return i}var P8=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=NDe(t.toml,t.ptr),i=PDe(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
902
902
  /*!
903
903
  * Copyright (c) Squirrel Chat et al., All rights reserved.
904
904
  * SPDX-License-Identifier: BSD-3-Clause
@@ -926,12 +926,12 @@ function PDe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop(
926
926
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
927
927
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
928
928
  */
929
- let IDe=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,LDe=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,RDe=/^[+-]?0[0-9_]/;function F8(e,t){let n=e[t++],r=n,i=n===`'`,a=n===e[t]&&n===e[t+1];a&&(e[t+=2]===`
929
+ let FDe=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,IDe=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,LDe=/^[+-]?0[0-9_]/;function F8(e,t){let n=e[t++],r=n,i=n===`'`,a=n===e[t]&&n===e[t+1];a&&(e[t+=2]===`
930
930
  `?t++:e[t]===`\r`&&e[t+1]===`
931
931
  `&&(t+=2));let o=``,s=t,c=0;for(let l=t;l<e.length;l++)if(n=e[l],a&&(n===`
932
932
  `||n===`\r`&&e[l+1]===`
933
933
  `))c&&=3;else if(n<` `&&n!==` `||n===``)throw new P8(`control characters are not allowed in strings`,{toml:e,ptr:l});else if((!c||c===3)&&n===r&&(!a||e[l+1]===r&&e[l+2]===r))return a&&(e[l+3]===r&&l++,e[l+3]===r&&l++),[c?o:o+e.slice(s,l),l+(a?3:1)];else if(!c)!i&&n===`\\`&&(o+=e.slice(s,s=l),c=1);else if(c===1){if(n===`x`||n===`u`||n===`U`){let t=0,r=n===`x`?2:n===`u`?4:8;for(let n=0;n<r;n++,l++){let n=e.charCodeAt(l+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new P8(`invalid non-hex character in unicode escape`,{toml:e,ptr:l+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new P8(`invalid unicode escape`,{toml:e,ptr:l});o+=String.fromCodePoint(t),s=l+1,c=0}else if(n===` `||n===` `)c=2;else{if(n===`b`)o+=`\b`;else if(n===`t`)o+=` `;else if(n===`n`)o+=`
934
- `;else if(n===`f`)o+=`\f`;else if(n===`r`)o+=`\r`;else if(n===`e`)o+=`\x1B`;else if(n===`"`)o+=`"`;else if(n===`\\`)o+=`\\`;else throw new P8(`unrecognized escape sequence`,{toml:e,ptr:l});s=l+1,c=0}}else if(n!==` `&&n!==` `){if(c===2)throw new P8(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:s});c=+(!i&&n===`\\`),s=l}throw new P8(`unfinished string`,{toml:e,ptr:t})}function zDe(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=IDe.test(e);if(i||LDe.test(e)){if(RDe.test(e))throw new P8(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new P8(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new P8(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new NDe(e);if(!a.isValid())throw new P8(`invalid value`,{toml:t,ptr:n});return a}
934
+ `;else if(n===`f`)o+=`\f`;else if(n===`r`)o+=`\r`;else if(n===`e`)o+=`\x1B`;else if(n===`"`)o+=`"`;else if(n===`\\`)o+=`\\`;else throw new P8(`unrecognized escape sequence`,{toml:e,ptr:l});s=l+1,c=0}}else if(n!==` `&&n!==` `){if(c===2)throw new P8(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:s});c=+(!i&&n===`\\`),s=l}throw new P8(`unfinished string`,{toml:e,ptr:t})}function RDe(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=FDe.test(e);if(i||IDe.test(e)){if(LDe.test(e))throw new P8(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new P8(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new P8(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new MDe(e);if(!a.isValid())throw new P8(`invalid value`,{toml:t,ptr:n});return a}
935
935
  /*!
936
936
  * Copyright (c) Squirrel Chat et al., All rights reserved.
937
937
  * SPDX-License-Identifier: BSD-3-Clause
@@ -964,7 +964,7 @@ function I8(e,t=0,n=e.length){let r=e.indexOf(`
964
964
  `)return n;if(r===`\r`&&e[n+1]===`
965
965
  `)return n+1;if(r<` `&&r!==` `||r===``)throw new P8(`control characters are not allowed in comments`,{toml:e,ptr:t})}return e.length}function R8(e,t,n,r){let i;for(;;){for(;(i=e[t])===` `||i===` `||!n&&(i===`
966
966
  `||i===`\r`&&e[t+1]===`
967
- `);)t++;if(r||i!==`#`)break;t=L8(e,t)}return t}function BDe(e,t,n,r,i=!1){if(!r)return t=I8(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=I8(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
967
+ `);)t++;if(r||i!==`#`)break;t=L8(e,t)}return t}function zDe(e,t,n,r,i=!1){if(!r)return t=I8(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=I8(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
968
968
  `||t===`\r`&&e[a+1]===`
969
969
  `))return a}throw new P8(`cannot find end of structure`,{toml:e,ptr:t})}
970
970
  /*!
@@ -994,8 +994,8 @@ function I8(e,t=0,n=e.length){let r=e.indexOf(`
994
994
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
995
995
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
996
996
  */
997
- function VDe(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(L8(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function z8(e,t,n,r,i){if(r===0)throw new P8(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?WDe(e,t,r,i):UDe(e,t,r,i);if(n){if(s=R8(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new P8(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}if(a===`"`||a===`'`){let[r,i]=F8(e,t);if(n){if(i=R8(e,i),e[i]&&e[i]!==`,`&&e[i]!==n&&e[i]!==`
998
- `&&e[i]!==`\r`)throw new P8(`unexpected character encountered`,{toml:e,ptr:i});e[i]===`,`&&i++}return[r,i]}let o=BDe(e,t,`,`,n),s=VDe(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new P8(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=R8(e,t+s[1]),e[o]===`,`&&o++),[zDe(s[0],e,t,i),o]}
997
+ function BDe(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(L8(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function z8(e,t,n,r,i){if(r===0)throw new P8(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?UDe(e,t,r,i):HDe(e,t,r,i);if(n){if(s=R8(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new P8(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}if(a===`"`||a===`'`){let[r,i]=F8(e,t);if(n){if(i=R8(e,i),e[i]&&e[i]!==`,`&&e[i]!==n&&e[i]!==`
998
+ `&&e[i]!==`\r`)throw new P8(`unexpected character encountered`,{toml:e,ptr:i});e[i]===`,`&&i++}return[r,i]}let o=zDe(e,t,`,`,n),s=BDe(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new P8(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=R8(e,t+s[1]),e[o]===`,`&&o++),[RDe(s[0],e,t,i),o]}
999
999
  /*!
1000
1000
  * Copyright (c) Squirrel Chat et al., All rights reserved.
1001
1001
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1023,8 +1023,8 @@ function VDe(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(L8(e,i),r=
1023
1023
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1024
1024
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1025
1025
  */
1026
- let HDe=/^[a-zA-Z0-9-_]+[ \t]*$/;function B8(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new P8(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `){if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new P8(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let[s,c]=F8(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=I8(l);if(u>-1)throw new P8(`newlines are not allowed in keys`,{toml:e,ptr:t+r+u});if(l.trimStart())throw new P8(`found extra tokens after the string part`,{toml:e,ptr:c});if(a<c&&(a=e.indexOf(n,c),a<0))throw new P8(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(s)}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!HDe.test(n))throw new P8(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}}while(r+1&&r<a);return[i,R8(e,a+1,!0,!0)]}function UDe(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new P8(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=L8(e,t);else if(o!==` `&&o!==` `&&o!==`
1027
- `&&o!==`\r`){let o,s=i,c=!1,[l,u]=B8(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new P8(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new P8(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=z8(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new P8(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function WDe(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new P8(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=L8(e,t);else if(a!==` `&&a!==` `&&a!==`
1026
+ let VDe=/^[a-zA-Z0-9-_]+[ \t]*$/;function B8(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new P8(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `){if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new P8(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let[s,c]=F8(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=I8(l);if(u>-1)throw new P8(`newlines are not allowed in keys`,{toml:e,ptr:t+r+u});if(l.trimStart())throw new P8(`found extra tokens after the string part`,{toml:e,ptr:c});if(a<c&&(a=e.indexOf(n,c),a<0))throw new P8(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(s)}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!VDe.test(n))throw new P8(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}}while(r+1&&r<a);return[i,R8(e,a+1,!0,!0)]}function HDe(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new P8(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=L8(e,t);else if(o!==` `&&o!==` `&&o!==`
1027
+ `&&o!==`\r`){let o,s=i,c=!1,[l,u]=B8(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new P8(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new P8(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=z8(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new P8(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function UDe(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new P8(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=L8(e,t);else if(a!==` `&&a!==` `&&a!==`
1028
1028
  `&&a!==`\r`){let a=z8(e,t-1,`]`,n-1,r);i.push(a[0]),t=a[1]}if(!a)throw new P8(`unfinished array encountered`,{toml:e,ptr:t});return[i,t]}
1029
1029
  /*!
1030
1030
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -1053,7 +1053,7 @@ let HDe=/^[a-zA-Z0-9-_]+[ \t]*$/;function B8(e,t,n=`=`){let r=t-1,i=[],a=e.index
1053
1053
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1054
1054
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1055
1055
  */
1056
- function V8(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function GDe(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=R8(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=B8(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new P8(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=V8(n[0],r,i,t?2:1);if(!c)throw new P8(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=B8(e,s),i=V8(r[0],a,o,0);if(!i)throw new P8(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=z8(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=R8(e,s,!0),e[s]&&e[s]!==`
1056
+ function V8(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function WDe(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=R8(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=B8(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new P8(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=V8(n[0],r,i,t?2:1);if(!c)throw new P8(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=B8(e,s),i=V8(r[0],a,o,0);if(!i)throw new P8(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=z8(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=R8(e,s,!0),e[s]&&e[s]!==`
1057
1057
  `&&e[s]!==`\r`)throw new P8(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:s});s=R8(e,s)}return r}
1058
1058
  /*!
1059
1059
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -1082,13 +1082,13 @@ function V8(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i
1082
1082
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1083
1083
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1084
1084
  */
1085
- let H8=/^[a-z0-9-_]+$/i;function U8(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function KDe(e){for(let t=0;t<e.length;t++)if(U8(e[t])!==`object`)return!1;return e.length!=0}function W8(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function G8(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Number.isInteger(e)&&(r||!Number.isSafeInteger(e))?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return W8(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return qDe(e,n,r);if(t===`array`)return JDe(e,n,r)}function qDe(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=H8.test(o)?o:W8(o),i+=` = `,i+=G8(e[o],U8(e[o]),t-1,n)}return i+` }`}function JDe(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=G8(e[i],U8(e[i]),t-1,n)}return r+` ]`}function YDe(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
1086
- `}[[${t}]]\n`,i+=K8(0,e[a],t,n,r);return i}function K8(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=U8(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=H8.test(c)?c:W8(c);if(e===`array`&&KDe(t[c]))o+=(o&&`
1087
- `)+YDe(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
1085
+ let H8=/^[a-z0-9-_]+$/i;function U8(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function GDe(e){for(let t=0;t<e.length;t++)if(U8(e[t])!==`object`)return!1;return e.length!=0}function W8(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function G8(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Number.isInteger(e)&&(r||!Number.isSafeInteger(e))?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return W8(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return KDe(e,n,r);if(t===`array`)return qDe(e,n,r)}function KDe(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=H8.test(o)?o:W8(o),i+=` = `,i+=G8(e[o],U8(e[o]),t-1,n)}return i+` }`}function qDe(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=G8(e[i],U8(e[i]),t-1,n)}return r+` ]`}function JDe(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
1086
+ `}[[${t}]]\n`,i+=K8(0,e[a],t,n,r);return i}function K8(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=U8(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=H8.test(c)?c:W8(c);if(e===`array`&&GDe(t[c]))o+=(o&&`
1087
+ `)+JDe(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
1088
1088
  `)+K8(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=G8(t[c],e,r,i),a+=`
1089
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function XDe(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(U8(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=K8(0,e,``,t,n);return r[r.length-1]===`
1089
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function YDe(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(U8(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=K8(0,e,``,t,n);return r[r.length-1]===`
1090
1090
  `?r:r+`
1091
- `}function q8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J8(e){let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`MODULE_NOT_FOUND`||t===`ERR_MODULE_NOT_FOUND`}function ZDe(e){return!e||typeof e!=`object`?String(e):`${typeof e} keys=[${Object.keys(e).join(`,`)}]`}function QDe(e,t){let n=[],r=new WeakSet,i=t;for(;i instanceof Error&&!r.has(i);)r.add(i),n.push(i.message),i=i.cause;return n.length===0?`${e}: ${ZDe(t)}`:`${e}: ${n.reverse().slice(0,5).join(` -> `)}`}function Y8(e,t){process.env.OK_DEBUG_NATIVE&&process.stderr.write(`[ok] native-config ${QDe(e,t)}\n`)}const $De=[`native`,`index.js`];function X8(e={},t=Y8){let n=e.moduleUrl??import.meta.url,r=e.requireModule??a(n);try{let e=M(we(n));return r(N(e,...$De))}catch(e){J8(e)||t(`bundled loader failed to load`,e)}try{return r(`@inkeep/open-knowledge-native-config`)}catch(e){return J8(e)||t(`workspace addon failed to load`,e),null}}function eOe(){let e=X8();return e&&typeof e.parseTomlToJson==`function`?e:null}function tOe(e){try{let t=e.parseTomlToJson(`probe = 1`);return typeof t==`string`&&t.includes(`probe`)}catch(e){return Y8(`addon loaded but probe failed`,e),!1}}function Z8(e){if(!q8(e))throw Error(`TOML root is not a table`);return e}function nOe(e){return{backend:`native`,parseToObject(t){return Z8(JSON.parse(e.parseTomlToJson(t)))},upsertEntry(t,n,r){let i=e.upsertMcpServer(t,n,JSON.stringify(r));return{text:i.text,existed:i.existed}},removeEntry(t,n){let r=e.removeMcpServer(t,n);return{text:r.text,existed:r.existed}},removeEntryKey(t,n,r){let i=e.removeMcpServerKey(t,n,r);return{text:i.text,existed:i.existed}}}}function rOe(){return{backend:`fallback`,parseToObject(e){return Z8(GDe(e))}}}function iOe(e=eOe){let t=e();return t&&tOe(t)?nOe(t):rOe()}let Q8=null;function $8(){return Q8===null&&(Q8=iOe()),Q8}function aOe(){let e=$8();return e.backend===`native`?e:void 0}const e5=sn,t5=xee,oOe=Cee,n5=`node`,r5={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},i5=`# ok-mcp-v2`,a5=`# ok-mcp-v2
1091
+ `}function q8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J8(e){let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`MODULE_NOT_FOUND`||t===`ERR_MODULE_NOT_FOUND`}function XDe(e){return!e||typeof e!=`object`?String(e):`${typeof e} keys=[${Object.keys(e).join(`,`)}]`}function ZDe(e,t){let n=[],r=new WeakSet,i=t;for(;i instanceof Error&&!r.has(i);)r.add(i),n.push(i.message),i=i.cause;return n.length===0?`${e}: ${XDe(t)}`:`${e}: ${n.reverse().slice(0,5).join(` -> `)}`}function Y8(e,t){process.env.OK_DEBUG_NATIVE&&process.stderr.write(`[ok] native-config ${ZDe(e,t)}\n`)}const QDe=[`native`,`index.js`];function X8(e={},t=Y8){let n=e.moduleUrl??import.meta.url,r=e.requireModule??a(n);try{let e=M(we(n));return r(N(e,...QDe))}catch(e){J8(e)||t(`bundled loader failed to load`,e)}try{return r(`@inkeep/open-knowledge-native-config`)}catch(e){return J8(e)||t(`workspace addon failed to load`,e),null}}function $De(){let e=X8();return e&&typeof e.parseTomlToJson==`function`?e:null}function eOe(e){try{let t=e.parseTomlToJson(`probe = 1`);return typeof t==`string`&&t.includes(`probe`)}catch(e){return Y8(`addon loaded but probe failed`,e),!1}}function Z8(e){if(!q8(e))throw Error(`TOML root is not a table`);return e}function tOe(e){return{backend:`native`,parseToObject(t){return Z8(JSON.parse(e.parseTomlToJson(t)))},upsertEntry(t,n,r){let i=e.upsertMcpServer(t,n,JSON.stringify(r));return{text:i.text,existed:i.existed}},removeEntry(t,n){let r=e.removeMcpServer(t,n);return{text:r.text,existed:r.existed}},removeEntryKey(t,n,r){let i=e.removeMcpServerKey(t,n,r);return{text:i.text,existed:i.existed}}}}function nOe(){return{backend:`fallback`,parseToObject(e){return Z8(WDe(e))}}}function rOe(e=$De){let t=e();return t&&eOe(t)?tOe(t):nOe()}let Q8=null;function $8(){return Q8===null&&(Q8=rOe()),Q8}function iOe(){let e=$8();return e.backend===`native`?e:void 0}const e5=sn,t5=xee,aOe=Cee,n5=`node`,r5={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},i5=`# ok-mcp-v2`,a5=`# ok-mcp-v2
1092
1092
  USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
1093
1093
  [ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
1094
1094
  BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
@@ -1124,7 +1124,7 @@ foreach ($d in $dirs) {
1124
1124
  if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
1125
1125
  }
1126
1126
  [Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
1127
- exit 127`,l5=`// ok-pi-bridge`,u5=`${l5}-v1`;function d5(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 v5(e,i5)}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 v5(e,o5)}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 v5(e,i5)}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 v5(e,o5)}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(u5)}return!1}function f5(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=be(e);if(me(t)===`cli.mjs`&&me(M(t))===`dist`)return t;let n=t.split(xe),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),a=i.length===0?xe:i.join(xe);return N(a,`packages`,`cli`,`dist`,`cli.mjs`)}function p5(e={}){return e.mode===`dev`?{command:n5,args:[f5(),`mcp`],env:{...r5}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,c5]}:{command:`/bin/sh`,args:[`-l`,`-c`,a5]}}function sOe(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[n5,f5(),`mcp`],environment:{...r5}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,c5]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,a5]}}function m5(e){if(typeof e!=`object`||!e)return!1;let t=e;return h5(t,p5({mode:`published`,platformName:`darwin`}))||h5(t,p5({mode:`published`,platformName:`win32`}))}function h5(e,t){return Object.keys(e).length===Object.keys(t).length&&cOe(e,t)}function cOe(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 g5(e,t){let n=e=>y5(e);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])}function lOe(e){return e.format===`toml`?$8().backend===`native`:e.format===`json`||e.format===`yaml`}function _5(e){return Array.isArray(e.command)?e.command:[e.command,...Array.isArray(e.args)?e.args:[]]}function v5(e,t){return typeof e==`string`&&e.trimStart().startsWith(t)}function y5(e){return v5(e,`# ok-mcp`)}function uOe(e){return typeof e==`string`&&(e===s5||e.startsWith(`${s5}@`))}function b5(e){if(typeof e!=`object`||!e)return!1;let t=_5(e),n=t.findIndex(e=>e===`-c`||e===`-Command`);return n>=0&&y5(t[n+1])?!0:t.some(uOe)}function dOe(e){if(typeof e!=`object`||!e)return!1;let t=_5(e);if(t[0]!==n5||t[2]!==`mcp`)return!1;try{return t[1]===f5()}catch{return!1}}const fOe=[`command`,`args`,`env`],pOe=[`type`,`command`,`environment`];function x5(e){return e.type===`local`&&Array.isArray(e.command)?pOe:fOe}function S5(e,t){if(typeof e!=`object`||!e)return[];let n=e;return x5(t).filter(e=>t[e]===void 0&&n[e]!==void 0)}function mOe(e,t){return e.format===`file`?null:e.buildEntry(t,{})}function hOe(e,t){return S5(e,t).length>0}function gOe(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.enabled===!1||typeof t.command!=`string`||!Array.isArray(t.args)?!1:g5(t.args,t.command)}function _Oe(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`&&g5(r,n)}function C5(e){return e===`win32`?Se:ve}function vOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.claude.json`)}function w5(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=e.env??process.env;if(t===`darwin`)return ve.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??Se.join(n,`AppData`,`Roaming`);return Se.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function T5(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.cursor`,`mcp.json`)}function yOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return(e.env??process.env).CODEX_HOME??C5(t).join(n,`.codex`)}function E5(e={}){return C5(e.platformName??process.platform).join(yOe(e),`config.toml`)}function D5(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=(e.env??process.env).COPILOT_HOME??C5(t).join(n,`.copilot`);return C5(t).join(r,`mcp-config.json`)}function bOe(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=e.env??process.env,i=C5(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 O5(e={}){return C5(e.platformName??process.platform).join(bOe(e),`opencode.json`)}function xOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.openclaw`,`openclaw.json`)}function SOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.hermes`,`config.yaml`)}function k5(e={}){let t=e.platformName??process.platform,n=e.home??k();return(e.env??process.env).PI_CODING_AGENT_DIR??C5(t).join(n,`.pi`,`agent`)}function COe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function wOe(e,t){let n=C5(t);return[{file:n.join(e,`.lmstudio`,`mcp.json`),dir:n.join(e,`.lmstudio`)},{file:n.join(e,`.cache`,`lm-studio`,`mcp.json`),dir:n.join(e,`.cache`,`lm-studio`)}]}function TOe(e){try{return w(e).length>0}catch{return!1}}function A5(e={}){let t=e.platformName??process.platform,[n,r]=wOe(e.home??k(),t),i=[n,r].find(e=>g(e.file));return i?i.file:TOe(r.dir)?r.file:n.file}function EOe(e){let t=e.serverName(``);return e.format===`toml`?`[${e.topLevelKey}.${t}]`:[e.topLevelKey,e.serverMapSubKey,t].filter(Boolean).join(`.`)}function DOe(e,t){let n;try{n=e.configPath(``,t)}catch{return null}return n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}const j5={claude:{id:`claude`,label:t5.claude,configPath:(e,t)=>vOe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.claude`),projectConfigPath:e=>N(e,`.mcp.json`),projectSkillPath:e=>N(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:t5[`claude-desktop`],configPath:(e,t)=>w5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(w5({home:t}))},cursor:{id:`cursor`,label:t5.cursor,configPath:(e,t)=>T5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(T5({home:t})),projectConfigPath:e=>N(e,`.cursor`,`mcp.json`),projectSkillPath:e=>N(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:t5.codex,configPath:(e,t)=>E5({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(E5({home:t})),projectConfigPath:e=>N(e,`.codex`,`config.toml`),projectSkillPath:e=>N(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},copilot:{id:`copilot`,label:t5.copilot,configPath:(e,t)=>D5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(D5({home:t})),projectSkillPath:e=>N(e,`.github`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:t5.opencode,configPath:(e,t)=>O5({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>vo,buildEntry:(e,t)=>sOe(t),scope:`global`,detectPath:(e,t)=>M(O5({home:t})),projectConfigPath:e=>N(e,`opencode.json`),projectSkillPath:e=>N(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:t5.openclaw,configPath:(e,t)=>xOe({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:t5.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:()=>vo,scope:`project`,detectPath:(e,t)=>k5({home:t}),projectConfigPath:e=>N(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>N(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:t5.antigravity,configPath:(e,t)=>COe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:t5[`lm-studio`],configPath:(e,t)=>A5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(A5({home:t})),offerOnlyWhenDetected:!0},hermes:{id:`hermes`,label:t5.hermes,configPath:(e,t)=>SOe({home:t}),format:`yaml`,topLevelKey:`mcp_servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.hermes`),offerOnlyWhenDetected:!0}};function OOe(e){let t=e.filter(e=>!Object.hasOwn(j5,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${e5.join(`, `)}`);return e.map(e=>j5[e])}var M5=i((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})),N5=i((e=>{let{InvalidArgumentError:t}=M5();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),P5=i((e=>{let{humanReadableArgName:t}=N5();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(`
1127
+ exit 127`,l5=`// ok-pi-bridge`,u5=`${l5}-v1`;function d5(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 v5(e,i5)}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 v5(e,o5)}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 v5(e,i5)}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 v5(e,o5)}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(u5)}return!1}function f5(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=be(e);if(me(t)===`cli.mjs`&&me(M(t))===`dist`)return t;let n=t.split(xe),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),a=i.length===0?xe:i.join(xe);return N(a,`packages`,`cli`,`dist`,`cli.mjs`)}function p5(e={}){return e.mode===`dev`?{command:n5,args:[f5(),`mcp`],env:{...r5}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,c5]}:{command:`/bin/sh`,args:[`-l`,`-c`,a5]}}function oOe(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[n5,f5(),`mcp`],environment:{...r5}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,c5]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,a5]}}function m5(e){if(typeof e!=`object`||!e)return!1;let t=e;return h5(t,p5({mode:`published`,platformName:`darwin`}))||h5(t,p5({mode:`published`,platformName:`win32`}))}function h5(e,t){return Object.keys(e).length===Object.keys(t).length&&sOe(e,t)}function sOe(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 g5(e,t){let n=e=>y5(e);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])}function cOe(e){return e.format===`toml`?$8().backend===`native`:e.format===`json`||e.format===`yaml`}function _5(e){return Array.isArray(e.command)?e.command:[e.command,...Array.isArray(e.args)?e.args:[]]}function v5(e,t){return typeof e==`string`&&e.trimStart().startsWith(t)}function y5(e){return v5(e,`# ok-mcp`)}function lOe(e){return typeof e==`string`&&(e===s5||e.startsWith(`${s5}@`))}function b5(e){if(typeof e!=`object`||!e)return!1;let t=_5(e),n=t.findIndex(e=>e===`-c`||e===`-Command`);return n>=0&&y5(t[n+1])?!0:t.some(lOe)}function uOe(e){if(typeof e!=`object`||!e)return!1;let t=_5(e);if(t[0]!==n5||t[2]!==`mcp`)return!1;try{return t[1]===f5()}catch{return!1}}const dOe=[`command`,`args`,`env`],fOe=[`type`,`command`,`environment`];function x5(e){return e.type===`local`&&Array.isArray(e.command)?fOe:dOe}function S5(e,t){if(typeof e!=`object`||!e)return[];let n=e;return x5(t).filter(e=>t[e]===void 0&&n[e]!==void 0)}function pOe(e,t){return e.format===`file`?null:e.buildEntry(t,{})}function mOe(e,t){return S5(e,t).length>0}function hOe(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.enabled===!1||typeof t.command!=`string`||!Array.isArray(t.args)?!1:g5(t.args,t.command)}function gOe(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`&&g5(r,n)}function C5(e){return e===`win32`?Se:ve}function _Oe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.claude.json`)}function w5(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=e.env??process.env;if(t===`darwin`)return ve.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??Se.join(n,`AppData`,`Roaming`);return Se.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function T5(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.cursor`,`mcp.json`)}function vOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return(e.env??process.env).CODEX_HOME??C5(t).join(n,`.codex`)}function E5(e={}){return C5(e.platformName??process.platform).join(vOe(e),`config.toml`)}function D5(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=(e.env??process.env).COPILOT_HOME??C5(t).join(n,`.copilot`);return C5(t).join(r,`mcp-config.json`)}function yOe(e={}){let t=e.platformName??process.platform,n=e.home??k(),r=e.env??process.env,i=C5(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 O5(e={}){return C5(e.platformName??process.platform).join(yOe(e),`opencode.json`)}function bOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.openclaw`,`openclaw.json`)}function xOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.hermes`,`config.yaml`)}function k5(e={}){let t=e.platformName??process.platform,n=e.home??k();return(e.env??process.env).PI_CODING_AGENT_DIR??C5(t).join(n,`.pi`,`agent`)}function SOe(e={}){let t=e.platformName??process.platform,n=e.home??k();return C5(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function COe(e,t){let n=C5(t);return[{file:n.join(e,`.lmstudio`,`mcp.json`),dir:n.join(e,`.lmstudio`)},{file:n.join(e,`.cache`,`lm-studio`,`mcp.json`),dir:n.join(e,`.cache`,`lm-studio`)}]}function wOe(e){try{return w(e).length>0}catch{return!1}}function A5(e={}){let t=e.platformName??process.platform,[n,r]=COe(e.home??k(),t),i=[n,r].find(e=>g(e.file));return i?i.file:wOe(r.dir)?r.file:n.file}function TOe(e){let t=e.serverName(``);return e.format===`toml`?`[${e.topLevelKey}.${t}]`:[e.topLevelKey,e.serverMapSubKey,t].filter(Boolean).join(`.`)}function EOe(e,t){let n;try{n=e.configPath(``,t)}catch{return null}return n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}const j5={claude:{id:`claude`,label:t5.claude,configPath:(e,t)=>_Oe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.claude`),projectConfigPath:e=>N(e,`.mcp.json`),projectSkillPath:e=>N(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:t5[`claude-desktop`],configPath:(e,t)=>w5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(w5({home:t}))},cursor:{id:`cursor`,label:t5.cursor,configPath:(e,t)=>T5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(T5({home:t})),projectConfigPath:e=>N(e,`.cursor`,`mcp.json`),projectSkillPath:e=>N(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:t5.codex,configPath:(e,t)=>E5({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(E5({home:t})),projectConfigPath:e=>N(e,`.codex`,`config.toml`),projectSkillPath:e=>N(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},copilot:{id:`copilot`,label:t5.copilot,configPath:(e,t)=>D5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(D5({home:t})),projectSkillPath:e=>N(e,`.github`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:t5.opencode,configPath:(e,t)=>O5({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>vo,buildEntry:(e,t)=>oOe(t),scope:`global`,detectPath:(e,t)=>M(O5({home:t})),projectConfigPath:e=>N(e,`opencode.json`),projectSkillPath:e=>N(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:t5.openclaw,configPath:(e,t)=>bOe({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:t5.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:()=>vo,scope:`project`,detectPath:(e,t)=>k5({home:t}),projectConfigPath:e=>N(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>N(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:t5.antigravity,configPath:(e,t)=>SOe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:t5[`lm-studio`],configPath:(e,t)=>A5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>M(A5({home:t})),offerOnlyWhenDetected:!0},hermes:{id:`hermes`,label:t5.hermes,configPath:(e,t)=>xOe({home:t}),format:`yaml`,topLevelKey:`mcp_servers`,serverName:()=>vo,buildEntry:(e,t)=>p5(t),scope:`global`,detectPath:(e,t)=>N(t??k(),`.hermes`),offerOnlyWhenDetected:!0}};function DOe(e){let t=e.filter(e=>!Object.hasOwn(j5,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${e5.join(`, `)}`);return e.map(e=>j5[e])}var M5=i((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})),N5=i((e=>{let{InvalidArgumentError:t}=M5();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),P5=i((e=>{let{humanReadableArgName:t}=N5();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(`
1128
1128
  `)}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,`
1129
1129
  `+` `.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(`
1130
1130
  `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),F5=i((e=>{let{InvalidArgumentError:t}=M5();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
@@ -1133,7 +1133,7 @@ exit 127`,l5=`// ok-pi-bridge`,u5=`${l5}-v1`;function d5(e){if(typeof e!=`object
1133
1133
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
1134
1134
  - too many short flags`):i.test(t)?Error(`${n}
1135
1135
  - too many long flags`):Error(`${n}
1136
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),kOe=i((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),AOe=i((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=N5(),{CommanderError:l}=M5(),{Help:u,stripColor:d}=P5(),{Option:f,DualOptions:p}=F5(),{suggestSimilar:m}=kOe();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
1136
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),OOe=i((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),kOe=i((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=N5(),{CommanderError:l}=M5(),{Help:u,stripColor:d}=P5(),{Option:f,DualOptions:p}=F5(),{suggestSimilar:m}=OOe();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
1137
1137
  - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new s(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
1138
1138
  Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new l(e,t,n)),o.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new f(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
1139
1139
  - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0||e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof f)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){o.versions?.electron&&(t.from=`electron`);let e=o.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=o.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:o.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
@@ -1142,7 +1142,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
1142
1142
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1143
1143
  - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
1144
1144
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
1145
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:jOe,createCommand:MOe,createArgument:NOe,createOption:POe,CommanderError:FOe,InvalidArgumentError:IOe,InvalidOptionArgumentError:LOe,Command:ROe,Argument:zOe,Option:BOe,Help:VOe}=e(i((e=>{let{Argument:t}=N5(),{Command:n}=AOe(),{CommanderError:r,InvalidArgumentError:i}=M5(),{Help:a}=P5(),{Option:o}=F5();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;function HOe(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{_(n)}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[`cannot access content directory ${n}: ${e instanceof Error?e.message:String(e)}`]}}let o;try{o=rDe({projectDir:t,contentDir:n})}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[e instanceof Error?e.message:String(e)]}}function s(e){let t;try{t=w(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${ye(n,e)||`.`}: ${r}`);return}for(let r of t){let t=N(e,r.name);if(r.isSymbolicLink()){let e;try{e=E(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${ye(n,t)}`):i.push(`cannot resolve symlink ${ye(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=te(e)}catch{continue}if(r.isDirectory()){let e=ye(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=ye(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=ye(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=ye(n,t);if(o.isExcluded(e))continue;a.push(e)}}}return s(n),{totalCount:a.length,sample:a.slice(0,r),contentDir:n,warnings:i}}const UOe=`${l5}-dev`;function WOe(e){return e.startsWith(l5)}function I5(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&WOe(n)}function GOe(e){return{command:`ok-pi-managed-extension`,args:[e]}}function L5(e={}){let t=e.mode===`dev`?UOe:u5,n={unix:p5({...e,platformName:`darwin`}),win32:p5({...e,platformName:`win32`})};return`${t}
1145
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:AOe,createCommand:jOe,createArgument:MOe,createOption:NOe,CommanderError:POe,InvalidArgumentError:FOe,InvalidOptionArgumentError:IOe,Command:LOe,Argument:ROe,Option:zOe,Help:BOe}=e(i((e=>{let{Argument:t}=N5(),{Command:n}=kOe(),{CommanderError:r,InvalidArgumentError:i}=M5(),{Help:a}=P5(),{Option:o}=F5();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;function VOe(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{_(n)}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[`cannot access content directory ${n}: ${e instanceof Error?e.message:String(e)}`]}}let o;try{o=nDe({projectDir:t,contentDir:n})}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[e instanceof Error?e.message:String(e)]}}function s(e){let t;try{t=w(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${ye(n,e)||`.`}: ${r}`);return}for(let r of t){let t=N(e,r.name);if(r.isSymbolicLink()){let e;try{e=E(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${ye(n,t)}`):i.push(`cannot resolve symlink ${ye(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=te(e)}catch{continue}if(r.isDirectory()){let e=ye(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=ye(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=ye(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=ye(n,t);if(o.isExcluded(e))continue;a.push(e)}}}return s(n),{totalCount:a.length,sample:a.slice(0,r),contentDir:n,warnings:i}}const HOe=`${l5}-dev`;function UOe(e){return e.startsWith(l5)}function I5(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&UOe(n)}function WOe(e){return{command:`ok-pi-managed-extension`,args:[e]}}function L5(e={}){let t=e.mode===`dev`?HOe:u5,n={unix:p5({...e,platformName:`darwin`}),win32:p5({...e,platformName:`win32`})};return`${t}
1146
1146
  /**
1147
1147
  * Open Knowledge bridge for Pi — MANAGED FILE, written by \`ok init\`.
1148
1148
  * Hand edits are overwritten whenever OK re-syncs this project; remove it
@@ -1485,56 +1485,56 @@ export default function okBridge(pi: {
1485
1485
  }
1486
1486
  });
1487
1487
  }
1488
- `}function KOe(e,t){let n=ye(B6(t),B6(e));return n.length>0&&!n.startsWith(`..`)&&!ge(n)}const qOe=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],W6({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function JOe(e,t={}){let n=t.homeDir??k(),r=t.gitTopLevel??qOe,i=be(e),a;try{a=E(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(G6(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=M(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&KOe(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}}function R5(e,t){let n;try{n=_(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.`);z5(e,t)}function YOe(e,t){z5(e,t)}function z5(e,t){B5(e,t)}function B5(e,t){let n=t,r;try{r=E(n)}catch{r=be(n)}let i=M(e);for(;i.length>1&&i!==xe;){let t;try{t=E(i)}catch(e){if(e.code===`ENOENT`){i=M(i);continue}throw e}let n=ye(r,t);if(n===``||!n.startsWith(`..`)&&!ge(n))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${r}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function V5(e,t){let n=M(t),r=g(t)?`overwritten`:`written`;if(r===`written`&&g(n))throw Error(`Refusing to replace ${n}: it exists but holds no SKILL.md, so it is not a bundle OpenKnowledge wrote. Move it aside and try again.`);return O(n,{recursive:!0,force:!0}),v(M(n),{recursive:!0}),m(e,n,{recursive:!0}),r}function H5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U5(e,t,n){try{if(te(n).size>10485760)return!1}catch{return!1}let r;try{r=S(n,`utf-8`)}catch{return!1}let i=[],a=ewe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!H5(a))return!1;let o=a[e.topLevelKey];if(!H5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!H5(s))return!1;let c=s[e.serverName(t)];return H5(c)&&c.enabled===!1?!1:b5(c)||dOe(c)}function XOe(e){let t=Qo[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:Mo(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:j5[n.editor]??null}function ZOe(e,t,n={}){if(!Tee.includes(e.id))return!0;let r=XOe(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&U5(r,t,i))return!0;try{return U5(e,t,e.configPath(t,n.home))}catch{return!1}}function QOe(e){let t=new Set(un.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function $Oe(e,t){if(QOe(t).length===0)return null;let n=N(e,us,fn,`SKILL.md`);try{let t=S8(`project`,{checkDesktop:!0});return R5(M(n),e),{editorId:`agents`,label:`.agents hub`,action:V5(t,n),path:n}}catch(e){return{editorId:`agents`,label:`.agents hub`,action:`failed`,path:n,error:e instanceof Error?e.message:String(e)}}}function W5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!ZOe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=S8(`project`,{checkDesktop:!0});R5(M(r),t);let i=V5(n,r);return{editorId:e.id,label:e.label,action:i,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function eke(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=M(n);return g(n)?(YOe(r,t),O(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function tke(){let e=X8();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function nke(e){let t=e,n=new Set;for(;;){let r;try{r=_(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=T(t)}catch(t){return Y8(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=ge(i)?i:N(M(t),i)}}let G5;function rke(){return G5===void 0&&(G5=tke()),G5}function K5(e,t=rke){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){Y8(`resolveSymlinkWritePath threw`,e)}return nke(e)}const q5=`**/.ok/*`,J5=`!**/${ls}/`;function Y5(e){let t=[`.ok/`,`.okignore`];for(let n of e5){let r=j5[n];r.projectConfigPath&&t.push(dke(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function X5(e){let t=N(e,...gB);if(!g(t))return[];try{let e=bB(S(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=cn[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function ike(e,t){let n=Z5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:Q5(n)};let r=$5(e);if(r.kind!==`ok`)return r.result;let i=g(r.path)?S(r.path,`utf-8`):``,a=new Set(X5(e)),o=[],s=a.size===0?i:i.split(`
1488
+ `}function GOe(e,t){let n=ye(B6(t),B6(e));return n.length>0&&!n.startsWith(`..`)&&!ge(n)}const KOe=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],W6({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function qOe(e,t={}){let n=t.homeDir??k(),r=t.gitTopLevel??KOe,i=be(e),a;try{a=E(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(G6(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=M(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&GOe(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}}function R5(e,t){let n;try{n=_(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.`);z5(e,t)}function JOe(e,t){z5(e,t)}function z5(e,t){B5(e,t)}function B5(e,t){let n=t,r;try{r=E(n)}catch{r=be(n)}let i=M(e);for(;i.length>1&&i!==xe;){let t;try{t=E(i)}catch(e){if(e.code===`ENOENT`){i=M(i);continue}throw e}let n=ye(r,t);if(n===``||!n.startsWith(`..`)&&!ge(n))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${r}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function V5(e,t){let n=M(t),r=g(t)?`overwritten`:`written`;if(r===`written`&&g(n))throw Error(`Refusing to replace ${n}: it exists but holds no SKILL.md, so it is not a bundle OpenKnowledge wrote. Move it aside and try again.`);return O(n,{recursive:!0,force:!0}),v(M(n),{recursive:!0}),m(e,n,{recursive:!0}),r}function H5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U5(e,t,n){try{if(te(n).size>10485760)return!1}catch{return!1}let r;try{r=S(n,`utf-8`)}catch{return!1}let i=[],a=ewe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!H5(a))return!1;let o=a[e.topLevelKey];if(!H5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!H5(s))return!1;let c=s[e.serverName(t)];return H5(c)&&c.enabled===!1?!1:b5(c)||uOe(c)}function YOe(e){let t=Qo[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:Mo(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:j5[n.editor]??null}function XOe(e,t,n={}){if(!Tee.includes(e.id))return!0;let r=YOe(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&U5(r,t,i))return!0;try{return U5(e,t,e.configPath(t,n.home))}catch{return!1}}function ZOe(e){let t=new Set(un.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function QOe(e,t){if(ZOe(t).length===0)return null;let n=N(e,us,fn,`SKILL.md`);try{let t=S8(`project`,{checkDesktop:!0});return R5(M(n),e),{editorId:`agents`,label:`.agents hub`,action:V5(t,n),path:n}}catch(e){return{editorId:`agents`,label:`.agents hub`,action:`failed`,path:n,error:e instanceof Error?e.message:String(e)}}}function W5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!XOe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=S8(`project`,{checkDesktop:!0});R5(M(r),t);let i=V5(n,r);return{editorId:e.id,label:e.label,action:i,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function $Oe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=M(n);return g(n)?(JOe(r,t),O(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function eke(){let e=X8();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function tke(e){let t=e,n=new Set;for(;;){let r;try{r=_(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=T(t)}catch(t){return Y8(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=ge(i)?i:N(M(t),i)}}let G5;function nke(){return G5===void 0&&(G5=eke()),G5}function K5(e,t=nke){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){Y8(`resolveSymlinkWritePath threw`,e)}return tke(e)}const q5=`**/.ok/*`,J5=`!**/${ls}/`;function Y5(e){let t=[`.ok/`,`.okignore`];for(let n of e5){let r=j5[n];r.projectConfigPath&&t.push(uke(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function X5(e){let t=N(e,...gB);if(!g(t))return[];try{let e=bB(S(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=cn[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function rke(e,t){let n=Z5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:Q5(n)};let r=$5(e);if(r.kind!==`ok`)return r.result;let i=g(r.path)?S(r.path,`utf-8`):``,a=new Set(X5(e)),o=[],s=a.size===0?i:i.split(`
1489
1489
  `).filter(e=>{let t=e.trim();return!a.has(t)||(o.push(t),!1)}).join(`
1490
1490
  `),c=n7(s),l=[],u=[];for(let e of t)t7(c,e)?u.push(e):l.push(e);if(l.length===0&&o.length===0)return{kind:`updated`,appended:l,alreadyPresent:u,removed:[]};let d=l.length===0||s.length===0||s.endsWith(`
1491
1491
  `)?``:`
1492
1492
  `,f=l.length===0?``:`${l.join(`
1493
- `)}\n`;try{re(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function ake(e,t){let n=$5(e);if(n.kind!==`ok`)return n.result;if(!g(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>e7(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(q5),i.add(J5);for(let t of X5(e))i.add(t);let a;try{a=S(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
1493
+ `)}\n`;try{re(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function ike(e,t){let n=$5(e);if(n.kind!==`ok`)return n.result;if(!g(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>e7(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(q5),i.add(J5);for(let t of X5(e))i.add(t);let a;try{a=S(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
1494
1494
  `),s=new Set,c=[];for(let e of o){let t=e.trim();if(i.has(t)){s.add(t);continue}c.push(e)}let l=[...s];if(s.size===0)return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let u=c.join(`
1495
- `);if(u!==a)try{re(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function oke(e){let t=$5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!g(t.path))return`shared`;let n;try{n=S(t.path,`utf-8`)}catch{return`shared`}let r=n7(n),i=Y5(e);for(let e of i)if(t7(r,e))return`local-only`;return r.has(q5)?`local-only`:`shared`}function ske(e){let t=$5(e);if(t.kind!==`ok`||!g(t.path))return[];let n;try{n=S(t.path,`utf-8`)}catch{return[]}let r=n7(n),i=[...Y5(e),...X5(e)].filter(e=>t7(r,e)),a=new Set(i),o=[];for(let e of Object.values(cn))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===q5||e===J5){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function Z5(e,t){let n=[];for(let r of t){let t=be(e,r);if(g(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Gz([r])],W6({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const cke=/^[\w.\-/]+$/;function lke(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function uke(e){return cke.test(e)?e:lke(Wz(e))}function Q5(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}-- ${uke(e)}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1495
+ `);if(u!==a)try{re(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function ake(e){let t=$5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!g(t.path))return`shared`;let n;try{n=S(t.path,`utf-8`)}catch{return`shared`}let r=n7(n),i=Y5(e);for(let e of i)if(t7(r,e))return`local-only`;return r.has(q5)?`local-only`:`shared`}function oke(e){let t=$5(e);if(t.kind!==`ok`||!g(t.path))return[];let n;try{n=S(t.path,`utf-8`)}catch{return[]}let r=n7(n),i=[...Y5(e),...X5(e)].filter(e=>t7(r,e)),a=new Set(i),o=[];for(let e of Object.values(cn))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===q5||e===J5){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function Z5(e,t){let n=[];for(let r of t){let t=be(e,r);if(g(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Gz([r])],W6({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const ske=/^[\w.\-/]+$/;function cke(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function lke(e){return ske.test(e)?e:cke(Wz(e))}function Q5(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}-- ${lke(e)}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1496
1496
  `)}function $5(e){let t=B_e(e);switch(t.kind){case`repository`:{let e=t.repository.readCommonDir();if(e.kind===`unreadable`)return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}};let n=N(e.path,`info`);return g(n)?{kind:`ok`,path:N(n,`exclude`)}:{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-info-dir`}}}case`absent`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-git`}};case`malformed-pointer`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`malformed-pointer`}};case`inaccessible`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}}}}function e7(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function t7(e,t){for(let n of e7(t))if(e.has(n))return!0;return!1}function n7(e){let t=new Set;for(let n of e.split(`
1497
- `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function dke(e,t){return fke(ye(t,e))}function fke(e){return xe===`/`?e:e.split(xe).join(`/`)}function r7(e){switch(e?.code){case`EACCES`:case`EPERM`:return`permission-denied`;case`ELOOP`:return`unresolved-symlink`;case`EISDIR`:case`ENOTDIR`:return`not-a-file`;case`ENOENT`:return`disappeared`;default:return`unreadable`}}function i7(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions, then retry`;case`missing-symlink-target`:return`the symlink target is missing; restore the target or correct the symlink, then retry`;case`unresolved-symlink`:return`the path or symlink could not be resolved; check path permissions and repair any symlink cycle, then retry`;case`not-a-file`:return`the path is not a regular file; restore the intended configuration file, then retry`;case`disappeared`:return`the file disappeared; retry to check its current state`;case`unreadable`:return`the file could not be read; check that the path is accessible, then retry`;default:throw Error(`unhandled configuration file decline reason: ${e}`)}}function pke(e){for(let t of e.split(`
1498
- `)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function a7(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function o7(e){try{return te(e).mode&511}catch{return}}function mke(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
1497
+ `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function uke(e,t){return dke(ye(t,e))}function dke(e){return xe===`/`?e:e.split(xe).join(`/`)}function r7(e){switch(e?.code){case`EACCES`:case`EPERM`:return`permission-denied`;case`ELOOP`:return`unresolved-symlink`;case`EISDIR`:case`ENOTDIR`:return`not-a-file`;case`ENOENT`:return`disappeared`;default:return`unreadable`}}function i7(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions, then retry`;case`missing-symlink-target`:return`the symlink target is missing; restore the target or correct the symlink, then retry`;case`unresolved-symlink`:return`the path or symlink could not be resolved; check path permissions and repair any symlink cycle, then retry`;case`not-a-file`:return`the path is not a regular file; restore the intended configuration file, then retry`;case`disappeared`:return`the file disappeared; retry to check its current state`;case`unreadable`:return`the file could not be read; check that the path is accessible, then retry`;default:throw Error(`unhandled configuration file decline reason: ${e}`)}}function fke(e){for(let t of e.split(`
1498
+ `)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function a7(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function o7(e){try{return te(e).mode&511}catch{return}}function pke(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
1499
1499
  `)?`\r
1500
1500
  `:`
1501
- `,a=S4(r,t,void 0,{formattingOptions:{...pke(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${C4(r,a)}`;return{text:o,changed:o!==e}}const hke={allowTrailingComma:!0,disallowComments:!1};function gke(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function s7(e){let t=[],n=twe(e,t,hke);return t.some(t=>!gke(t,e))||n?.type!==`object`?null:n}function c7(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&x4(e)===t&&(n+=1)}return n}function l7(e,t){NQ(e,`${JSON.stringify(t,null,2)}\n`)}function _ke(e,t){let n=XDe(t);NQ(e,n.endsWith(`
1502
- `)?n:`${n}\n`)}function vke(e,t){let n=(0,tn.stringify)(t);NQ(e,n.endsWith(`
1503
- `)?n:`${n}\n`)}const u7=10485760;function d7(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>d7(e,t[n]));if(q8(e)&&q8(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&d7(e[n],t[n]))}return!1}function yke(e,t,n){return q8(e)&&n.every(n=>d7(e[n],t[n]))}function bke(e){for(let t of e.split(`
1504
- `)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function f7(e,t,n){return t===void 0?[e,n]:[e,t,n]}function p7(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function m7(e,t,n){let r=e[t];return n===void 0?r:q8(r)?r[n]:void 0}function xke(e,t,n,r,i,a=!1,o=!1){if(!g(e))return o?{kind:`unchanged`}:(l7(e,p7(t,i,n,r)),{kind:`written`});let s;try{s=S(e,`utf-8`)}catch(e){return Y8(`json config read failed`,e),{kind:`declined`,reason:r7(e)}}if(s.trim()===``)return o?{kind:`unchanged`}:(l7(e,p7(t,i,n,r)),{kind:`written`});if(Buffer.byteLength(s,`utf-8`)>u7)return{kind:`declined`,reason:`oversize`};let c=s7(s);if(!c)return{kind:`declined`,reason:`unparseable`};if(c7(c,t)>1)return{kind:`declined`,reason:`duplicate-container`};let l=m7(x4(c),t,i),u=q8(l)?l[n]:void 0,d=u!==void 0,f=x5(r);if(d&&a?m5(u):d&&yke(u,r,f))return{kind:o?`unchanged`:`overwritten`};let p=s.charCodeAt(0)===65279,m=p?s.slice(1):s,h=m.includes(`\r
1501
+ `,a=S4(r,t,void 0,{formattingOptions:{...fke(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${C4(r,a)}`;return{text:o,changed:o!==e}}const mke={allowTrailingComma:!0,disallowComments:!1};function hke(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function s7(e){let t=[],n=twe(e,t,mke);return t.some(t=>!hke(t,e))||n?.type!==`object`?null:n}function c7(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&x4(e)===t&&(n+=1)}return n}function l7(e,t){NQ(e,`${JSON.stringify(t,null,2)}\n`)}function gke(e,t){let n=YDe(t);NQ(e,n.endsWith(`
1502
+ `)?n:`${n}\n`)}function _ke(e,t){let n=(0,tn.stringify)(t);NQ(e,n.endsWith(`
1503
+ `)?n:`${n}\n`)}const u7=10485760;function d7(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>d7(e,t[n]));if(q8(e)&&q8(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&d7(e[n],t[n]))}return!1}function vke(e,t,n){return q8(e)&&n.every(n=>d7(e[n],t[n]))}function yke(e){for(let t of e.split(`
1504
+ `)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function f7(e,t,n){return t===void 0?[e,n]:[e,t,n]}function p7(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function m7(e,t,n){let r=e[t];return n===void 0?r:q8(r)?r[n]:void 0}function bke(e,t,n,r,i,a=!1,o=!1){if(!g(e))return o?{kind:`unchanged`}:(l7(e,p7(t,i,n,r)),{kind:`written`});let s;try{s=S(e,`utf-8`)}catch(e){return Y8(`json config read failed`,e),{kind:`declined`,reason:r7(e)}}if(s.trim()===``)return o?{kind:`unchanged`}:(l7(e,p7(t,i,n,r)),{kind:`written`});if(Buffer.byteLength(s,`utf-8`)>u7)return{kind:`declined`,reason:`oversize`};let c=s7(s);if(!c)return{kind:`declined`,reason:`unparseable`};if(c7(c,t)>1)return{kind:`declined`,reason:`duplicate-container`};let l=m7(x4(c),t,i),u=q8(l)?l[n]:void 0,d=u!==void 0,f=x5(r);if(d&&a?m5(u):d&&vke(u,r,f))return{kind:o?`unchanged`:`overwritten`};let p=s.charCodeAt(0)===65279,m=p?s.slice(1):s,h=m.includes(`\r
1505
1505
  `)?`\r
1506
1506
  `:`
1507
- `,_={...bke(m),eol:h},v=f7(t,i,n),y=m;if(o)for(let e of d?S5(u,r):[]){let t=S4(y,[...v,e],void 0,{formattingOptions:_});y=C4(y,t)}else if(d&&!a&&b5(u))for(let e of f){let t=S4(y,[...v,e],r[e],{formattingOptions:_});y=C4(y,t)}else{let e=S4(y,v,r,{formattingOptions:_});y=C4(y,e)}let b=`${p?``:``}${y}`;return b!==s&&NQ(e,b,{mode:o7(e)}),o&&b===s?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}function Ske(e,t,n,r,i,a=!1,o=!1){let s=``;if(g(t))try{s=S(t,`utf-8`)}catch(e){return Y8(`toml config read failed`,e),{kind:`declined`,reason:r7(e)}}let c=s.trim()===``;if(c&&o)return{kind:`unchanged`};if(e.backend===`fallback`)return c?(_ke(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let l=s.charCodeAt(0)===65279,u=l?s.slice(1):s,d=a7(u),f=c||u.endsWith(`
1508
- `),p,m=!1;try{let t=Cke(e,u,n,r);if(o){let n=u;for(let a of t===void 0?[]:S5(t,i))n=e.removeEntryKey(n,r,a).text;p={text:n,existed:t!==void 0}}else{let n=wke(t,i,a);m=n.kind===`replace`;let o=m?e.removeEntry(u,r).text:u;if(n.kind===`merge`)for(let t of n.prune)o=e.removeEntryKey(o,r,t).text;p=e.upsertEntry(o,r,i)}}catch(e){return Y8(`upsertEntry failed`,e),{kind:`declined`,reason:`unparseable`}}let h=p.text;f?h.endsWith(`
1507
+ `,_={...yke(m),eol:h},v=f7(t,i,n),y=m;if(o)for(let e of d?S5(u,r):[]){let t=S4(y,[...v,e],void 0,{formattingOptions:_});y=C4(y,t)}else if(d&&!a&&b5(u))for(let e of f){let t=S4(y,[...v,e],r[e],{formattingOptions:_});y=C4(y,t)}else{let e=S4(y,v,r,{formattingOptions:_});y=C4(y,e)}let b=`${p?``:``}${y}`;return b!==s&&NQ(e,b,{mode:o7(e)}),o&&b===s?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}function xke(e,t,n,r,i,a=!1,o=!1){let s=``;if(g(t))try{s=S(t,`utf-8`)}catch(e){return Y8(`toml config read failed`,e),{kind:`declined`,reason:r7(e)}}let c=s.trim()===``;if(c&&o)return{kind:`unchanged`};if(e.backend===`fallback`)return c?(gke(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let l=s.charCodeAt(0)===65279,u=l?s.slice(1):s,d=a7(u),f=c||u.endsWith(`
1508
+ `),p,m=!1;try{let t=Ske(e,u,n,r);if(o){let n=u;for(let a of t===void 0?[]:S5(t,i))n=e.removeEntryKey(n,r,a).text;p={text:n,existed:t!==void 0}}else{let n=Cke(t,i,a);m=n.kind===`replace`;let o=m?e.removeEntry(u,r).text:u;if(n.kind===`merge`)for(let t of n.prune)o=e.removeEntryKey(o,r,t).text;p=e.upsertEntry(o,r,i)}}catch(e){return Y8(`upsertEntry failed`,e),{kind:`declined`,reason:`unparseable`}}let h=p.text;f?h.endsWith(`
1509
1509
  `)||(h=`${h}\n`):h=h.replace(/\n+$/,``),d&&(h=h.replace(/\r\n/g,`
1510
1510
  `).replace(/\n/g,`\r
1511
- `));let _=`${l?``:``}${h}`;return _!==s&&NQ(t,_,{mode:o7(t)}),o&&_===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function Cke(e,t,n,r){if(t.trim()===``)return;let i=e.parseToObject(t)[n],a=q8(i)?i[r]:void 0;return q8(a)?a:void 0}function wke(e,t,n){return e===void 0||m5(e)?{kind:`merge`,prune:[]}:n||!b5(e)?{kind:`replace`}:{kind:`merge`,prune:S5(e,t)}}function Tke(e,t,n,r,i=!1,a=!1){let o=``;if(g(e))try{o=S(e,`utf-8`)}catch(e){return Y8(`yaml config read failed`,e),{kind:`declined`,reason:r7(e)}}if(o.trim()===``)return a?{kind:`unchanged`}:(vke(e,{[t]:{[n]:r}}),{kind:`written`});if(Buffer.byteLength(o,`utf-8`)>u7)return{kind:`declined`,reason:`oversize`};let s=o.charCodeAt(0)===65279,c=s?o.slice(1):o,l=(0,tn.parseDocument)(c);if(l.errors.length>0)return{kind:`declined`,reason:`unparseable`};let u=[t,n],d=l.hasIn(u);l.hasIn([t])&&!(0,tn.isCollection)(l.getIn([t],!0))&&l.deleteIn([t]);let f=l.getIn(u,!0),p=d&&(0,tn.isCollection)(f)&&(i?m5(f.toJSON()):b5(f.toJSON()));if(a){if(d&&(0,tn.isCollection)(f))for(let e of S5(f.toJSON(),r))l.deleteIn([...u,e])}else if(p)for(let e of x5(r))r[e]===void 0?l.deleteIn([...u,e]):l.setIn([...u,e],l.createNode(r[e]));else l.setIn(u,l.createNode(r));let m=l.toString(),h=a7(c);c.endsWith(`
1511
+ `));let _=`${l?``:``}${h}`;return _!==s&&NQ(t,_,{mode:o7(t)}),o&&_===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function Ske(e,t,n,r){if(t.trim()===``)return;let i=e.parseToObject(t)[n],a=q8(i)?i[r]:void 0;return q8(a)?a:void 0}function Cke(e,t,n){return e===void 0||m5(e)?{kind:`merge`,prune:[]}:n||!b5(e)?{kind:`replace`}:{kind:`merge`,prune:S5(e,t)}}function wke(e,t,n,r,i=!1,a=!1){let o=``;if(g(e))try{o=S(e,`utf-8`)}catch(e){return Y8(`yaml config read failed`,e),{kind:`declined`,reason:r7(e)}}if(o.trim()===``)return a?{kind:`unchanged`}:(_ke(e,{[t]:{[n]:r}}),{kind:`written`});if(Buffer.byteLength(o,`utf-8`)>u7)return{kind:`declined`,reason:`oversize`};let s=o.charCodeAt(0)===65279,c=s?o.slice(1):o,l=(0,tn.parseDocument)(c);if(l.errors.length>0)return{kind:`declined`,reason:`unparseable`};let u=[t,n],d=l.hasIn(u);l.hasIn([t])&&!(0,tn.isCollection)(l.getIn([t],!0))&&l.deleteIn([t]);let f=l.getIn(u,!0),p=d&&(0,tn.isCollection)(f)&&(i?m5(f.toJSON()):b5(f.toJSON()));if(a){if(d&&(0,tn.isCollection)(f))for(let e of S5(f.toJSON(),r))l.deleteIn([...u,e])}else if(p)for(let e of x5(r))r[e]===void 0?l.deleteIn([...u,e]):l.setIn([...u,e],l.createNode(r[e]));else l.setIn(u,l.createNode(r));let m=l.toString(),h=a7(c);c.endsWith(`
1512
1512
  `)?m.endsWith(`
1513
1513
  `)||(m=`${m}\n`):m=m.replace(/\n+$/,``),h&&(m=m.replace(/\r\n/g,`
1514
1514
  `).replace(/\n/g,`\r
1515
- `));let _=`${s?``:``}${m}`;return _!==o&&NQ(e,_,{mode:o7(e)}),a&&_===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const Eke=`open-knowledge-ui`;function h7(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return g(r)}catch{return!1}}function g7(e,t,n){try{let r=be(M(e.configPath(t,n))),i=be(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+xe)}catch{return!1}}function _7(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!g(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||g7(e,t,r);if(!i&&c&&!h7(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{R5(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return Oke(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||v(M(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{FQ(`${o}.lock`,()=>{let t=K5(o).writePath;if(s||v(M(t),{recursive:!0}),e.format===`toml`){let r=Ske($8(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=Tke(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=xke(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Dke={pi:L5};function Oke(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Dke[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{v(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{FQ(`${t}.lock`,()=>{let e=null;try{e=S(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}NQ(t,c,e===null?void 0:{mode:o7(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}async function kke(e){let t=OOe(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>_7(t,``,n,e.home))}function v7(e,t,n,r){let i=b7(e,t,n,r);return i.kind===`present`?i.entry:null}function y7(e,t,n,r){let i=m7(e,t,r);if(!q8(i))return{kind:`no-entry`};let a=i[n];return q8(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function b7(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!g(i))return{kind:`absent`};try{if(te(i).size>u7)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:r7(e)}}let a;try{a=S(i,`utf-8`)}catch(e){return{kind:`decline`,reason:r7(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:GOe(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=$8().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return y7(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,tn.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:y7(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=s7(a);return s?c7(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:y7(x4(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function Ake(e,t){let n=[];for(let r of e5)r!==`claude-desktop`&&h7(j5[r],e,t)&&n.push(r);return n}function x7(e){return e===`opencode`?_Oe:gOe}function jke(e,t,n){let r=j5[e],i=x7(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=v7(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}const S7=8192;function C7(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function Mke(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Nke=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Pke(e){return e.replace(Nke,`$1"[REDACTED-DEVICE-ID]"`)}function w7(e){return Pke(Mke(e))}const Fke=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ike(e){if(typeof e!=`string`)return null;let t=Fke.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function Lke(e){let t=b(e,`r`);try{let e=Buffer.alloc(S7),n=0,r=!1;for(;n<S7;){let i=C(t,e,n,S7-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{f(t)}}function Rke(e){try{let t=Lke(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Ike(a)}}catch{return{kind:`unreadable`}}}function zke(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function Bke(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=w(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=N(e,t.name),r;try{r=te(n).mtimeMs}catch{continue}if(r<i)continue;let c=Rke(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!zke(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function T7(){return N(k(),`.ok`,`bug-reports`)}function Vke(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=T7(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function E7(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let e=S(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return g(N(e,`.ok`))?Ne(`sha256`).update(be(e)).digest(`hex`).slice(0,12):null}function Hke(){let e={timestamp:new Date().toISOString(),platform:le(),osType:de(),osRelease:ue(),hostname:`[redacted]`,uptime:fe(),freeMem:se(),totalMem:j(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,W6({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const Uke=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function D7(e){let t=me(e);return Uke.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function Wke(e,t){return A7(e,t).files}const Gke=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function O7(e,t=`com.inkeep.open-knowledge`){let n=N(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=w(n)}catch{return[]}return Gke.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>N(n,e.entry)))}function k7(e){if(!g(e))return[];try{let t=new Map;for(let n of w(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>N(e,t))}catch{return[]}}function A7(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=w(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(D7),i=[],a=r.filter(t=>{try{return S(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!D7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function Kke(e){let t=N(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,Fu].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function qke(e){let t=N(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function Jke(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ne(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function j7(e){let t=e.revealDocNames?e.content:Jke(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=CB(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function M7(e){for(let t of e.files)try{let n=S(t,`utf8`);j7({zipfile:e.zipfile,name:`${e.prefix}/${me(t)}`,content:t.endsWith(`.ips`)?w7(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function Yke(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??N(k(),`.ok`,`logs`),s=t.projectDir?E7(t.projectDir,i):null;v(M(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=Hke();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=A7(s,o),{files:d}=t.projectDir?Kke(t.projectDir):{files:[]},{files:f}=t.projectDir?qke(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await Promise.resolve().then(()=>e(i4(),1)),b=new y;M7({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:qL,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??me(e.sourcePath)}`;b.addBuffer(t,n),_.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&j7({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${me(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`);let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${me(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${qL}/${me(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!D7(e)&&!O.has(e)):[],ie=C.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ae=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],oe=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...re.map(e=>`- ${e}`),``]:[],...ee.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...ee.map(e=>`- ${e}`),``]:[],...C.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...C.map(e=>`- ${e}`),``]:[],...ne.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${SB.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:ae].join(`
1516
- `);b.addBuffer(Buffer.from(oe,`utf8`),`README.md`),b.end();let se=h(r);return b.outputStream.pipe(se),await new Promise((e,t)=>{se.on(`close`,e),se.on(`error`,t)}),i?.info({bundlePath:r,fileCount:_.length,redactionCount:D},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:_,redactions:g,redactedLineCount:D,generatedAt:E.generatedAt}}}function N7(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function P7(e){return Ne(`sha256`).update(e).digest(`hex`)}function F7(e){return N(be(e),`.ok`,`pi-trust`)}function I7(e,t){return N(F7(e),P7(be(t)))}function L7(e,t,n){return N(I7(e,t),`${P7(n)}.json`)}var R7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${N7(e)} ${N7(t)}; ${N7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function z7(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new R7(e,`could not ${t}: ${i}`,a,n)}function B7(e){let t;try{t=_(e)}catch(t){if(t.code===`ENOENT`)return!1;throw z7(e,`be inspected`,t)}if(!t.isDirectory())throw new R7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function V7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function H7(e,t){if(!q8(e)||!V7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==be(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==be(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==be(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!q8(e.previous))throw new R7(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&V7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&V7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new R7(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function U7(e,t,n){let r;try{r=_(n)}catch(e){throw z7(n,`be inspected`,e)}if(!r.isFile())throw new R7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=S(n,`utf8`)}catch(e){throw z7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new R7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=H7(a,n);if(o.cwd!==be(t)||n!==L7(e,t,o.canonicalTrustPath))throw new R7(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function W7(e,t){let{record:n,path:r}=t;for(let t of[F7(e),I7(e,n.cwd)])if(!B7(t))throw new R7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=U7(e,n.cwd,r);if(!Le(i.record,n))throw new R7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function Xke(e,t,n,r,i){let a={version:1,cwd:be(t),configuredTrustPath:be(n),canonicalTrustPath:be(r),state:`pending`,previous:i},o=L7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Le(H7(JSON.parse(s),o),a))throw new R7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);B7(F7(e)),B7(M(o));try{v(M(o),{recursive:!0,mode:448})}catch(e){throw z7(M(o),`be created`,e)}let c;try{c=_(o,{throwIfNoEntry:!1})}catch(e){throw z7(o,`be inspected`,e)}if(c)throw new R7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{NQ(o,s,{mode:384})}catch(e){throw z7(o,`be written`,e)}return{path:o,record:a}}function Zke(e,t){let n=W7(e,t);if(n.record.state!==`pending`)throw new R7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{NQ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw z7(n.path,`be committed`,e)}return{path:n.path,record:r}}function G7(e,t){if(!B7(F7(e)))return[];let n=I7(e,t);if(!B7(n))return[];let r;try{r=w(n).sort()}catch(e){throw z7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>U7(e,t,N(n,r)))}function K7(e,t){let n=W7(e,t);try{ne(n.path)}catch(e){throw z7(n.path,`be removed after reconciling its grant`,e)}for(let t of[M(n.path),F7(e)])try{ee(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw z7(t,`be removed after reconciling its grant`,e)}}var Qke=i(((e,n)=>{var r=t(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),$ke=i(((e,n)=>{var r=t(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),eAe=i(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),q7=i(((e,n)=>{var r=t(`fs`),i=Qke(),a=$ke(),o=eAe(),s=t(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
1517
- GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),t(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),tAe=i(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),nAe=i((e=>{var t=tAe();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),rAe=i(((e,t)=>{t.exports=nAe()})),iAe=i(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),aAe=i(((e,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=t(`assert`),o=iAe(),s=/^win/i.test(r.platform),c=t(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),oAe=i(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),sAe=i(((e,n)=>{let r=t(`path`),i=q7(),a=rAe(),o=aAe(),s=oAe(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),cAe=i(((e,t)=>{let n=q7();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),J7=e(i(((e,t)=>{let n=sAe(),{toPromise:r,toSync:i,toSyncOptions:a}=cAe();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const Y7=5e3;function X7(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${Y7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Z7(e,t){}function Q7(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function lAe(e,t,n){await Abe(`${t}.ok.lock`,async()=>{let t=performance.now()+Y7,r;for(;;)try{r=await J7.default.lock(M(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await ze(X7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}Q7(i,e)},{onWarn:Z7})}function uAe(e,t,n){FQ(`${t}.ok.lock`,()=>{let t=performance.now()+Y7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=J7.default.lockSync(M(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,X7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}Q7(a,e)},{onWarn:Z7})}const dAe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var $7=class extends Error{name=`PiResourceInspectionError`};function e9(e){let t;try{t=_(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=te(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new $7(i7(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function fAe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function pAe(e,t,n){let r=e;try{let i=E(e),a;r=t;try{a=E(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=be(t)}let o=N(a,`.agents`,`skills`),s=[];for(let e of dAe)r=N(i,`.pi`,e),e9(r)&&s.push(r);if(r=N(i,`.pi`,`extensions`),e9(r))for(let t of w(r).sort()){let i=N(r,t);be(n)!==N(be(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[N(i,`.pi`,`skills`),N(i,`.agents`,`skills`)])if(e!==o&&(r=e,e9(e)))for(let t of w(e).sort())fAe(t)||s.push(N(e,t));let c=M(i);for(;c!==i;){r=N(c,`.agents`,`skills`),r!==o&&e9(r)&&s.push(r);let e=M(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${N7(r)}: ${e instanceof $7?e.message:i7(r7(e))}`}}}function t9(e){let t;try{t=_(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:r7(e)}}let n=K5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!te(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:r7(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function n9(e,t,n){let r=be(e),i=k5({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:j5.pi.projectConfigPath(r),trustPath:N(i,`trust.json`)}}function r9(e){try{let t=E(e);return te(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${N7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${N7(e)} could not be resolved or accessed: ${N7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function i9(e){let t=r9(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${N7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function a9(e,t,n){let r=b7(j5.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return d5(i)?{state:`own-current`,text:a}:I5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function o9(e,t){let n;try{n=S(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:r7(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return q8(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
1518
- `)}:{state:`unreadable`,reason:`invalid-json`}}function mAe(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return i7(e)}}function s9(e,t){return{kind:`refused`,error:`trust store ${N7(e)}: ${mAe(t)}`}}function c9(e){let t=t9(e);try{switch(t.kind){case`declined`:return s9(e,t.reason);case`ready`:return{kind:`ready`,path:E(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=M(e),r=[me(e)],i=_(n,{throwIfNoEntry:!1});for(;!i;){let t=M(n);if(t===n)return s9(e,`unavailable-root`);r.unshift(me(n)),n=t,i=_(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:N(E(n),...r)}}catch(t){return s9(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:r7(t))}}catch(t){return s9(e,r7(t))}}function l9(e,t){let n=c9(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?s9(e,`path-changed`):n}function hAe(e,t,n){let r=n9(e,t,n),i=r9(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=a9(r.cwd,r.bridgePath,t).state,o=c9(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:o9(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:gAe(r.bridgePath).displayNames}}function gAe(e){let t=M(e),n=me(e);try{return{displayNames:w(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>N7(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function _Ae(e,t={mode:`published`},n,r,i){let a=n9(e,n,r),o=r9(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${N7(i)} no longer matches the current directory ${N7(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=a9(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=L5(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=_7(j5.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:N7(e.error)}}let l=await vAe(a.trustPath,o.project,n??k());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function vAe(e,t,n){let r=t.canonical,i=c9(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{v(M(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await lAe(e,i.path,()=>{let o=i9(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=l9(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=o9(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=s9(e,c.reason).error;return}let l=d9(n,()=>{let t=G7(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&K7(n,t),Xke(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
1519
- `:``),f=o7(s.path);NQ(s.path,d,f===void 0?void 0:{mode:f}),d9(n,()=>Zke(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}return a}function yAe(e){let t=[],n=e;try{for(;;){if(_(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=E(n);return te(e).isDirectory()?(d(e,p.X_OK),N(e,...t)):void 0}let e=M(n);if(e===n)return;t.unshift(me(n)),n=e}}catch{return}}function u9(e){let t={"not-present":0,removed:1,"kept-unowned":2,"kept-shared":3,"kept-unverified":4,"refused-unreadable":5,failed:6},n=e.reduce((e,n)=>t[n.action]>t[e.action]?n:e,{action:`not-present`}),r=e.flatMap(e=>e.error??[]),i=e.flatMap(e=>e.detail??[]);return r.length>0?{action:n.error===void 0?`failed`:n.action,error:[...r,...i].join(`
1515
+ `));let _=`${s?``:``}${m}`;return _!==o&&NQ(e,_,{mode:o7(e)}),a&&_===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const Tke=`open-knowledge-ui`;function h7(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return g(r)}catch{return!1}}function g7(e,t,n){try{let r=be(M(e.configPath(t,n))),i=be(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+xe)}catch{return!1}}function _7(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!g(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||g7(e,t,r);if(!i&&c&&!h7(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{R5(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return Dke(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||v(M(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{FQ(`${o}.lock`,()=>{let t=K5(o).writePath;if(s||v(M(t),{recursive:!0}),e.format===`toml`){let r=xke($8(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=wke(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=bke(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Eke={pi:L5};function Dke(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Eke[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{v(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{FQ(`${t}.lock`,()=>{let e=null;try{e=S(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}NQ(t,c,e===null?void 0:{mode:o7(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}async function Oke(e){let t=DOe(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>_7(t,``,n,e.home))}function v7(e,t,n,r){let i=b7(e,t,n,r);return i.kind===`present`?i.entry:null}function y7(e,t,n,r){let i=m7(e,t,r);if(!q8(i))return{kind:`no-entry`};let a=i[n];return q8(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function b7(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!g(i))return{kind:`absent`};try{if(te(i).size>u7)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:r7(e)}}let a;try{a=S(i,`utf-8`)}catch(e){return{kind:`decline`,reason:r7(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:WOe(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=$8().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return y7(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,tn.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:y7(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=s7(a);return s?c7(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:y7(x4(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function kke(e,t){let n=[];for(let r of e5)r!==`claude-desktop`&&h7(j5[r],e,t)&&n.push(r);return n}function x7(e){return e===`opencode`?gOe:hOe}function Ake(e,t,n){let r=j5[e],i=x7(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=v7(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}const S7=8192;function C7(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function jke(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Mke=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Nke(e){return e.replace(Mke,`$1"[REDACTED-DEVICE-ID]"`)}function w7(e){return Nke(jke(e))}const Pke=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Fke(e){if(typeof e!=`string`)return null;let t=Pke.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function Ike(e){let t=b(e,`r`);try{let e=Buffer.alloc(S7),n=0,r=!1;for(;n<S7;){let i=C(t,e,n,S7-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{f(t)}}function Lke(e){try{let t=Ike(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Fke(a)}}catch{return{kind:`unreadable`}}}function Rke(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function zke(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=w(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=N(e,t.name),r;try{r=te(n).mtimeMs}catch{continue}if(r<i)continue;let c=Lke(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Rke(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function T7(){return N(k(),`.ok`,`bug-reports`)}function Bke(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=T7(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function E7(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let e=S(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return g(N(e,`.ok`))?Ne(`sha256`).update(be(e)).digest(`hex`).slice(0,12):null}function Vke(){let e={timestamp:new Date().toISOString(),platform:le(),osType:de(),osRelease:ue(),hostname:`[redacted]`,uptime:fe(),freeMem:se(),totalMem:j(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,W6({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const Hke=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function D7(e){let t=me(e);return Hke.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function Uke(e,t){return A7(e,t).files}const Wke=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function O7(e,t=`com.inkeep.open-knowledge`){let n=N(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=w(n)}catch{return[]}return Wke.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>N(n,e.entry)))}function k7(e){if(!g(e))return[];try{let t=new Map;for(let n of w(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>N(e,t))}catch{return[]}}function A7(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=w(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(D7),i=[],a=r.filter(t=>{try{return S(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!D7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function Gke(e){let t=N(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,Fu].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function Kke(e){let t=N(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function qke(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ne(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function j7(e){let t=e.revealDocNames?e.content:qke(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=CB(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function M7(e){for(let t of e.files)try{let n=S(t,`utf8`);j7({zipfile:e.zipfile,name:`${e.prefix}/${me(t)}`,content:t.endsWith(`.ips`)?w7(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function Jke(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??N(k(),`.ok`,`logs`),s=t.projectDir?E7(t.projectDir,i):null;v(M(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=Vke();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=A7(s,o),{files:d}=t.projectDir?Gke(t.projectDir):{files:[]},{files:f}=t.projectDir?Kke(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await Promise.resolve().then(()=>e(i4(),1)),b=new y;M7({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:qL,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),M7({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??me(e.sourcePath)}`;b.addBuffer(t,n),_.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&j7({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${me(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`);let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${me(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${qL}/${me(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!D7(e)&&!O.has(e)):[],ie=C.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ae=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],oe=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...re.map(e=>`- ${e}`),``]:[],...ee.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...ee.map(e=>`- ${e}`),``]:[],...C.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...C.map(e=>`- ${e}`),``]:[],...ne.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${SB.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:ae].join(`
1516
+ `);b.addBuffer(Buffer.from(oe,`utf8`),`README.md`),b.end();let se=h(r);return b.outputStream.pipe(se),await new Promise((e,t)=>{se.on(`close`,e),se.on(`error`,t)}),i?.info({bundlePath:r,fileCount:_.length,redactionCount:D},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:_,redactions:g,redactedLineCount:D,generatedAt:E.generatedAt}}}function N7(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function P7(e){return Ne(`sha256`).update(e).digest(`hex`)}function F7(e){return N(be(e),`.ok`,`pi-trust`)}function I7(e,t){return N(F7(e),P7(be(t)))}function L7(e,t,n){return N(I7(e,t),`${P7(n)}.json`)}var R7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${N7(e)} ${N7(t)}; ${N7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function z7(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new R7(e,`could not ${t}: ${i}`,a,n)}function B7(e){let t;try{t=_(e)}catch(t){if(t.code===`ENOENT`)return!1;throw z7(e,`be inspected`,t)}if(!t.isDirectory())throw new R7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function V7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function H7(e,t){if(!q8(e)||!V7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==be(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==be(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==be(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!q8(e.previous))throw new R7(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&V7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&V7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new R7(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function U7(e,t,n){let r;try{r=_(n)}catch(e){throw z7(n,`be inspected`,e)}if(!r.isFile())throw new R7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=S(n,`utf8`)}catch(e){throw z7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new R7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=H7(a,n);if(o.cwd!==be(t)||n!==L7(e,t,o.canonicalTrustPath))throw new R7(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function W7(e,t){let{record:n,path:r}=t;for(let t of[F7(e),I7(e,n.cwd)])if(!B7(t))throw new R7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=U7(e,n.cwd,r);if(!Le(i.record,n))throw new R7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function Yke(e,t,n,r,i){let a={version:1,cwd:be(t),configuredTrustPath:be(n),canonicalTrustPath:be(r),state:`pending`,previous:i},o=L7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Le(H7(JSON.parse(s),o),a))throw new R7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);B7(F7(e)),B7(M(o));try{v(M(o),{recursive:!0,mode:448})}catch(e){throw z7(M(o),`be created`,e)}let c;try{c=_(o,{throwIfNoEntry:!1})}catch(e){throw z7(o,`be inspected`,e)}if(c)throw new R7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{NQ(o,s,{mode:384})}catch(e){throw z7(o,`be written`,e)}return{path:o,record:a}}function Xke(e,t){let n=W7(e,t);if(n.record.state!==`pending`)throw new R7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{NQ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw z7(n.path,`be committed`,e)}return{path:n.path,record:r}}function G7(e,t){if(!B7(F7(e)))return[];let n=I7(e,t);if(!B7(n))return[];let r;try{r=w(n).sort()}catch(e){throw z7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>U7(e,t,N(n,r)))}function K7(e,t){let n=W7(e,t);try{ne(n.path)}catch(e){throw z7(n.path,`be removed after reconciling its grant`,e)}for(let t of[M(n.path),F7(e)])try{ee(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw z7(t,`be removed after reconciling its grant`,e)}}var Zke=i(((e,n)=>{var r=t(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),Qke=i(((e,n)=>{var r=t(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),$ke=i(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),q7=i(((e,n)=>{var r=t(`fs`),i=Zke(),a=Qke(),o=$ke(),s=t(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
1517
+ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),t(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),eAe=i(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),tAe=i((e=>{var t=eAe();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),nAe=i(((e,t)=>{t.exports=tAe()})),rAe=i(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),iAe=i(((e,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=t(`assert`),o=rAe(),s=/^win/i.test(r.platform),c=t(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),aAe=i(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),oAe=i(((e,n)=>{let r=t(`path`),i=q7(),a=nAe(),o=iAe(),s=aAe(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),sAe=i(((e,t)=>{let n=q7();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),J7=e(i(((e,t)=>{let n=oAe(),{toPromise:r,toSync:i,toSyncOptions:a}=sAe();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const Y7=5e3;function X7(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${Y7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Z7(e,t){}function Q7(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function cAe(e,t,n){await Abe(`${t}.ok.lock`,async()=>{let t=performance.now()+Y7,r;for(;;)try{r=await J7.default.lock(M(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await ze(X7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}Q7(i,e)},{onWarn:Z7})}function lAe(e,t,n){FQ(`${t}.ok.lock`,()=>{let t=performance.now()+Y7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=J7.default.lockSync(M(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,X7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}Q7(a,e)},{onWarn:Z7})}const uAe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var $7=class extends Error{name=`PiResourceInspectionError`};function e9(e){let t;try{t=_(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=te(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new $7(i7(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function dAe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function fAe(e,t,n){let r=e;try{let i=E(e),a;r=t;try{a=E(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=be(t)}let o=N(a,`.agents`,`skills`),s=[];for(let e of uAe)r=N(i,`.pi`,e),e9(r)&&s.push(r);if(r=N(i,`.pi`,`extensions`),e9(r))for(let t of w(r).sort()){let i=N(r,t);be(n)!==N(be(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[N(i,`.pi`,`skills`),N(i,`.agents`,`skills`)])if(e!==o&&(r=e,e9(e)))for(let t of w(e).sort())dAe(t)||s.push(N(e,t));let c=M(i);for(;c!==i;){r=N(c,`.agents`,`skills`),r!==o&&e9(r)&&s.push(r);let e=M(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${N7(r)}: ${e instanceof $7?e.message:i7(r7(e))}`}}}function t9(e){let t;try{t=_(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:r7(e)}}let n=K5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!te(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:r7(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function n9(e,t,n){let r=be(e),i=k5({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:j5.pi.projectConfigPath(r),trustPath:N(i,`trust.json`)}}function r9(e){try{let t=E(e);return te(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${N7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${N7(e)} could not be resolved or accessed: ${N7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function i9(e){let t=r9(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${N7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function a9(e,t,n){let r=b7(j5.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return d5(i)?{state:`own-current`,text:a}:I5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function o9(e,t){let n;try{n=S(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:r7(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return q8(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
1518
+ `)}:{state:`unreadable`,reason:`invalid-json`}}function pAe(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return i7(e)}}function s9(e,t){return{kind:`refused`,error:`trust store ${N7(e)}: ${pAe(t)}`}}function c9(e){let t=t9(e);try{switch(t.kind){case`declined`:return s9(e,t.reason);case`ready`:return{kind:`ready`,path:E(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=M(e),r=[me(e)],i=_(n,{throwIfNoEntry:!1});for(;!i;){let t=M(n);if(t===n)return s9(e,`unavailable-root`);r.unshift(me(n)),n=t,i=_(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:N(E(n),...r)}}catch(t){return s9(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:r7(t))}}catch(t){return s9(e,r7(t))}}function l9(e,t){let n=c9(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?s9(e,`path-changed`):n}function mAe(e,t,n){let r=n9(e,t,n),i=r9(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=a9(r.cwd,r.bridgePath,t).state,o=c9(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:o9(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:hAe(r.bridgePath).displayNames}}function hAe(e){let t=M(e),n=me(e);try{return{displayNames:w(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>N7(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function gAe(e,t={mode:`published`},n,r,i){let a=n9(e,n,r),o=r9(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${N7(i)} no longer matches the current directory ${N7(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=a9(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=L5(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=_7(j5.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:N7(e.error)}}let l=await _Ae(a.trustPath,o.project,n??k());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function _Ae(e,t,n){let r=t.canonical,i=c9(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{v(M(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await cAe(e,i.path,()=>{let o=i9(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=l9(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=o9(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=s9(e,c.reason).error;return}let l=d9(n,()=>{let t=G7(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&K7(n,t),Yke(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
1519
+ `:``),f=o7(s.path);NQ(s.path,d,f===void 0?void 0:{mode:f}),d9(n,()=>Xke(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}return a}function vAe(e){let t=[],n=e;try{for(;;){if(_(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=E(n);return te(e).isDirectory()?(d(e,p.X_OK),N(e,...t)):void 0}let e=M(n);if(e===n)return;t.unshift(me(n)),n=e}}catch{return}}function u9(e){let t={"not-present":0,removed:1,"kept-unowned":2,"kept-shared":3,"kept-unverified":4,"refused-unreadable":5,failed:6},n=e.reduce((e,n)=>t[n.action]>t[e.action]?n:e,{action:`not-present`}),r=e.flatMap(e=>e.error??[]),i=e.flatMap(e=>e.detail??[]);return r.length>0?{action:n.error===void 0?`failed`:n.action,error:[...r,...i].join(`
1520
1520
  `)}:n.detail===void 0?n:{...n,detail:i.join(`
1521
- `)}}function bAe(e,t,n,r={}){let i=n9(e,t,n),a=t??k(),o=r9(i.cwd),s=o.kind===`refused`&&r.recordedOnly?yAe(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=d9(a,()=>{let e=G7(a,i.cwd);return c===void 0||c===i.cwd?e:[...G7(a,c),...e]})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}if(l.length===0&&r.recordedOnly)return o.kind===`ready`||s!==void 0?{action:`not-present`}:{action:`kept-unverified`,error:`${o.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`};if(o.kind===`refused`){if(l.length===0)return{action:`kept-unverified`,error:o.error};let e=l.map(({path:e,record:t})=>`key ${N7(JSON.stringify(t.cwd))}; configured store ${N7(JSON.stringify(t.configuredTrustPath))}; recorded destination ${N7(JSON.stringify(t.canonicalTrustPath))}; ownership record ${N7(JSON.stringify(e))} (${t.state})`);return{action:`kept-unverified`,error:[`${o.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,...e,`To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.`].join(`
1522
- `)}}let u=pAe(o.project.canonical,a,j5.pi.projectConfigPath(o.project.canonical));if(u.kind===`unreadable`)return{action:`kept-unverified`,error:u.error};let d=u.kind===`shared`?u.paths:[],f=[],p=new Map,m=(e,t)=>{let n=p.get(e);if(!n){let t=c9(e);if(t.kind===`refused`){f.push({action:`refused-unreadable`,error:t.error});return}n={trustPath:e,resolved:t,keys:new Map},p.set(e,n)}if(t){if(n.resolved.path!==t.record.canonicalTrustPath){f.push({action:`refused-unreadable`,error:`Pi trust store ${N7(e)} no longer points to its recorded destination ${N7(t.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`});return}n.keys.set(t.record.cwd,{cwd:t.record.cwd,mode:`recorded`,receipt:t})}};for(let e of l)m(e.record.configuredTrustPath,e);m(i.trustPath);for(let e of p.values()){for(let t of[o.project.canonical,i.cwd])e.keys.has(t)||e.keys.set(t,{cwd:t,mode:`inspect`,receipt:l.find(n=>n.record.cwd===t&&n.record.canonicalTrustPath===e.resolved.path)});f.push(xAe(e,a,d,o.project))}return u9(f)}function d9(e,t){try{return t()}catch(t){throw t instanceof R7?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${N7(N(e,`.ok`,`pi-trust`))}: ${N7(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function xAe(e,t,n,r){let{trustPath:i,resolved:a}=e,o=[...e.keys.values()];if(!o.some(e=>e.mode===`recorded`)&&a.kind===`missing`)return{action:`not-present`};if(a.kind===`missing`)try{_(M(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${N7(M(a.path))} is unavailable: ${N7(e instanceof Error?e.message:String(e))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`}}let s=[],c={result:{action:`not-present`}};try{uAe(i,a.path,()=>{let e=i9(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=l9(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=o9(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:s9(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:d9(t,()=>G7(t,e.cwd).find(e=>e.record.canonicalTrustPath===l.path))}));if(d.some(e=>e.receipt&&e.receipt.record.configuredTrustPath!==e.expectedConfiguredPath)){c.result={action:`failed`,error:`The Pi trust ownership record changed during cleanup; retry to read its current location.`};return}for(let e of d){try{SAe(e,t,i,l.path,u,n,r,c)}catch(t){let n=N7(t instanceof Error?t.message:String(t)),r=t instanceof R7?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${N7(JSON.stringify(e.cwd))} in ${N7(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:N7(e instanceof Error?e.message:String(e))})}return u9([...s,c.result])}function SAe(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&d9(t,()=>K7(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${N7(JSON.stringify(c))} entry from ${N7(n)}; parent-folder and global trust settings still apply.`;if(a.length>0&&c===o.canonical){let n=`kept Pi's folder trust because other resources still need it: ${a.slice(0,3).map(e=>N7(JSON.stringify(e))).join(`, `)}${a.length>3?` (+${a.length-3} more)`:``}. ${u} Removing this grant may stop Pi from loading those resources, including any not listed here.`;s.result={action:`kept-shared`,detail:n},l&&e.mode===`recorded`&&d9(t,()=>K7(t,l)),s.result={action:`kept-shared`,detail:`${n} ${l?e.mode===`recorded`?`OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.`:`OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.`:`OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.`}`};return}if(e.mode===`inspect`||!l||l.record.state===`pending`){let e=l?l.record.state===`pending`?`its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.`:`OpenKnowledge must reconcile its recorded location at ${N7(l.record.configuredTrustPath)} before removing it.`:`no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.`;s.result={action:`kept-unowned`,detail:`${c===o.canonical?`kept Pi's folder trust because ${e}`:`kept a Pi trust entry under a non-canonical project path because ${e} Pi uses the real project directory instead of this key.`} ${u}`};return}let d={...i.entries};l.record.previous.present?d[c]=l.record.previous.value:delete d[c];let f=JSON.stringify(d,null,2)+(i.trailingNewline?`
1523
- `:``),p=o7(r);NQ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,d9(t,()=>K7(t,l)),s.result={action:`removed`}}function CAe(e){return d5(e)||m5(e)||I5(e)}const f9=10485760;function p9(e,t,n,r=!1){let i=bAe(e,t,n,{recordedOnly:r});switch(i.action){case`removed`:case`not-present`:return{trust:i.action};case`kept-shared`:case`kept-unowned`:return{trust:i.action,trustDetail:i.detail};case`failed`:case`refused-unreadable`:case`kept-unverified`:{let e=r?`Trust cleanup remains incomplete`:`The bridge file was left untouched`;throw Error(`Pi trust cleanup failed (${i.action}):\n${i.error}\n${e} so cleanup can be retried.`)}default:throw Error(`unhandled Pi trust cleanup result: ${i}`)}}function m9(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=p9(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function wAe(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=t9(a);if(o.kind===`not-present`)return m9(e,t,n,i);if(o.kind===`declined`)return o;let s=b7(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return m9(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!CAe(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=p9(t,n,i);try{O(a,{force:!0})}catch(t){throw e.trustDetail?Error(`${t instanceof Error?t.message:String(t)}\n${e.trustDetail}`,{cause:t}):t}return{kind:`removed`,...e}}return e.format===`toml`?DAe(o.path,c):e.format===`yaml`?EAe(o.path,e.topLevelKey,c):TAe(o.path,e.topLevelKey,e.serverMapSubKey,c)}function TAe(e,t,n,r){let i;try{i=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}if(Buffer.byteLength(i,`utf-8`)>f9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=mke(i,f7(t,n,r));return o?(NQ(e,a,{mode:o7(e)}),{kind:`removed`}):{kind:`not-present`}}function EAe(e,t,n){let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}if(Buffer.byteLength(r,`utf-8`)>f9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,tn.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=a7(a);a.trim()===``||a.endsWith(`
1521
+ `)}}function yAe(e,t,n,r={}){let i=n9(e,t,n),a=t??k(),o=r9(i.cwd),s=o.kind===`refused`&&r.recordedOnly?vAe(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=d9(a,()=>{let e=G7(a,i.cwd);return c===void 0||c===i.cwd?e:[...G7(a,c),...e]})}catch(e){return{action:`failed`,error:N7(e instanceof Error?e.message:String(e))}}if(l.length===0&&r.recordedOnly)return o.kind===`ready`||s!==void 0?{action:`not-present`}:{action:`kept-unverified`,error:`${o.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`};if(o.kind===`refused`){if(l.length===0)return{action:`kept-unverified`,error:o.error};let e=l.map(({path:e,record:t})=>`key ${N7(JSON.stringify(t.cwd))}; configured store ${N7(JSON.stringify(t.configuredTrustPath))}; recorded destination ${N7(JSON.stringify(t.canonicalTrustPath))}; ownership record ${N7(JSON.stringify(e))} (${t.state})`);return{action:`kept-unverified`,error:[`${o.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,...e,`To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.`].join(`
1522
+ `)}}let u=fAe(o.project.canonical,a,j5.pi.projectConfigPath(o.project.canonical));if(u.kind===`unreadable`)return{action:`kept-unverified`,error:u.error};let d=u.kind===`shared`?u.paths:[],f=[],p=new Map,m=(e,t)=>{let n=p.get(e);if(!n){let t=c9(e);if(t.kind===`refused`){f.push({action:`refused-unreadable`,error:t.error});return}n={trustPath:e,resolved:t,keys:new Map},p.set(e,n)}if(t){if(n.resolved.path!==t.record.canonicalTrustPath){f.push({action:`refused-unreadable`,error:`Pi trust store ${N7(e)} no longer points to its recorded destination ${N7(t.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`});return}n.keys.set(t.record.cwd,{cwd:t.record.cwd,mode:`recorded`,receipt:t})}};for(let e of l)m(e.record.configuredTrustPath,e);m(i.trustPath);for(let e of p.values()){for(let t of[o.project.canonical,i.cwd])e.keys.has(t)||e.keys.set(t,{cwd:t,mode:`inspect`,receipt:l.find(n=>n.record.cwd===t&&n.record.canonicalTrustPath===e.resolved.path)});f.push(bAe(e,a,d,o.project))}return u9(f)}function d9(e,t){try{return t()}catch(t){throw t instanceof R7?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${N7(N(e,`.ok`,`pi-trust`))}: ${N7(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function bAe(e,t,n,r){let{trustPath:i,resolved:a}=e,o=[...e.keys.values()];if(!o.some(e=>e.mode===`recorded`)&&a.kind===`missing`)return{action:`not-present`};if(a.kind===`missing`)try{_(M(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${N7(M(a.path))} is unavailable: ${N7(e instanceof Error?e.message:String(e))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`}}let s=[],c={result:{action:`not-present`}};try{lAe(i,a.path,()=>{let e=i9(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=l9(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=o9(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:s9(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:d9(t,()=>G7(t,e.cwd).find(e=>e.record.canonicalTrustPath===l.path))}));if(d.some(e=>e.receipt&&e.receipt.record.configuredTrustPath!==e.expectedConfiguredPath)){c.result={action:`failed`,error:`The Pi trust ownership record changed during cleanup; retry to read its current location.`};return}for(let e of d){try{xAe(e,t,i,l.path,u,n,r,c)}catch(t){let n=N7(t instanceof Error?t.message:String(t)),r=t instanceof R7?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${N7(JSON.stringify(e.cwd))} in ${N7(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:N7(e instanceof Error?e.message:String(e))})}return u9([...s,c.result])}function xAe(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&d9(t,()=>K7(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${N7(JSON.stringify(c))} entry from ${N7(n)}; parent-folder and global trust settings still apply.`;if(a.length>0&&c===o.canonical){let n=`kept Pi's folder trust because other resources still need it: ${a.slice(0,3).map(e=>N7(JSON.stringify(e))).join(`, `)}${a.length>3?` (+${a.length-3} more)`:``}. ${u} Removing this grant may stop Pi from loading those resources, including any not listed here.`;s.result={action:`kept-shared`,detail:n},l&&e.mode===`recorded`&&d9(t,()=>K7(t,l)),s.result={action:`kept-shared`,detail:`${n} ${l?e.mode===`recorded`?`OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.`:`OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.`:`OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.`}`};return}if(e.mode===`inspect`||!l||l.record.state===`pending`){let e=l?l.record.state===`pending`?`its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.`:`OpenKnowledge must reconcile its recorded location at ${N7(l.record.configuredTrustPath)} before removing it.`:`no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.`;s.result={action:`kept-unowned`,detail:`${c===o.canonical?`kept Pi's folder trust because ${e}`:`kept a Pi trust entry under a non-canonical project path because ${e} Pi uses the real project directory instead of this key.`} ${u}`};return}let d={...i.entries};l.record.previous.present?d[c]=l.record.previous.value:delete d[c];let f=JSON.stringify(d,null,2)+(i.trailingNewline?`
1523
+ `:``),p=o7(r);NQ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,d9(t,()=>K7(t,l)),s.result={action:`removed`}}function SAe(e){return d5(e)||m5(e)||I5(e)}const f9=10485760;function p9(e,t,n,r=!1){let i=yAe(e,t,n,{recordedOnly:r});switch(i.action){case`removed`:case`not-present`:return{trust:i.action};case`kept-shared`:case`kept-unowned`:return{trust:i.action,trustDetail:i.detail};case`failed`:case`refused-unreadable`:case`kept-unverified`:{let e=r?`Trust cleanup remains incomplete`:`The bridge file was left untouched`;throw Error(`Pi trust cleanup failed (${i.action}):\n${i.error}\n${e} so cleanup can be retried.`)}default:throw Error(`unhandled Pi trust cleanup result: ${i}`)}}function m9(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=p9(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function CAe(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=t9(a);if(o.kind===`not-present`)return m9(e,t,n,i);if(o.kind===`declined`)return o;let s=b7(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return m9(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!SAe(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=p9(t,n,i);try{O(a,{force:!0})}catch(t){throw e.trustDetail?Error(`${t instanceof Error?t.message:String(t)}\n${e.trustDetail}`,{cause:t}):t}return{kind:`removed`,...e}}return e.format===`toml`?EAe(o.path,c):e.format===`yaml`?TAe(o.path,e.topLevelKey,c):wAe(o.path,e.topLevelKey,e.serverMapSubKey,c)}function wAe(e,t,n,r){let i;try{i=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}if(Buffer.byteLength(i,`utf-8`)>f9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=pke(i,f7(t,n,r));return o?(NQ(e,a,{mode:o7(e)}),{kind:`removed`}):{kind:`not-present`}}function TAe(e,t,n){let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}if(Buffer.byteLength(r,`utf-8`)>f9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,tn.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=a7(a);a.trim()===``||a.endsWith(`
1524
1524
  `)?c.endsWith(`
1525
1525
  `)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
1526
1526
  `).replace(/\n/g,`\r
1527
- `));let u=`${i?``:``}${c}`;return u!==r&&NQ(e,u,{mode:o7(e)}),{kind:`removed`}}function DAe(e,t){let n=$8();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=a7(a),s=a.trim()===``||a.endsWith(`
1527
+ `));let u=`${i?``:``}${c}`;return u!==r&&NQ(e,u,{mode:o7(e)}),{kind:`removed`}}function EAe(e,t){let n=$8();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:r7(e)}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=a7(a),s=a.trim()===``||a.endsWith(`
1528
1528
  `),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
1529
1529
  `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
1530
1530
  `).replace(/\n/g,`\r
1531
- `));let u=`${i?``:``}${l}`;return u!==r&&NQ(e,u,{mode:o7(e)}),{kind:`removed`}}function OAe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function kAe(e){let{priorCommand:t,priorArgs:n}=h9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function h9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function g9(e,t,n={}){let r=gDe(e,t),i;try{i=S(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r}}let o=a&&typeof a==`object`?a:{},s=`machineId`in o&&typeof o.machineId==`string`?o.machineId!==(n.machineId??hDe()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??ce());if(!a||typeof a!=`object`||!wEe(a.pid))return{status:`corrupt`,lockPath:r,...s?{foreignHost:!0}:{}};let c=a.pid,l=`machineId`in o&&typeof o.machineId==`string`||`hostname`in o&&typeof o.hostname==`string`;return s?{status:`foreign-host`,lockPath:r,lock:a}:(n.isAlive??V6)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}async function AAe(e,t=void 0){let n=g9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=vDe(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500),redirect:`manual`});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function jAe(e,t={}){return{targets:NAe(e,t.isAlive??V6)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}async function MAe(e){let t=e.inspect??(()=>g9(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??AAe,o=e.logger??void 0,s=jAe(t(),{isAlive:e.isAlive});if(s.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:s.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let c=[],l=[];for(let e of s.targets)try{n(e.pid,`SIGTERM`),c.push(e)}catch(t){l.push({target:e,error:t instanceof Error?t.message:String(t)})}return c.length>0&&r(`Stopped: ${c.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:c.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:l.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),l.length>0&&i(`Failed to stop: ${l.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:c,failed:l,hadTargets:!0}}function NAe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function _9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,tn.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return q8(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function PAe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=lu({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function FAe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=LQ(`user`,t),s=AQ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=_9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=ju({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?Nu(i.value):i.value;return t&&a.push(...oR({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=be(t,`.ok`,`config.yml`),u=c(l,!0),d=c(LQ(`project-local`,t)),f=sR(s.value,u,d),p=jDe.safeParse(f);if(!p.success){let e=_9(l),t={code:`SCHEMA_INVALID`,issues:PAe(p.error.issues,e)};throw Error(Eu(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function v9(e){return e.replace(/:\d+$/,``)}function y9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function b9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=hR(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function x9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=hR(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function IAe(e){let t=b9(e);if(t)return{kind:`doc`,...t};let n=x9(e);return n?{kind:`folder`,...n}:null}async function LAe(e,t){let n,r;try{n=await De(be(e)),r=await De(be(M(e)))}catch{return{kind:`not-git`}}if(!S9(n,r))return{kind:`symlink-escape`};let i=N(n,`.git`),a;try{a=te(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await De(i)}catch{return{kind:`not-git`}}if(!S9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=z_e(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=y9(c);if(l===null)return{kind:`non-github`};let u=hR(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function S9(e,t){if(e===t)return!0;let n=ye(t,e);return n.length>0&&!n.startsWith(`..`)&&!ge(n)}const RAe=`# >>> open-knowledge cli >>>`,zAe=`# <<< open-knowledge cli <<<`,BAe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function VAe(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}function C9(e,t,n=[]){let r=g(N(e,y8[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function HAe(e,t){let n=e5.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=un.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:us}));return[...n,...r]}function w9(e,t,n,r){let i=xwe(e,HAe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function UAe(e,t){let n=(t??k()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function WAe(e,t){let n=j5[e];return g7(n,``,t)&&!h7(n,``,t)}function T9(e,t,n,r,i){let a=j5[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?UAe(o,r):void 0,c=b7(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&WAe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];d5(r)&&i.push(`reclaim-permissive`),m5(r)&&i.push(`pre-approval-exact`),x7(e)(r)&&i.push(`injection-functional`);let o=mOe(a,n);return i.length>0&&(o!==null&&hOe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:lOe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function GAe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Mo(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:C9(N(n,us),`discovery`,w9(n,ln,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=ln[i];return e===null||n===void 0?null:C8(n).some(e=>e.editorId===i)?C9(N(n,e),`discovery`,w9(n,ln,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=cn[i];return e===null?null:C9(N(t,e),`project`,w9(t,cn,i,`project`))}case`editor-user-config`:return T9(i,e.strictness,t,n);case`editor-project-config`:{let r=wee[i];return r===null?null:T9(i,e.strictness,t,n,N(t,r))}}}}[...b8.map(e=>y8[e])];function KAe(e){if(!ge(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=be(e);if(t===xe||M(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function E9(e){let t=KAe(e),n=[];for(let e of b8){let r=y8[e];n.push({path:N(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of pn)n.push({path:N(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function qAe(e,t){let n=[];for(let r of E9(e))if(r.bundleId===t)try{O(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}`)}const JAe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=_7(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=W5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function YAe(e,t,n={},r=JAe){let i=[];for(let a of t){let t=j5[a];for(let a of r)i.push(a.write(t,e,n))}let a=$Oe(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function XAe(e,t,n={}){return{integrations:YAe(e,t,n)}}function D9(e,t){let n=ln[e];return n===null?null:N(t,...n.split(`/`),y8.discovery,`SKILL.md`)}function ZAe(e,t){let n=D9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!C8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=S8(`discovery`,{checkDesktop:!0});return B5(M(n),t),{editorId:e,label:e,action:V5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function QAe(e){return g(N(e,...`.agents/skills`.split(`/`),y8.discovery))?!0:sn.some(t=>{let n=D9(t,e);return n!==null&&g(M(n))})}function $Ae(e,t){let n=D9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=M(n);try{return g(n)?(B5(r,t),O(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function eje(e){return AQ({absPath:LQ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function O9({home:e=k(),env:t=process.env}={}){let n=eje(e),{override:r,preferenceList:i}=Fbe(t),{locale:a,source:o}=hB({override:r,storedPreference:n,supportedLocales:Xc,preferenceList:i,autoDetectableLocales:Qc});return{preference:n,locale:a,source:o,systemLanguages:i}}function k9(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function tje(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A9(e,t){if(typeof e==`string`)return k9(e,t.contentDir);if(Array.isArray(e))return e.map(e=>A9(e,t));if(!tje(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=A9(i,t);return n}function j9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1531
+ `));let u=`${i?``:``}${l}`;return u!==r&&NQ(e,u,{mode:o7(e)}),{kind:`removed`}}function DAe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function OAe(e){let{priorCommand:t,priorArgs:n}=h9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function h9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function g9(e,t,n={}){let r=hDe(e,t),i;try{i=S(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r}}let o=a&&typeof a==`object`?a:{},s=`machineId`in o&&typeof o.machineId==`string`?o.machineId!==(n.machineId??mDe()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??ce());if(!a||typeof a!=`object`||!CEe(a.pid))return{status:`corrupt`,lockPath:r,...s?{foreignHost:!0}:{}};let c=a.pid,l=`machineId`in o&&typeof o.machineId==`string`||`hostname`in o&&typeof o.hostname==`string`;return s?{status:`foreign-host`,lockPath:r,lock:a}:(n.isAlive??V6)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}async function kAe(e,t=void 0){let n=g9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=_De(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500),redirect:`manual`});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function AAe(e,t={}){return{targets:MAe(e,t.isAlive??V6)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}async function jAe(e){let t=e.inspect??(()=>g9(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??kAe,o=e.logger??void 0,s=AAe(t(),{isAlive:e.isAlive});if(s.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:s.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let c=[],l=[];for(let e of s.targets)try{n(e.pid,`SIGTERM`),c.push(e)}catch(t){l.push({target:e,error:t instanceof Error?t.message:String(t)})}return c.length>0&&r(`Stopped: ${c.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:c.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:l.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),l.length>0&&i(`Failed to stop: ${l.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:c,failed:l,hadTargets:!0}}function MAe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function _9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,tn.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return q8(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function NAe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=lu({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function PAe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=LQ(`user`,t),s=AQ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=_9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=ju({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?Nu(i.value):i.value;return t&&a.push(...oR({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=be(t,`.ok`,`config.yml`),u=c(l,!0),d=c(LQ(`project-local`,t)),f=sR(s.value,u,d),p=ADe.safeParse(f);if(!p.success){let e=_9(l),t={code:`SCHEMA_INVALID`,issues:NAe(p.error.issues,e)};throw Error(Eu(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function v9(e){return e.replace(/:\d+$/,``)}function y9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:v9(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function b9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=hR(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function x9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=hR(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function FAe(e){let t=b9(e);if(t)return{kind:`doc`,...t};let n=x9(e);return n?{kind:`folder`,...n}:null}async function IAe(e,t){let n,r;try{n=await De(be(e)),r=await De(be(M(e)))}catch{return{kind:`not-git`}}if(!S9(n,r))return{kind:`symlink-escape`};let i=N(n,`.git`),a;try{a=te(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await De(i)}catch{return{kind:`not-git`}}if(!S9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=z_e(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=y9(c);if(l===null)return{kind:`non-github`};let u=hR(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function S9(e,t){if(e===t)return!0;let n=ye(t,e);return n.length>0&&!n.startsWith(`..`)&&!ge(n)}const LAe=`# >>> open-knowledge cli >>>`,RAe=`# <<< open-knowledge cli <<<`,zAe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function BAe(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}function C9(e,t,n=[]){let r=g(N(e,y8[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function VAe(e,t){let n=e5.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=un.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:us}));return[...n,...r]}function w9(e,t,n,r){let i=xwe(e,VAe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function HAe(e,t){let n=(t??k()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function UAe(e,t){let n=j5[e];return g7(n,``,t)&&!h7(n,``,t)}function T9(e,t,n,r,i){let a=j5[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?HAe(o,r):void 0,c=b7(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&UAe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];d5(r)&&i.push(`reclaim-permissive`),m5(r)&&i.push(`pre-approval-exact`),x7(e)(r)&&i.push(`injection-functional`);let o=pOe(a,n);return i.length>0&&(o!==null&&mOe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:cOe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function WAe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Mo(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:C9(N(n,us),`discovery`,w9(n,ln,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=ln[i];return e===null||n===void 0?null:C8(n).some(e=>e.editorId===i)?C9(N(n,e),`discovery`,w9(n,ln,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=cn[i];return e===null?null:C9(N(t,e),`project`,w9(t,cn,i,`project`))}case`editor-user-config`:return T9(i,e.strictness,t,n);case`editor-project-config`:{let r=wee[i];return r===null?null:T9(i,e.strictness,t,n,N(t,r))}}}}[...b8.map(e=>y8[e])];function GAe(e){if(!ge(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=be(e);if(t===xe||M(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function E9(e){let t=GAe(e),n=[];for(let e of b8){let r=y8[e];n.push({path:N(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of pn)n.push({path:N(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function KAe(e,t){let n=[];for(let r of E9(e))if(r.bundleId===t)try{O(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}`)}const qAe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=_7(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=W5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function JAe(e,t,n={},r=qAe){let i=[];for(let a of t){let t=j5[a];for(let a of r)i.push(a.write(t,e,n))}let a=QOe(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function YAe(e,t,n={}){return{integrations:JAe(e,t,n)}}function D9(e,t){let n=ln[e];return n===null?null:N(t,...n.split(`/`),y8.discovery,`SKILL.md`)}function XAe(e,t){let n=D9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!C8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=S8(`discovery`,{checkDesktop:!0});return B5(M(n),t),{editorId:e,label:e,action:V5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function ZAe(e){return g(N(e,...`.agents/skills`.split(`/`),y8.discovery))?!0:sn.some(t=>{let n=D9(t,e);return n!==null&&g(M(n))})}function QAe(e,t){let n=D9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=M(n);try{return g(n)?(B5(r,t),O(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function $Ae(e){return AQ({absPath:LQ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function O9({home:e=k(),env:t=process.env}={}){let n=$Ae(e),{override:r,preferenceList:i}=Fbe(t),{locale:a,source:o}=hB({override:r,storedPreference:n,supportedLocales:Xc,preferenceList:i,autoDetectableLocales:Qc});return{preference:n,locale:a,source:o,systemLanguages:i}}function k9(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function eje(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A9(e,t){if(typeof e==`string`)return k9(e,t.contentDir);if(Array.isArray(e))return e.map(e=>A9(e,t));if(!eje(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=A9(i,t);return n}function j9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1532
1532
  `),i=n.split(`
1533
1533
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(e!==i.length-1||n!==``){if(n.length===0){a.push(``);continue}try{let e=A9(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
1534
1534
  `)}\n`:a.join(`
1535
1535
  `);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
1536
1536
  `)?`
1537
- `:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const nje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function rje(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const ije=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function aje(e){let t={contentDir:e.contentDir};for(let n of ije)for(let r of P9(N(e.stagingDir,n)))rje(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=me(n);n.endsWith(`.jsonl`)?j9(n,t):nje.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function oje(e){return N(e,...I9,z9)}function sje(e){return N(e,...I9,B9)}function cje(e){return N(e,...L9,V9)}function lje(e){return N(e,...L9,H9)}function uje(e){return N(e,...R9,U9)}function dje(e){return N(e,...R9,W9)}const G9=1e3;async function fje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function pje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function mje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function hje(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1538
- `)}\n`:null}catch{return null}}function gje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function _je(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function vje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function yje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function bje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return bje(e.maxBytes)}function xje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function Sje(e){return Ne(`sha256`).update(e).digest(`hex`)}function Cje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const wje=[`"doc.name"`,`"docName"`];function Tje(e){let t=S(e,`utf-8`),n=0;for(let e of wje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Eje=new Set([`.jsonl`]);function Dje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Eje.has(e.slice(t))}const Oje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function kje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Oje.has(e.slice(t))}function Aje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!kje(r))continue;let{redacted:i,patterns:a,lineCount:o}=CB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function jje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??fje,a=r.fetchAgentEffects??pje,o=r.fetchWatcherRecent??mje,s=r.readShadowHead??gje,c=r.readCheckpointRefs??_je,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.3-beta.0`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??vje,h=r.isOtlpPushEnabled??yje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(oje(n),N(_,`telemetry`,z9)),Z9(sje(n),N(_,`telemetry`,B9)),Z9(cje(n),N(_,`logs`,V9)),Z9(lje(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,qL,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=hje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(uje(n),N(_,`state`,U9)),Z9(dje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Pu),N(_,`state`,Pu)),Z9(N(b,Fu),N(_,`state`,Fu));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1539
- `:`not-running (${w})\n`;re(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(e.diagnosticReports,y);if(re(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&aje({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=Aje(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??me(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=xje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Dje(t)?Cje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=Tje(e))}let fe={applied:k};ce!==null&&(fe.secretScrub=ce);let pe={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:Sje(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:A};re(N(_,`manifest.json`),`${JSON.stringify(pe,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:pe,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function Mje(e){let{collected:t,outputPath:n}=e,r=M(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new UCe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function Nje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=q8(t)?t.content:void 0,i=q8(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return be(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return be(e)}async function Pje(e,t,n,r,i){let a=E7(t,e.logger),o=await jje({contentDir:Nje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Wke(a,e.userLogsDir??N(k(),`.ok`,`logs`)),...O7(e.cachesDir??N(k(),`Library`,`Caches`))],userStateFiles:k7(e.bugReportsDir??T7()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(M(e.outputPath),{recursive:!0}),await Mje({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Fje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>Bke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Pje(e,t,n,r,i());let{zipPath:a,summary:o}=await Yke({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:O7(e.cachesDir??N(k(),`Library`,`Caches`)),bugReportLedgerFiles:k7(e.bugReportsDir??T7()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{e5 as ALL_EDITOR_IDS,t5 as EDITOR_LABELS,j5 as EDITOR_TARGETS,oOe as HOSTS_WITH_USER_SKILL_DIR,Eke as LAUNCH_CONFIG_NAME,RAe as PATH_SHIM_BEGIN,BAe as PATH_SHIM_BLOCK_RE,zAe as PATH_SHIM_END,ike as addOkPathsToGitExclude,R5 as assertProjectPathSafe,p5 as buildManagedServerEntry,OAe as buildMcpConfigDeclineEvent,kAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Fje as collectReportBundle,GAe as createCliProbeResolver,on as createTokenStore,Vke as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,Ake as detectInstalledEditors,S5 as droppedManagedKeys,DOe as editorConfigPathDisplay,EOe as editorEntryLocator,_Ae as ensurePiBridge,Q5 as formatTrackedRemediation,ske as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,aOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,d5 as isEntryUpToDate,m5 as isOwnManagedEntry,FAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,IAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,VAe as pathInstallMarkerPath,HOe as previewContent,jke as probeOwnManagedEditorMcpEntry,hAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,oke as readSharingMode,CB as redactContent,ake as removeOkPathsFromGitExclude,wAe as removeOwnMcpEntry,eke as removeProjectSkill,qAe as removeUserGlobalSkillBundle,$Ae as removeUserSkill,JOe as resolveProjectRoot,MAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,QAe as userSkillPresentAnywhere,LAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,XAe as writeProjectAiIntegrations,W5 as writeProjectSkill,kke as writeUserMcpConfigs,ZAe as writeUserSkill};
1537
+ `:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const tje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function nje(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const rje=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function ije(e){let t={contentDir:e.contentDir};for(let n of rje)for(let r of P9(N(e.stagingDir,n)))nje(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=me(n);n.endsWith(`.jsonl`)?j9(n,t):tje.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function aje(e){return N(e,...I9,z9)}function oje(e){return N(e,...I9,B9)}function sje(e){return N(e,...L9,V9)}function cje(e){return N(e,...L9,H9)}function lje(e){return N(e,...R9,U9)}function uje(e){return N(e,...R9,W9)}const G9=1e3;async function dje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function fje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function pje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function mje(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1538
+ `)}\n`:null}catch{return null}}function hje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function gje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function _je(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function vje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function yje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return yje(e.maxBytes)}function bje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function xje(e){return Ne(`sha256`).update(e).digest(`hex`)}function Sje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Cje=[`"doc.name"`,`"docName"`];function wje(e){let t=S(e,`utf-8`),n=0;for(let e of Cje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Tje=new Set([`.jsonl`]);function Eje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Tje.has(e.slice(t))}const Dje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Oje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Dje.has(e.slice(t))}function kje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Oje(r))continue;let{redacted:i,patterns:a,lineCount:o}=CB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function Aje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??dje,a=r.fetchAgentEffects??fje,o=r.fetchWatcherRecent??pje,s=r.readShadowHead??hje,c=r.readCheckpointRefs??gje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.77.3`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??_je,h=r.isOtlpPushEnabled??vje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(aje(n),N(_,`telemetry`,z9)),Z9(oje(n),N(_,`telemetry`,B9)),Z9(sje(n),N(_,`logs`,V9)),Z9(cje(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,qL,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=mje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(lje(n),N(_,`state`,U9)),Z9(uje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Pu),N(_,`state`,Pu)),Z9(N(b,Fu),N(_,`state`,Fu));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1539
+ `:`not-running (${w})\n`;re(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(e.diagnosticReports,y);if(re(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&ije({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=kje(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??me(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=bje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Eje(t)?Sje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=wje(e))}let fe={applied:k};ce!==null&&(fe.secretScrub=ce);let pe={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:xje(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:A};re(N(_,`manifest.json`),`${JSON.stringify(pe,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:pe,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function jje(e){let{collected:t,outputPath:n}=e,r=M(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new UCe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function Mje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=q8(t)?t.content:void 0,i=q8(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return be(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return be(e)}async function Nje(e,t,n,r,i){let a=E7(t,e.logger),o=await Aje({contentDir:Mje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Uke(a,e.userLogsDir??N(k(),`.ok`,`logs`)),...O7(e.cachesDir??N(k(),`Library`,`Caches`))],userStateFiles:k7(e.bugReportsDir??T7()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(M(e.outputPath),{recursive:!0}),await jje({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Pje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>zke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Nje(e,t,n,r,i());let{zipPath:a,summary:o}=await Jke({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:O7(e.cachesDir??N(k(),`Library`,`Caches`)),bugReportLedgerFiles:k7(e.bugReportsDir??T7()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{e5 as ALL_EDITOR_IDS,t5 as EDITOR_LABELS,j5 as EDITOR_TARGETS,aOe as HOSTS_WITH_USER_SKILL_DIR,Tke as LAUNCH_CONFIG_NAME,LAe as PATH_SHIM_BEGIN,zAe as PATH_SHIM_BLOCK_RE,RAe as PATH_SHIM_END,rke as addOkPathsToGitExclude,R5 as assertProjectPathSafe,p5 as buildManagedServerEntry,DAe as buildMcpConfigDeclineEvent,OAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Pje as collectReportBundle,WAe as createCliProbeResolver,on as createTokenStore,Bke as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,kke as detectInstalledEditors,S5 as droppedManagedKeys,EOe as editorConfigPathDisplay,TOe as editorEntryLocator,gAe as ensurePiBridge,Q5 as formatTrackedRemediation,oke as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,iOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,d5 as isEntryUpToDate,m5 as isOwnManagedEntry,PAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,FAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,BAe as pathInstallMarkerPath,VOe as previewContent,Ake as probeOwnManagedEditorMcpEntry,mAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,ake as readSharingMode,CB as redactContent,ike as removeOkPathsFromGitExclude,CAe as removeOwnMcpEntry,$Oe as removeProjectSkill,KAe as removeUserGlobalSkillBundle,QAe as removeUserSkill,qOe as resolveProjectRoot,jAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,ZAe as userSkillPresentAnywhere,IAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,YAe as writeProjectAiIntegrations,W5 as writeProjectSkill,Oke as writeUserMcpConfigs,XAe as writeUserSkill};
1540
1540
  //# sourceMappingURL=index.mjs.map