@inkeep/open-knowledge 0.42.0-beta.12 → 0.42.0-beta.13

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 (32) hide show
  1. package/dist/{acp-harness-probe-CjydUqQ4.mjs → acp-harness-probe-PwxCSk8L.mjs} +2 -2
  2. package/dist/assets/skills/discovery/SKILL.md +1 -1
  3. package/dist/assets/skills/project/SKILL.md +1 -1
  4. package/dist/cli.mjs +6 -6
  5. package/dist/constants-CcMCMPg3.mjs +2 -0
  6. package/dist/index.d.mts +17 -17
  7. package/dist/index.mjs +1 -1
  8. package/dist/{init-DnPkN5n-.mjs → init-C_ZFDDwH.mjs} +3 -3
  9. package/dist/init-lRVOzPU9.mjs +1 -0
  10. package/dist/{launch-json-removal-BA-sCNdT.mjs → launch-json-removal-DPvJksib.mjs} +2 -2
  11. package/dist/{loader-DCNyG4ZR.mjs → loader-0YCBN4cH.mjs} +2 -2
  12. package/dist/loader-CSY1M15w.mjs +1 -0
  13. package/dist/preview-CiaBar1u.mjs +1 -0
  14. package/dist/{preview-CfZ5AA27.mjs → preview-Cjg4sLCV.mjs} +2 -2
  15. package/dist/public/assets/FeedbackForm-BtLP5P4r.js +1 -0
  16. package/dist/public/assets/ReportBugDialogBody-CkyHWZh9.js +3 -0
  17. package/dist/public/assets/{index-BOJ7Bris.js → index-CFaXQy8P.js} +101 -101
  18. package/dist/public/index.html +1 -1
  19. package/dist/{repair-launch-json-qcHlix78.mjs → repair-launch-json-CZawWAqd.mjs} +2 -2
  20. package/dist/{repair-mcp-configs-DHQ158Ii.mjs → repair-mcp-configs-DpdVVhiU.mjs} +2 -2
  21. package/dist/src-9fqRbYyu.mjs +22 -0
  22. package/dist/{start-B9UTrPaX.mjs → start-FUQOcvoI.mjs} +2 -2
  23. package/dist/start-eE4o515K.mjs +1 -0
  24. package/package.json +4 -4
  25. package/dist/constants-DDOp7euF.mjs +0 -2
  26. package/dist/init-Nb6wwQ_E.mjs +0 -1
  27. package/dist/loader-Bk0QXISJ.mjs +0 -1
  28. package/dist/preview-D-Bg4IXi.mjs +0 -1
  29. package/dist/public/assets/FeedbackForm-BKWqxmdO.js +0 -1
  30. package/dist/public/assets/ReportBugDialogBody-CAnsRf9T.js +0 -2
  31. package/dist/src-DIp07PRS.mjs +0 -22
  32. package/dist/start-9dga8r1v.mjs +0 -1
@@ -58,7 +58,7 @@
58
58
  -->
59
59
  <script>(() => { let t = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (r === 'light' || r === 'dark' || r === 'system') t = r; } catch {} let ct = null; try { const c = localStorage.getItem('ok-color-theme-v1'); if (c && ['dracula', 'catppuccin-frappe', 'catppuccin-latte', 'monokai', 'gruvbox', 'solarized', 'custom'].includes(c)) ct = c; } catch {} let dark = t === 'dark'; if (t === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } let customCss = null; if (ct === 'custom') { try { const raw = localStorage.getItem('ok-custom-theme-v1'); if (raw) { const o = JSON.parse(raw); if (o?.css) { customCss = o.css; dark = !!o.dark; } } } catch {} if (!customCss) ct = null; } else if (ct) { dark = !['catppuccin-latte'].includes(ct); } if (dark) document.documentElement.classList.add('dark'); if (ct) document.documentElement.setAttribute('data-color-theme', ct); if (customCss) { const s = document.createElement('style'); s.id = 'ok-custom-theme'; s.textContent = customCss; document.head.appendChild(s); } if (window.okDesktop) { document.documentElement.classList.add('electron-mode'); document.documentElement.classList.add(`electron-platform-${window.okDesktop.platform}`); } })();</script>
