@inkeep/open-knowledge 0.78.0-beta.10 → 0.78.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-CXGN1QtU.mjs +1 -0
  3. package/dist/{dist-D0uRdq0j.mjs → dist-BUEFqEdv.mjs} +1 -1
  4. package/dist/{dist-DbCJL2ix.mjs → dist-uCKY80_9.mjs} +365 -365
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-BG8NJ1yd.mjs +1 -0
  7. package/dist/{init-DPzjXJk6.mjs → init-CkF5Pwyt.mjs} +2 -2
  8. package/dist/{launch-json-removal-D7IyQyG2.mjs → launch-json-removal-CT-zn4_h.mjs} +1 -1
  9. package/dist/{loader-BHji_QKg.mjs → loader-Cl1695lT.mjs} +1 -1
  10. package/dist/loader-DuTmIaWH.mjs +1 -0
  11. package/dist/{open-browser-ryZAJZiH.mjs → open-browser-CPOeQw4d.mjs} +1 -1
  12. package/dist/preview-BnmGvLf-.mjs +1 -0
  13. package/dist/{preview-wk_vGSMt.mjs → preview-CjRN7_qW.mjs} +1 -1
  14. package/dist/{registry-probes-BvjEMgkO.mjs → registry-probes-BNzSXcyt.mjs} +1 -1
  15. package/dist/{removal-file-path-BOLLNPZH.mjs → removal-file-path-CVZDI2Zp.mjs} +1 -1
  16. package/dist/{repair-launch-json-CjZgWdLx.mjs → repair-launch-json-D7hkCnL6.mjs} +1 -1
  17. package/dist/{repair-mcp-configs-BFE8DeRv.mjs → repair-mcp-configs-C84mr9tJ.mjs} +1 -1
  18. package/dist/{src-DXzRiJCv.mjs → src-CuAz4eVb.mjs} +1 -1
  19. package/dist/src-DwTH-pQF.mjs +1 -0
  20. package/dist/start-AhCYXorn.mjs +1 -0
  21. package/dist/{start-4RfZNqUz.mjs → start-BAXJOEI_.mjs} +3 -3
  22. package/package.json +4 -4
  23. package/dist/constants--RMFEFDe.mjs +0 -1
  24. package/dist/init-C3VOIhjL.mjs +0 -1
  25. package/dist/loader-BA9hG8a4.mjs +0 -1
  26. package/dist/preview-jVdboVNe.mjs +0 -1
  27. package/dist/src-vGVlX20c.mjs +0 -1
  28. package/dist/start-DuNW9-se.mjs +0 -1
