@inkeep/open-knowledge 0.70.1 → 0.70.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -94,7 +94,7 @@
94
94
  -->
95
95
  <script>(() => { try { const raw = localStorage.getItem('ok-language-v1'); if (!raw) return; const o = JSON.parse(raw); if (typeof o?.locale !== 'string' || !/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{2,8})*$/.test(o.locale)) return; document.documentElement.lang = o.locale; document.documentElement.dir = o.dir === 'rtl' ? 'rtl' : 'ltr'; } catch {} })();</script>
96
96
  <style>html { background-color: #fafafa } html.dark { background-color: #171717 }</style>
97
- <script type="module" crossorigin src="./assets/index-CBirdBL7.js"></script>
97
+ <script type="module" crossorigin src="./assets/index-DMDo5dFr.js"></script>
98
98
  <link rel="modulepreload" crossorigin href="./assets/chunk-CYidjpOJ.js">
99
99
  <link rel="modulepreload" crossorigin href="./assets/react-f2sANaYj.js">
100
100
  <link rel="modulepreload" crossorigin href="./assets/react-dom-DPxgxlDT.js">
@@ -1,4 +1,4 @@
1
- import{Gl as e,Gu as t,Uu as n,Vu as r,Wu as i,eu as a,qc as o,qu as s}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{Ao as c,Ki as l,Ln as u,go as ee,ko as te,m as d,to as ne,wo as f}from"./dist-BfGPmTI1.mjs";import{$ as p,A as m,C as re,D as h,K as g,O as _,P as ie,Q as ae,W as oe,Y as se,Z as ce,at as le,d as ue,et as v,f as de,it as y,k as fe,o as b,st as pe,tt as me,v as he,w as x,x as ge,y as _e}from"./init-EA4nTQPs.mjs";import{t as ve}from"./is-object-BGze3w87.mjs";import{spawn as S}from"node:child_process";import{basename as ye,dirname as C,join as w,resolve as be,win32 as xe}from"node:path";import{existsSync as T,mkdirSync as E,readFileSync as D,readdirSync as Se,rmSync as O,statSync as Ce,writeFileSync as we}from"node:fs";import{homedir as k}from"node:os";var A=e();const j=`open-knowledge`;function M(e){try{e()}catch{}}var N=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(j,e).getPassword()}catch(t){return M(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return M(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return M(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(j,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(j,e).deletePassword()}catch{}}},P=class{backend=`file`;authFile;constructor(e){this.authFile=e??w(k(),`.ok`,`auth.yml`)}read(){if(!T(this.authFile))return{};try{let e=D(this.authFile,`utf-8`);return(0,A.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=C(this.authFile);T(t)||E(t,{recursive:!0,mode:448}),we(this.authFile,(0,A.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},Te=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ~/.ok/auth.yml to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function F(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(j,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
1
+ import{Gl as e,Gu as t,Uu as n,Vu as r,Wu as i,eu as a,qc as o,qu as s}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{Ao as c,Ki as l,Ln as u,go as ee,ko as te,m as d,to as ne,wo as f}from"./dist-BfGPmTI1.mjs";import{$ as p,A as m,C as re,D as h,K as g,O as _,P as ie,Q as ae,W as oe,Y as se,Z as ce,at as le,d as ue,et as v,f as de,it as y,k as fe,o as b,st as pe,tt as me,v as he,w as x,x as ge,y as _e}from"./init-Dl36o0mH.mjs";import{t as ve}from"./is-object-BGze3w87.mjs";import{spawn as S}from"node:child_process";import{basename as ye,dirname as C,join as w,resolve as be,win32 as xe}from"node:path";import{existsSync as T,mkdirSync as E,readFileSync as D,readdirSync as Se,rmSync as O,statSync as Ce,writeFileSync as we}from"node:fs";import{homedir as k}from"node:os";var A=e();const j=`open-knowledge`;function M(e){try{e()}catch{}}var N=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(j,e).getPassword()}catch(t){return M(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return M(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return M(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(j,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(j,e).deletePassword()}catch{}}},P=class{backend=`file`;authFile;constructor(e){this.authFile=e??w(k(),`.ok`,`auth.yml`)}read(){if(!T(this.authFile))return{};try{let e=D(this.authFile,`utf-8`);return(0,A.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=C(this.authFile);T(t)||E(t,{recursive:!0,mode:448}),we(this.authFile,(0,A.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},Te=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ~/.ok/auth.yml to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function F(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(j,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
2
  `),M(()=>t?.onBackendSelected?.({backend:`keyring`})),new Te(new N(t?.onKeychainRead),new P(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml) — OS keychain unavailable: ${r}\n`),M(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new P(e)}}function I(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (~/.ok/auth.yml)\n`),r(new P(e))},n)});try{return await Promise.race([F(e),r])}catch{return new P(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Ee(e){let t=I(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function De(e){let t=I(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function Oe(e,t){let n=[],r=new P(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));let i;try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(j,`__probe__`);let r,a=await new N(e=>{e.kind===`read-error`&&(r=e.error??`read-error`)}).get(e);if(r!==void 0)i=r;else if(a!=null)try{new t(j,e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function ke(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function L(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function R(e){return ne({detached:!0,stdio:`ignore`,shell:!1,env:ke(e)})}function z(e,t,n={}){let r=(n.spawn??S)(e,[...t],R(n.env??process.env));return r.unref(),r}function Ae(e,t,n={}){let r=n.spawn??S,i=n.timeoutMs??2e3;return new Promise(a=>{let o=!1,s=e=>{o||(o=!0,a(e))},c=setTimeout(()=>s({ok:!1,reason:`timeout`}),i);try{let i=r(e,[...t],R(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(L(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(L(e))}})}const B=`com.inkeep.open-knowledge`,V=`OpenKnowledge.app`,H=`/Applications/${V}`;function je(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return Ce(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function Me(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(U(e,H))return H;let t=e.homeDir??k(),n=w(t,`Applications`,V);return U(e,n)?n:null}function U(e,t){return W(e,w(t,`Contents`,`MacOS`,`OpenKnowledge`))}function W(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}const Ne=[`@inkeepopen-knowledge-desktop`,`OpenKnowledge`];function Pe(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 Ne){let r=xe.join(t,`Programs`,n,`OpenKnowledge.exe`);if(W(e,r))return r}return null}function Fe(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&e.execPath.endsWith(`/openknowledge`))return e.execPath;let t=`/opt/OpenKnowledge/openknowledge`;return W(e,t)?t:null}function Ie(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`?Me(e):e.platform===`win32`?Pe(e):Fe(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 Le(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`){z(`open`,[`-b`,B],{spawn:e.spawn});return}let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}z(i,[],{spawn:e.spawn})}function Re(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found (checked the standard install locations for this OS). Install it from https://openknowledge.ai/download, 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 G(e,t){let n=be(e),r=t===void 0?y():y({home:t,env:{}});return{cwd:n,bridgePath:g.pi.projectConfigPath?.(n)??``,trustPath:w(r,`trust.json`)}}function K(e,t,n){let r=b(g.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return p(i)?{state:`own-current`,text:a}:x(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function q(e,t){let n;try{n=D(e,`utf-8`)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,entries:null,trailingNewline:!1}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,entries:null,trailingNewline:!1}}return ve(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
3
3
  `)}:{state:`unreadable`,entries:null,trailingNewline:!1}}function ze(e,t){let n=G(e,t),r=K(n.cwd,n.bridgePath,t).state,i=q(n.trustPath,n.cwd).state;return{...n,bridge:r,trust:i,bridgeLoadable:(r===`own-current`||r===`own-stale`)&&i===`trusted`,otherExtensions:J(n.bridgePath).names}}function J(e){let t=C(e),n=ye(e);try{return{names:Se(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort(),verified:!0}}catch(e){let t=e.code;return{names:[],verified:t===`ENOENT`||t===`ENOTDIR`}}}async function Be(e,t={mode:`published`},n){let r=G(e,n),i=K(r.cwd,r.bridgePath,n);if(i.state===`foreign`)return{...r,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(i.state===`unreadable`)return{...r,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let a;if(i.state===`absent`)a=`written`;else{let e;try{e=re(t)}catch{e=void 0}a=e!==void 0&&i.text===e?`unchanged`:`refreshed`}if(a!==`unchanged`){let e=_e(g.pi,r.cwd,t,n,r.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...r,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error??`bridge write ${e.action}`}}let o=await Ve(r.trustPath,r.cwd);return{...r,ok:o.action===`already-trusted`||o.action===`added`,bridge:a,trust:o.action,...o.error===void 0?{}:{error:o.error}}}async function Ve(e,t){try{E(C(e),{recursive:!0})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}let n={action:`added`};try{await te(`${e}.lock`,async()=>{let r=q(e,t);if(r.state===`trusted`){n.action=`already-trusted`;return}if(r.entries===null){n.action=`refused-unreadable`;return}let i={...r.entries,[t]:!0},a=JSON.stringify(i,null,2)+(r.trailingNewline?`
4
4
  `:``),o=h(e);f(e,a,o===void 0?void 0:{mode:o}),n.action=`added`})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}return n.action===`refused-unreadable`?{action:`refused-unreadable`,error:`trust store is not a readable JSON object`}:{action:n.action}}function He(e,t){let n=G(e,t),r=J(n.bridgePath);if(!r.verified)return{action:`kept-unverified`,error:`could not read the Pi extensions folder`};if(r.names.length>0)return{action:`kept-shared`};if(!T(n.trustPath))return{action:`not-present`};let i={action:`removed`};try{c(`${n.trustPath}.lock`,()=>{let e=q(n.trustPath,n.cwd);if(e.entries===null){i.action=e.state===`unreadable`?`refused-unreadable`:`not-present`;return}if(!(n.cwd in e.entries)){i.action=`not-present`;return}let t={...e.entries};delete t[n.cwd];let r=JSON.stringify(t,null,2)+(e.trailingNewline?`
@@ -1 +1 @@
1
- import{t as e}from"./launch-json-removal-DT1kb6WW.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`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
1
+ import{t as e}from"./launch-json-removal-3O2NwIMf.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`,severity:`info`,reason:`reclaim-disabled`}),{outcome:{configPath:a,outcome:`skipped-reclaim-disabled`},repairedCount:0};let o;try{o=(n.removeOwnLaunchEntryFn??e)(n.projectDir)}catch(e){let t=e instanceof Error?e.message:String(e);return i({event:`launch-json-repair-write-failed`,severity:`warn`,configPath:a}),{outcome:{configPath:a,outcome:`write-failed`,error:t},repairedCount:0}}let s=o.kind===`removed`;return s&&i({event:`launch-json-repair-removed`,severity:`info`,configPath:a}),{outcome:{configPath:a,outcome:o.kind},repairedCount:+!!s}}function r(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{n as repairLaunchJson};
@@ -1 +1 @@
1
- import{ga as e}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{$ as t,K as n,W as r,X as i,f as a,y as o}from"./init-EA4nTQPs.mjs";import{homedir as s}from"node:os";function c(e){let{priorCommand:t,priorArgs:n}=l(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function l(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function u(e){let t=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return t({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of r){let r=n[o],s=d(()=>r.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:r,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:t})),r.projectConfigPath){let n=r.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:r,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:t}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(n){let r={scope:n.scope,editorId:n.editorId,configPath:n.configPath},s=a(n.target,n.cwd,n.home,n.configPathOverride);if(s===null)return{...r,outcome:`no-entry`};if(n.target.format===`file`){if(t(s))return{...r,outcome:`canonical`}}else{let t=e(s);if(t.kind===`recognized`&&t.disposition===`keep`){let e=i(s,n.target.buildEntry(n.cwd,{}));if(e.length===0)return{...r,outcome:`canonical`};let t=p(n,r,o(n.target,n.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},n.home,n.configPathOverride));return(t.outcome===`repaired`||t.outcome===`canonical`)&&n.logger({event:t.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:t.outcome===`repaired`?`info`:`warn`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,keys:e}),t.outcome===`canonical`?{...r,outcome:`prune-unchanged`}:t}if(t.kind===`declined`&&n.scope===`project`)return n.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,reason:t.reason}),{...r,outcome:`foreign`,reason:t.reason}}return n.logger({...c({scope:n.scope,surface:`cli-repair`,editorId:n.editorId,configPath:n.configPath,priorEntry:s}),severity:`info`}),p(n,r,o(n.target,n.cwd,{mode:`published`,skipAvailabilityCheck:!0},n.home,n.configPathOverride))}function p(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function m(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as n,u as repairMcpConfigs,c as t};
1
+ import{ga as e}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{$ as t,K as n,W as r,X as i,f as a,y as o}from"./init-Dl36o0mH.mjs";import{homedir as s}from"node:os";function c(e){let{priorCommand:t,priorArgs:n}=l(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function l(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function u(e){let t=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return t({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of r){let r=n[o],s=d(()=>r.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:r,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:t})),r.projectConfigPath){let n=r.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:r,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:t}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(n){let r={scope:n.scope,editorId:n.editorId,configPath:n.configPath},s=a(n.target,n.cwd,n.home,n.configPathOverride);if(s===null)return{...r,outcome:`no-entry`};if(n.target.format===`file`){if(t(s))return{...r,outcome:`canonical`}}else{let t=e(s);if(t.kind===`recognized`&&t.disposition===`keep`){let e=i(s,n.target.buildEntry(n.cwd,{}));if(e.length===0)return{...r,outcome:`canonical`};let t=p(n,r,o(n.target,n.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},n.home,n.configPathOverride));return(t.outcome===`repaired`||t.outcome===`canonical`)&&n.logger({event:t.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:t.outcome===`repaired`?`info`:`warn`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,keys:e}),t.outcome===`canonical`?{...r,outcome:`prune-unchanged`}:t}if(t.kind===`declined`&&n.scope===`project`)return n.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,reason:t.reason}),{...r,outcome:`foreign`,reason:t.reason}}return n.logger({...c({scope:n.scope,surface:`cli-repair`,editorId:n.editorId,configPath:n.configPath,priorEntry:s}),severity:`info`}),p(n,r,o(n.target,n.cwd,{mode:`published`,skipAvailabilityCheck:!0},n.home,n.configPathOverride))}function p(e,t,n){if(n.action===`failed`){let r=n.error??`unknown write failure`;return e.logger({event:`mcp-config-repair-write-failed`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,error:r}),{...t,outcome:`write-failed`,error:r}}return n.action===`declined`?(e.logger({event:`mcp-config-repair-declined`,severity:`warn`,scope:e.scope,editorId:e.editorId,configPath:e.configPath,reason:n.declineReason}),{...t,outcome:`declined`,reason:n.declineReason}):n.action===`skipped-flag`?{...t,outcome:`canonical`}:{...t,outcome:`repaired`}}function m(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as n,u as repairMcpConfigs,c as t};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import"./init-Dl36o0mH.mjs";import"./src-DmZyPc_9.mjs";import"./registry-probes-DbzstoJN.mjs";import"./start-C5pItnpl.mjs";import{n as e}from"./loader-CvpazbE1.mjs";import"./preview-B_eP6zkI.mjs";import"./cli.mjs";import"./repair-mcp-configs-Da0GMl66.mjs";export{e as loadConfig};
@@ -1,4 +1,4 @@
1
- import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$u as t,Bs as n,Dn as r,Gl as i,In as a,On as o,ac as s,ic as c,lo as l,ns as u,ps as ee,sc as te}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{$i as d,Do as f,Eo as p,Hr as m,Jn as h,Jr as g,Oo as _,Qn as v,Rn as y,Tt as b,dr as x,ei as S,m as C,ni as w,ti as T,to as E,vi as D,wn as O,yi as k}from"./dist-BfGPmTI1.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{ht as j,nt as M,rt as N}from"./init-EA4nTQPs.mjs";import{c as ne}from"./colors-r_owlCuY.mjs";import{l as P}from"./registry-probes-3_EeBR0_.mjs";import{t as re}from"./is-object-BGze3w87.mjs";import{n as ie}from"./constants-COow1ASd.mjs";import"./loader-DDMBB5EK.mjs";import"./preview-BE5m2CFL.mjs";import{execSync as ae,spawnSync as oe}from"node:child_process";import{basename as F,dirname as I,isAbsolute as se,join as L,relative as R,resolve as z,sep as B}from"node:path";import{closeSync as ce,cpSync as le,createWriteStream as ue,existsSync as V,lstatSync as de,mkdirSync as H,mkdtempSync as fe,openSync as pe,readFileSync as U,readSync as me,readdirSync as W,rmSync as G,rmdirSync as he,statSync as ge,writeFileSync as K}from"node:fs";import{arch as _e,freemem as ve,homedir as q,hostname as ye,platform as be,release as xe,tmpdir as Se,totalmem as Ce,type as we,uptime as Te}from"node:os";import"node:fs/promises";import{createHash as Ee}from"node:crypto";let De;function Oe(){return De}function ke(e,t){if(t!==void 0&&t.length>0)return t;try{return v(e)?.rootPath}catch{return}}function Ae(e){let t=ke(e.cwd,e.configuredProjectName),n=O({name:`cli`,project:t});return De=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}const je=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function Me(e,t,n=v){if(e!==void 0&&!je.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ne=null;function Pe(e){Ne=e}function Fe(){return Ne??process.cwd()}const Ie=`Open Knowledge`;function Le(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return M(t).join(N({...e,platformName:t}),n)}function Re(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=M(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`@inkeepopen-knowledge-desktop-updater`)}function ze(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Be(e){let t=L(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return ze(n)??[]}function Ve(e){let t=L(e,`state.json`);if(!V(t))return!1;try{return ze(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const He=8192;function Ue(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function We(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Ge=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ke(e){return e.replace(Ge,`$1"[REDACTED-DEVICE-ID]"`)}function qe(e){return Ke(We(e))}const Je=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ye(e){if(typeof e!=`string`)return null;let t=Je.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function Xe(e){let t=pe(e,`r`);try{let e=Buffer.alloc(He),n=0,r=!1;for(;n<He;){let i=me(t,e,n,He-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{ce(t)}}function Ze(e){try{let t=Xe(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Ye(a)}}catch{return{kind:`unreadable`}}}function Qe(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function $e(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=W(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=L(e,t.name),r;try{r=ge(n).mtimeMs}catch{continue}if(r<i)continue;let c=Ze(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Qe(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function J(){return L(q(),`.ok`,`bug-reports`)}function et(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=L(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=L(n,`${r}-${e}.zip`);return i}function tt(e,t){let n=L(e,`.ok`,`config.yml`);if(V(n))try{let e=U(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 V(L(e,`.ok`))?Ee(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function nt(){let e={timestamp:new Date().toISOString(),platform:be(),osType:we(),osRelease:xe(),hostname:`[redacted]`,uptime:Te(),freeMem:ve(),totalMem:Ce(),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`,E({encoding:`utf8`})).trim()}catch{}try{let t=L(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const rt=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function it(e){let t=F(e);return rt.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function at(e,t){return lt(e,t).files}const ot=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function st(e,t=P){let n=L(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return ot.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>L(n,e.entry)))}function ct(e){if(!V(e))return[];try{let t=new Map;for(let n of W(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-r.length):n.slice(0,-5),i=t.get(e);i===void 0?t.set(e,[n]):i.push(n)}return[...t.values()].slice(-25).flat().map(t=>L(e,t))}catch{return[]}}function lt(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>L(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(it),i=[],a=r.filter(t=>{try{return U(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!it(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function ut(e){let t=L(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,c].map(e=>L(t,e)).filter(e=>V(e))}:{files:[]}}function dt(e){let t=L(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>L(t,e)).filter(e=>V(e))}:{files:[]}}function ft(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ee(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function pt(e){let t=e.revealDocNames?e.content:ft(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=u(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function Y(e){for(let t of e.files)try{let n=U(t,`utf8`);pt({zipfile:e.zipfile,name:`${e.prefix}/${F(t)}`,content:t.endsWith(`.ips`)?qe(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function mt(t){let{redact:n,outputPath:r,logger:i}=t,s=t.revealDocNames??!1,c=t.userLogsDir??L(q(),`.ok`,`logs`),l=t.projectDir?tt(t.projectDir,i):null;H(I(r),{recursive:!0}),i?.info({projectSlug:l},`gathering diagnostic data`);let u=nt();u.desktop=t.desktop??null,u.language=t.language??null;let{files:ee,excludedByProjectSlug:te}=lt(l,c),{files:d}=t.projectDir?ut(t.projectDir):{files:[]},{files:f}=t.projectDir?dt(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:ee.length,logFilesExcludedByProjectSlug:te,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:_}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new _;Y({zipfile:v,files:[...ee,...p],prefix:`logs`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:d,prefix:`lockdir`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:o,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??F(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&pt({zipfile:v,name:`note.txt`,content:t.note,redact:n,revealDocNames:s,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${F(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Ue(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`);let S=JSON.stringify(u,null,2);v.addBuffer(Buffer.from(S,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let C={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:l,files:g,redactions:h,sysinfo:u};v.addBuffer(Buffer.from(JSON.stringify(C,null,2),`utf8`),`MANIFEST.json`);let w=h.reduce((e,t)=>e+t.lineCount,0),T=new Set(p.map(e=>`logs/${F(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((t.bugReportLedgerFiles??[]).map(e=>`${o}/${F(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!it(e)&&!T.has(e)):[],A=b.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],j=A.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...A]:[`Redaction was disabled for this bundle; file contents are unmodified.`],M=[`# Bug Report Bundle`,``,`Generated: ${C.generatedAt}`,`Project: ${l??`(unscoped)`}`,`Discipline version: ${C.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...k.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...k.map(e=>`- ${e}`),``]:[],...E.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...E.map(e=>`- ${e}`),``]:[],...b.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...b.map(e=>`- ${e}`),``]:[],...O.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...O.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${a.join(`, `)}`,w>0?`${w} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...A,``,`This bundle is safe to attach to a GitHub issue.`]:j].join(`
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$u as t,Bs as n,Dn as r,Gl as i,In as a,On as o,ac as s,ic as c,lo as l,ns as u,ps as ee,sc as te}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{$i as d,Do as f,Eo as p,Hr as m,Jn as h,Jr as g,Oo as _,Qn as v,Rn as y,Tt as b,dr as x,ei as S,m as C,ni as w,ti as T,to as E,vi as D,wn as O,yi as k}from"./dist-BfGPmTI1.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{ht as j,nt as M,rt as N}from"./init-Dl36o0mH.mjs";import{c as ne}from"./colors-r_owlCuY.mjs";import{l as P}from"./registry-probes-DbzstoJN.mjs";import{t as re}from"./is-object-BGze3w87.mjs";import{n as ie}from"./constants-B4vbt8P8.mjs";import"./loader-CvpazbE1.mjs";import"./preview-B_eP6zkI.mjs";import{execSync as ae,spawnSync as oe}from"node:child_process";import{basename as F,dirname as I,isAbsolute as se,join as L,relative as R,resolve as z,sep as B}from"node:path";import{closeSync as ce,cpSync as le,createWriteStream as ue,existsSync as V,lstatSync as de,mkdirSync as H,mkdtempSync as fe,openSync as pe,readFileSync as U,readSync as me,readdirSync as W,rmSync as G,rmdirSync as he,statSync as ge,writeFileSync as K}from"node:fs";import{arch as _e,freemem as ve,homedir as q,hostname as ye,platform as be,release as xe,tmpdir as Se,totalmem as Ce,type as we,uptime as Te}from"node:os";import"node:fs/promises";import{createHash as Ee}from"node:crypto";let De;function Oe(){return De}function ke(e,t){if(t!==void 0&&t.length>0)return t;try{return v(e)?.rootPath}catch{return}}function Ae(e){let t=ke(e.cwd,e.configuredProjectName),n=O({name:`cli`,project:t});return De=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}const je=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function Me(e,t,n=v){if(e!==void 0&&!je.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ne=null;function Pe(e){Ne=e}function Fe(){return Ne??process.cwd()}const Ie=`Open Knowledge`;function Le(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return M(t).join(N({...e,platformName:t}),n)}function Re(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=M(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`@inkeepopen-knowledge-desktop-updater`)}function ze(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Be(e){let t=L(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return ze(n)??[]}function Ve(e){let t=L(e,`state.json`);if(!V(t))return!1;try{return ze(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const He=8192;function Ue(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function We(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const Ge=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ke(e){return e.replace(Ge,`$1"[REDACTED-DEVICE-ID]"`)}function qe(e){return Ke(We(e))}const Je=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ye(e){if(typeof e!=`string`)return null;let t=Je.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function Xe(e){let t=pe(e,`r`);try{let e=Buffer.alloc(He),n=0,r=!1;for(;n<He;){let i=me(t,e,n,He-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{ce(t)}}function Ze(e){try{let t=Xe(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Ye(a)}}catch{return{kind:`unreadable`}}}function Qe(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function $e(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=W(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=L(e,t.name),r;try{r=ge(n).mtimeMs}catch{continue}if(r<i)continue;let c=Ze(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Qe(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function J(){return L(q(),`.ok`,`bug-reports`)}function et(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=L(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=L(n,`${r}-${e}.zip`);return i}function tt(e,t){let n=L(e,`.ok`,`config.yml`);if(V(n))try{let e=U(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 V(L(e,`.ok`))?Ee(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function nt(){let e={timestamp:new Date().toISOString(),platform:be(),osType:we(),osRelease:xe(),hostname:`[redacted]`,uptime:Te(),freeMem:ve(),totalMem:Ce(),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`,E({encoding:`utf8`})).trim()}catch{}try{let t=L(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const rt=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function it(e){let t=F(e);return rt.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function at(e,t){return lt(e,t).files}const ot=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function st(e,t=P){let n=L(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return ot.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>L(n,e.entry)))}function ct(e){if(!V(e))return[];try{let t=new Map;for(let n of W(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-r.length):n.slice(0,-5),i=t.get(e);i===void 0?t.set(e,[n]):i.push(n)}return[...t.values()].slice(-25).flat().map(t=>L(e,t))}catch{return[]}}function lt(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>L(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(it),i=[],a=r.filter(t=>{try{return U(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!it(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function ut(e){let t=L(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,c].map(e=>L(t,e)).filter(e=>V(e))}:{files:[]}}function dt(e){let t=L(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>L(t,e)).filter(e=>V(e))}:{files:[]}}function ft(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ee(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function pt(e){let t=e.revealDocNames?e.content:ft(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=u(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function Y(e){for(let t of e.files)try{let n=U(t,`utf8`);pt({zipfile:e.zipfile,name:`${e.prefix}/${F(t)}`,content:t.endsWith(`.ips`)?qe(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function mt(t){let{redact:n,outputPath:r,logger:i}=t,s=t.revealDocNames??!1,c=t.userLogsDir??L(q(),`.ok`,`logs`),l=t.projectDir?tt(t.projectDir,i):null;H(I(r),{recursive:!0}),i?.info({projectSlug:l},`gathering diagnostic data`);let u=nt();u.desktop=t.desktop??null,u.language=t.language??null;let{files:ee,excludedByProjectSlug:te}=lt(l,c),{files:d}=t.projectDir?ut(t.projectDir):{files:[]},{files:f}=t.projectDir?dt(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:ee.length,logFilesExcludedByProjectSlug:te,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:_}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new _;Y({zipfile:v,files:[...ee,...p],prefix:`logs`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:d,prefix:`lockdir`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:o,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:s,bundleFiles:g,redactions:h,logger:i});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??F(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&pt({zipfile:v,name:`note.txt`,content:t.note,redact:n,revealDocNames:s,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${F(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Ue(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`);let S=JSON.stringify(u,null,2);v.addBuffer(Buffer.from(S,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let C={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:l,files:g,redactions:h,sysinfo:u};v.addBuffer(Buffer.from(JSON.stringify(C,null,2),`utf8`),`MANIFEST.json`);let w=h.reduce((e,t)=>e+t.lineCount,0),T=new Set(p.map(e=>`logs/${F(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((t.bugReportLedgerFiles??[]).map(e=>`${o}/${F(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!it(e)&&!T.has(e)):[],A=b.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],j=A.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...A]:[`Redaction was disabled for this bundle; file contents are unmodified.`],M=[`# Bug Report Bundle`,``,`Generated: ${C.generatedAt}`,`Project: ${l??`(unscoped)`}`,`Discipline version: ${C.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...k.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...k.map(e=>`- ${e}`),``]:[],...E.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...E.map(e=>`- ${e}`),``]:[],...b.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...b.map(e=>`- ${e}`),``]:[],...O.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...O.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${a.join(`, `)}`,w>0?`${w} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...A,``,`This bundle is safe to attach to a GitHub issue.`]:j].join(`
2
2
  `);v.addBuffer(Buffer.from(M,`utf8`),`README.md`),v.end();let N=ue(r);return v.outputStream.pipe(N),await new Promise((e,t)=>{N.on(`close`,e),N.on(`error`,t)}),i?.info({bundlePath:r,fileCount:g.length,redactionCount:w},`bundle written`),{zipPath:r,summary:{projectSlug:l,files:g,redactions:h,redactedLineCount:w,generatedAt:C.generatedAt}}}var ht=i(),gt=e(A(),1),X=e(ne(),1);function _t(e){let t=_(`user`,e,e);return p({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function vt({home:e=q(),env:t=process.env}={}){let r=_t(e),{override:i,preferenceList:a}=f(t),{locale:o,source:s}=ee({override:i,storedPreference:r,supportedLocales:te,preferenceList:a,autoDetectableLocales:n});return{preference:r,locale:o,source:s,systemLanguages:a}}function yt(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function bt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){if(typeof e==`string`)return yt(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Z(e,t));if(!bt(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=Z(i,t);return n}function xt(e,t){let n=U(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
3
3
  `),i=n.split(`
4
4
  `),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=Z(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
@@ -1,5 +1,5 @@
1
- import{Qs as e,Uu as t,Zi as n,ds as r,eu as i,ms as a,pt as o,vo as s}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{E as c,Eo as l,Oo as u,Ur as d,_i as f,ei as p,ii as m,zo as h}from"./dist-BfGPmTI1.mjs";import{F as g,K as _,N as v,_t as y,b,gt as x,ht as S,ot as C,y as w}from"./init-EA4nTQPs.mjs";import{a as T,c as E,d as D,f as O,i as ee,n as k,o as A,p as j,r as M,s as N,t as te,u as P,v as F}from"./registry-probes-3_EeBR0_.mjs";import{n as ne}from"./constants-COow1ASd.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,join as re,resolve as B}from"node:path";import{existsSync as V,realpathSync as ie}from"node:fs";import{homedir as ae,tmpdir as oe}from"node:os";import{rm as se}from"node:fs/promises";import{setTimeout as ce}from"node:timers/promises";const le=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function H(e,t={}){let{login:n}=t,r=t._exec??I,i=U(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=W(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=W(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function U(e){return[`gh`,...le.filter(e)]}function W(e,t,n){for(let r of t)try{let t=e(r,n,ue).toString().trim();if(t.length>0)return t}catch{}}function de(e,t={}){let n=t._exec??I,r=U(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=W(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=fe(a,e);if(t)return t}let o=W(n,r,i);if(o!==void 0){let e=_e(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function fe(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const pe=/Logged in to \S+ account (\S+) \(/,me=/(?:Failed to log in to|Timeout trying to log in to) \S+/,he=/^\s*-\s*Active account:\s*true\s*$/,ge=/\u001b\[[0-9;]*m/g;function _e(e){let t=[],n;for(let r of e.split(`
2
- `)){let e=r.replace(ge,``),i=pe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(me.test(e)){n=void 0;continue}n&&he.test(e)&&(n.active=!0)}return t}const ve={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){h(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function ye(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}async function be(e,t,n){if(_[e].scope!==`global`)return q();if(n===`absent`)return ye(A(_[e],``,t.home).kind);let r=(await b({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function xe(e,n,r){let i=t[e];if(i===null)return q();let a=re(n.cwd,i);if(r===`absent`)return ye(A(_[e],n.cwd,void 0,a).kind);let o=w(_[e],n.cwd,ve,void 0,a);switch(o.action){case`written`:case`overwritten`:return{action:o.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function Se(e,t,n){let r=t.home??ae();if(n===`absent`){let t=M(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=T(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function Ce(e,t,n){if(n===`absent`){let n=v(_[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=g(_[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function we(e){return t=>{if(t.pathId===void 0)return Y();let n=i(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return be(n.editor,e,t.desired);case`editor-project-config`:return xe(n.editor,e,t.desired);case`editor-project-skill-root`:return Ce(n.editor,e,t.desired);case`editor-user-skill-root`:return Se(n.editor,e,t.desired)}}}function Te(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Ee(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function De(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function Oe(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function ke(t){if(t===`off`)return`off`;if(!e.test(t))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return t}function Ae(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function je(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Me(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||Ae(e.host))&&e.isTTY}function Ne(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Pe(e){return Ne(`--external-url`,e)}function Fe(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=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}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${c}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??oe,r=t.realpathFn??ie,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function Ie(e,t,n=e=>se(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))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`)}else process.stderr.write(`[start] leaving ${t} in place: only ${c}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Le(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{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-Ct3NR8HA.mjs`),x=e.log??g(`start`),S=e.singleFile!==void 0,w=S?f(e.singleFile).canonicalFilePath:void 0,T=w?l(w):void 0,D=w?c(w):void 0,O,A=!1;if(T!==void 0){if(e.projectDir!==void 0){if(O=e.projectDir,!Q(O))throw new Z(O);o(u(O,`.ok`,`config.yml`))||y(O,T)}else O=h(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){x.warn({ephemeralProjectDir:O},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await se(O,{recursive:!0,force:!0})}catch(e){x.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!S){if(!i&&!d(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?x.debug({event:e},`[start] reclaim sweep event`):x.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-C270pJvs.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r}).outcomes.filter(e=>e.outcome!==`no-entry`&&e.outcome!==`canonical`&&e.outcome!==`repaired`&&e.outcome!==`foreign`);i.length>0&&x.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){x.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-CTFrVTHP.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){x.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!S&&!o(P)&&(s(P,{recursive:!0}),x.info({contentDir:P},`Created content directory`));let ne=F(),I=m(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&x.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}L=await p({config:t,contentDir:P,projectDir:O??n,contentRoot:S?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:C(),...S?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>k(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:e=>N(e),agentIntegrations:(()=>{let e={cwd:O??n,home:ae()};return{probe:te(e),execute:we(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Le(M===void 0?n:Ie(n,M),{log:x,exit:e.idleExit})},log:x,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}})}catch(e){throw await j(),e}let R=L.destroy,z=A?async()=>{try{await R()}finally{await j()}}:R;return{httpServer:L.httpServer,destroy:z,lockDir:L.lockDir,contentDir:P,port:L.port,ready:L.ready,degraded:L.degraded}}function Re(e,t,n=()=>l({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function ze(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function Be(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Ve(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 He(e,t){let i=Re(e,t.singleFile),c=Be(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Fe(m);let h;try{h=r(process.env)}catch(e){throw e instanceof o&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=n(i,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=t.bind!==void 0&&t.bind.length>0?t.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=a(g),S=v??(_||b===void 0?[...x.bind]:[b]);je({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=t.externalUrl,E=a(n(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
1
+ import{Qs as e,Uu as t,Zi as n,ds as r,eu as i,ms as a,pt as o,vo as s}from"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import{E as c,Eo as l,Oo as u,Ur as d,_i as f,ei as p,ii as m,zo as h}from"./dist-BfGPmTI1.mjs";import{F as g,K as _,N as v,_t as y,b,gt as x,ht as S,ot as C,y as w}from"./init-Dl36o0mH.mjs";import{a as T,c as E,d as D,f as O,i as ee,n as k,o as A,p as j,r as M,s as N,t as te,u as P,v as F}from"./registry-probes-DbzstoJN.mjs";import{n as ne}from"./constants-B4vbt8P8.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,join as re,resolve as B}from"node:path";import{existsSync as V,realpathSync as ie}from"node:fs";import{homedir as ae,tmpdir as oe}from"node:os";import{rm as se}from"node:fs/promises";import{setTimeout as ce}from"node:timers/promises";const le=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function H(e,t={}){let{login:n}=t,r=t._exec??I,i=U(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=W(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=W(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function U(e){return[`gh`,...le.filter(e)]}function W(e,t,n){for(let r of t)try{let t=e(r,n,ue).toString().trim();if(t.length>0)return t}catch{}}function de(e,t={}){let n=t._exec??I,r=U(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=W(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=fe(a,e);if(t)return t}let o=W(n,r,i);if(o!==void 0){let e=_e(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function fe(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const pe=/Logged in to \S+ account (\S+) \(/,me=/(?:Failed to log in to|Timeout trying to log in to) \S+/,he=/^\s*-\s*Active account:\s*true\s*$/,ge=/\u001b\[[0-9;]*m/g;function _e(e){let t=[],n;for(let r of e.split(`
2
+ `)){let e=r.replace(ge,``),i=pe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(me.test(e)){n=void 0;continue}n&&he.test(e)&&(n.active=!0)}return t}const ve={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){h(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function ye(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}async function be(e,t,n){if(_[e].scope!==`global`)return q();if(n===`absent`)return ye(A(_[e],``,t.home).kind);let r=(await b({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function xe(e,n,r){let i=t[e];if(i===null)return q();let a=re(n.cwd,i);if(r===`absent`)return ye(A(_[e],n.cwd,void 0,a).kind);let o=w(_[e],n.cwd,ve,void 0,a);switch(o.action){case`written`:case`overwritten`:return{action:o.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function Se(e,t,n){let r=t.home??ae();if(n===`absent`){let t=M(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=T(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function Ce(e,t,n){if(n===`absent`){let n=v(_[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=g(_[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function we(e){return t=>{if(t.pathId===void 0)return Y();let n=i(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return be(n.editor,e,t.desired);case`editor-project-config`:return xe(n.editor,e,t.desired);case`editor-project-skill-root`:return Ce(n.editor,e,t.desired);case`editor-user-skill-root`:return Se(n.editor,e,t.desired)}}}function Te(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Ee(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function De(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function Oe(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function ke(t){if(t===`off`)return`off`;if(!e.test(t))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return t}function Ae(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function je(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Me(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||Ae(e.host))&&e.isTTY}function Ne(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Pe(e){return Ne(`--external-url`,e)}function Fe(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=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}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${c}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??oe,r=t.realpathFn??ie,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function Ie(e,t,n=e=>se(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))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`)}else process.stderr.write(`[start] leaving ${t} in place: only ${c}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Le(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{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-Ct3NR8HA.mjs`),x=e.log??g(`start`),S=e.singleFile!==void 0,w=S?f(e.singleFile).canonicalFilePath:void 0,T=w?l(w):void 0,D=w?c(w):void 0,O,A=!1;if(T!==void 0){if(e.projectDir!==void 0){if(O=e.projectDir,!Q(O))throw new Z(O);o(u(O,`.ok`,`config.yml`))||y(O,T)}else O=h(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){x.warn({ephemeralProjectDir:O},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await se(O,{recursive:!0,force:!0})}catch(e){x.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!S){if(!i&&!d(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?x.debug({event:e},`[start] reclaim sweep event`):x.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-Da0GMl66.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r}).outcomes.filter(e=>e.outcome!==`no-entry`&&e.outcome!==`canonical`&&e.outcome!==`repaired`&&e.outcome!==`foreign`);i.length>0&&x.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){x.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-BwywFZwu.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){x.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!S&&!o(P)&&(s(P,{recursive:!0}),x.info({contentDir:P},`Created content directory`));let ne=F(),I=m(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&x.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}L=await p({config:t,contentDir:P,projectDir:O??n,contentRoot:S?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:C(),...S?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>k(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:e=>N(e),agentIntegrations:(()=>{let e={cwd:O??n,home:ae()};return{probe:te(e),execute:we(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Le(M===void 0?n:Ie(n,M),{log:x,exit:e.idleExit})},log:x,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}})}catch(e){throw await j(),e}let R=L.destroy,z=A?async()=>{try{await R()}finally{await j()}}:R;return{httpServer:L.httpServer,destroy:z,lockDir:L.lockDir,contentDir:P,port:L.port,ready:L.ready,degraded:L.degraded}}function Re(e,t,n=()=>l({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function ze(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function Be(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Ve(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 He(e,t){let i=Re(e,t.singleFile),c=Be(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Fe(m);let h;try{h=r(process.env)}catch(e){throw e instanceof o&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=n(i,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=t.bind!==void 0&&t.bind.length>0?t.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=a(g),S=v??(_||b===void 0?[...x.bind]:[b]);je({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=t.externalUrl,E=a(n(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
3
3
  `)))}let D=t.port===void 0?void 0:Number(t.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,ee=D??O??i.server?.port,k=Oe({explicitDir:t.reactShellDistDir,only:t.only,findBundledDir:De}),A=k.dir;k.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let j;try{j=await $({config:i,cwd:m,host:C,port:ee,bind:w,...t.serveContentAssets===void 0?{}:{serveContentAssets:t.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:s(t.idleShutdown??E.idleShutdown),serverRuntime:E,...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof X&&(console.error(f(e.message)),process.exit(1)),e instanceof Z&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-Ct3NR8HA.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),e instanceof t.MissingOkConfigError&&(console.error(f(e.message)),process.exit(1)),Ge(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await Ue({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ce(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=We(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=Ke(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let M=!1,N=async e=>{if(M)return;M=!0;let[t,...n]=Ve(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await j.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{N(`SIGINT`)}),process.once(`SIGTERM`,()=>{N(`SIGTERM`)});let te=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${j.port}`,P=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${j.port}`:void 0,F=te;console.log(l({name:`open-knowledge`,version:ne,localUrl:F,networkUrl:P,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let I={"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`};j.ready.then(async()=>{if(j.degraded.length>0){console.log();for(let e of j.degraded){let t=I[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(Me({openBrowser:t.openBrowser!==!1&&E.openBrowser,explicitOn:t.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:t.singleFile!==void 0,only:t.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-rcp8z_R5.mjs`);e(F)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function Ue(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:p(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function We(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function Ge(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function Ke(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.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`."}catch{return null}}function qe(e){return new S(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,Ee).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,ke).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ze).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>`).addOption(new y(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new y(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Pe).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
4
4
  `),process.exit(2)),t.projectDir!==void 0&&t.singleFile===void 0&&(process.stderr.write(`error: option '--project-dir' requires '--single-file'
5
5
  `),process.exit(2)),t.mode===`app`){let e=[];if(t.port!==void 0&&e.push(`--port`),t.bind!==void 0&&e.push(`--bind`),t.only!==void 0&&e.push(`--only`),t.idleShutdown!==void 0&&e.push(`--idle-shutdown`),t.openBrowser===!1&&e.push(`--no-open-browser`),t.externalUrl!==void 0&&e.push(`--external-url`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=D(P());if(n.available){O({spawn:L},n);return}console.error(j(n.reason)),process.exit(1)}await He(n,t)})}export{Ke as C,de as D,H as E,qe as S,Le as T,Be as _,We as a,Me as b,Q as c,ke as d,Ee as f,Re as g,Ue as h,Fe as i,Ge as l,Te as m,X as n,Ve as o,De as p,$ as r,Ae as s,Z as t,Pe as u,Oe as v,Ie as w,je as x,He as y};
@@ -0,0 +1 @@
1
+ import{S as e,m as t,p as n,r}from"./start-C5pItnpl.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,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.70.1",
3
+ "version": "0.70.3",
4
4
  "description": "Local-first, agent-friendly Markdown knowledge base with a cross-platform CLI and web editor",
5
5
  "keywords": [
6
6
  "knowledge-base",
@@ -70,10 +70,10 @@
70
70
  "ajv-formats": "^3.0.1",
71
71
  "tsdown": "^0.22.14",
72
72
  "typescript": "~7.0.2",
73
- "@inkeep/open-knowledge-app": "0.70.1",
74
- "@inkeep/open-knowledge-core": "0.70.1",
75
- "@inkeep/open-knowledge-server": "0.70.1",
76
- "@inkeep/open-knowledge-native-config": "0.0.0"
73
+ "@inkeep/open-knowledge-core": "0.70.3",
74
+ "@inkeep/open-knowledge-native-config": "0.0.0",
75
+ "@inkeep/open-knowledge-server": "0.70.3",
76
+ "@inkeep/open-knowledge-app": "0.70.3"
77
77
  },
78
78
  "scripts": {
79
79
  "build:cli": "rm -rf dist && tsdown",
@@ -1 +0,0 @@
1
- import"./md-manager-BGnqyqi1-Eez8IlhB.mjs";var e=`0.70.1`;const t=`config.yml`,n=e;export{n,t};
@@ -1 +0,0 @@
1
- import"./dist-BfGPmTI1.mjs";import{_ as e}from"./init-EA4nTQPs.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-DDMBB5EK.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-BE5m2CFL.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{t as e}from"./index-CBirdBL7.js";export{e as FeedbackForm};
@@ -1 +0,0 @@
1
- import"./md-manager-BGnqyqi1-Eez8IlhB.mjs";import"./init-EA4nTQPs.mjs";import"./src-G0L-cT9k.mjs";import"./registry-probes-3_EeBR0_.mjs";import"./start-UjUGzwOh.mjs";import{n as e}from"./loader-DDMBB5EK.mjs";import"./preview-BE5m2CFL.mjs";import"./cli.mjs";import"./repair-mcp-configs-C270pJvs.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{S as e,m as t,p as n,r}from"./start-UjUGzwOh.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};