60
60
  <style>html { background-color: #fafafa } html.dark { background-color: #171717 }</style>
61
- <script type="module" crossorigin src="./assets/index-BOJ7Bris.js"></script>
61
+ <script type="module" crossorigin src="./assets/index-CFaXQy8P.js"></script>
62
62
  <link rel="modulepreload" crossorigin href="./assets/chunk-CYidjpOJ.js">
63
63
  <link rel="modulepreload" crossorigin href="./assets/dist-q14fBS3T.js">
64
64
  <link rel="modulepreload" crossorigin href="./assets/react-f2sANaYj.js">
@@ -1,2 +1,2 @@
1
- import{t as e}from"./launch-json-removal-BA-sCNdT.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=e(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`||o.kind===`removed-file`;return s&&i({event:`launch-json-repair-removed`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
2
- //# sourceMappingURL=repair-launch-json-qcHlix78.mjs.map
1
+ import{t as e}from"./launch-json-removal-DPvJksib.mjs";import{join as t}from"node:path";function n(n){let i=n.logger??r,a=t(n.projectDir,`.claude`,`launch.json`);if(n.reclaimDisableEnv===`1`)return i({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=e(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`||o.kind===`removed-file`;return s&&i({event:`launch-json-repair-removed`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
2
+ //# sourceMappingURL=repair-launch-json-CZawWAqd.mjs.map
@@ -1,2 +1,2 @@
1
- import{d as e,l as t,v as n}from"./write-project-skill-CeYehb7h.mjs";import{d as r,v as i}from"./init-DnPkN5n-.mjs";import{t as a}from"./mcp-migrate-event-CWx0WLdE.mjs";import{homedir as o}from"node:os";function s(n){let r=n.logger??u,i=n.home??o(),a=[];if(n.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=e[o],s=c(()=>t.configPath(``,i));if(s!==null&&a.push(l({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let e=t.projectConfigPath,i=c(()=>e(n.projectDir));i!==null&&a.push(l({scope:`project`,editorId:o,target:t,home:void 0,cwd:n.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function c(e){try{return e()}catch{return null}}function l(e){let t={scope:e.scope,editorId:e.editorId,configPath:e.configPath},o=r(e.target,e.cwd,e.home,e.configPathOverride);if(o===null)return{...t,outcome:`no-entry`};if(n(o))return{...t,outcome:`canonical`};e.logger(a({scope:e.scope,surface:`cli-repair`,editorId:e.editorId,configPath:e.configPath,priorEntry:o}));let s=i(e.target,e.cwd,{mode:`published`,skipAvailabilityCheck:!0},e.home,e.configPathOverride);if(s.action===`failed`){let n=s.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:n}),{...t,outcome:`write-failed`,error:n}}return s.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:s.declineReason}),{...t,outcome:`declined`}):{...t,outcome:`repaired`}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{s as repairMcpConfigs};
2
- //# sourceMappingURL=repair-mcp-configs-DHQ158Ii.mjs.map
1
+ import{d as e,l as t,v as n}from"./write-project-skill-CeYehb7h.mjs";import{d as r,v as i}from"./init-C_ZFDDwH.mjs";import{t as a}from"./mcp-migrate-event-CWx0WLdE.mjs";import{homedir as o}from"node:os";function s(n){let r=n.logger??u,i=n.home??o(),a=[];if(n.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=e[o],s=c(()=>t.configPath(``,i));if(s!==null&&a.push(l({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let e=t.projectConfigPath,i=c(()=>e(n.projectDir));i!==null&&a.push(l({scope:`project`,editorId:o,target:t,home:void 0,cwd:n.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function c(e){try{return e()}catch{return null}}function l(e){let t={scope:e.scope,editorId:e.editorId,configPath:e.configPath},o=r(e.target,e.cwd,e.home,e.configPathOverride);if(o===null)return{...t,outcome:`no-entry`};if(n(o))return{...t,outcome:`canonical`};e.logger(a({scope:e.scope,surface:`cli-repair`,editorId:e.editorId,configPath:e.configPath,priorEntry:o}));let s=i(e.target,e.cwd,{mode:`published`,skipAvailabilityCheck:!0},e.home,e.configPathOverride);if(s.action===`failed`){let n=s.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:n}),{...t,outcome:`write-failed`,error:n}}return s.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:s.declineReason}),{...t,outcome:`declined`}):{...t,outcome:`repaired`}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{s as repairMcpConfigs};
2
+ //# sourceMappingURL=repair-mcp-configs-DpdVVhiU.mjs.map
@@ -0,0 +1,22 @@
1
+ import{o as e}from"./chunk-DTipWd-i.mjs";import{F as t,I as n,Pa as r}from"./src-CJ8mKCzo.mjs";import{Ai as i,ct as a,hn as o,lt as s,ot as c,st as l,ui as u,ya as d}from"./src-CIFd3tOE.mjs";import{K as f}from"./sleep-B2L0pvp4.mjs";import{O as p,P as m}from"./fs-traced-Cc6WsRtP.mjs";import{b as h,u as g,v as _,y as v}from"./server-lock-Cr23NqXF.mjs";import{t as y}from"./yazl-BafwB467.mjs";import{C as b,d as x,i as ee,v as te,y as S}from"./write-project-skill-CeYehb7h.mjs";import{c as C}from"./colors-BsmVIwfM.mjs";import"./acp-harness-probe-PwxCSk8L.mjs";import{D as ne,E as re,S as w,T,_ as ie,b as E,o as D,v as O}from"./init-C_ZFDDwH.mjs";import{n as k}from"./constants-CcMCMPg3.mjs";import{t as A}from"./is-object-ByG7RnjH.mjs";import"./loader-0YCBN4cH.mjs";import"./preview-Cjg4sLCV.mjs";import{execSync as ae,spawnSync as oe}from"node:child_process";import{basename as j,dirname as M,isAbsolute as se,join as N,relative as ce,resolve as P,sep as le}from"node:path";import{cpSync as ue,createWriteStream as de,existsSync as F,lstatSync as fe,mkdirSync as I,mkdtempSync as pe,readFileSync as L,readdirSync as R,readlinkSync as me,rmSync as z,statSync as he,writeFileSync as B}from"node:fs";import{arch as ge,freemem as _e,homedir as V,hostname as ve,platform as ye,release as be,tmpdir as xe,totalmem as Se,type as Ce,uptime as we}from"node:os";import{realpath as H}from"node:fs/promises";import{createHash as U}from"node:crypto";var Te=f();const Ee=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function De(e,t,n=o){if(e!==void 0&&!Ee.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Oe=null;function ke(e){Oe=e}function Ae(){return Oe??process.cwd()}const je=[{name:`macos-home-path`,regex:/\/Users\/[^/]+\//g,replacement:`~/`},{name:`linux-home-path`,regex:/\/home\/[^/]+\//g,replacement:`~/`},{name:`github-pat`,regex:/\b(ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}\b/g,replacement:`[REDACTED-GH-PAT]`},{name:`aws-access-key`,regex:/\b(AKIA|ASIA|ABIA)[A-Z2-7]{16}\b/g,replacement:`[REDACTED-AWS-KEY]`},{name:`anthropic-key`,regex:/\bsk-ant-api03-[A-Za-z0-9_-]{20,}\b/g,replacement:`[REDACTED-ANTHROPIC]`},{name:`openai-key`,regex:/\bsk-[A-Za-z0-9]{20,}\b/g,replacement:`[REDACTED-OPENAI]`},{name:`bearer-token`,regex:/([Aa]uthorization:\s*[Bb]earer\s+)\S+/g,replacement:`$1[REDACTED]`},{name:`jwt`,regex:/eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,replacement:`[REDACTED-JWT]`},{name:`url-credentials`,regex:/:\/\/[^/\s:@]+:[^/\s:@]+@/g,replacement:`://[REDACTED]@`}],Me=je.map(e=>e.name);function Ne(e){let t=new Set,n=0;return{redacted:e.split(`
2
+ `).map(e=>{let r=e;for(let{name:e,regex:i,replacement:a}of je)i.lastIndex=0,i.test(r)&&(t.add(e),n++,i.lastIndex=0,r=r.replace(i,a));return r}).join(`
3
+ `),patterns:[...t],lineCount:n}}function Pe(){return N(V(),`.ok`,`bug-reports`)}function Fe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Pe(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;F(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function Ie(e,t){let n=N(e,`.ok`,`config.yml`);if(F(n))try{let e=L(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 F(N(e,`.ok`))?U(`sha256`).update(P(e)).digest(`hex`).slice(0,12):null}function Le(){let e={timestamp:new Date().toISOString(),platform:ye(),osType:Ce(),osRelease:be(),hostname:`[redacted]`,uptime:we(),freeMem:_e(),totalMem:Se(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=ae(`sw_vers -productVersion 2>/dev/null`,u({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);F(t)&&(e.okVersion=JSON.parse(L(t,`utf8`)).version)}catch{}return e}function Re(e,t){return ze(e,t).files}function ze(e,t){if(!F(t))return{files:[]};let n=R(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(e&&n.length>0){let t=n.filter(t=>{try{return L(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});t.length>0&&(n=t)}return{files:n}}function Be(e){let n=N(e,`.ok`,`local`);return F(n)?{files:[`server.lock`,`last-spawn-error.log`,t].map(e=>N(n,e)).filter(e=>F(e))}:{files:[]}}function Ve(e){let t=N(e,`.ok`,`local`,`logs`);return F(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>F(e))}:{files:[]}}function He(e){if(e.redact){let{redacted:t,patterns:n,lineCount:r}=Ne(e.content);e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name),n.length>0&&e.redactions.push({file:e.name,lineCount:r,patterns:n})}else e.zipfile.addBuffer(Buffer.from(e.content,`utf8`),e.name),e.bundleFiles.push(e.name)}function Ue(e){for(let t of e.files)try{He({zipfile:e.zipfile,name:`${e.prefix}/${j(t)}`,content:L(t,`utf8`),redact:e.redact,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 We(t){let{redact:n,outputPath:r,logger:i}=t,a=t.userLogsDir??N(V(),`.ok`,`logs`),o=t.projectDir?Ie(t.projectDir,i):null;I(M(r),{recursive:!0}),i?.info({projectSlug:o},`gathering diagnostic data`);let s=Le();s.desktop=t.desktop??null;let{files:c}=ze(o,a),{files:l}=t.projectDir?Be(t.projectDir):{files:[]},{files:u}=t.projectDir?Ve(t.projectDir):{files:[]};i?.info({logFileCount:c.length,lockFileCount:l.length,localSinkFileCount:u.length},`files collected`);let d=[],f=[],{ZipFile:p}=await import(`./yazl-vwTkB7U0.mjs`).then(t=>e(t.default,1)),m=new p;Ue({zipfile:m,files:c,prefix:`logs`,redact:n,bundleFiles:f,redactions:d,logger:i}),Ue({zipfile:m,files:l,prefix:`lockdir`,redact:n,bundleFiles:f,redactions:d,logger:i}),Ue({zipfile:m,files:u,prefix:`local-logs`,redact:n,bundleFiles:f,redactions:d,logger:i});for(let e of t.extraFiles??[])try{let t=L(e.sourcePath),n=`extra/${e.zipName??j(e.sourcePath)}`;m.addBuffer(t,n),f.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&He({zipfile:m,name:`note.txt`,content:t.note,redact:n,bundleFiles:f,redactions:d});let h=JSON.stringify(s,null,2);m.addBuffer(Buffer.from(h,`utf8`),`sysinfo.json`),f.push(`sysinfo.json`);let g={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:o,files:f,redactions:d,sysinfo:s};m.addBuffer(Buffer.from(JSON.stringify(g,null,2),`utf8`),`MANIFEST.json`);let _=d.reduce((e,t)=>e+t.lineCount,0),v=[`# Bug Report Bundle`,``,`Generated: ${g.generatedAt}`,`Project: ${o??`(unscoped)`}`,`Discipline version: ${g.disciplineVersion}`,``,`## Contents`,``,...f.map(e=>`- ${e}`),``,`## Privacy`,``,...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Me.join(`, `)}`,_>0?`${_} line(s) were scrubbed across ${d.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`]:[`Redaction was disabled for this bundle; file contents are unmodified.`]].join(`
4
+ `);m.addBuffer(Buffer.from(v,`utf8`),`README.md`),m.end();let y=de(r);return m.outputStream.pipe(y),await new Promise((e,t)=>{y.on(`close`,e),y.on(`error`,t)}),i?.info({bundlePath:r,fileCount:f.length,redactionCount:_},`bundle written`),{zipPath:r,summary:{projectSlug:o,files:f,redactions:d,redactedLineCount:_,generatedAt:g.generatedAt}}}var Ge=e(y(),1),W=e(C(),1);const Ke=new Set([`doc.name`,`currentDoc`]);function qe(e){return`doc:${U(`sha256`).update(e).digest(`hex`).slice(0,8)}`}function Je(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function Ye(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=qe(e);return t.originalToHashed.set(e,r),Je(t,e,r),r}function Xe(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K(e,t){if(typeof e==`string`)return Xe(e,t.contentDir);if(Array.isArray(e))return e.map(e=>K(e,t));if(!G(e))return e;let n=typeof e.key==`string`&&Ke.has(e.key)&&G(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&G(a)){let e=Ye(n,t);r[i]={...a,stringValue:e}}else Ke.has(i)&&typeof a==`string`?r[i]=Ye(a,t):r[i]=K(a,t);return r}function Ze(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function Qe(e,t){let n=L(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
5
+ `),i=n.split(`
6
+ `),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=K(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}B(e,r?`${a.join(`
7
+ `)}\n`:a.join(`
8
+ `))}function $e(e,t){let n=L(e,`utf-8`);if(n.trim().length!==0)try{let r=K(JSON.parse(n),t),i=n.endsWith(`
9
+ `)?`
10
+ `:``;B(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=Ze(Xe(n,t.contentDir),t);r!==n&&B(e,r)}}function et(e,t){let n=L(e,`utf-8`),r=Xe(n,t.contentDir);r!==n&&B(e,r)}function tt(e){try{return R(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const nt=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function rt(e){return/\.log\.\d+$/.test(e)}function it(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||rt(e)}function at(e){let t={contentDir:e.contentDir,docNameMap:{},originalToHashed:new Map,docNameCollisions:{}};for(let n of[`telemetry`,`logs`,`process`])for(let r of tt(N(e.stagingDir,n)))it(r)?Qe(r,t):r.endsWith(`.json`)?$e(r,t):et(r,t);for(let n of tt(N(e.stagingDir,`state`))){let e=j(n);n.endsWith(`.jsonl`)?Qe(n,t):nt.has(e)?$e(n,t):et(n,t)}return{docNameMap:t.docNameMap,docNameCollisions:t.docNameCollisions}}const ot=[`.ok`,`local`,`telemetry`],st=[`.ok`,`local`,`logs`],ct=`spans-current.jsonl`,lt=`spans-prev.jsonl`,ut=`server-current.jsonl`,dt=`server-prev.jsonl`;function ft(e){return N(e,...ot,ct)}function pt(e){return N(e,...ot,lt)}function mt(e){return N(e,...st,ut)}function ht(e){return N(e,...st,dt)}const gt=1e3;async function _t(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(gt)});return t.ok?await t.text():null}catch{return null}}async function vt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(gt)});return t.ok?await t.text():null}catch{return null}}async function yt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(gt)});return t.ok?await t.text():null}catch{return null}}function bt(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(`
11
+ `)}\n`:null}catch{return null}}function xt(e){let t=N(e,`.git`,`ok`);if(!F(t))return null;let n=oe(`git`,[`-C`,t,`log`,`--oneline`,`-50`],u({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function St(e){let t=N(e,`.git`,`ok`);if(!F(t))return null;let n=oe(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],u({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Ct(){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 wt(){return{nodeVersion:process.version,platform:ye(),arch:ge()}}function Tt(){return process.env.OTEL_SDK_DISABLED===`false`}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Et(e){if(!F(e))return{};let t;try{t=(0,Te.parse)(L(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(!q(t))return{};let n=t.telemetry;if(!q(n))return{};let r=n.localSink;return q(r)?r:{}}function Dt(e){return typeof e==`boolean`?e:void 0}function Ot(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function J(e){if(q(e))return Ot(e.maxBytes)}function kt(e){let t=Et(p(`project`,e)),n=Et(p(`project-local`,e));return{enabled:Dt(n.enabled)??Dt(t.enabled)??!0,spansMaxBytes:J(n.spans)??J(t.spans)??52428800,logsMaxBytes:J(n.logs)??J(t.logs)??26214400}}function At(e){return U(`sha256`).update(e).digest(`hex`)}function jt(e){let t=L(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}function Mt(e){let t=L(e,`utf-8`),n=`"doc.name"`,r=0,i=t.indexOf(n);for(;i!==-1;)r++,i=t.indexOf(n,i+10);return r}function Y(e,t){return F(e)?(I(M(t),{recursive:!0}),ue(e,t),!0):!1}function Nt(e){let t=[],n=e=>{let r=R(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 Pt=new Set([`.jsonl`]);function Ft(e){let t=e.lastIndexOf(`.`);return t===-1?!1:Pt.has(e.slice(t))}const It=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`]);function Lt(e){if(rt(e))return!0;let t=e.lastIndexOf(`.`);return t===-1?!1:It.has(e.slice(t))}function Rt(e){let t=[];for(let n of Nt(e)){let r=zt(e,n);if(!Lt(r))continue;let{redacted:i,patterns:a,lineCount:o}=Ne(L(n,`utf-8`));a.length!==0&&(B(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function zt(e,t){return ce(e,t).split(le).join(`/`)}async function Bt(e){let r=P(e.contentDir),i=P(e.projectDir??e.contentDir),a=e.deps??{},o=a.fetchAgentPresence??_t,s=a.fetchAgentEffects??vt,c=a.fetchWatcherRecent??yt,l=a.readShadowHead??xt,u=a.readCheckpointRefs??St,d=a.now??(()=>new Date),f=a.okVersion??(()=>k),p=a.readDesktopEnv??Ct,m=a.readRuntime??wt,h=a.isOtlpPushEnabled??Tt,g=pe(N(xe(),`ok-bundle-`));try{I(N(g,`telemetry`),{recursive:!0}),I(N(g,`logs`),{recursive:!0}),I(N(g,`state`),{recursive:!0}),Y(ft(i),N(g,`telemetry`,ct)),Y(pt(i),N(g,`telemetry`,lt)),Y(mt(i),N(g,`logs`,ut)),Y(ht(i),N(g,`logs`,dt));for(let t of e.userLogFiles??[])Y(t,N(g,`logs`,j(t)));let _=N(i,`.ok`,`local`),v=N(_,`server.lock`),y=`not-running`,b=`no server.lock`,x=null;if(F(v)){Y(v,N(g,`state`,`server.lock`));try{let e=L(v,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?x=t.port:b=`lock present but no port`}catch{b=`lock present but unparseable`}}if(x!==null){let e=await o(x);e===null?b=`agent-presence endpoint at :${x} unreachable`:(B(N(g,`state`,`agent-presence.json`),e),y=`running`,b=``);let t=await s(x);t!==null&&B(N(g,`state`,`agent-effects.json`),t);let n=await c(x);if(n!==null){let e=bt(n);e!==null&&B(N(g,`state`,`watcher-recent.jsonl`),e)}}let ee=l(r);ee!==null&&B(N(g,`state`,`shadow-head.txt`),ee);let te=u(r);te!==null&&B(N(g,`state`,`checkpoint-refs.txt`),te),Y(N(_,`last-spawn-error.log`),N(g,`state`,`last-spawn-error.log`)),Y(N(_,n),N(g,`state`,n)),Y(N(_,t),N(g,`state`,t));let S=m(),C=p(),ne={ok:{version:f(),nodeVersion:S.nodeVersion,platform:S.platform,arch:S.arch},host:{desktop:C}};B(N(g,`state`,`runtime.json`),`${JSON.stringify(ne,null,2)}\n`);let re=y===`running`?`running
12
+ `:`not-running (${b})\n`;if(B(N(g,`state`,`server-status.txt`),re),e.processDir&&F(e.processDir)){let t=N(g,`process`);I(t,{recursive:!0}),ue(e.processDir,t,{recursive:!0})}let w=null;e.redact===!0&&(w=at({stagingDir:g,contentDir:r})),e.note&&B(N(g,`note.txt`),e.note);let T=null;e.scrubSecrets===!0&&(T=Rt(g));for(let t of e.extraFiles??[])Y(t.sourcePath,N(g,`extra`,t.zipName??j(t.sourcePath)))||a.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let ie=kt(i),E=Nt(g),D=[],O=0,k=0;for(let e of E){let t=zt(g,e),n=he(e).size,r=Ft(t)?jt(e):0;D.push({path:t,bytes:n,lines:r}),O+=n,t.startsWith(`telemetry/`)&&Ft(t)&&(k+=Mt(e))}let A=w===null?{applied:!1,docNameMapSidecar:null}:Object.keys(w.docNameCollisions).length>0?{applied:!0,docNameMapSidecar:null,docNameCollisions:w.docNameCollisions}:{applied:!0,docNameMapSidecar:null};T!==null&&(A.secretScrub=T);let ae={schemaVersion:1,createdAt:d().toISOString(),ok:{version:f(),nodeVersion:S.nodeVersion,platform:S.platform,arch:S.arch},host:{desktop:C},contentDir:{pathSha256:At(r),absolutePath:w===null?r:`<CONTENT_DIR>`},telemetry:{localSink:ie,otlpPushEnabled:h()},redaction:A,serverStatus:y,files:D};B(N(g,`manifest.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=E.some(e=>{try{return L(e,`utf-8`).includes(r)}catch{return!1}}),M={totalBytes:O,fileCount:D.length,docNameCount:k,contentDirVisible:oe,redacted:w!==null},se=!1;return{stagingDir:g,manifest:ae,summary:M,redactionMapPayload:w===null?null:{docNameMap:w.docNameMap,docNameCollisions:w.docNameCollisions},cleanup:()=>{se||(se=!0,z(g,{recursive:!0,force:!0}))}}}catch(e){throw z(g,{recursive:!0,force:!0}),e}}async function Vt(e){let{collected:t,outputPath:n}=e,r=M(n);if(!F(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);if(t.redactionMapPayload!==null){let e=`${j(n,`.zip`)}.docnames.json`,r={...t.manifest,redaction:{...t.manifest.redaction,applied:!0,docNameMapSidecar:e}};B(N(t.stagingDir,`manifest.json`),`${JSON.stringify(r,null,2)}\n`)}let i=new Ge.ZipFile,a=Nt(t.stagingDir);for(let e of a){let n=zt(t.stagingDir,e);i.addFile(e,n)}i.end(),t.redactionMapPayload!==null&&B(N(r,`${j(n,`.zip`)}.docnames.json`),`${JSON.stringify({docNameMap:t.redactionMapPayload.docNameMap,docNameCollisions:t.redactionMapPayload.docNameCollisions},null,2)}\n`,{mode:384});let o=de(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 Ht(e,t){let n=N(e,`.ok`,`config.yml`);if(F(n))try{let t=(0,Te.parse)(L(n,`utf-8`)),r=A(t)?t.content:void 0,i=A(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return P(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 P(e)}async function Ut(e,t,n){let r=Ie(t,e.logger),i=await Bt({contentDir:Ht(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:Re(r,e.userLogsDir??N(V(),`.ok`,`logs`)),deps:{readDesktopEnv:n,logger:e.logger}});try{I(M(e.outputPath),{recursive:!0}),await Vt({collected:i,outputPath:e.outputPath});let t=i.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:r,files:i.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:i.manifest.createdAt}}}finally{i.cleanup()}}async function Wt(e){let{projectDir:t}=e,n=e.readDesktopEnv??Ct;if(e.level===`full`&&t!==void 0)return Ut(e,t,n);let{zipPath:r,summary:i}=await We({projectDir:t,redact:e.redact,outputPath:e.outputPath,userLogsDir:e.userLogsDir,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n()});return{zipPath:r,summary:{level:e.level,systemWide:t===void 0,projectSlug:i.projectSlug,files:i.files,redactions:i.redactions,redactedLineCount:i.redactedLineCount,generatedAt:i.generatedAt}}}function X(e,t,n={}){let r=g(e,t);if(!F(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(L(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!v(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??_)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};if(typeof a.machineId==`string`)return a.machineId===(n.machineId??h())?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a};let o=n.host??ve();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Gt(e){return e.replace(/:\d+$/,``)}function Kt(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Gt(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Gt(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Gt(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 qt(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=r(t.hostname);if(n===null)return null;let i=t.pathname.split(`/`).filter(e=>e.length>0);if(i.length<5||i[2]!==`blob`)return null;let a,o,s,c;try{a=decodeURIComponent(i[0]),o=decodeURIComponent(i[1]),s=decodeURIComponent(i[3]),c=i.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.length===0||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function Jt(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=r(t.hostname);if(n===null)return null;let i=t.pathname.split(`/`);if(i.length<5||i[0]!==``||i[3]!==`tree`)return null;let a=i.slice(5);a.length===1&&a[0]===``&&a.pop();let o,s,c,l;try{o=decodeURIComponent(i[1]),s=decodeURIComponent(i[2]),c=decodeURIComponent(i[4]),l=a.map(e=>decodeURIComponent(e))}catch{return null}return!o||!s||!c||l.some(e=>e.length===0)?null:{host:n,owner:o,repo:s,branch:c,path:l.join(`/`)}}function Yt(e){let t=qt(e);if(t)return{kind:`doc`,...t};let n=Jt(e);return n?{kind:`folder`,...n}:null}const Xt=`# >>> open-knowledge cli >>>`,Zt=`# <<< open-knowledge cli <<<`,Qt=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function $t(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const en={existsSync:e=>F(e),readFileSync:(e,t)=>L(e,t),lstatSync:e=>fe(e),readlinkSync:e=>me(e)};function tn(e,t=en){let n=$t(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function nn(e){let t=e.replace(Qt,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function rn(e,t,n=en){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}function an(e){return te(e)||S(e)||w(e)}const on=10*1024*1024;function sn(e,t,n,r){let i=D(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!an(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);return e.format===`file`?(z(a,{force:!0}),{kind:`removed`}):e.format===`toml`?un(a,o):e.format===`yaml`?ln(a,e.topLevelKey,o):cn(a,e.topLevelKey,e.serverMapSubKey,o)}function cn(e,t,n,r){let i;try{i=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>on)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=ne(i,ie(t,n,r));return o?(m(e,a,{mode:T(e)}),{kind:`removed`}):{kind:`not-present`}}function ln(e,t,n){let r;try{r=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(r,`utf-8`)>on)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,Te.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=re(a);a.trim()===``||a.endsWith(`
13
+ `)?c.endsWith(`
14
+ `)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
15
+ `).replace(/\n/g,`\r
16
+ `));let u=`${i?``:``}${c}`;return u!==r&&m(e,u,{mode:T(e)}),{kind:`removed`}}function un(e,t){let n=E();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=re(a),s=a.trim()===``||a.endsWith(`
17
+ `),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(`
18
+ `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
19
+ `).replace(/\n/g,`\r
20
+ `));let u=`${i?``:``}${l}`;return u!==r&&m(e,u,{mode:T(e)}),{kind:`removed`}}function dn(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function fn(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function pn(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:l(r),command:r,isDesktop:dn(r)}}function mn(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Z(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&mn(e)?`ui-orphan`:`stale`}const hn=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function gn(e){switch(e){case`running`:return W.default.green(e);case`desktop`:return W.default.blue(e);case`foreign`:return W.default.cyan(e);case`ui-orphan`:return W.default.magenta(e);case`stale`:return W.default.yellow(e)}}function _n(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function vn(e){return`${_n(e.server.usage)} | ${_n(e.ui?.usage??null)}`}function yn(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function bn(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Z(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,yn(e),vn(e),t,String(n),fn(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=gn(Z(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=W.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
21
+ `)}async function xn(e={}){let t=e.discover??c,n=e.inspect??X,r=e.log??(e=>console.log(e)),i=e.resolveCommand??a,o=e.resolveUsage??s,l=await t(),u=[];for(let e of l){let t=n(e,`server`),r=n(e,`ui`),a=pn(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:o(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:o(r.lock.pid));a!=null&&u.push(a)}if(e.json){let e=u.map(e=>({...e,displayStatus:Z(e)}));r(JSON.stringify(e,null,2));return}r(bn(e.all?u:u.filter(e=>hn.has(Z(e)))))}function Sn(){return new b(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await xn({all:t.all===!0||e===`all`,json:t.json===!0})})}function Cn(e,t,n={}){let r=n.isAlive??_,i=[];for(let[n,a]of[[`server`,e],[`ui`,t]])(a.status===`alive`||a.status===`foreign-host`&&r(a.lock.pid))&&i.push({name:n,pid:a.lock.pid,port:a.lock.port});return{targets:i}}function wn(e){let t=e.inspect??(t=>X(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Cn(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Q(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function Tn(e,t=_){let n=await c(),r=null;for(let i of n){let n=X(i,`server`),a=X(i,`ui`);if(Q(n,t)&&n.lock.port===e||Q(a,t)&&a.lock.port===e)return i;r===null&&(Q(n,t)&&n.lock.pid===e||Q(a,t)&&a.lock.pid===e)&&(r=i)}return r}function $(e){let t=wn({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function En(e){return new b(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=wn({lockDir:i(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await xn({});return}if(n===`all`){let e=await c();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=X(n,`server`),r=X(n,`ui`);!Q(e,_)&&!Q(r,_)||($(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await Tn(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}$(t);return}$(i(P(Ae(),n)))})}function Dn(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}async function On(e,t){let n,i;try{n=await H(P(e)),i=await H(P(M(e)))}catch{return{kind:`not-git`}}if(!kn(n,i))return{kind:`symlink-escape`};let a=N(n,`.git`),o;try{o=he(a)}catch{return{kind:`not-git`}}if(o.isDirectory()){let e;try{e=await H(a)}catch{return{kind:`not-git`}}if(!kn(e,n))return{kind:`symlink-escape`}}else if(!o.isFile())return{kind:`not-git`};let s=d(n);if(s.kind!==`repository`)return{kind:`not-git`};let c=s.repository.readRemoteUrl(`origin`);if(c.kind===`unreadable`)return{kind:`not-git`};if(c.kind===`absent`)return c.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let l=c.url,u=Kt(l);if(u===null)return{kind:`non-github`};let f=r(u.hostname);if(f===null)return{kind:`non-github`};let p=f===t.host.toLowerCase(),m=u.owner.toLowerCase()===t.owner.toLowerCase(),h=u.name.toLowerCase()===t.repo.toLowerCase();return!p&&m&&h?{kind:`wrong-host`,actualHost:f}:!p||!m||!h?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://${f}/${u.owner}/${u.name}.git`}}function kn(e,t){if(e===t)return!0;let n=ce(t,e);return n.length>0&&!n.startsWith(`..`)&&!se(n)}const An=[{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=O(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=ee(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 jn(e,t,n={},r=An){let i=[];for(let a of t){let t=x[a];for(let a of r)i.push(a.write(t,e,n))}return i}function Mn(e,t,n={}){return{integrations:jn(e,t,n)}}export{Fe as C,ke as D,Ae as E,De as O,Vt as S,Ne as T,Jt as _,En as a,Wt as b,Xt as c,rn as d,$t as f,Yt as g,qt as h,wn as i,Qt as l,nn as m,On as n,Sn as o,tn as p,Dn as r,sn as s,Mn as t,Zt as u,Kt as v,Pe as w,Bt as x,X as y};
22
+ //# sourceMappingURL=src-9fqRbYyu.mjs.map
@@ -1,3 +1,3 @@
1
- import{L as e,P as t}from"./src-CJ8mKCzo.mjs";import{_i as n,a as r,gn as i,ui as a}from"./src-CIFd3tOE.mjs";import{C as o,w as s}from"./write-project-skill-CeYehb7h.mjs";import{a as c,n as l,t as u}from"./acp-harness-probe-CjydUqQ4.mjs";import{n as d}from"./constants-DDOp7euF.mjs";import{spawn as f}from"node:child_process";import{basename as p,dirname as m,join as h,win32 as g}from"node:path";import{closeSync as _,existsSync as v,mkdirSync as y,openSync as b,statSync as x}from"node:fs";import{homedir as S}from"node:os";import{rm as C}from"node:fs/promises";import{setTimeout as w}from"node:timers/promises";function T(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function E(e,t,n={}){let r=(n.spawn??f)(e,[...t],a({detached:!0,stdio:`ignore`,env:T(n.env??process.env)}));return r.unref(),r}const D=`OpenKnowledge.app`,O=`/Applications/${D}`;function k(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return x(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function A(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(j(e,O))return O;let t=h(e.homeDir??S(),`Applications`,D);return j(e,t)?t:null}function j(e,t){return M(e,h(t,`Contents`,`MacOS`,`OpenKnowledge`))}function M(e,t){try{let n=e.statSync(t);return n&&typeof n.isFile==`function`?n.isFile():!1}catch{return!1}}const N=[`@inkeepopen-knowledge-desktop`,`OpenKnowledge`];function P(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&/\\OpenKnowledge\.exe$/i.test(e.execPath))return e.execPath;let t=e.env.LOCALAPPDATA;if(t)for(let n of N){let r=g.join(t,`Programs`,n,`OpenKnowledge.exe`);if(M(e,r))return r}return null}function F(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&e.execPath.endsWith(`/openknowledge`))return e.execPath;let t=`/opt/OpenKnowledge/openknowledge`;return M(e,t)?t:null}function I(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`};let t;try{t=e.platform===`darwin`?A(e):e.platform===`win32`?P(e):F(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function L(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;if(n("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)"),r===`darwin`){E(`open`,[`-b`,`com.inkeep.open-knowledge`],{spawn:e.spawn});return}let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}E(i,[],{spawn:e.spawn})}function R(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function z(e){return h(m(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const B=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function ee(e){if(e.platform!==`darwin`||!B.test(e.execPath))return null;let t=z(e.execPath);return e.exists(t)?t:null}function V(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??v,a=r[1];return a?{command:ee({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function te(e,t){return e.host??t.HOST??`127.0.0.1`}function H(e){let t=p(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var U=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function W(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function G(t){v(t.lockDir)||y(t.lockDir,{recursive:!0});let n=b(h(t.lockDir,e),`w`),r=t.spawn??f,{PORT:i,...a}=process.env,o=V();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],windowsHide:!0,cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{_(n)}catch{}}}function K(e,t,n){return e??(n===void 0?t:void 0)}function q(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function J(e,t,n){return e??+(t!=null&&!n)}async function Y(e){let t=e.spawn??f,n=V(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,windowsHide:!0,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=J(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function X(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const ne=t;function Z(e,t,n=e=>C(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function Q(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function $(e){let t=e.sigtermGraceMs??ne,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>w(e)),i=e.reason??`teardown`;try{let a=e.readUiLock(),o=e.spawnedUiPid();if(a&&e.isAlive(a.pid)&&a.pid!==o)e.log?.info({pid:a.pid,port:a.port,spawnedUiPid:o},`${i}: ui.lock holder is not our spawned sibling — leaving it alone`);else if(a&&e.isAlive(a.pid))try{e.killPid(a.pid,`SIGTERM`),e.log?.info({pid:a.pid,port:a.port},`${i}: SIGTERM UI sibling`);let o=Date.now()+t;for(;Date.now()<o&&e.isAlive(a.pid);)await r(n);if(e.isAlive(a.pid))try{e.killPid(a.pid,`SIGKILL`),e.log?.warn({pid:a.pid,graceMs:t},`${i}: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:a.pid,err:t},`${i}: SIGKILL failed`)}}catch(t){e.log?.warn({pid:a.pid,err:t},`${i}: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t},`${i}: UI lookup failed; proceeding`)}}function re(e){let{destroy:t,...n}=e;return async()=>{await $({...n,reason:`idle-shutdown`}),await t()}}async function ie(e){let{config:t,cwd:a,host:o}=e,s=e.skipAutoInit??!1,d=e.skipUiAutoSpawn??!1,f=e.idleThresholdMs??18e5,{existsSync:p,mkdirSync:m}=await import(`node:fs`),{basename:h,dirname:g}=await import(`node:path`),{bootServer:_,getLogger:v,isProcessAlive:y,readUiLock:b,resolveContentDir:x,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./src-DHVO9P4d.mjs`),T=e.log??v(`start`),E=e.singleFile!==void 0,D=e.projectDir??a,O=E?r(e.singleFile).canonicalFilePath:void 0,k=O?g(O):void 0,A=O?h(O):void 0;if(!E){if(!s&&!i(a))throw new U(a);let t=process.env.OK_RECLAIM_DISABLE??null,n=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&T.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-DHQ158Ii.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-qcHlix78.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-Buq5QlSJ.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let j=k??x(t,a);!E&&!p(j)&&(m(j,{recursive:!0}),T.info({contentDir:j},`Created content directory`));let M=null,N=null,P=async({lockDir:t})=>{if(M=W({uiLock:b(t),isAlive:y}),M.action===`spawn`&&!d)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];N=G({lockDir:t,cwd:a,spawn:e.spawn,args:n}).pid??null,T.info({reason:M.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else M.action===`skip`&&T.info({port:M.port,pid:M.pid},`UI already running at port ${M.port}`)},F=e.reactShellDistDir===void 0,I=c(),L=n();{let e=S(E?D:a),t=Date.now(),n=await C(e);n!==`no-drain`&&T.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let R=await _({config:t,contentDir:j,projectDir:E?D:a,contentRoot:E?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:l,tokenStore:I,embeddingsKeyStore:L,...E?{ephemeral:!0,singleDocRelPath:A,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>u(e,t),attachUiSibling:F,idleShutdownMs:f,skipAutoInit:!0,...F?{spawnUiSiblingFn:P}:{},idleShutdownHandler:t=>{let n=re({readUiLock:()=>b(R.lockDir),spawnedUiPid:()=>N,isAlive:y,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:T});return Q(E?Z(n,D):n,{log:T,exit:e.idleExit})},log:T,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});M||={action:`skip`,reason:`alive`,pid:0,port:0};let z=M,B=null;if(z.action===`skip`)B=z.port>0?z.port:null;else if(!d){let t=e.uiBindTimeoutMs??3e3;B=await X({readUiLock:()=>b(R.lockDir),now:Date.now,sleep:e=>w(e),timeoutMs:t,pollIntervalMs:50}),B===null&&T.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:R.httpServer,destroy:R.destroy,lockDir:R.lockDir,contentDir:j,port:R.port,ready:R.ready,degraded:R.degraded,uiSpawnDecision:M,spawnedUiPid:N,resolvedUiPort:B}}function ae(e){if(e===`browser`||e===`app`)return e;throw new s(`--mode must be 'browser' or 'app'`)}function oe(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new s(`--ui-port must be a port number between 1 and 65535`);return t}function se(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function ce(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function le(e,t){let n=se(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner--DGfdMN8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-MGDi6UGf.mjs`),c=process.cwd(),l=e;process.title=H(c);let u=te(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=K(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./src-DHVO9P4d.mjs`);if(q(m,e(t(c)))){await Y({cwd:c,uiPort:m});return}}let g;try{g=await ie({config:l,cwd:c,host:u,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets===void 0?{}:{serveContentAssets:t.serveContentAssets},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof U&&(console.error(o(e.message)),process.exit(1));let t=await import(`./src-DHVO9P4d.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&ue(e,t)){await Y({cwd:c,uiPort:m});return}let n=de(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=ce(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));if(g.spawnedUiPid!==null)try{let{getLogger:e,isProcessAlive:t,readUiLock:n}=await import(`./src-DHVO9P4d.mjs`);await $({readUiLock:()=>n(g.lockDir),spawnedUiPid:()=>g.spawnedUiPid,isAlive:t,killPid:(e,t)=>process.kill(e,t),log:e(`start`),reason:`shutdown`})}catch(e){console.error(`${o(`ui sibling teardown failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`)}try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${u}:${g.port}`,b=u===`0.0.0.0`||u===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${u}:${x}`:y;console.log(r({name:`open-knowledge`,version:d,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-CXby8R3t.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function ue(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function de(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=h(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function fe(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,oe).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ae).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
1
+ import{L as e,P as t}from"./src-CJ8mKCzo.mjs";import{_i as n,a as r,gn as i,ui as a}from"./src-CIFd3tOE.mjs";import{C as o,w as s}from"./write-project-skill-CeYehb7h.mjs";import{a as c,n as l,t as u}from"./acp-harness-probe-PwxCSk8L.mjs";import{n as d}from"./constants-CcMCMPg3.mjs";import{spawn as f}from"node:child_process";import{basename as p,dirname as m,join as h,win32 as g}from"node:path";import{closeSync as _,existsSync as v,mkdirSync as y,openSync as b,statSync as x}from"node:fs";import{homedir as S}from"node:os";import{rm as C}from"node:fs/promises";import{setTimeout as w}from"node:timers/promises";function T(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function E(e,t,n={}){let r=(n.spawn??f)(e,[...t],a({detached:!0,stdio:`ignore`,env:T(n.env??process.env)}));return r.unref(),r}const D=`OpenKnowledge.app`,O=`/Applications/${D}`;function k(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return x(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function A(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(j(e,O))return O;let t=h(e.homeDir??S(),`Applications`,D);return j(e,t)?t:null}function j(e,t){return M(e,h(t,`Contents`,`MacOS`,`OpenKnowledge`))}function M(e,t){try{let n=e.statSync(t);return n&&typeof n.isFile==`function`?n.isFile():!1}catch{return!1}}const N=[`@inkeepopen-knowledge-desktop`,`OpenKnowledge`];function P(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&/\\OpenKnowledge\.exe$/i.test(e.execPath))return e.execPath;let t=e.env.LOCALAPPDATA;if(t)for(let n of N){let r=g.join(t,`Programs`,n,`OpenKnowledge.exe`);if(M(e,r))return r}return null}function F(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&e.execPath.endsWith(`/openknowledge`))return e.execPath;let t=`/opt/OpenKnowledge/openknowledge`;return M(e,t)?t:null}function I(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`&&e.platform!==`win32`&&e.platform!==`linux`)return{available:!1,reason:`unsupported-platform`};let t;try{t=e.platform===`darwin`?A(e):e.platform===`win32`?P(e):F(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:!(e.isTTY===!0||e.platform===`win32`&&e.isTTY===void 0&&!e.env.CI)||e.env.SSH_CONNECTION||e.env.SSH_TTY||e.platform===`linux`&&!e.env.DISPLAY&&!e.env.WAYLAND_DISPLAY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function L(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;if(n("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)"),r===`darwin`){E(`open`,[`-b`,`com.inkeep.open-knowledge`],{spawn:e.spawn});return}let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}E(i,[],{spawn:e.spawn})}function R(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it, or omit --mode for browser mode.`;case`darwin-only`:case`unsupported-platform`:return`Desktop app is not available on this platform. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect the desktop install (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available but launch dispatch did not fire (caller bug).`}}function z(e){return h(m(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const B=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function ee(e){if(e.platform!==`darwin`||!B.test(e.execPath))return null;let t=z(e.execPath);return e.exists(t)?t:null}function V(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??v,a=r[1];return a?{command:ee({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function te(e,t){return e.host??t.HOST??`127.0.0.1`}function H(e){let t=p(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var U=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function W(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function G(t){v(t.lockDir)||y(t.lockDir,{recursive:!0});let n=b(h(t.lockDir,e),`w`),r=t.spawn??f,{PORT:i,...a}=process.env,o=V();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],windowsHide:!0,cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{_(n)}catch{}}}function K(e,t,n){return e??(n===void 0?t:void 0)}function q(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function J(e,t,n){return e??+(t!=null&&!n)}async function Y(e){let t=e.spawn??f,n=V(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,windowsHide:!0,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=J(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function X(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const ne=t;function Z(e,t,n=e=>C(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function Q(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function $(e){let t=e.sigtermGraceMs??ne,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>w(e)),i=e.reason??`teardown`;try{let a=e.readUiLock(),o=e.spawnedUiPid();if(a&&e.isAlive(a.pid)&&a.pid!==o)e.log?.info({pid:a.pid,port:a.port,spawnedUiPid:o},`${i}: ui.lock holder is not our spawned sibling — leaving it alone`);else if(a&&e.isAlive(a.pid))try{e.killPid(a.pid,`SIGTERM`),e.log?.info({pid:a.pid,port:a.port},`${i}: SIGTERM UI sibling`);let o=Date.now()+t;for(;Date.now()<o&&e.isAlive(a.pid);)await r(n);if(e.isAlive(a.pid))try{e.killPid(a.pid,`SIGKILL`),e.log?.warn({pid:a.pid,graceMs:t},`${i}: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:a.pid,err:t},`${i}: SIGKILL failed`)}}catch(t){e.log?.warn({pid:a.pid,err:t},`${i}: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t},`${i}: UI lookup failed; proceeding`)}}function re(e){let{destroy:t,...n}=e;return async()=>{await $({...n,reason:`idle-shutdown`}),await t()}}async function ie(e){let{config:t,cwd:a,host:o}=e,s=e.skipAutoInit??!1,d=e.skipUiAutoSpawn??!1,f=e.idleThresholdMs??18e5,{existsSync:p,mkdirSync:m}=await import(`node:fs`),{basename:h,dirname:g}=await import(`node:path`),{bootServer:_,getLogger:v,isProcessAlive:y,readUiLock:b,resolveContentDir:x,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./src-DHVO9P4d.mjs`),T=e.log??v(`start`),E=e.singleFile!==void 0,D=e.projectDir??a,O=E?r(e.singleFile).canonicalFilePath:void 0,k=O?g(O):void 0,A=O?h(O):void 0;if(!E){if(!s&&!i(a))throw new U(a);let t=process.env.OK_RECLAIM_DISABLE??null,n=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&T.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-DpdVVhiU.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-CZawWAqd.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-Buq5QlSJ.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:n})}catch(e){T.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let j=k??x(t,a);!E&&!p(j)&&(m(j,{recursive:!0}),T.info({contentDir:j},`Created content directory`));let M=null,N=null,P=async({lockDir:t})=>{if(M=W({uiLock:b(t),isAlive:y}),M.action===`spawn`&&!d)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];N=G({lockDir:t,cwd:a,spawn:e.spawn,args:n}).pid??null,T.info({reason:M.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else M.action===`skip`&&T.info({port:M.port,pid:M.pid},`UI already running at port ${M.port}`)},F=e.reactShellDistDir===void 0,I=c(),L=n();{let e=S(E?D:a),t=Date.now(),n=await C(e);n!==`no-drain`&&T.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let R=await _({config:t,contentDir:j,projectDir:E?D:a,contentRoot:E?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:l,tokenStore:I,embeddingsKeyStore:L,...E?{ephemeral:!0,singleDocRelPath:A,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>u(e,t),attachUiSibling:F,idleShutdownMs:f,skipAutoInit:!0,...F?{spawnUiSiblingFn:P}:{},idleShutdownHandler:t=>{let n=re({readUiLock:()=>b(R.lockDir),spawnedUiPid:()=>N,isAlive:y,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:T});return Q(E?Z(n,D):n,{log:T,exit:e.idleExit})},log:T,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});M||={action:`skip`,reason:`alive`,pid:0,port:0};let z=M,B=null;if(z.action===`skip`)B=z.port>0?z.port:null;else if(!d){let t=e.uiBindTimeoutMs??3e3;B=await X({readUiLock:()=>b(R.lockDir),now:Date.now,sleep:e=>w(e),timeoutMs:t,pollIntervalMs:50}),B===null&&T.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:R.httpServer,destroy:R.destroy,lockDir:R.lockDir,contentDir:j,port:R.port,ready:R.ready,degraded:R.degraded,uiSpawnDecision:M,spawnedUiPid:N,resolvedUiPort:B}}function ae(e){if(e===`browser`||e===`app`)return e;throw new s(`--mode must be 'browser' or 'app'`)}function oe(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new s(`--ui-port must be a port number between 1 and 65535`);return t}function se(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function ce(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function le(e,t){let n=se(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner--DGfdMN8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-MGDi6UGf.mjs`),c=process.cwd(),l=e;process.title=H(c);let u=te(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=K(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./src-DHVO9P4d.mjs`);if(q(m,e(t(c)))){await Y({cwd:c,uiPort:m});return}}let g;try{g=await ie({config:l,cwd:c,host:u,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets===void 0?{}:{serveContentAssets:t.serveContentAssets},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof U&&(console.error(o(e.message)),process.exit(1));let t=await import(`./src-DHVO9P4d.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&ue(e,t)){await Y({cwd:c,uiPort:m});return}let n=de(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=ce(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));if(g.spawnedUiPid!==null)try{let{getLogger:e,isProcessAlive:t,readUiLock:n}=await import(`./src-DHVO9P4d.mjs`);await $({readUiLock:()=>n(g.lockDir),spawnedUiPid:()=>g.spawnedUiPid,isAlive:t,killPid:(e,t)=>process.kill(e,t),log:e(`start`),reason:`shutdown`})}catch(e){console.error(`${o(`ui sibling teardown failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`)}try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${u}:${g.port}`,b=u===`0.0.0.0`||u===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${u}:${x}`:y;console.log(r({name:`open-knowledge`,version:d,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-CXby8R3t.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function ue(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function de(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=h(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function fe(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,oe).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ae).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
2
2
  `),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.uiPort!==void 0&&e.push(`--ui-port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=I(k());if(n.available){L({spawn:f},n);return}console.error(R(n.reason)),process.exit(1)}await le(n,t)})}export{k as C,E,V as S,L as T,fe as _,J as a,Z as b,H as c,K as d,te as f,G as g,q as h,re as i,ce as l,le as m,X as n,Y as o,se as p,ie as r,W as s,U as t,ue as u,$ as v,I as w,Q as x,de as y};
3
- //# sourceMappingURL=start-B9UTrPaX.mjs.map
3
+ //# sourceMappingURL=start-FUQOcvoI.mjs.map
@@ -0,0 +1 @@
1
+ import{_ as e,f as t,r as n}from"./start-FUQOcvoI.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.42.0-beta.12",
3
+ "version": "0.42.0-beta.13",
4
4
  "license": "GPL-3.0-or-later",
5
5
  "private": false,
6
6
  "type": "module",
@@ -61,10 +61,10 @@
61
61
  "ajv-formats": "^3.0.1",
62
62
  "tsdown": "^0.21.7",
63
63
  "typescript": "^5.9.3",
64
- "@inkeep/open-knowledge-app": "0.42.0-beta.12",
65
- "@inkeep/open-knowledge-core": "0.42.0-beta.12",
64
+ "@inkeep/open-knowledge-core": "0.42.0-beta.13",
65
+ "@inkeep/open-knowledge-app": "0.42.0-beta.13",
66
66
  "@inkeep/open-knowledge-native-config": "0.0.0",
67
- "@inkeep/open-knowledge-server": "0.42.0-beta.12"
67
+ "@inkeep/open-knowledge-server": "0.42.0-beta.13"
68
68
  },
69
69
  "scripts": {
70
70
  "build:cli": "tsdown",
@@ -1,2 +0,0 @@
1
- import"./src-CJ8mKCzo.mjs";var e=`0.42.0-beta.12`;const t=`config.yml`,n=e;export{n,t};
2
- //# sourceMappingURL=constants-DDOp7euF.mjs.map
@@ -1 +0,0 @@
1
- import{g as e}from"./init-DnPkN5n-.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-DCNyG4ZR.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-CfZ5AA27.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{t as e}from"./index-BOJ7Bris.js";export{e as FeedbackForm};
@@ -1,2 +0,0 @@
1
- import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./jsx-runtime-BUgB2tll.js";import{t as n}from"./react-f2sANaYj.js";import{n as r,r as i}from"./dist-Nvb76hAm.js";import{t as a}from"./compiler-runtime-BfE3aGVn.js";import{t as o}from"./createLucideIcon-DAkhoPjT.js";import{t as s}from"./button-Gol9BgNB.js";import{a as c,c as l,i as u,n as d,o as f,s as p,t as m}from"./dialog-TkFkuYVg.js";import{t as h}from"./checkbox-DY-vIhnZ.js";import{o as g}from"./dist-DbWN0KUu.js";import{t as _}from"./check-GqWaoTdV.js";import{n as v,t as y}from"./CopyButton-1Q6Wnnjb.js";import{t as b}from"./loader-circle-Cg5SU7AZ.js";import{n as ee}from"./BugReportHistory-B0qbbAw0.js";import{t as te}from"./triangle-alert-Clgvyc7B.js";import{t as ne}from"./input-D0ZW0Opq.js";import{t as re}from"./badge-Dba4cvJR.js";import{t as x}from"./external-link-T4Nj1gcG.js";import{n as ie}from"./clipboard-adapter--Ja4oXEM.js";import{t as ae}from"./textarea-RSYJwPz9.js";var oe=o(`archive`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8`,key:`1s80jp`}],[`path`,{d:`M10 12h4`,key:`a56b0p`}]]),se=o(`shield`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}]]),ce=a(),S=e(n(),1),C=t(),w=`support@inkeep.com`;function le(e){return`mailto:${w}?subject=${encodeURIComponent(e)}`}function ue(e){let t=(0,ce.c)(7),{href:n}=e,r,i;t[0]===n?(r=t[1],i=t[2]):(r=e=>x(e,n),i=e=>x(e,n),t[0]=n,t[1]=r,t[2]=i);let a;return t[3]!==n||t[4]!==r||t[5]!==i?(a=(0,C.jsx)(`a`,{href:n,onClick:r,onAuxClick:i,className:`text-primary hover:underline`,children:w}),t[3]=n,t[4]=r,t[5]=i,t[6]=a):a=t[6],a}function de(e,t){let n=e.trim();if(t===void 0)return n===``?void 0:n;let r=t.join(`
2
- `);return n===``?r:`${n}\n\n${r}`}function fe(e){let t=[`Crash source: ${e.source}`];return e.docName!==void 0&&t.push(`Document: ${e.docName}`),e.errorMessage!==void 0&&t.push(`Error: ${e.errorMessage}`),t}function pe(e){return[`Crash source: ${e.kind===`render-process-gone`?`renderer process crash (reason: ${e.context.reason})`:e.kind===`child-process-gone`?`${e.context.processType} process crash (reason: ${e.context.reason})`:e.context.dirtyShutdown?`previous session ended without a clean quit`:`new crash dump found from the previous session`}`,`Crash event: ${e.eventId}`]}var me={step:`compose`,creating:!1,createError:null};function he(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.max(1,Math.round(e/1024))} KB`:`${e} B`}function T(e){return e.split(/[\\/]/).pop()??e}function ge(e){return e.summary.files.some(e=>e.startsWith(`extra/`)&&e!==g)}function E(e){let t=(0,ce.c)(93),{open:n,onOpenChange:a,systemWide:o,crashContext:g,crashInvite:x,screenshot:oe}=e,w=o===void 0?!1:o,T=oe===void 0?null:oe,{_:E}=i(),[D,O]=(0,S.useState)(me),[k,be]=(0,S.useState)(``),[A,xe]=(0,S.useState)(g!==void 0||x!==void 0),j=x?.minidumpAvailable===!0,[M,Se]=(0,S.useState)(j),[N,Ce]=(0,S.useState)(!0),[we,Te]=(0,S.useState)(0),P=(0,S.useRef)(0),Ee=(0,S.useId)(),De=(0,S.useId)(),Oe=(0,S.useId)(),F=(0,S.useId)(),I=(0,S.useId)(),L=(0,S.useId)(),R=(0,S.useId)(),z=(0,S.useId)(),B=(0,S.useId)(),V=(0,S.useId)(),H=(0,S.useId)(),U=D.step===`sending`,ke;t[0]!==g||t[1]!==x?(ke=g===void 0?x===void 0?void 0:pe(x):fe(g),t[0]=g,t[1]=x,t[2]=ke):ke=t[2];let W=ke,Ae,je;t[3]===U?(Ae=t[4],je=t[5]):(Ae=()=>{if(!U)return;Te(0);let e=Date.now(),t=setInterval(()=>{let t=(Date.now()-e)/1e3;Te(Math.min(.9,1-Math.exp(-t/3)))},200);return()=>{clearInterval(t)}},je=[U],t[3]=U,t[4]=Ae,t[5]=je),(0,S.useEffect)(Ae,je);let Me;t[6]!==g||t[7]!==j||t[8]!==x||t[9]!==a||t[10]!==D.step?(Me=function(e){!e&&D.step===`sending`||(e||(P.current+=1,(D.step===`success`||D.step===`email`||D.step===`failure`)&&(be(``),xe(g!==void 0||x!==void 0),Se(j),Ce(!0)),O(me)),a(e))},t[6]=g,t[7]=j,t[8]=x,t[9]=a,t[10]=D.step,t[11]=Me):Me=t[11];let G=Me,Ne;t[12]!==E||t[13]!==j||t[14]!==A||t[15]!==M||t[16]!==N||t[17]!==k||t[18]!==W||t[19]!==T?(Ne=async function(){let e=window.okDesktop?.bugReport;if(!e){O({step:`compose`,creating:!1,createError:E({id:`_0JUKX`})});return}let t=P.current+=1;O({step:`compose`,creating:!0,createError:null});let n=await e.create({level:A?`full`:`standard`,note:de(k,W),...j?{includeCrashDump:M}:{},...T===null?{}:{includeScreenshot:N}});P.current===t&&(n.ok?O({step:`review`,report:{zipPath:n.zipPath,zipSizeBytes:n.zipSizeBytes,summary:n.summary}}):O({step:`compose`,creating:!1,createError:n.error}))},t[12]=E,t[13]=j,t[14]=A,t[15]=M,t[16]=N,t[17]=k,t[18]=W,t[19]=T,t[20]=Ne):Ne=t[20];let Pe=Ne,Fe;t[21]!==k||t[22]!==W?(Fe=async function(e){let t=window.okDesktop?.bugReport;if(!t)return;let n=P.current+=1;O({step:`sending`,report:e});let r=await t.send({zipPath:e.zipPath,metadata:{level:e.summary.level,systemWide:e.summary.systemWide,projectSlug:e.summary.projectSlug,note:de(k,W)}});P.current===n&&(r.ok?O({step:`success`,report:e,reference:r.reference}):r.reason===`email-draft`?O({step:`email`,report:e,mailtoUrl:r.fallback.mailtoUrl}):O({step:`failure`,report:e,mailtoUrl:r.fallback.mailtoUrl}))},t[21]=k,t[22]=W,t[23]=Fe):Fe=t[23];let K=Fe,Ie;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(Ie=function(e){P.current+=1,O({step:`review`,report:e})},t[24]=Ie):Ie=t[24];let Le=Ie,Re;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Re=function(e){window.okDesktop?.shell.showItemInFolder(e)},t[25]=Re):Re=t[25];let ze=Re,Be;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(Be=function(e){window.okDesktop?.shell.openExternal(e)},t[26]=Be):Be=t[26];let Ve=Be,He;t[27]===we?He=t[28]:(He=Math.round(we*100),t[27]=we,t[28]=He);let Ue=He,We=!U,q;t[29]!==E||t[30]!==g||t[31]!==j||t[32]!==x||t[33]!==A||t[34]!==I||t[35]!==F||t[36]!==R||t[37]!==L||t[38]!==Pe||t[39]!==G||t[40]!==M||t[41]!==N||t[42]!==Oe||t[43]!==De||t[44]!==k||t[45]!==Ee||t[46]!==D.createError||t[47]!==D.creating||t[48]!==D.step||t[49]!==T||t[50]!==B||t[51]!==z||t[52]!==w||t[53]!==H?(q=D.step===`compose`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(p,{children:[(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`cd5EXh`})}),x===void 0&&(0,C.jsx)(c,{children:(0,C.jsx)(r,{id:`rD-woT`})})]}),(0,C.jsxs)(d,{className:`flex flex-col gap-5`,children:[x!==void 0&&(0,C.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-md border border-chart-3/35 bg-chart-3/10 px-3 py-2.5 text-sm`,children:[(0,C.jsx)(te,{className:`mt-0.5 size-4 shrink-0 text-chart-3`,"aria-hidden":`true`}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`p`,{className:`font-medium`,children:(0,C.jsx)(r,{id:`_IGfXZ`})}),(0,C.jsx)(c,{className:`mt-0.5 text-xs`,children:(0,C.jsx)(r,{id:`03wKPg`})})]})]}),D.createError!==null&&(0,C.jsxs)(`div`,{role:`alert`,className:`flex items-start gap-2.5 rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2.5 text-sm`,children:[(0,C.jsx)(v,{className:`mt-0.5 size-4 shrink-0 text-destructive`,"aria-hidden":`true`}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`p`,{className:`font-medium`,children:(0,C.jsx)(r,{id:`wVa83H`})}),(0,C.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:D.createError}),(0,C.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:(0,C.jsx)(r,{id:`5PHgV2`,components:{0:(0,C.jsx)(`code`,{className:`font-mono`})}})})]})]}),(0,C.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,C.jsxs)(`label`,{htmlFor:Ee,className:`text-sm font-medium`,children:[x===void 0?(0,C.jsx)(r,{id:`y_K0Dz`}):(0,C.jsx)(r,{id:`60vpJN`}),` `,(0,C.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:(0,C.jsx)(r,{id:`NzluOx`})})]}),(0,C.jsx)(ae,{id:Ee,value:k,onChange:e=>be(e.target.value),placeholder:E(x===void 0?{id:`YLMBSd`}:{id:`T3j-7o`}),rows:3,className:`resize-none`,disabled:D.creating})]}),(0,C.jsxs)(`div`,{role:`group`,"aria-labelledby":H,className:`flex flex-col gap-3.5`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,C.jsx)(`p`,{id:H,className:`text-sm font-medium`,children:(0,C.jsx)(r,{id:`WJjviG`})}),x===void 0&&(0,C.jsx)(`p`,{className:`text-1sm text-muted-foreground`,children:g===void 0?(0,C.jsx)(r,{id:`2H43L8`}):(0,C.jsx)(r,{id:`GZzDqc`})})]}),(0,C.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,C.jsx)(h,{id:De,checked:!0,disabled:!0,"aria-describedby":Oe,className:`mt-0.5`}),(0,C.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,C.jsxs)(`label`,{htmlFor:De,className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,C.jsx)(r,{id:`FgRAvd`}),(0,C.jsx)(re,{variant:`primary`,className:`text-2xs`,children:(0,C.jsx)(r,{id:`C0hoX6`})})]}),(0,C.jsx)(`p`,{id:Oe,className:`text-1sm text-muted-foreground`,children:w?(0,C.jsx)(r,{id:`ZoOlzR`}):(0,C.jsx)(r,{id:`2FnYUD`})})]})]}),(0,C.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,C.jsx)(h,{id:F,checked:A,onCheckedChange:e=>xe(e===!0),"aria-describedby":I,disabled:D.creating,className:`mt-0.5`}),(0,C.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,C.jsx)(`label`,{htmlFor:F,className:`text-sm font-medium`,children:(0,C.jsx)(r,{id:`zvjCD4`})}),(0,C.jsx)(`p`,{id:I,className:`text-1sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`ULRb5t`})})]})]}),T!==null&&(0,C.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,C.jsx)(h,{id:z,checked:N,onCheckedChange:e=>Ce(e===!0),"aria-describedby":B,disabled:D.creating,className:`mt-0.5`}),(0,C.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,C.jsx)(`label`,{htmlFor:z,className:`text-sm font-medium`,children:(0,C.jsx)(r,{id:`IxyZXD`})}),(0,C.jsx)(`p`,{id:B,className:`text-1sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`yzYE4B`})}),(0,C.jsx)(`div`,{className:`mt-2 overflow-hidden rounded-md border bg-muted/40`,children:(0,C.jsx)(`img`,{src:T.dataUrl,alt:E({id:`WuntOK`}),className:`block max-h-44 w-full object-contain transition-opacity motion-reduce:transition-none ${N?`opacity-100`:`opacity-40`}`})})]})]}),j&&(0,C.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,C.jsx)(h,{id:L,checked:M,onCheckedChange:e=>Se(e===!0),"aria-describedby":R,disabled:D.creating,className:`mt-0.5`}),(0,C.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,C.jsx)(`label`,{htmlFor:L,className:`text-sm font-medium`,children:(0,C.jsx)(r,{id:`8TvlHF`})}),(0,C.jsx)(`p`,{id:R,className:`text-1sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`jnCROW`})})]})]})]}),x===void 0&&g===void 0?(0,C.jsx)(ee,{}):null]}),(0,C.jsxs)(f,{children:[(0,C.jsx)(s,{variant:`ghost`,className:`font-mono uppercase`,onClick:()=>G(!1),children:x===void 0?(0,C.jsx)(r,{id:`dEgA5A`}):(0,C.jsx)(r,{id:`PBxg_E`})}),(0,C.jsxs)(s,{onClick:()=>void Pe(),disabled:D.creating,children:[D.creating&&(0,C.jsx)(b,{className:`size-4 animate-spin motion-reduce:animate-none`,"aria-hidden":`true`}),(0,C.jsx)(r,{id:`Si7mIR`})]})]})]}),t[29]=E,t[30]=g,t[31]=j,t[32]=x,t[33]=A,t[34]=I,t[35]=F,t[36]=R,t[37]=L,t[38]=Pe,t[39]=G,t[40]=M,t[41]=N,t[42]=Oe,t[43]=De,t[44]=k,t[45]=Ee,t[46]=D.createError,t[47]=D.creating,t[48]=D.step,t[49]=T,t[50]=B,t[51]=z,t[52]=w,t[53]=H,t[54]=q):q=t[54];let J;t[55]!==K||t[56]!==D.report||t[57]!==D.step?(J=D.step===`review`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(p,{children:[(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`2AIVbm`})}),(0,C.jsx)(c,{children:(0,C.jsx)(r,{id:`3l_cXP`})})]}),(0,C.jsxs)(d,{className:`flex flex-col gap-4`,children:[(0,C.jsx)(ye,{zipPath:D.report.zipPath,zipSizeBytes:D.report.zipSizeBytes,fileCount:D.report.summary.files.length,rawDumpIncluded:ge(D.report),onReveal:ze}),(0,C.jsxs)(`div`,{className:`flex items-start gap-2 rounded-md border bg-muted/50 px-3 py-2.5 text-xs text-muted-foreground`,children:[(0,C.jsx)(se,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,C.jsx)(`span`,{children:(0,C.jsx)(r,{id:`-o5XAG`})})]})]}),(0,C.jsxs)(f,{className:`sm:justify-between`,children:[(0,C.jsx)(s,{variant:`ghost`,className:`font-mono uppercase`,onClick:()=>O(me),children:(0,C.jsx)(r,{id:`iH8pgl`})}),(0,C.jsx)(s,{onClick:()=>void K(D.report),children:(0,C.jsx)(r,{id:`O9oQJS`})})]})]}),t[55]=K,t[56]=D.report,t[57]=D.step,t[58]=J):J=t[58];let Y;t[59]!==E||t[60]!==D.report||t[61]!==D.step||t[62]!==Ue?(Y=D.step===`sending`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(p,{children:[(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`M5_9s2`})}),(0,C.jsx)(c,{className:`sr-only`,children:(0,C.jsx)(r,{id:`MJqRO6`})})]}),(0,C.jsxs)(d,{className:`flex flex-col gap-3`,children:[(0,C.jsxs)(`div`,{role:`status`,className:`flex items-center gap-2.5 text-sm`,children:[(0,C.jsx)(b,{className:`size-4 shrink-0 animate-spin text-primary motion-reduce:animate-none`,"aria-hidden":`true`}),(0,C.jsx)(r,{id:`qmL1UG`}),(0,C.jsx)(`span`,{className:`ml-auto text-xs text-muted-foreground`,children:(0,C.jsx)(r,{id:`JJcBCm`,values:{0:he(D.report.zipSizeBytes)}})})]}),(0,C.jsx)(`div`,{role:`progressbar`,"aria-label":E({id:`M5_9s2`}),className:`h-1.5 overflow-hidden rounded-full bg-secondary`,children:(0,C.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Ue}%`}})})]}),(0,C.jsxs)(f,{className:`sm:justify-between`,children:[(0,C.jsx)(s,{variant:`ghost`,className:`font-mono uppercase`,onClick:()=>Le(D.report),children:(0,C.jsx)(r,{id:`dEgA5A`})}),(0,C.jsx)(s,{disabled:!0,children:(0,C.jsx)(r,{id:`O9oQJS`})})]})]}),t[59]=E,t[60]=D.report,t[61]=D.step,t[62]=Ue,t[63]=Y):Y=t[63];let X;t[64]!==E||t[65]!==G||t[66]!==D.reference||t[67]!==D.step||t[68]!==V?(X=D.step===`success`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d,{children:(0,C.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,C.jsxs)(`div`,{role:`status`,className:`flex flex-col gap-3`,children:[(0,C.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,C.jsx)(_,{className:`size-5 shrink-0 text-primary`,"aria-hidden":`true`}),(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`IYciRC`})})]}),(0,C.jsx)(c,{children:(0,C.jsx)(r,{id:`2myNzt`})})]}),(0,C.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,C.jsx)(`label`,{htmlFor:V,className:`text-sm font-medium`,children:(0,C.jsx)(r,{id:`M-IF14`})}),(0,C.jsxs)(`div`,{className:`relative`,children:[(0,C.jsx)(ne,{id:V,readOnly:!0,value:D.reference,onFocus:ve,onClick:_e,className:`select-all bg-muted pr-9 font-mono text-sm font-medium tracking-wide`}),(0,C.jsx)(`div`,{className:`absolute inset-y-0 right-1 flex items-center`,children:(0,C.jsx)(y,{copyContent:D.reference,clipboardWrite:ie})})]})]}),(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`fxJk_6`,components:{0:(0,C.jsx)(`span`,{className:`font-medium text-foreground`}),1:(0,C.jsx)(ue,{href:le(E({id:`qEEfPk`,values:{0:D.reference}}))})}})})]})}),(0,C.jsx)(f,{children:(0,C.jsx)(s,{onClick:()=>G(!1),children:(0,C.jsx)(r,{id:`DPfwMq`})})})]}),t[64]=E,t[65]=G,t[66]=D.reference,t[67]=D.step,t[68]=V,t[69]=X):X=t[69];let Z;t[70]!==G||t[71]!==D.mailtoUrl||t[72]!==D.report||t[73]!==D.step?(Z=D.step===`email`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(p,{children:[(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`6zzhQL`})}),(0,C.jsx)(c,{children:(0,C.jsx)(r,{id:`UTgWxm`})})]}),(0,C.jsxs)(d,{className:`flex flex-col gap-4`,children:[(0,C.jsx)(ye,{zipPath:D.report.zipPath,zipSizeBytes:D.report.zipSizeBytes,fileCount:D.report.summary.files.length,rawDumpIncluded:ge(D.report),onReveal:ze}),(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`9XIEYq`,components:{0:(0,C.jsx)(ue,{href:D.mailtoUrl})}})})]}),(0,C.jsxs)(f,{className:`sm:justify-between`,children:[(0,C.jsx)(s,{variant:`ghost`,className:`font-mono uppercase`,onClick:()=>G(!1),children:(0,C.jsx)(r,{id:`yz7wBu`})}),(0,C.jsx)(s,{onClick:()=>Ve(D.mailtoUrl),children:(0,C.jsx)(r,{id:`GuaJb-`})})]})]}),t[70]=G,t[71]=D.mailtoUrl,t[72]=D.report,t[73]=D.step,t[74]=Z):Z=t[74];let Q;t[75]!==G||t[76]!==K||t[77]!==D.mailtoUrl||t[78]!==D.report||t[79]!==D.step?(Q=D.step===`failure`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(p,{children:[(0,C.jsx)(l,{children:(0,C.jsx)(r,{id:`Wi-VWy`})}),(0,C.jsx)(c,{className:`sr-only`,children:(0,C.jsx)(r,{id:`1OKzC_`})})]}),(0,C.jsxs)(d,{className:`flex flex-col gap-4`,children:[(0,C.jsxs)(`div`,{role:`alert`,className:`flex items-start gap-2.5 rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2.5 text-sm`,children:[(0,C.jsx)(v,{className:`mt-0.5 size-4 shrink-0 text-destructive`,"aria-hidden":`true`}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`p`,{className:`font-medium`,children:(0,C.jsx)(r,{id:`Oawo4U`})}),(0,C.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:(0,C.jsx)(r,{id:`2-CeZn`})})]})]}),(0,C.jsx)(ye,{zipPath:D.report.zipPath,zipSizeBytes:D.report.zipSizeBytes,fileCount:null,rawDumpIncluded:ge(D.report),onReveal:ze}),(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:(0,C.jsx)(r,{id:`9XIEYq`,components:{0:(0,C.jsx)(ue,{href:D.mailtoUrl})}})})]}),(0,C.jsxs)(f,{className:`sm:justify-between`,children:[(0,C.jsx)(s,{variant:`ghost`,className:`font-mono uppercase`,onClick:()=>G(!1),children:(0,C.jsx)(r,{id:`yz7wBu`})}),(0,C.jsxs)(`div`,{className:`flex flex-col-reverse gap-2 sm:flex-row`,children:[(0,C.jsx)(s,{variant:`outline`,className:`font-mono uppercase`,onClick:()=>void K(D.report),children:(0,C.jsx)(r,{id:`KDw4GX`})}),(0,C.jsx)(s,{onClick:()=>Ve(D.mailtoUrl),children:(0,C.jsx)(r,{id:`GuaJb-`})})]})]})]}),t[75]=G,t[76]=K,t[77]=D.mailtoUrl,t[78]=D.report,t[79]=D.step,t[80]=Q):Q=t[80];let $;t[81]!==We||t[82]!==q||t[83]!==J||t[84]!==Y||t[85]!==X||t[86]!==Z||t[87]!==Q?($=(0,C.jsxs)(u,{className:`sm:max-w-xl`,showCloseButton:We,children:[q,J,Y,X,Z,Q]}),t[81]=We,t[82]=q,t[83]=J,t[84]=Y,t[85]=X,t[86]=Z,t[87]=Q,t[88]=$):$=t[88];let Ge;return t[89]!==G||t[90]!==n||t[91]!==$?(Ge=(0,C.jsx)(m,{open:n,onOpenChange:G,children:$}),t[89]=G,t[90]=n,t[91]=$,t[92]=Ge):Ge=t[92],Ge}function _e(e){return e.currentTarget.select()}function ve(e){return e.currentTarget.select()}function ye(e){let t=(0,ce.c)(23),{zipPath:n,zipSizeBytes:i,fileCount:a,rawDumpIncluded:o,onReveal:c}=e,l;t[0]===n?l=t[1]:(l=T(n),t[0]=n,t[1]=l);let u=l,d;t[2]===i?d=t[3]:(d=he(i),t[2]=i,t[3]=d);let f=d,p;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(p=(0,C.jsx)(`div`,{className:`flex items-center justify-center size-8 rounded-md bg-muted`,children:(0,C.jsx)(oe,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":`true`})}),t[4]=p):p=t[4];let m;t[5]===u?m=t[6]:(m=(0,C.jsx)(`p`,{className:`truncate text-1sm`,title:u,children:u}),t[5]=u,t[6]=m);let h;t[7]!==a||t[8]!==o||t[9]!==f?(h=(0,C.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a===null?o?(0,C.jsx)(r,{id:`_FLBbi`,values:{sizeText:f}}):(0,C.jsx)(r,{id:`89y7ar`,values:{sizeText:f}}):o?(0,C.jsx)(r,{id:`sn5BEU`,values:{sizeText:f,fileCount:a}}):(0,C.jsx)(r,{id:`3DJEEt`,values:{sizeText:f,fileCount:a}})}),t[7]=a,t[8]=o,t[9]=f,t[10]=h):h=t[10];let g;t[11]!==m||t[12]!==h?(g=(0,C.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5`,children:[m,h]}),t[11]=m,t[12]=h,t[13]=g):g=t[13];let _;t[14]!==c||t[15]!==n?(_=()=>c(n),t[14]=c,t[15]=n,t[16]=_):_=t[16];let v;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(v=(0,C.jsx)(r,{id:`LtSYdi`}),t[17]=v):v=t[17];let y;t[18]===_?y=t[19]:(y=(0,C.jsx)(s,{variant:`link`,className:`h-auto shrink-0 p-0 text-xs`,onClick:_,children:v}),t[18]=_,t[19]=y);let b;return t[20]!==g||t[21]!==y?(b=(0,C.jsxs)(`div`,{className:`flex items-center gap-2.5 rounded-md border px-3 py-2.5`,children:[p,g,y]}),t[20]=g,t[21]=y,t[22]=b):b=t[22],b}export{E as default};
@@ -1,22 +0,0 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{F as t,I as n,Pa as r}from"./src-CJ8mKCzo.mjs";import{Ai as i,ct as a,hn as o,lt as s,ot as c,st as l,ui as u,ya as d}from"./src-CIFd3tOE.mjs";import{K as f}from"./sleep-B2L0pvp4.mjs";import{O as p,P as m}from"./fs-traced-Cc6WsRtP.mjs";import{b as h,u as g,v as _,y as v}from"./server-lock-Cr23NqXF.mjs";import{t as y}from"./yazl-BafwB467.mjs";import{C as b,d as x,i as ee,v as te,y as S}from"./write-project-skill-CeYehb7h.mjs";import{c as ne}from"./colors-BsmVIwfM.mjs";import"./acp-harness-probe-CjydUqQ4.mjs";import{D as re,E as ie,S as C,T as w,_ as ae,b as oe,o as T,v as E}from"./init-DnPkN5n-.mjs";import{n as D}from"./constants-DDOp7euF.mjs";import{t as O}from"./is-object-ByG7RnjH.mjs";import"./loader-DCNyG4ZR.mjs";import"./preview-CfZ5AA27.mjs";import{execSync as se,spawnSync as k}from"node:child_process";import{basename as A,dirname as j,isAbsolute as M,join as N,relative as ce,resolve as P,sep as le}from"node:path";import{cpSync as ue,createWriteStream as de,existsSync as F,lstatSync as fe,mkdirSync as I,mkdtempSync as pe,readFileSync as L,readdirSync as me,readlinkSync as he,rmSync as ge,statSync as _e,writeFileSync as R}from"node:fs";import{arch as ve,freemem as ye,homedir as be,hostname as xe,platform as Se,release as Ce,tmpdir as we,totalmem as Te,type as Ee,uptime as De}from"node:os";import{realpath as z}from"node:fs/promises";import{createHash as B}from"node:crypto";var V=f();const Oe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function ke(e,t,n=o){if(e!==void 0&&!Oe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ae=null;function je(e){Ae=e}function Me(){return Ae??process.cwd()}const Ne=[{name:`macos-home-path`,regex:/\/Users\/[^/]+\//g,replacement:`~/`},{name:`linux-home-path`,regex:/\/home\/[^/]+\//g,replacement:`~/`},{name:`github-pat`,regex:/\b(ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}\b/g,replacement:`[REDACTED-GH-PAT]`},{name:`aws-access-key`,regex:/\b(AKIA|ASIA|ABIA)[A-Z2-7]{16}\b/g,replacement:`[REDACTED-AWS-KEY]`},{name:`anthropic-key`,regex:/\bsk-ant-api03-[A-Za-z0-9_-]{20,}\b/g,replacement:`[REDACTED-ANTHROPIC]`},{name:`openai-key`,regex:/\bsk-[A-Za-z0-9]{20,}\b/g,replacement:`[REDACTED-OPENAI]`},{name:`bearer-token`,regex:/([Aa]uthorization:\s*[Bb]earer\s+)\S+/g,replacement:`$1[REDACTED]`},{name:`jwt`,regex:/eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,replacement:`[REDACTED-JWT]`},{name:`url-credentials`,regex:/:\/\/[^/\s:@]+:[^/\s:@]+@/g,replacement:`://[REDACTED]@`}],Pe=Ne.map(e=>e.name);function H(e){let t=new Set,n=0;return{redacted:e.split(`
2
- `).map(e=>{let r=e;for(let{name:e,regex:i,replacement:a}of Ne)i.lastIndex=0,i.test(r)&&(t.add(e),n++,i.lastIndex=0,r=r.replace(i,a));return r}).join(`
3
- `),patterns:[...t],lineCount:n}}function Fe(){return N(be(),`.ok`,`bug-reports`)}function Ie(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=Fe(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;F(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function Le(e,t){let n=N(e,`.ok`,`config.yml`);if(F(n))try{let e=L(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 F(N(e,`.ok`))?B(`sha256`).update(P(e)).digest(`hex`).slice(0,12):null}function Re(){let e={timestamp:new Date().toISOString(),platform:Se(),osType:Ee(),osRelease:Ce(),hostname:`[redacted]`,uptime:De(),freeMem:ye(),totalMem:Te(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=se(`sw_vers -productVersion 2>/dev/null`,u({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);F(t)&&(e.okVersion=JSON.parse(L(t,`utf8`)).version)}catch{}return e}function ze(e,t){if(!F(t))return{files:[]};let n=me(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(e&&n.length>0){let t=n.filter(t=>{try{return L(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});t.length>0&&(n=t)}return{files:n}}function Be(e){let n=N(e,`.ok`,`local`);return F(n)?{files:[`server.lock`,`last-spawn-error.log`,t].map(e=>N(n,e)).filter(e=>F(e))}:{files:[]}}function Ve(e){let t=N(e,`.ok`,`local`,`logs`);return F(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>F(e))}:{files:[]}}function He(e){if(e.redact){let{redacted:t,patterns:n,lineCount:r}=H(e.content);e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name),n.length>0&&e.redactions.push({file:e.name,lineCount:r,patterns:n})}else e.zipfile.addBuffer(Buffer.from(e.content,`utf8`),e.name),e.bundleFiles.push(e.name)}function U(e){for(let t of e.files)try{He({zipfile:e.zipfile,name:`${e.prefix}/${A(t)}`,content:L(t,`utf8`),redact:e.redact,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 Ue(t){let{redact:n,outputPath:r,logger:i}=t,a=t.userLogsDir??N(be(),`.ok`,`logs`),o=t.projectDir?Le(t.projectDir,i):null;I(j(r),{recursive:!0}),i?.info({projectSlug:o},`gathering diagnostic data`);let s=Re();s.desktop=t.desktop??null;let{files:c}=ze(o,a),{files:l}=t.projectDir?Be(t.projectDir):{files:[]},{files:u}=t.projectDir?Ve(t.projectDir):{files:[]};i?.info({logFileCount:c.length,lockFileCount:l.length,localSinkFileCount:u.length},`files collected`);let d=[],f=[],{ZipFile:p}=await import(`./yazl-vwTkB7U0.mjs`).then(t=>e(t.default,1)),m=new p;U({zipfile:m,files:c,prefix:`logs`,redact:n,bundleFiles:f,redactions:d,logger:i}),U({zipfile:m,files:l,prefix:`lockdir`,redact:n,bundleFiles:f,redactions:d,logger:i}),U({zipfile:m,files:u,prefix:`local-logs`,redact:n,bundleFiles:f,redactions:d,logger:i});for(let e of t.extraFiles??[])try{let t=L(e.sourcePath),n=`extra/${e.zipName??A(e.sourcePath)}`;m.addBuffer(t,n),f.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&He({zipfile:m,name:`note.txt`,content:t.note,redact:n,bundleFiles:f,redactions:d});let h=JSON.stringify(s,null,2);m.addBuffer(Buffer.from(h,`utf8`),`sysinfo.json`),f.push(`sysinfo.json`);let g={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:o,files:f,redactions:d,sysinfo:s};m.addBuffer(Buffer.from(JSON.stringify(g,null,2),`utf8`),`MANIFEST.json`);let _=d.reduce((e,t)=>e+t.lineCount,0),v=[`# Bug Report Bundle`,``,`Generated: ${g.generatedAt}`,`Project: ${o??`(unscoped)`}`,`Discipline version: ${g.disciplineVersion}`,``,`## Contents`,``,...f.map(e=>`- ${e}`),``,`## Privacy`,``,...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Pe.join(`, `)}`,_>0?`${_} line(s) were scrubbed across ${d.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`]:[`Redaction was disabled for this bundle; file contents are unmodified.`]].join(`
4
- `);m.addBuffer(Buffer.from(v,`utf8`),`README.md`),m.end();let y=de(r);return m.outputStream.pipe(y),await new Promise((e,t)=>{y.on(`close`,e),y.on(`error`,t)}),i?.info({bundlePath:r,fileCount:f.length,redactionCount:_},`bundle written`),{zipPath:r,summary:{projectSlug:o,files:f,redactions:d,redactedLineCount:_,generatedAt:g.generatedAt}}}var We=e(y(),1),W=e(ne(),1);const Ge=new Set([`doc.name`,`currentDoc`]);function Ke(e){return`doc:${B(`sha256`).update(e).digest(`hex`).slice(0,8)}`}function qe(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function Je(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Ke(e);return t.originalToHashed.set(e,r),qe(t,e,r),r}function G(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e,t){if(typeof e==`string`)return G(e,t.contentDir);if(Array.isArray(e))return e.map(e=>q(e,t));if(!K(e))return e;let n=typeof e.key==`string`&&Ge.has(e.key)&&K(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&K(a)){let e=Je(n,t);r[i]={...a,stringValue:e}}else Ge.has(i)&&typeof a==`string`?r[i]=Je(a,t):r[i]=q(a,t);return r}function Ye(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function Xe(e,t){let n=L(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
5
- `),i=n.split(`
6
- `),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=q(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}R(e,r?`${a.join(`
7
- `)}\n`:a.join(`
8
- `))}function Ze(e,t){let n=L(e,`utf-8`);if(n.trim().length!==0)try{let r=q(JSON.parse(n),t),i=n.endsWith(`
9
- `)?`
10
- `:``;R(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=Ye(G(n,t.contentDir),t);r!==n&&R(e,r)}}function Qe(e,t){let n=L(e,`utf-8`),r=G(n,t.contentDir);r!==n&&R(e,r)}function $e(e){try{return me(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const et=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function tt(e){let t={contentDir:e.contentDir,docNameMap:{},originalToHashed:new Map,docNameCollisions:{}};for(let n of[`telemetry`,`logs`,`process`])for(let r of $e(N(e.stagingDir,n)))r.endsWith(`.jsonl`)?Xe(r,t):r.endsWith(`.json`)?Ze(r,t):Qe(r,t);for(let n of $e(N(e.stagingDir,`state`))){let e=A(n);n.endsWith(`.jsonl`)?Xe(n,t):et.has(e)?Ze(n,t):Qe(n,t)}return{docNameMap:t.docNameMap,docNameCollisions:t.docNameCollisions}}const nt=[`.ok`,`local`,`telemetry`],rt=[`.ok`,`local`,`logs`],it=`spans-current.jsonl`,at=`spans-prev.jsonl`,ot=`server-current.jsonl`,st=`server-prev.jsonl`;function ct(e){return N(e,...nt,it)}function lt(e){return N(e,...nt,at)}function ut(e){return N(e,...rt,ot)}function dt(e){return N(e,...rt,st)}const ft=1e3;async function pt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(ft)});return t.ok?await t.text():null}catch{return null}}async function mt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(ft)});return t.ok?await t.text():null}catch{return null}}async function ht(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(ft)});return t.ok?await t.text():null}catch{return null}}function gt(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(`
11
- `)}\n`:null}catch{return null}}function _t(e){let t=N(e,`.git`,`ok`);if(!F(t))return null;let n=k(`git`,[`-C`,t,`log`,`--oneline`,`-50`],u({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function vt(e){let t=N(e,`.git`,`ok`);if(!F(t))return null;let n=k(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],u({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function yt(){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 bt(){return{nodeVersion:process.version,platform:Se(),arch:ve()}}function xt(){return process.env.OTEL_SDK_DISABLED===`false`}function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function St(e){if(!F(e))return{};let t;try{t=(0,V.parse)(L(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(!J(t))return{};let n=t.telemetry;if(!J(n))return{};let r=n.localSink;return J(r)?r:{}}function Ct(e){return typeof e==`boolean`?e:void 0}function wt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y(e){if(J(e))return wt(e.maxBytes)}function Tt(e){let t=St(p(`project`,e)),n=St(p(`project-local`,e));return{enabled:Ct(n.enabled)??Ct(t.enabled)??!0,spansMaxBytes:Y(n.spans)??Y(t.spans)??52428800,logsMaxBytes:Y(n.logs)??Y(t.logs)??26214400}}function Et(e){return B(`sha256`).update(e).digest(`hex`)}function Dt(e){let t=L(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}function Ot(e){let t=L(e,`utf-8`),n=`"doc.name"`,r=0,i=t.indexOf(n);for(;i!==-1;)r++,i=t.indexOf(n,i+10);return r}function X(e,t){return F(e)?(I(j(t),{recursive:!0}),ue(e,t),!0):!1}function kt(e){let t=[],n=e=>{let r=me(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 At=new Set([`.jsonl`]);function jt(e){let t=e.lastIndexOf(`.`);return t===-1?!1:At.has(e.slice(t))}const Mt=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`]);function Nt(e){let t=e.lastIndexOf(`.`);return t===-1?!1:Mt.has(e.slice(t))}function Pt(e){let t=[];for(let n of kt(e)){let r=Ft(e,n);if(!Nt(r))continue;let{redacted:i,patterns:a,lineCount:o}=H(L(n,`utf-8`));a.length!==0&&(R(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function Ft(e,t){return ce(e,t).split(le).join(`/`)}async function It(e){let r=P(e.contentDir),i=P(e.projectDir??e.contentDir),a=e.deps??{},o=a.fetchAgentPresence??pt,s=a.fetchAgentEffects??mt,c=a.fetchWatcherRecent??ht,l=a.readShadowHead??_t,u=a.readCheckpointRefs??vt,d=a.now??(()=>new Date),f=a.okVersion??(()=>D),p=a.readDesktopEnv??yt,m=a.readRuntime??bt,h=a.isOtlpPushEnabled??xt,g=pe(N(we(),`ok-bundle-`));try{I(N(g,`telemetry`),{recursive:!0}),I(N(g,`logs`),{recursive:!0}),I(N(g,`state`),{recursive:!0}),X(ct(i),N(g,`telemetry`,it)),X(lt(i),N(g,`telemetry`,at)),X(ut(i),N(g,`logs`,ot)),X(dt(i),N(g,`logs`,st));let _=N(i,`.ok`,`local`),v=N(_,`server.lock`),y=`not-running`,b=`no server.lock`,x=null;if(F(v)){X(v,N(g,`state`,`server.lock`));try{let e=L(v,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?x=t.port:b=`lock present but no port`}catch{b=`lock present but unparseable`}}if(x!==null){let e=await o(x);e===null?b=`agent-presence endpoint at :${x} unreachable`:(R(N(g,`state`,`agent-presence.json`),e),y=`running`,b=``);let t=await s(x);t!==null&&R(N(g,`state`,`agent-effects.json`),t);let n=await c(x);if(n!==null){let e=gt(n);e!==null&&R(N(g,`state`,`watcher-recent.jsonl`),e)}}let ee=l(r);ee!==null&&R(N(g,`state`,`shadow-head.txt`),ee);let te=u(r);te!==null&&R(N(g,`state`,`checkpoint-refs.txt`),te),X(N(_,`last-spawn-error.log`),N(g,`state`,`last-spawn-error.log`)),X(N(_,n),N(g,`state`,n)),X(N(_,t),N(g,`state`,t));let S=m(),ne=p(),re={ok:{version:f(),nodeVersion:S.nodeVersion,platform:S.platform,arch:S.arch},host:{desktop:ne}};R(N(g,`state`,`runtime.json`),`${JSON.stringify(re,null,2)}\n`);let ie=y===`running`?`running
12
- `:`not-running (${b})\n`;if(R(N(g,`state`,`server-status.txt`),ie),e.processDir&&F(e.processDir)){let t=N(g,`process`);I(t,{recursive:!0}),ue(e.processDir,t,{recursive:!0})}let C=null;e.redact===!0&&(C=tt({stagingDir:g,contentDir:r})),e.note&&R(N(g,`note.txt`),e.note);let w=null;e.scrubSecrets===!0&&(w=Pt(g));for(let t of e.extraFiles??[])X(t.sourcePath,N(g,`extra`,t.zipName??A(t.sourcePath)))||a.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let ae=Tt(i),oe=kt(g),T=[],E=0,D=0;for(let e of oe){let t=Ft(g,e),n=_e(e).size,r=jt(t)?Dt(e):0;T.push({path:t,bytes:n,lines:r}),E+=n,t.startsWith(`telemetry/`)&&jt(t)&&(D+=Ot(e))}let O=C===null?{applied:!1,docNameMapSidecar:null}:Object.keys(C.docNameCollisions).length>0?{applied:!0,docNameMapSidecar:null,docNameCollisions:C.docNameCollisions}:{applied:!0,docNameMapSidecar:null};w!==null&&(O.secretScrub=w);let se={schemaVersion:1,createdAt:d().toISOString(),ok:{version:f(),nodeVersion:S.nodeVersion,platform:S.platform,arch:S.arch},host:{desktop:ne},contentDir:{pathSha256:Et(r),absolutePath:C===null?r:`<CONTENT_DIR>`},telemetry:{localSink:ae,otlpPushEnabled:h()},redaction:O,serverStatus:y,files:T};R(N(g,`manifest.json`),`${JSON.stringify(se,null,2)}\n`);let k=oe.some(e=>{try{return L(e,`utf-8`).includes(r)}catch{return!1}}),j={totalBytes:E,fileCount:T.length,docNameCount:D,contentDirVisible:k,redacted:C!==null},M=!1;return{stagingDir:g,manifest:se,summary:j,redactionMapPayload:C===null?null:{docNameMap:C.docNameMap,docNameCollisions:C.docNameCollisions},cleanup:()=>{M||(M=!0,ge(g,{recursive:!0,force:!0}))}}}catch(e){throw ge(g,{recursive:!0,force:!0}),e}}async function Lt(e){let{collected:t,outputPath:n}=e,r=j(n);if(!F(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);if(t.redactionMapPayload!==null){let e=`${A(n,`.zip`)}.docnames.json`,r={...t.manifest,redaction:{...t.manifest.redaction,applied:!0,docNameMapSidecar:e}};R(N(t.stagingDir,`manifest.json`),`${JSON.stringify(r,null,2)}\n`)}let i=new We.ZipFile,a=kt(t.stagingDir);for(let e of a){let n=Ft(t.stagingDir,e);i.addFile(e,n)}i.end(),t.redactionMapPayload!==null&&R(N(r,`${A(n,`.zip`)}.docnames.json`),`${JSON.stringify({docNameMap:t.redactionMapPayload.docNameMap,docNameCollisions:t.redactionMapPayload.docNameCollisions},null,2)}\n`,{mode:384});let o=de(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 Rt(e,t){let n=N(e,`.ok`,`config.yml`);if(F(n))try{let t=(0,V.parse)(L(n,`utf-8`)),r=O(t)?t.content:void 0,i=O(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return P(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 P(e)}async function zt(e,t,n){let r=await It({contentDir:Rt(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,deps:{readDesktopEnv:n,logger:e.logger}});try{I(j(e.outputPath),{recursive:!0}),await Lt({collected:r,outputPath:e.outputPath});let n=r.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:Le(t,e.logger),files:r.manifest.files.map(e=>e.path),redactions:n?.redactions??[],redactedLineCount:n?.redactedLineCount??0,generatedAt:r.manifest.createdAt}}}finally{r.cleanup()}}async function Bt(e){let{projectDir:t}=e,n=e.readDesktopEnv??yt;if(e.level===`full`&&t!==void 0)return zt(e,t,n);let{zipPath:r,summary:i}=await Ue({projectDir:t,redact:e.redact,outputPath:e.outputPath,userLogsDir:e.userLogsDir,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n()});return{zipPath:r,summary:{level:e.level,systemWide:t===void 0,projectSlug:i.projectSlug,files:i.files,redactions:i.redactions,redactedLineCount:i.redactedLineCount,generatedAt:i.generatedAt}}}function Z(e,t,n={}){let r=g(e,t);if(!F(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(L(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!v(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??_)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};if(typeof a.machineId==`string`)return a.machineId===(n.machineId??h())?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a};let o=n.host??xe();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Vt(e){return e.replace(/:\d+$/,``)}function Ht(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Vt(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Vt(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Vt(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 Ut(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=r(t.hostname);if(n===null)return null;let i=t.pathname.split(`/`).filter(e=>e.length>0);if(i.length<5||i[2]!==`blob`)return null;let a,o,s,c;try{a=decodeURIComponent(i[0]),o=decodeURIComponent(i[1]),s=decodeURIComponent(i[3]),c=i.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.length===0||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function Wt(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=r(t.hostname);if(n===null)return null;let i=t.pathname.split(`/`);if(i.length<5||i[0]!==``||i[3]!==`tree`)return null;let a=i.slice(5);a.length===1&&a[0]===``&&a.pop();let o,s,c,l;try{o=decodeURIComponent(i[1]),s=decodeURIComponent(i[2]),c=decodeURIComponent(i[4]),l=a.map(e=>decodeURIComponent(e))}catch{return null}return!o||!s||!c||l.some(e=>e.length===0)?null:{host:n,owner:o,repo:s,branch:c,path:l.join(`/`)}}function Gt(e){let t=Ut(e);if(t)return{kind:`doc`,...t};let n=Wt(e);return n?{kind:`folder`,...n}:null}const Kt=`# >>> open-knowledge cli >>>`,qt=`# <<< open-knowledge cli <<<`,Jt=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function Yt(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const Xt={existsSync:e=>F(e),readFileSync:(e,t)=>L(e,t),lstatSync:e=>fe(e),readlinkSync:e=>he(e)};function Zt(e,t=Xt){let n=Yt(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function Qt(e){let t=e.replace(Jt,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function $t(e,t,n=Xt){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}function en(e){return te(e)||S(e)||C(e)}const tn=10*1024*1024;function nn(e,t,n,r){let i=T(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!en(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);return e.format===`file`?(ge(a,{force:!0}),{kind:`removed`}):e.format===`toml`?on(a,o):e.format===`yaml`?an(a,e.topLevelKey,o):rn(a,e.topLevelKey,e.serverMapSubKey,o)}function rn(e,t,n,r){let i;try{i=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>tn)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=re(i,ae(t,n,r));return o?(m(e,a,{mode:w(e)}),{kind:`removed`}):{kind:`not-present`}}function an(e,t,n){let r;try{r=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(r,`utf-8`)>tn)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,V.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=ie(a);a.trim()===``||a.endsWith(`
13
- `)?c.endsWith(`
14
- `)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
15
- `).replace(/\n/g,`\r
16
- `));let u=`${i?``:``}${c}`;return u!==r&&m(e,u,{mode:w(e)}),{kind:`removed`}}function on(e,t){let n=oe();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=L(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=ie(a),s=a.trim()===``||a.endsWith(`
17
- `),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(`
18
- `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
19
- `).replace(/\n/g,`\r
20
- `));let u=`${i?``:``}${l}`;return u!==r&&m(e,u,{mode:w(e)}),{kind:`removed`}}function sn(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function cn(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function ln(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:l(r),command:r,isDesktop:sn(r)}}function un(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Q(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&un(e)?`ui-orphan`:`stale`}const dn=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function fn(e){switch(e){case`running`:return W.default.green(e);case`desktop`:return W.default.blue(e);case`foreign`:return W.default.cyan(e);case`ui-orphan`:return W.default.magenta(e);case`stale`:return W.default.yellow(e)}}function pn(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function mn(e){return`${pn(e.server.usage)} | ${pn(e.ui?.usage??null)}`}function hn(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function gn(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Q(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,hn(e),mn(e),t,String(n),cn(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=fn(Q(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=W.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
21
- `)}async function _n(e={}){let t=e.discover??c,n=e.inspect??Z,r=e.log??(e=>console.log(e)),i=e.resolveCommand??a,o=e.resolveUsage??s,l=await t(),u=[];for(let e of l){let t=n(e,`server`),r=n(e,`ui`),a=ln(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:o(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:o(r.lock.pid));a!=null&&u.push(a)}if(e.json){let e=u.map(e=>({...e,displayStatus:Q(e)}));r(JSON.stringify(e,null,2));return}r(gn(e.all?u:u.filter(e=>dn.has(Q(e)))))}function vn(){return new b(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await _n({all:t.all===!0||e===`all`,json:t.json===!0})})}function yn(e,t,n={}){let r=n.isAlive??_,i=[];for(let[n,a]of[[`server`,e],[`ui`,t]])(a.status===`alive`||a.status===`foreign-host`&&r(a.lock.pid))&&i.push({name:n,pid:a.lock.pid,port:a.lock.port});return{targets:i}}function bn(e){let t=e.inspect??(t=>Z(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=yn(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function $(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function xn(e,t=_){let n=await c(),r=null;for(let i of n){let n=Z(i,`server`),a=Z(i,`ui`);if($(n,t)&&n.lock.port===e||$(a,t)&&a.lock.port===e)return i;r===null&&($(n,t)&&n.lock.pid===e||$(a,t)&&a.lock.pid===e)&&(r=i)}return r}function Sn(e){let t=bn({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function Cn(e){return new b(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=bn({lockDir:i(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await _n({});return}if(n===`all`){let e=await c();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=Z(n,`server`),r=Z(n,`ui`);!$(e,_)&&!$(r,_)||(Sn(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await xn(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}Sn(t);return}Sn(i(P(Me(),n)))})}function wn(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}async function Tn(e,t){let n,i;try{n=await z(P(e)),i=await z(P(j(e)))}catch{return{kind:`not-git`}}if(!En(n,i))return{kind:`symlink-escape`};let a=N(n,`.git`),o;try{o=_e(a)}catch{return{kind:`not-git`}}if(o.isDirectory()){let e;try{e=await z(a)}catch{return{kind:`not-git`}}if(!En(e,n))return{kind:`symlink-escape`}}else if(!o.isFile())return{kind:`not-git`};let s=d(n);if(s.kind!==`repository`)return{kind:`not-git`};let c=s.repository.readRemoteUrl(`origin`);if(c.kind===`unreadable`)return{kind:`not-git`};if(c.kind===`absent`)return c.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let l=c.url,u=Ht(l);if(u===null)return{kind:`non-github`};let f=r(u.hostname);if(f===null)return{kind:`non-github`};let p=f===t.host.toLowerCase(),m=u.owner.toLowerCase()===t.owner.toLowerCase(),h=u.name.toLowerCase()===t.repo.toLowerCase();return!p&&m&&h?{kind:`wrong-host`,actualHost:f}:!p||!m||!h?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://${f}/${u.owner}/${u.name}.git`}}function En(e,t){if(e===t)return!0;let n=ce(t,e);return n.length>0&&!n.startsWith(`..`)&&!M(n)}const Dn=[{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=E(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=ee(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 On(e,t,n={},r=Dn){let i=[];for(let a of t){let t=x[a];for(let a of r)i.push(a.write(t,e,n))}return i}function kn(e,t,n={}){return{integrations:On(e,t,n)}}export{Ie as C,je as D,Me as E,ke as O,Lt as S,H as T,Wt as _,Cn as a,Bt as b,Kt as c,$t as d,Yt as f,Gt as g,Ut as h,bn as i,Jt as l,Qt as m,Tn as n,vn as o,Zt as p,wn as r,nn as s,kn as t,qt as u,Ht as v,Fe as w,It as x,Z as y};
22
- //# sourceMappingURL=src-DIp07PRS.mjs.map
@@ -1 +0,0 @@
1
- import{_ as e,f as t,r as n}from"./start-B9UTrPaX.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};