package/dist/index.mjs CHANGED
@@ -1535,6 +1535,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
1535
1535
  `);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
1536
1536
  `)?`
1537
1537
  `:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const gje=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function _je(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const vje=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function yje(e){let t={contentDir:e.contentDir};for(let n of vje)for(let r of P9(N(e.stagingDir,n)))_je(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=me(n);n.endsWith(`.jsonl`)?j9(n,t):gje.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function bje(e){return N(e,...I9,z9)}function xje(e){return N(e,...I9,B9)}function Sje(e){return N(e,...L9,V9)}function Cje(e){return N(e,...L9,H9)}function wje(e){return N(e,...R9,U9)}function Tje(e){return N(e,...R9,W9)}const G9=1e3;async function Eje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function Dje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function Oje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function kje(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1538
- `)}\n`:null}catch{return null}}function Aje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function jje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function Mje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Nje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function Pje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Pje(e.maxBytes)}function Fje(e){let t=J9(RX(`project`,e)),n=J9(RX(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function Ije(e){return Ne(`sha256`).update(e).digest(`hex`)}function Lje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Rje=[`"doc.name"`,`"docName"`];function zje(e){let t=S(e,`utf-8`),n=0;for(let e of Rje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Bje=new Set([`.jsonl`]);function Vje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Bje.has(e.slice(t))}const Hje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Uje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Hje.has(e.slice(t))}function Wje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Uje(r))continue;let{redacted:i,patterns:a,lineCount:o}=kB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function Gje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Eje,a=r.fetchAgentEffects??Dje,o=r.fetchWatcherRecent??Oje,s=r.readShadowHead??Aje,c=r.readCheckpointRefs??jje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.78.0-beta.10`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??Mje,h=r.isOtlpPushEnabled??Nje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(bje(n),N(_,`telemetry`,z9)),Z9(xje(n),N(_,`telemetry`,B9)),Z9(Sje(n),N(_,`logs`,V9)),Z9(Cje(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,eR,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=kje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(wje(n),N(_,`state`,U9)),Z9(Tje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Ru),N(_,`state`,Ru)),Z9(N(b,zu),N(_,`state`,zu)),Z9(N(b,Lu),N(_,`state`,Lu));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1538
+ `)}\n`:null}catch{return null}}function Aje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function jje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],H6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function Mje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function Nje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function Pje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return Pje(e.maxBytes)}function Fje(e){let t=J9(RX(`project`,e)),n=J9(RX(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function Ije(e){return Ne(`sha256`).update(e).digest(`hex`)}function Lje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const Rje=[`"doc.name"`,`"docName"`];function zje(e){let t=S(e,`utf-8`),n=0;for(let e of Rje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Bje=new Set([`.jsonl`]);function Vje(e){let t=e.lastIndexOf(`.`);return t!==-1&&Bje.has(e.slice(t))}const Hje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Uje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Hje.has(e.slice(t))}function Wje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!Uje(r))continue;let{redacted:i,patterns:a,lineCount:o}=kB(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function Gje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Eje,a=r.fetchAgentEffects??Dje,o=r.fetchWatcherRecent??Oje,s=r.readShadowHead??Aje,c=r.readCheckpointRefs??jje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.78.0-beta.11`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??Mje,h=r.isOtlpPushEnabled??Nje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(bje(n),N(_,`telemetry`,z9)),Z9(xje(n),N(_,`telemetry`,B9)),Z9(Sje(n),N(_,`logs`,V9)),Z9(Cje(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,eR,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=kje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(wje(n),N(_,`state`,U9)),Z9(Tje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Ru),N(_,`state`,Ru)),Z9(N(b,zu),N(_,`state`,zu)),Z9(N(b,Lu),N(_,`state`,Lu));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1539
1539
  `:`not-running (${w})\n`;re(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(e.diagnosticReports,y);if(re(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&yje({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=Wje(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??me(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=Fje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=Vje(t)?Lje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=zje(e))}let fe={applied:k};ce!==null&&(fe.secretScrub=ce);let pe={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:Ije(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:A};re(N(_,`manifest.json`),`${JSON.stringify(pe,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:pe,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function Kje(e){let{collected:t,outputPath:n}=e,r=M(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new JCe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function qje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=G8(t)?t.content:void 0,i=G8(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return be(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return be(e)}async function Jje(e,t,n,r,i){let a=E7(t,e.logger),o=await Gje({contentDir:qje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...iAe(a,e.userLogsDir??N(k(),`.ok`,`logs`)),...O7(e.cachesDir??N(k(),`Library`,`Caches`))],userStateFiles:k7(e.bugReportsDir??T7()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(M(e.outputPath),{recursive:!0}),await Kje({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Yje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>$ke(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Jje(e,t,n,r,i());let{zipPath:a,summary:o}=await lAe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:O7(e.cachesDir??N(k(),`Library`,`Caches`)),bugReportLedgerFiles:k7(e.bugReportsDir??T7()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Q8 as ALL_EDITOR_IDS,$8 as EDITOR_LABELS,k5 as EDITOR_TARGETS,bOe as HOSTS_WITH_USER_SKILL_DIR,zke as LAUNCH_CONFIG_NAME,QAe as PATH_SHIM_BEGIN,eje as PATH_SHIM_BLOCK_RE,$Ae as PATH_SHIM_END,I5 as ProjectPathSafetyError,_ke as addOkPathsToGitExclude,L5 as assertProjectPathSafe,d5 as buildManagedServerEntry,HAe as buildMcpConfigDeclineEvent,UAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Yje as collectReportBundle,aje as createCliProbeResolver,on as createTokenStore,tAe as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,Uke as detectInstalledEditors,b5 as droppedManagedKeys,VOe as editorConfigPathDisplay,BOe as editorEntryLocator,jAe as ensurePiBridge,Q5 as formatTrackedRemediation,bke as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,yOe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,l5 as isEntryUpToDate,f5 as isOwnManagedEntry,YAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,XAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,tje as pathInstallMarkerPath,nke as previewContent,Wke as probeOwnManagedEditorMcpEntry,kAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,yke as readSharingMode,kB as redactContent,vke as removeOkPathsFromGitExclude,RAe as removeOwnMcpEntry,mke as removeProjectSkill,sje as removeUserGlobalSkillBundle,pje as removeUserSkill,cke as resolveProjectRoot,KAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,fje as userSkillPresentAnywhere,ZAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,uje as writeProjectAiIntegrations,U5 as writeProjectSkill,Hke as writeUserMcpConfigs,dje as writeUserSkill};
1540
1540
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ import"./dist-uCKY80_9.mjs";import{_ as e}from"./init-CkF5Pwyt.mjs";export{e as runInit};
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$l as r,Fd as i,Hd as a,Ju as o,Kd as s,Mt as c,Uu as l,Vd as u,Vl as d,Wd as f,Xd as p,Yl as m,Zd as h,gs as g,ic as _,qd as v,vs as y,zu as b}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Do as x,Eo as S,Fr as ee,Gn as te,Go as ne,H as re,Ji as ie,L as ae,No as C,Oo as oe,Or as se,Qi as ce,Qt as le,R as ue,Rn as de,Sr as fe,To as pe,Tt as me,Yi as he,at as ge,da as _e,fo as ve,ko as ye,lo as be,m as xe,mo as Se,qr as Ce,rt as we,zo as Te}from"./dist-DbCJL2ix.mjs";import{i as w,n as T,o as E,r as Ee,s as D,t as O}from"./colors-r_owlCuY.mjs";import{t as k}from"./is-object-BGze3w87.mjs";import{t as De}from"./constants--RMFEFDe.mjs";import{t as Oe}from"./preview-wk_vGSMt.mjs";import{createRequire as ke}from"node:module";import{execFileSync as Ae}from"node:child_process";import je,{basename as Me,dirname as A,isAbsolute as Ne,join as j,posix as Pe,relative as M,resolve as N,sep as P,win32 as Fe}from"node:path";import F from"node:process";import{fileURLToPath as Ie}from"node:url";import{cpSync as Le,existsSync as I,lstatSync as Re,mkdirSync as ze,readFileSync as L,readdirSync as Be,readlinkSync as Ve,realpathSync as He,rmSync as Ue,statSync as We,writeFileSync as Ge}from"node:fs";import{homedir as R}from"node:os";import{inspect as Ke,stripVTControlCharacters as qe,styleText as z}from"node:util";import*as Je from"node:readline";import{AsyncLocalStorage as Ye,AsyncResource as Xe}from"node:async_hooks";var Ze=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),Qe=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),$e=n((e=>{let{humanReadableArgName:t}=Qe();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
1
+ import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$l as r,Fd as i,Hd as a,Ju as o,Kd as s,Mt as c,Uu as l,Vd as u,Vl as d,Wd as f,Xd as p,Yl as m,Zd as h,gs as g,ic as _,qd as v,vs as y,zu as b}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Do as x,Eo as S,Fr as ee,Gn as te,Go as ne,H as re,Ji as ie,L as ae,No as C,Oo as oe,Or as se,Qi as ce,Qt as le,R as ue,Rn as de,Sr as fe,To as pe,Tt as me,Yi as he,at as ge,da as _e,fo as ve,ko as ye,lo as be,m as xe,mo as Se,qr as Ce,rt as we,zo as Te}from"./dist-uCKY80_9.mjs";import{i as w,n as T,o as E,r as Ee,s as D,t as O}from"./colors-r_owlCuY.mjs";import{t as k}from"./is-object-BGze3w87.mjs";import{t as De}from"./constants-CXGN1QtU.mjs";import{t as Oe}from"./preview-CjRN7_qW.mjs";import{createRequire as ke}from"node:module";import{execFileSync as Ae}from"node:child_process";import je,{basename as Me,dirname as A,isAbsolute as Ne,join as j,posix as Pe,relative as M,resolve as N,sep as P,win32 as Fe}from"node:path";import F from"node:process";import{fileURLToPath as Ie}from"node:url";import{cpSync as Le,existsSync as I,lstatSync as Re,mkdirSync as ze,readFileSync as L,readdirSync as Be,readlinkSync as Ve,realpathSync as He,rmSync as Ue,statSync as We,writeFileSync as Ge}from"node:fs";import{homedir as R}from"node:os";import{inspect as Ke,stripVTControlCharacters as qe,styleText as z}from"node:util";import*as Je from"node:readline";import{AsyncLocalStorage as Ye,AsyncResource as Xe}from"node:async_hooks";var Ze=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),Qe=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),$e=n((e=>{let{humanReadableArgName:t}=Qe();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
2
2
  `)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
3
3
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
4
4
  `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),et=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
689
689
  `));let g=`${s?``:``}${m}`;return g!==o&&C(e,g,{mode:Ca(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const _o=e=>e!==`project`,vo=e=>e!==`user`;async function yo(){let e=await Ma({message:`Where should the MCP server be configured?
690
690
  `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function bo(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??yo)():`both`}async function xo(e){return La({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:"OK config stays on this machine only; teammates do not see it. Safe escape hatch via `ok config-sharing share`."}]})}async function So(e){if(e.sharing!==void 0)return e.sharing;let t=Ki(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??xo)(t):t}var Co=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}};function wo(e){if(e===void 0||e===!0)return new Set(we);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(me.filter(e=>t.includes(e)))}function To(e,t,n){let r=N(n,e),i;try{i=We(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Co(`--content-dir path does not exist: ${r}`):new Co(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Co(`--content-dir must be a directory: ${r}`);let a=Eo(t),o=Eo(r),s=M(a,o);if(s.startsWith(`..`)||Ne(s))throw new Co(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Eo(e){try{return He(e)}catch{return e}}const Do=`open-knowledge-ui`;function Oo(e,t,n){try{let r=e.detectPath?.(t,n)??A(e.configPath(t,n));return I(r)}catch{return!1}}function ko(e,t,n){try{let r=N(A(e.configPath(t,n))),i=N(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+P)}catch{return!1}}function Ao(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!I(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||ko(e,t,r);if(!i&&c&&!Oo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{oa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return Mo(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||ze(A(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{Te(`${o}.lock`,()=>{let t=Xa(o).writePath;if(s||ze(A(t),{recursive:!0}),e.format===`toml`){let r=po(Hr(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=go(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=fo(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const jo={pi:Ha};function Mo(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=jo[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{ze(A(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{Te(`${t}.lock`,()=>{let e=null;try{e=L(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}C(t,c,e===null?void 0:{mode:Ca(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function No(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!I(n)))return{editorId:e.id,label:e.label,path:n}}async function Po(e){let t=zi(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>Ao(t,``,n,e.home))}function Fo(e,t,n,r){let i=Lo(e,t,n,r);return i.kind===`present`?i.entry:null}function Io(e,t,n,r){let i=uo(e,t,r);if(!k(i))return{kind:`no-entry`};let a=i[n];return k(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function Lo(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!I(i))return{kind:`absent`};try{if(We(i).size>io)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:ya(e)}}let a;try{a=L(i,`utf-8`)}catch(e){return{kind:`decline`,reason:ya(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:Va(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=Hr().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return Io(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,J.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:Io(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=$a(a);return s?eo(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:Io(S(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function Ro(e={}){let t=N(e.cwd??process.cwd()),n=Ga(t,{homeDir:e.home}),i=n.projectRoot;if(ee(i,e.home??R()))throw new re(i);let a=!I(j(i,`.ok`)),o=n.gitRootPromoted?M(i,t):void 0,s=e.contentDir===void 0?n.defaultContentDir:To(e.contentDir,i,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${i}`):n.gitRootPromoted&&a&&s===`.`&&process.stderr.write(`${D(`[ok] Content scope promoted to the git repo root: ${i}`)}\n Ran in ${o}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`ok init --content-dir .\`, or set content.dir: ${o} in .ok/config.yml.\n`);let c={mode:e.devMcp?`dev`:`published`},l=await te(i),u;try{u=fe(i,{contentDir:s})}catch(t){let r=$.claude.configPath(i,e.home);return{projectRoot:i,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:l.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let d=u.created.includes(De),f=!1;if(l.didInit)try{f=Se(i)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${i}: ${e instanceof Error?e.message:String(e)}`)}try{ie(i)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${i}: ${e instanceof Error?e.message:String(e)}`)}let p=await bo({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),m=e.editors??Wo(i,e.home),h=e.editors??m,g=zi(m),_=zi(h),v=e.mcp===!1||p===null,y=Array.from(new Map([...g,...v?[]:_].map(e=>[e.id,e])).values()),b=g.filter(t=>Oo(t,i,e.home)),x=[],S=[],ne=new Set;for(let t of y){if(v){let n=``;try{n=t.configPath(i,e.home)}catch{}x.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(i)});continue}if(_o(p)&&g.includes(t)&&t.scope===`global`&&x.push(Ao(t,i,c,e.home)),vo(p)&&_.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(i),r=Ao(t,i,c,e.home,n);x.push(r),(r.action===`written`||r.action===`overwritten`)&&ne.add(n)}}let ae=new Set;for(let t of _){let n=t.projectSkillPath?.(i);!n||ae.has(n)||(ae.add(n),S.push(_a(t,i,{home:e.home})))}let C=ga(i,_.map(e=>e.id));C&&S.push(C);let oe=S.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(oe.length>0){let t=e.home??R();he({source:r,skills:[xe.project],agents:oe,scope:i},{home:t,enabled:_e(t).enabled})}let ce=!v&&p!==null&&vo(p)?_.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,le=v?[]:b.map(e=>No(e,i)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ue=e.installUserSkill??se,pe=e.home??R(),ge=wo(e.skills),ye=!1,be=!1,Ce=!1,we=!1,Te=!1;for(let t of me){if(!ge.has(t))continue;await ve(pe,xe[t],!0).catch(()=>{}),ye=!0;let n=await ue({home:e.home,bundleId:t,force:!0});n===`installed`?be=!0:n===`failed`?Ce=!0:n===`no-hosts`?Te=!0:we=!0}let w=Ce?`failed`:be?`installed`:ye&&we?`skip-current`:ye&&Te?`no-hosts`:`declined`,T=be?de(pe).map(e=>e.editorId):[],E=v?`skipped-flag`:`skipped-missing`,Ee=x.find(e=>e.editorId===`claude`)??x[0]??{action:E,configPath:$.claude.configPath(i,e.home)},O=await zo({projectRoot:i,desiredMode:await So({sharing:e.sharing,projectRoot:i,isTTY:e.isTTY,freshProject:a,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:i,contentCreated:u.created,contentUpdated:u.updated,contentSkipped:u.skipped,editors:x,projectSkills:S,legacyProjectConfigs:le,skillInstall:w,skillHosts:T,didGitInit:l.didInit,rootGitignoreCreated:f,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDir:d?s:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Ee.action,mcpPath:Ee.configPath,mcpError:`error`in Ee?Ee.error:void 0,projectScopeUnsupportedLabels:ce,sharing:O}}async function zo(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=Ki(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=Hi(t);if(n===`local-only`){let e=Wi(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:Bo(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=Gi(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:Bo(t,o,`remove`)}function Bo(e,t,n){let r=Ki(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function Vo(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function Ho(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let s=j(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`Content scaffolded at ${s}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(O(`Content already present at ${s}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(O(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let e=r.configPath.startsWith(t)?M(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),i=r.serverName===`open-knowledge`?``:` (${r.serverName})`,a=r.configScope===`project`?` (project)`:``,o=`${r.label}${a}`,s=` `.repeat(Math.max(1,20-o.length)),c=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${o}${s}${e} ${E(`registered`)}${i}${c}`);break;case`overwritten`:n.push(` ${o}${s}${e} ${E(`updated`)}${i}${c}`);break;case`skipped-missing`:n.push(` ${o}${s}${e} config root missing; skipped`);break;case`failed`:n.push(` ${o}${s}${e} ${Ee(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${o}${s}${e} left unchanged (${Vo(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(O(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?M(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${E(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${E(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${Ee(`FAILED`)}: ${r.error}`)}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${M(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(O(`User-global skill:`)),e.skillInstall){case`installed`:{let t=(e.skillHosts??[]).map(e=>X[e]??e),r=t.length>0?t.join(`, `):`the shared ~/.agents store`;n.push(` open-knowledge ${E(`installed for ${r}`)}`),n.push(` ${T(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${T(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`);break}case`skip-current`:n.push(` open-knowledge ${E(`already installed at current version`)}`);break;case`declined`:n.push(` open-knowledge ${T(`skipped for this run (--no-skills)`)}`),n.push(` ${T(`Nothing was installed or removed. Any built-in skills already on this`)}`),n.push(` ${T(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${T(` ok init`)}`);break;case`no-hosts`:n.push(` open-knowledge ${T(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${D(`open-knowledge install failed — MCP still configured; retry with:`)}`),n.push(` ${D(` ok repair-skills`)}`)}if(e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(D(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(D(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`ok init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(" To scope to just that sub-folder, re-run `ok init --content-dir .` from there, or set"),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(Oe(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...qo(e.sharing,t)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${E(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${w(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${w(`ok seed --list-packs`)} — browse the starter packs`),n.push(` - ${w(`ok seed`)} — scaffold an empty repo`),n.push(` 4. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}return n.join(`
691
691
  `)}function Uo(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function Wo(e,t){let n=[];for(let r of Wr)r!==`claude-desktop`&&Oo($[r],e,t)&&n.push(r);return n}function Go(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:Ke(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function Ko(){return new ut(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new ft(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new ft(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new ft(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?Go():null;try{let r;try{r=await Ro({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Co||e instanceof re){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof ae||e instanceof ue){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof ge){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
692
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-BA9hG8a4.mjs`),{resolveContentDir:s}=await import(`./dist-D0uRdq0j.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-jVdboVNe.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(Uo(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${Ho(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function qo(e,t){let n=[];switch(e.kind){case`applied`:return n.push(O(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${E(`local-only`)} — appended ${e.appended.length} path(s) to ${O(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${E(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${E(`local-only`)} — already excluded; nothing to do.`):n.push(` ${E(`local-only`)}`):e.action===`removed`?n.push(` ${E(`shared`)} — removed OK paths from ${O(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${E(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(D(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
692
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-DuTmIaWH.mjs`),{resolveContentDir:s}=await import(`./dist-BUEFqEdv.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-BnmGvLf-.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(Uo(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${Ho(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function qo(e,t){let n=[];switch(e.kind){case`applied`:return n.push(O(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${E(`local-only`)} — appended ${e.appended.length} path(s) to ${O(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${E(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${E(`local-only`)} — already excluded; nothing to do.`):n.push(` ${E(`local-only`)}`):e.action===`removed`?n.push(` ${E(`shared`)} — removed OK paths from ${O(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${E(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(D(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
693
693
  `))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${w(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(D(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${w(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${w(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(D(`Sharing mode unavailable: ${e.reason}.`));return n}}export{yi as $,wa as A,Wi as B,Ga as C,ut as Ct,Ma as D,La as E,oa as F,Ji as G,qi as H,sa as I,Wr as J,Ki as K,va as L,ya as M,aa as N,Ca as O,la as P,Z as Q,ua as R,Xa as S,St,Ba as T,ft as Tt,Ui as U,Qi as V,Hi as W,$ as X,X as Y,Gr as Z,Ro as _,Hn as _t,Uo as a,Si as at,Po as b,Jt as bt,Ho as c,Pi as ct,Oo as d,Hr as dt,vi as et,Fo as f,Y as ft,So as g,$n as gt,To as h,Pr as ht,zo as i,ii as it,ba as j,Sa as k,qo as l,ci as lt,bo as m,jr as mt,Do as n,xi as nt,Lo as o,Q as ot,wo as p,Mr as pt,Gi as q,jo as r,ti as rt,Wo as s,Ci as st,Co as t,bi as tt,Ko as u,Ur as ut,co as v,Qt as vt,Ha as w,ct as wt,ko as x,V as xt,Ao as y,Yt as yt,_a as z};
@@ -1 +1 @@
1
- import{Eo as e,No as t,ko as n}from"./dist-DbCJL2ix.mjs";import{A as r,M as i,O as a}from"./init-DPzjXJk6.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-BOLLNPZH.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:i(e)}}let g=[],_=n(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=r(h,[`configurations`,y]);return x?(t(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
1
+ import{Eo as e,No as t,ko as n}from"./dist-uCKY80_9.mjs";import{A as r,M as i,O as a}from"./init-CkF5Pwyt.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-CVZDI2Zp.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:i(e)}}let g=[],_=n(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=r(h,[`configurations`,y]);return x?(t(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
@@ -1 +1 @@
1
- import{Ol as e,cl as t,gl as n,no as r,ol as i,os as a,zu as o}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Fo as s,Lo as c,x as l}from"./dist-DbCJL2ix.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants--RMFEFDe.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=o();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(n){let o=n??process.cwd(),u=[],p=[],m=[],h=[],g=c(`user`,o),_=s({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(t,n=!1)=>{let a=v(t);if(a.diagnostic!==void 0&&p.push(a.diagnostic),a.value===null)return{};let o=i({value:a.value,file:a.path,source:a.source,doc:a.doc});p.push(...o),u.push(t);let s=o.length>0?e(a.value):a.value;return n&&h.push(...r({value:s,file:a.path,source:a.source,doc:a.doc})),s},x=f(o,`.ok`,d),S=b(x,!0),C=b(c(`project-local`,o)),w=a(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),n={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(t(n))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
1
+ import{Ol as e,cl as t,gl as n,no as r,ol as i,os as a,zu as o}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Fo as s,Lo as c,x as l}from"./dist-uCKY80_9.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-CXGN1QtU.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=o();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(n){let o=n??process.cwd(),u=[],p=[],m=[],h=[],g=c(`user`,o),_=s({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(t,n=!1)=>{let a=v(t);if(a.diagnostic!==void 0&&p.push(a.diagnostic),a.value===null)return{};let o=i({value:a.value,file:a.path,source:a.source,doc:a.doc});p.push(...o),u.push(t);let s=o.length>0?e(a.value):a.value;return n&&h.push(...r({value:s,file:a.path,source:a.source,doc:a.doc})),s},x=f(o,`.ok`,d),S=b(x,!0),C=b(c(`project-local`,o)),w=a(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),n={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(t(n))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-Cl1695lT.mjs";export{e as loadConfig};
@@ -1 +1 @@
1
- import{lo as e}from"./dist-DbCJL2ix.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
1
+ import{lo as e}from"./dist-uCKY80_9.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-CjRN7_qW.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,2 +1,2 @@
1
- import{yn as e}from"./dist-DbCJL2ix.mjs";import"./constants--RMFEFDe.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);a.push(``);let c=t(i,`.ok`,`config.yml`);return r(c)?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
1
+ import{yn as e}from"./dist-uCKY80_9.mjs";import"./constants-CXGN1QtU.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);a.push(``);let c=t(i,`.ok`,`config.yml`);return r(c)?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
2
2
  `)}export{c as n,l as t};
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$a as r,Gd as i,Ju as a,Ud as o,Vd as s,Vl as c,Wd as l,eo as u,it as d,qd as f,zu as p}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{$n as m,No as h,Qi as g,Rn as _,Ro as v,lo as y,m as b,wn as x,wo as ee,zo as S}from"./dist-DbCJL2ix.mjs";import{$ as te,A as ne,J as re,M as C,O as w,P as ie,R as ae,T as oe,X as T,at as se,ct as ce,d as le,dt as ue,f as de,it as fe,j as pe,k as me,lt as he,nt as ge,o as _e,rt as ve,tt as ye,v as be,w as xe,x as Se,y as Ce}from"./init-DPzjXJk6.mjs";import{t as we}from"./is-object-BGze3w87.mjs";import{t as Te}from"./removal-file-path-BOLLNPZH.mjs";import{spawn as Ee}from"node:child_process";import{basename as E,dirname as D,join as O,resolve as k,win32 as De}from"node:path";import{accessSync as Oe,constants as A,existsSync as j,lstatSync as M,mkdirSync as ke,readFileSync as N,readdirSync as P,realpathSync as F,rmSync as Ae,rmdirSync as je,statSync as I,unlinkSync as Me,writeFileSync as Ne}from"node:fs";import{homedir as L}from"node:os";import{createHash as Pe}from"node:crypto";import{isDeepStrictEqual as Fe}from"node:util";import{setTimeout as Ie}from"node:timers/promises";var Le=p();let Re;function ze(){return Re}function Be(e,t){if(t!==void 0&&t.length>0)return t;try{return m(e)?.rootPath}catch{return}}function Ve(e){let t=Be(e.cwd,e.configuredProjectName),n=x({name:`cli`,project:t});return Re=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}const R=`open-knowledge`;function z(e){try{e()}catch{}}var He=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(R,e).getPassword()}catch(t){return z(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return z(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return z(()=>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(R,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(R,e).deletePassword()}catch{}}},B=class{backend=`file`;authFile;constructor(e){this.authFile=e??O(L(),`.ok`,`auth.yml`)}read(){if(!j(this.authFile))return{};try{let e=N(this.authFile,`utf-8`);return(0,Le.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=D(this.authFile);j(t)||ke(t,{recursive:!0,mode:448}),Ne(this.authFile,(0,Le.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)}},Ue=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 We(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(R,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
1
+ import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$a as r,Gd as i,Ju as a,Ud as o,Vd as s,Vl as c,Wd as l,eo as u,it as d,qd as f,zu as p}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{$n as m,No as h,Qi as g,Rn as _,Ro as v,lo as y,m as b,wn as x,wo as ee,zo as S}from"./dist-uCKY80_9.mjs";import{$ as te,A as ne,J as re,M as C,O as w,P as ie,R as ae,T as oe,X as T,at as se,ct as ce,d as le,dt as ue,f as de,it as fe,j as pe,k as me,lt as he,nt as ge,o as _e,rt as ve,tt as ye,v as be,w as xe,x as Se,y as Ce}from"./init-CkF5Pwyt.mjs";import{t as we}from"./is-object-BGze3w87.mjs";import{t as Te}from"./removal-file-path-CVZDI2Zp.mjs";import{spawn as Ee}from"node:child_process";import{basename as E,dirname as D,join as O,resolve as k,win32 as De}from"node:path";import{accessSync as Oe,constants as A,existsSync as j,lstatSync as M,mkdirSync as ke,readFileSync as N,readdirSync as P,realpathSync as F,rmSync as Ae,rmdirSync as je,statSync as I,unlinkSync as Me,writeFileSync as Ne}from"node:fs";import{homedir as L}from"node:os";import{createHash as Pe}from"node:crypto";import{isDeepStrictEqual as Fe}from"node:util";import{setTimeout as Ie}from"node:timers/promises";var Le=p();let Re;function ze(){return Re}function Be(e,t){if(t!==void 0&&t.length>0)return t;try{return m(e)?.rootPath}catch{return}}function Ve(e){let t=Be(e.cwd,e.configuredProjectName),n=x({name:`cli`,project:t});return Re=n,n.info({command:e.command,cwd:e.cwd,project:t},`cli command started`),n}const R=`open-knowledge`;function z(e){try{e()}catch{}}var He=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(R,e).getPassword()}catch(t){return z(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return z(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return z(()=>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(R,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(R,e).deletePassword()}catch{}}},B=class{backend=`file`;authFile;constructor(e){this.authFile=e??O(L(),`.ok`,`auth.yml`)}read(){if(!j(this.authFile))return{};try{let e=N(this.authFile,`utf-8`);return(0,Le.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=D(this.authFile);j(t)||ke(t,{recursive:!0,mode:448}),Ne(this.authFile,(0,Le.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)}},Ue=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 We(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(R,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
2
  `),z(()=>t?.onBackendSelected?.({backend:`keyring`})),new Ue(new He(t?.onKeychainRead),new B(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`),z(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new B(e)}}function Ge(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 B(e))},n)});try{return await Promise.race([We(e),r])}catch{return new B(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function Ke(e){let t=Ge(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}function qe(e){let t=Ge(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 Je(e,t){let n=[],r=new B(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(R,`__probe__`);let r,a=await new He(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(R,e).deletePassword(),n.push(`keychain`)}catch(e){i=e instanceof Error?e.name:`delete-error`}}catch{}return{touched:n,keychainError:i}}function Ye(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Xe(e){let t=e?.code;return t===`ENOENT`||t===`EACCES`||t===`EPERM`?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function Ze(e){return y({detached:!0,stdio:`ignore`,shell:!1,env:Ye(e)})}function Qe(e,t,n={}){let r=(n.spawn??Ee)(e,[...t],Ze(n.env??process.env));return r.unref(),r}function $e(e,t,n={}){let r=n.spawn??Ee,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],Ze(n.env??process.env));i.once(`error`,e=>{clearTimeout(c),s(Xe(e))}),i.once(`spawn`,()=>{clearTimeout(c),s({ok:!0})});try{i.unref()}catch{}}catch(e){clearTimeout(c),s(Xe(e))}})}const et=d.stable.appId,V=[d.stable,d.beta];function tt(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return I(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function nt(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}let t=e.homeDir??L();for(let n of V)for(let r of[O(t,`Applications`),`/Applications`]){let t=O(r,`${n.productName}.app`);if(rt(e,O(t,`Contents`,`MacOS`,n.productName)))return t}return null}function rt(e,t){try{let n=e.statSync(t);return n?typeof n.isFile==`function`&&n.isFile():!1}catch{return!1}}function it(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&V.find(t=>e.execPath.toLowerCase().endsWith(`\\${r(t).toLowerCase()}`)))return e.execPath;let t=e.env.LOCALAPPDATA;if(t)for(let n of V)for(let i of u(n)){let a=De.join(t,`Programs`,i,r(n));if(rt(e,a))return a}return null}function at(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`&&V.find(t=>e.execPath.endsWith(`/${t.linuxExecutableName}`)))return e.execPath;for(let t of V){let n=`/opt/${t.productName}/${t.linuxExecutableName}`;if(rt(e,n))return n}return null}function ot(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`?nt(e):e.platform===`win32`?it(e):at(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 st(e,t){let n=e.log??(e=>console.error(e)),r=e.platform??process.platform;n("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let i=t?.bundlePath;if(!i){n(`Desktop launch skipped: no resolved desktop executable (caller bug).`);return}if(r===`darwin`){Qe(`open`,[`-a`,i],{spawn:e.spawn});return}Qe(i,[],{spawn:e.spawn})}function ct(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 H(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function lt(e){return Pe(`sha256`).update(e).digest(`hex`)}function U(e){return O(k(e),`.ok`,`pi-trust`)}function ut(e,t){return O(U(e),lt(k(t)))}function dt(e,t,n){return O(ut(e,t),`${lt(n)}.json`)}var W=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${H(e)} ${H(t)}; ${H(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function G(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new W(e,`could not ${t}: ${i}`,a,n)}function K(e){let t;try{t=M(e)}catch(t){if(t.code===`ENOENT`)return!1;throw G(e,`be inspected`,t)}if(!t.isDirectory())throw new W(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function ft(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function pt(e,t){if(!we(e)||!ft(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==k(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==k(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==k(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!we(e.previous))throw new W(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&ft(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&ft(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new W(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function mt(e,t,n){let r;try{r=M(n)}catch(e){throw G(n,`be inspected`,e)}if(!r.isFile())throw new W(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=N(n,`utf8`)}catch(e){throw G(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new W(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=pt(a,n);if(o.cwd!==k(t)||n!==dt(e,t,o.canonicalTrustPath))throw new W(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function ht(e,t){let{record:n,path:r}=t;for(let t of[U(e),ut(e,n.cwd)])if(!K(t))throw new W(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=mt(e,n.cwd,r);if(!Fe(i.record,n))throw new W(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function gt(e,t,n,r,i){let a={version:1,cwd:k(t),configuredTrustPath:k(n),canonicalTrustPath:k(r),state:`pending`,previous:i},o=dt(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Fe(pt(JSON.parse(s),o),a))throw new W(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);K(U(e)),K(D(o));try{ke(D(o),{recursive:!0,mode:448})}catch(e){throw G(D(o),`be created`,e)}let c;try{c=M(o,{throwIfNoEntry:!1})}catch(e){throw G(o,`be inspected`,e)}if(c)throw new W(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{h(o,s,{mode:384})}catch(e){throw G(o,`be written`,e)}return{path:o,record:a}}function _t(e,t){let n=ht(e,t);if(n.record.state!==`pending`)throw new W(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{h(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw G(n.path,`be committed`,e)}return{path:n.path,record:r}}function q(e,t){if(!K(U(e)))return[];let n=ut(e,t);if(!K(n))return[];let r;try{r=P(n).sort()}catch(e){throw G(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>mt(e,t,O(n,r)))}function J(e,t){let n=ht(e,t);try{Me(n.path)}catch(e){throw G(n.path,`be removed after reconciling its grant`,e)}for(let t of[D(n.path),U(e)])try{je(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw G(t,`be removed after reconciling its grant`,e)}}var vt=n(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),yt=n(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),bt=n(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),xt=n(((t,n)=>{var r=e(`fs`),i=vt(),a=yt(),o=bt(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
3
3
  GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=ne,e.createWriteStream=re;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,S=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=ee);var v=e.WriteStream;v&&(S.prototype=Object.create(v.prototype),S.prototype.open=te),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return S},set:function(e){S=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=S;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function ee(){var e=this;w(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function S(e,t){return this instanceof S?(v.apply(this,arguments),this):S.apply(Object.create(S.prototype),arguments)}function te(){var e=this;w(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var C=e.open;e.open=w;function w(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return C(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),St=n(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Ct=n((e=>{var t=St();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),wt=n(((e,t)=>{t.exports=Ct()})),Tt=n(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),Et=n(((t,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=e(`assert`),o=Tt(),s=/^win/i.test(r.platform),c=e(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),Dt=n(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Ot=n(((t,n)=>{let r=e(`path`),i=xt(),a=wt(),o=Et(),s=Dt(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),kt=n(((e,t)=>{let n=xt();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),At=t(n(((e,t)=>{let n=Ot(),{toPromise:r,toSync:i,toSyncOptions:a}=kt();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const jt=5e3;function Mt(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${jt}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Nt(e,t){ze()?.warn(t,e)}function Pt(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function Ft(e,t,n){await v(`${t}.ok.lock`,async()=>{let t=performance.now()+jt,r;for(;;)try{r=await At.default.lock(D(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Ie(Mt(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}Pt(i,e)},{onWarn:Nt})}function It(e,t,n){S(`${t}.ok.lock`,()=>{let t=performance.now()+jt,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=At.default.lockSync(D(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,Mt(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}Pt(a,e)},{onWarn:Nt})}const Lt=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var Rt=class extends Error{name=`PiResourceInspectionError`};function Y(e){let t;try{t=M(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=I(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new Rt(pe(`missing-symlink-target`),{cause:e}):e}return Oe(e,A.R_OK|(n.isDirectory()?A.X_OK:0)),!0}function zt(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function Bt(e,t,n){let r=e;try{let i=F(e),a;r=t;try{a=F(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=k(t)}let o=O(a,`.agents`,`skills`),s=[];for(let e of Lt)r=O(i,`.pi`,e),Y(r)&&s.push(r);if(r=O(i,`.pi`,`extensions`),Y(r))for(let t of P(r).sort()){let i=O(r,t);k(n)!==O(k(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[O(i,`.pi`,`skills`),O(i,`.agents`,`skills`)])if(e!==o&&(r=e,Y(e)))for(let t of P(e).sort())zt(t)||s.push(O(e,t));let c=D(i);for(;c!==i;){r=O(c,`.agents`,`skills`),r!==o&&Y(r)&&s.push(r);let e=D(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${H(r)}: ${e instanceof Rt?e.message:pe(C(e))}`}}}function Vt(e,t,n){let r=k(e),i=ce({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:T.pi.projectConfigPath(r),trustPath:O(i,`trust.json`)}}function X(e){try{let t=F(e);return I(t).isDirectory()?(Oe(t,A.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${H(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${H(e)} could not be resolved or accessed: ${H(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function Ht(e){let t=X(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${H(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function Ut(e,t,n){let r=_e(T.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 ve(i)?{state:`own-current`,text:a}:oe(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function Wt(e,t){let n;try{n=N(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:C(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return we(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
4
4
  `)}:{state:`unreadable`,reason:`invalid-json`}}function Gt(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return pe(e)}}function Z(e,t){return{kind:`refused`,error:`trust store ${H(e)}: ${Gt(t)}`}}function Q(e){let t=Te(e);try{switch(t.kind){case`declined`:return Z(e,t.reason);case`ready`:return{kind:`ready`,path:F(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=D(e),r=[E(e)],i=M(n,{throwIfNoEntry:!1});for(;!i;){let t=D(n);if(t===n)return Z(e,`unavailable-root`);r.unshift(E(n)),n=t,i=M(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:O(F(n),...r)}}catch(t){return Z(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:C(t))}}catch(t){return Z(e,C(t))}}function Kt(e,t){let n=Q(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?Z(e,`path-changed`):n}function qt(e,t,n){let r=Vt(e,t,n),i=X(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=Ut(r.cwd,r.bridgePath,t).state,o=Q(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:Wt(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:Jt(r.bridgePath).displayNames}}function Jt(e){let t=D(e),n=E(e);try{return{displayNames:P(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>H(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function Yt(e,t={mode:`published`},n,r,i){let a=Vt(e,n,r),o=X(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${H(i)} no longer matches the current directory ${H(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=Ut(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=xe(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=Ce(T.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:H(e.error)}}let l=await Xt(a.trustPath,o.project,n??L());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function Xt(e,t,n){let r=t.canonical,i=Q(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{ke(D(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:H(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await Ft(e,i.path,()=>{let o=Ht(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=Kt(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=Wt(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=Z(e,c.reason).error;return}let l=$(n,()=>{let t=q(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&J(n,t),gt(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
@@ -1 +1 @@
1
- import{M as e,S as t}from"./init-DPzjXJk6.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(t){return t.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:e(t)}}let o=t(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(t){return{kind:`declined`,reason:a&&t.code===`ENOENT`?`missing-symlink-target`:e(t)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
1
+ import{M as e,S as t}from"./init-CkF5Pwyt.mjs";import{lstatSync as n,statSync as r}from"node:fs";function i(i){let a;try{a=n(i).isSymbolicLink()}catch(t){return t.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:e(t)}}let o=t(i);if(o.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!r(o.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(t){return{kind:`declined`,reason:a&&t.code===`ENOENT`?`missing-symlink-target`:e(t)}}return{kind:`ready`,path:o.writePath,symlink:a}}export{i as t};
@@ -1 +1 @@
1
- import{t as e}from"./launch-json-removal-D7IyQyG2.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-CT-zn4_h.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{Aa as e}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{J as t,X as n,et as r,f as i,rt as a,y as o}from"./init-DPzjXJk6.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 r=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=d(()=>t.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},s=i(t.target,t.cwd,t.home,t.configPathOverride);if(s===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(s))return{...n,outcome:`canonical`}}else{let i=e(s);if(i.kind===`recognized`&&i.disposition===`keep`){let e=r(s,t.target.buildEntry(t.cwd,{}));if(e.length===0)return{...n,outcome:`canonical`};let i=p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(i.outcome===`repaired`||i.outcome===`canonical`)&&t.logger({event:i.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:i.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),i.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:i}if(i.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:i.reason}),{...n,outcome:`foreign`,reason:i.reason}}return t.logger({...c({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:s}),severity:`info`}),p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.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{Aa as e}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{J as t,X as n,et as r,f as i,rt as a,y as o}from"./init-CkF5Pwyt.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 r=e.logger??m,i=e.home??s(),a=[];if(e.reclaimDisableEnv===`1`)return r({event:`mcp-config-repair-skipped`,severity:`info`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of t){let t=n[o],s=d(()=>t.configPath(``,i));if(s!==null&&a.push(f({scope:`user`,editorId:o,target:t,home:i,cwd:``,configPath:s,configPathOverride:void 0,logger:r})),t.projectConfigPath){let n=t.projectConfigPath,i=d(()=>n(e.projectDir));i!==null&&a.push(f({scope:`project`,editorId:o,target:t,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:r}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function d(e){try{return e()}catch{return null}}function f(t){let n={scope:t.scope,editorId:t.editorId,configPath:t.configPath},s=i(t.target,t.cwd,t.home,t.configPathOverride);if(s===null)return{...n,outcome:`no-entry`};if(t.target.format===`file`){if(a(s))return{...n,outcome:`canonical`}}else{let i=e(s);if(i.kind===`recognized`&&i.disposition===`keep`){let e=r(s,t.target.buildEntry(t.cwd,{}));if(e.length===0)return{...n,outcome:`canonical`};let i=p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0,pruneOnly:!0},t.home,t.configPathOverride));return(i.outcome===`repaired`||i.outcome===`canonical`)&&t.logger({event:i.outcome===`repaired`?`mcp-config-repair-pruned`:`mcp-config-repair-prune-unchanged`,severity:i.outcome===`repaired`?`info`:`warn`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,keys:e}),i.outcome===`canonical`?{...n,outcome:`prune-unchanged`}:i}if(i.kind===`declined`&&t.scope===`project`)return t.logger({event:`mcp-config-repair-skipped-foreign`,severity:`info`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,reason:i.reason}),{...n,outcome:`foreign`,reason:i.reason}}return t.logger({...c({scope:t.scope,surface:`cli-repair`,editorId:t.editorId,configPath:t.configPath,priorEntry:s}),severity:`info`}),p(t,n,o(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.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,4 +1,4 @@
1
- import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$d as t,Bn as n,Cc as r,Ds as i,Eo as a,Jc as o,Mn as s,Rs as c,Yc as l,Zc as u,jn as d,xc as ee,zu as te}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{$n as f,Fo as p,Io as m,Kr as h,Lo as g,Qr as _,Si as v,Tt as y,Yn as b,ai as x,fr as S,ii as C,lo as w,m as T,oa as E,oi as D,xi as O,zn as k}from"./dist-DbCJL2ix.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{Ct as ne,ot as j,st as M}from"./init-DPzjXJk6.mjs";import{b as re,l as ie}from"./registry-probes-BvjEMgkO.mjs";import{c as N}from"./colors-r_owlCuY.mjs";import{t as P}from"./is-object-BGze3w87.mjs";import{n as ae}from"./constants--RMFEFDe.mjs";import"./loader-BHji_QKg.mjs";import"./preview-wk_vGSMt.mjs";import{execSync as oe,spawnSync as F}from"node:child_process";import{basename as I,dirname as L,isAbsolute as se,join as R,relative as ce,resolve as z,sep as B}from"node:path";import{closeSync as le,cpSync as ue,createWriteStream as de,existsSync as V,lstatSync as fe,mkdirSync as H,mkdtempSync as pe,openSync as me,readFileSync as U,readSync as he,readdirSync as W,rmSync as G,rmdirSync as ge,statSync as _e,writeFileSync as K}from"node:fs";import{arch as ve,freemem as ye,homedir as q,hostname as be,platform as xe,release as Se,tmpdir as Ce,totalmem as we,type as Te,uptime as Ee}from"node:os";import"node:fs/promises";import{createHash as De}from"node:crypto";const Oe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function ke(e,t,n=f){if(e!==void 0&&!Oe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ae=null;function je(e){Ae=e}function Me(){return Ae??process.cwd()}const Ne=`Open Knowledge`;function Pe(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return j(t).join(M({...e,platformName:t}),n)}function Fe(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=j(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 Ie(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 Le(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return Ie(n)??[]}function Re(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return Ie(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const ze=8192;function Be(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 Ve(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const He=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ue(e){return e.replace(He,`$1"[REDACTED-DEVICE-ID]"`)}function We(e){return Ue(Ve(e))}const Ge=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ke(e){if(typeof e!=`string`)return null;let t=Ge.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 qe(e){let t=me(e,`r`);try{let e=Buffer.alloc(ze),n=0,r=!1;for(;n<ze;){let i=he(t,e,n,ze-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{le(t)}}function Je(e){try{let t=qe(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:Ke(a)}}catch{return{kind:`unreadable`}}}function Ye(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function Xe(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=R(e,t.name),r;try{r=_e(n).mtimeMs}catch{continue}if(r<i)continue;let c=Je(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Ye(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 R(q(),`.ok`,`bug-reports`)}function Ze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=R(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=R(n,`${r}-${e}.zip`);return i}function Qe(e,t){let n=R(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(R(e,`.ok`))?De(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function $e(){let e={timestamp:new Date().toISOString(),platform:xe(),osType:Te(),osRelease:Se(),hostname:`[redacted]`,uptime:Ee(),freeMem:ye(),totalMem:we(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=oe(`sw_vers -productVersion 2>/dev/null`,w({encoding:`utf8`})).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const et=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function tt(e){let t=I(e);return et.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function nt(e,t){return ot(e,t).files}const rt=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function it(e,t=ie){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return rt.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=>R(n,e.entry)))}function at(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,-d.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>R(e,t))}catch{return[]}}function ot(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(tt),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=>!tt(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function st(e){let t=R(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,o,ee].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function ct(e){let t=R(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function lt(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#${De(`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 ut(e){let t=e.revealDocNames?e.content:lt(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:a}=i(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:a,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`);ut({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?We(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 dt(t){let{redact:r,outputPath:i,logger:a}=t,o=t.revealDocNames??!1,c=t.userLogsDir??R(q(),`.ok`,`logs`),l=t.projectDir?Qe(t.projectDir,a):null;H(L(i),{recursive:!0}),a?.info({projectSlug:l},`gathering diagnostic data`);let u=$e();u.desktop=t.desktop??null,u.language=t.language??null;let{files:d,excludedByProjectSlug:ee}=ot(l,c),{files:te}=t.projectDir?st(t.projectDir):{files:[]},{files:f}=t.projectDir?ct(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];a?.info({logFileCount:d.length,logFilesExcludedByProjectSlug:ee,lockFileCount:te.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:[...d,...p],prefix:`logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:te,prefix:`lockdir`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:s,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??I(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&ut({zipfile:v,name:`note.txt`,content:t.note,redact:r,revealDocNames:o,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${I(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(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/${I(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((t.bugReportLedgerFiles??[]).map(e=>`${s}/${I(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!tt(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.`]:[],ne=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.`],j=[`# 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}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${n.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.`]:ne].join(`
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$d as t,Bn as n,Cc as r,Ds as i,Eo as a,Jc as o,Mn as s,Rs as c,Yc as l,Zc as u,jn as d,xc as ee,zu as te}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{$n as f,Fo as p,Io as m,Kr as h,Lo as g,Qr as _,Si as v,Tt as y,Yn as b,ai as x,fr as S,ii as C,lo as w,m as T,oa as E,oi as D,xi as O,zn as k}from"./dist-uCKY80_9.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{Ct as ne,ot as j,st as M}from"./init-CkF5Pwyt.mjs";import{b as re,l as ie}from"./registry-probes-BNzSXcyt.mjs";import{c as N}from"./colors-r_owlCuY.mjs";import{t as P}from"./is-object-BGze3w87.mjs";import{n as ae}from"./constants-CXGN1QtU.mjs";import"./loader-Cl1695lT.mjs";import"./preview-CjRN7_qW.mjs";import{execSync as oe,spawnSync as F}from"node:child_process";import{basename as I,dirname as L,isAbsolute as se,join as R,relative as ce,resolve as z,sep as B}from"node:path";import{closeSync as le,cpSync as ue,createWriteStream as de,existsSync as V,lstatSync as fe,mkdirSync as H,mkdtempSync as pe,openSync as me,readFileSync as U,readSync as he,readdirSync as W,rmSync as G,rmdirSync as ge,statSync as _e,writeFileSync as K}from"node:fs";import{arch as ve,freemem as ye,homedir as q,hostname as be,platform as xe,release as Se,tmpdir as Ce,totalmem as we,type as Te,uptime as Ee}from"node:os";import"node:fs/promises";import{createHash as De}from"node:crypto";const Oe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function ke(e,t,n=f){if(e!==void 0&&!Oe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ae=null;function je(e){Ae=e}function Me(){return Ae??process.cwd()}const Ne=`Open Knowledge`;function Pe(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return j(t).join(M({...e,platformName:t}),n)}function Fe(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=j(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 Ie(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 Le(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return Ie(n)??[]}function Re(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return Ie(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const ze=8192;function Be(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 Ve(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const He=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ue(e){return e.replace(He,`$1"[REDACTED-DEVICE-ID]"`)}function We(e){return Ue(Ve(e))}const Ge=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ke(e){if(typeof e!=`string`)return null;let t=Ge.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 qe(e){let t=me(e,`r`);try{let e=Buffer.alloc(ze),n=0,r=!1;for(;n<ze;){let i=he(t,e,n,ze-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{le(t)}}function Je(e){try{let t=qe(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:Ke(a)}}catch{return{kind:`unreadable`}}}function Ye(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function Xe(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=R(e,t.name),r;try{r=_e(n).mtimeMs}catch{continue}if(r<i)continue;let c=Je(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Ye(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 R(q(),`.ok`,`bug-reports`)}function Ze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=R(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=R(n,`${r}-${e}.zip`);return i}function Qe(e,t){let n=R(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(R(e,`.ok`))?De(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function $e(){let e={timestamp:new Date().toISOString(),platform:xe(),osType:Te(),osRelease:Se(),hostname:`[redacted]`,uptime:Ee(),freeMem:ye(),totalMem:we(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=oe(`sw_vers -productVersion 2>/dev/null`,w({encoding:`utf8`})).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const et=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function tt(e){let t=I(e);return et.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function nt(e,t){return ot(e,t).files}const rt=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function it(e,t=ie){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return rt.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=>R(n,e.entry)))}function at(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,-d.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>R(e,t))}catch{return[]}}function ot(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(tt),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=>!tt(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function st(e){let t=R(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,o,ee].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function ct(e){let t=R(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function lt(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#${De(`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 ut(e){let t=e.revealDocNames?e.content:lt(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:a}=i(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:a,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`);ut({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?We(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 dt(t){let{redact:r,outputPath:i,logger:a}=t,o=t.revealDocNames??!1,c=t.userLogsDir??R(q(),`.ok`,`logs`),l=t.projectDir?Qe(t.projectDir,a):null;H(L(i),{recursive:!0}),a?.info({projectSlug:l},`gathering diagnostic data`);let u=$e();u.desktop=t.desktop??null,u.language=t.language??null;let{files:d,excludedByProjectSlug:ee}=ot(l,c),{files:te}=t.projectDir?st(t.projectDir):{files:[]},{files:f}=t.projectDir?ct(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];a?.info({logFileCount:d.length,logFilesExcludedByProjectSlug:ee,lockFileCount:te.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:[...d,...p],prefix:`logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:te,prefix:`lockdir`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:s,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??I(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&ut({zipfile:v,name:`note.txt`,content:t.note,redact:r,revealDocNames:o,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${I(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(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/${I(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((t.bugReportLedgerFiles??[]).map(e=>`${s}/${I(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!tt(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.`]:[],ne=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.`],j=[`# 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}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${n.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.`]:ne].join(`
2
2
  `);v.addBuffer(Buffer.from(j,`utf8`),`README.md`),v.end();let M=de(i);return v.outputStream.pipe(M),await new Promise((e,t)=>{M.on(`close`,e),M.on(`error`,t)}),a?.info({bundlePath:i,fileCount:g.length,redactionCount:w},`bundle written`),{zipPath:i,summary:{projectSlug:l,files:g,redactions:h,redactedLineCount:w,generatedAt:C.generatedAt}}}var ft=te(),pt=e(A(),1),X=e(N(),1);function mt(e){let t=g(`user`,e,e);return p({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function ht({home:e=q(),env:t=process.env}={}){let n=mt(e),{override:i,preferenceList:a}=m(t),{locale:o,source:s}=c({override:i,storedPreference:n,supportedLocales:u,preferenceList:a,autoDetectableLocales:r});return{preference:n,locale:o,source:s,systemLanguages:a}}function gt(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function _t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vt(e,t){if(typeof e==`string`)return gt(e,t.contentDir);if(Array.isArray(e))return e.map(e=>vt(e,t));if(!_t(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=vt(i,t);return n}function yt(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=vt(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import"./init-CkF5Pwyt.mjs";import"./registry-probes-BNzSXcyt.mjs";import"./src-CuAz4eVb.mjs";import"./start-BAXJOEI_.mjs";import{n as e}from"./loader-Cl1695lT.mjs";import"./preview-CjRN7_qW.mjs";import"./cli.mjs";import"./repair-mcp-configs-C84mr9tJ.mjs";export{e as loadConfig};
@@ -0,0 +1 @@
1
+ import{S as e,m as t,p as n,r}from"./start-BAXJOEI_.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
@@ -1,5 +1,5 @@
1
- import{Is as e,Ju as t,Po as n,Ud as r,_t as i,ua as a,zc as o,zs as s}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Fo as c,Jo as l,Lo as u,bi as d,ci as f,ii as p,k as m,qr as h}from"./dist-DbCJL2ix.mjs";import{Ct as g,L as _,Tt as v,X as y,b,ut as x,wt as S,y as C,z as w}from"./init-DPzjXJk6.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-BvjEMgkO.mjs";import{n as ne}from"./constants--RMFEFDe.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){l(`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`}}}function be(e,t,n,r,i){let a=y[e];try{let o=A(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),ye(o.kind)}catch(i){return l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function xe(e,t,n){if(y[e].scope!==`global`)return q();if(n===`absent`)return be(e,``,t.home,void 0,t.env);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 Se(e,t,n){let i=r[e];if(i===null)return q();let a=re(t.cwd,i);if(n===`absent`)return be(e,t.cwd,t.home,a,t.env);let o=C(y[e],t.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 Ce(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 we(e,t,n){if(n===`absent`){let n=_(y[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=w(y[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 Te(e){return n=>{if(n.pathId===void 0)return Y();let r=t(n.pathId);if(r===null||r.kind===`central-skill-store`)return Y();switch(r.kind){case`editor-user-config`:return xe(r.editor,e,n.desired);case`editor-project-config`:return Se(r.editor,e,n.desired);case`editor-project-skill-root`:return we(r.editor,e,n.desired);case`editor-user-skill-root`:return Ce(r.editor,e,n.desired)}}}function Ee(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function De(e){if(e===`server`)return e;throw new S(`--only must be 'server'`)}function Oe(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 ke(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 Ae(e){if(e===`off`)return`off`;if(!o.test(e))throw new S(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function je(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Me(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Ne(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||je(e.host))&&e.isTTY}function Pe(e,t){let n;try{n=new URL(t)}catch{throw new S(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new S(`${e} must be an http(s) origin (got: ${t})`);return t}function Fe(e){return Pe(`--external-url`,e)}function Ie(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 ${m}* 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 Le(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 ${m}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function $(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 Re(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:m,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-D0uRdq0j.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?d(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=m(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){S.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){S.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!C){if(!i&&!h(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-BFE8DeRv.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&&S.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-CjZgWdLx.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!C&&!o(P)&&(s(P,{recursive:!0}),S.info({contentDir:P},`Created content directory`));let ne=F(),I=f(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&S.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:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:x(),...C?{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,t)=>N(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:O??n,home:ae(),env:process.env};return{probe:te(e),execute:Te(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 $(M===void 0?n:Le(n,M),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}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 ze(e,t,n=()=>c({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Be(e){if(e===`browser`||e===`app`)return e;throw new S(`--mode must be 'browser' or 'app'`)}function Ve(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function He(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 Ue(t,r){let o=ze(t,r.singleFile),c=Ve(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=Ie(m);let h;try{h=e(process.env)}catch(e){throw e instanceof i&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=a(o,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=r.bind!==void 0&&r.bind.length>0?r.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=s(g),S=v??(_||b===void 0?[...x.bind]:[b]);Me({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=r.externalUrl,E=s(a(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
- `)))}let D=r.port===void 0?void 0:Number(r.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,ee=D??O??o.server?.port,k=ke({explicitDir:r.reactShellDistDir,only:r.only,findBundledDir:Oe}),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 Re({config:o,cwd:m,host:C,port:ee,bind:w,...r.serveContentAssets===void 0?{}:{serveContentAssets:r.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:n(r.idleShutdown??E.idleShutdown),serverRuntime:E,...r.singleFile?{singleFile:r.singleFile}:{},...r.projectDir?{projectDir:r.projectDir}:{},...r.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}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-D0uRdq0j.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||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),Ke(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await We({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]=Ge(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=qe(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]=He(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(Ne({openBrowser:r.openBrowser!==!1&&E.openBrowser,explicitOn:r.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:r.singleFile!==void 0,only:r.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-ryZAJZiH.mjs`);e(F)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function We(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 Ge(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 Ke(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function qe(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 Je(e){return new g(`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)`,De).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)`,Ae).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Be).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 v(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new v(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new v(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).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).`,Fe).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'
1
+ import{Is as e,Ju as t,Po as n,Ud as r,_t as i,ua as a,zc as o,zs as s}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Fo as c,Jo as l,Lo as u,bi as d,ci as f,ii as p,k as m,qr as h}from"./dist-uCKY80_9.mjs";import{Ct as g,L as _,Tt as v,X as y,b,ut as x,wt as S,y as C,z as w}from"./init-CkF5Pwyt.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-BNzSXcyt.mjs";import{n as ne}from"./constants-CXGN1QtU.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){l(`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`}}}function be(e,t,n,r,i){let a=y[e];try{let o=A(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),ye(o.kind)}catch(i){return l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function xe(e,t,n){if(y[e].scope!==`global`)return q();if(n===`absent`)return be(e,``,t.home,void 0,t.env);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 Se(e,t,n){let i=r[e];if(i===null)return q();let a=re(t.cwd,i);if(n===`absent`)return be(e,t.cwd,t.home,a,t.env);let o=C(y[e],t.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 Ce(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 we(e,t,n){if(n===`absent`){let n=_(y[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=w(y[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 Te(e){return n=>{if(n.pathId===void 0)return Y();let r=t(n.pathId);if(r===null||r.kind===`central-skill-store`)return Y();switch(r.kind){case`editor-user-config`:return xe(r.editor,e,n.desired);case`editor-project-config`:return Se(r.editor,e,n.desired);case`editor-project-skill-root`:return we(r.editor,e,n.desired);case`editor-user-skill-root`:return Ce(r.editor,e,n.desired)}}}function Ee(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function De(e){if(e===`server`)return e;throw new S(`--only must be 'server'`)}function Oe(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 ke(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 Ae(e){if(e===`off`)return`off`;if(!o.test(e))throw new S(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function je(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Me(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Ne(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||je(e.host))&&e.isTTY}function Pe(e,t){let n;try{n=new URL(t)}catch{throw new S(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new S(`${e} must be an http(s) origin (got: ${t})`);return t}function Fe(e){return Pe(`--external-url`,e)}function Ie(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 ${m}* 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 Le(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 ${m}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function $(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 Re(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:m,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-BUEFqEdv.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?d(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=m(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){S.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){S.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!C){if(!i&&!h(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-C84mr9tJ.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&&S.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-D7hkCnL6.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!C&&!o(P)&&(s(P,{recursive:!0}),S.info({contentDir:P},`Created content directory`));let ne=F(),I=f(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&S.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:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:x(),...C?{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,t)=>N(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:O??n,home:ae(),env:process.env};return{probe:te(e),execute:Te(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 $(M===void 0?n:Le(n,M),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}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 ze(e,t,n=()=>c({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Be(e){if(e===`browser`||e===`app`)return e;throw new S(`--mode must be 'browser' or 'app'`)}function Ve(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function He(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 Ue(t,r){let o=ze(t,r.singleFile),c=Ve(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=Ie(m);let h;try{h=e(process.env)}catch(e){throw e instanceof i&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=a(o,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=r.bind!==void 0&&r.bind.length>0?r.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=s(g),S=v??(_||b===void 0?[...x.bind]:[b]);Me({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=r.externalUrl,E=s(a(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
+ `)))}let D=r.port===void 0?void 0:Number(r.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,ee=D??O??o.server?.port,k=ke({explicitDir:r.reactShellDistDir,only:r.only,findBundledDir:Oe}),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 Re({config:o,cwd:m,host:C,port:ee,bind:w,...r.serveContentAssets===void 0?{}:{serveContentAssets:r.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:n(r.idleShutdown??E.idleShutdown),serverRuntime:E,...r.singleFile?{singleFile:r.singleFile}:{},...r.projectDir?{projectDir:r.projectDir}:{},...r.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}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-BUEFqEdv.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||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),Ke(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await We({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]=Ge(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=qe(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]=He(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(Ne({openBrowser:r.openBrowser!==!1&&E.openBrowser,explicitOn:r.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:r.singleFile!==void 0,only:r.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-CPOeQw4d.mjs`);e(F)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function We(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 Ge(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 Ke(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function qe(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 Je(e){return new g(`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)`,De).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)`,Ae).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Be).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 v(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new v(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new v(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).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).`,Fe).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 Ue(n,t)})}export{qe as C,de as D,H as E,Je as S,$ as T,Ve as _,Ge as a,Ne as b,Q as c,Ae as d,De as f,ze as g,We as h,Ie as i,Ke as l,Ee as m,X as n,He as o,Oe as p,Re as r,je as s,Z as t,Fe as u,ke as v,Le as w,Me as x,Ue as y};