@inkeep/open-knowledge 0.86.12-beta.0 → 0.86.13-beta.0

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 (95) hide show
  1. package/dist/cli.mjs +68 -68
  2. package/dist/constants-owtVyfa1.mjs +1 -0
  3. package/dist/dist-CerHybyM.mjs +2212 -0
  4. package/dist/dist-fzYMjYEW.mjs +1 -0
  5. package/dist/index.mjs +211 -205
  6. package/dist/init-Br75Da84.mjs +1 -0
  7. package/dist/{init-Cb5cGxKf.mjs → init-PHFeZ_1F.mjs} +19 -19
  8. package/dist/{launch-json-removal-1jdDi23_.mjs → launch-json-removal-GsI1u0J-.mjs} +1 -1
  9. package/dist/loader-CCiGCpiY.mjs +1 -0
  10. package/dist/{loader-Cnmmedih.mjs → loader-CyiDGUuQ.mjs} +1 -1
  11. package/dist/{md-manager-BGnqyqi1-C80pMLi7.mjs → md-manager-BGnqyqi1-B6Vk34FK.mjs} +171 -165
  12. package/dist/{open-browser-DdYx0HOD.mjs → open-browser-BL65djdM.mjs} +1 -1
  13. package/dist/parse-worker.mjs +1 -1
  14. package/dist/{preview-C2nZOEOF.mjs → preview-4TMET2jL.mjs} +1 -1
  15. package/dist/preview-DG2fmjZi.mjs +1 -0
  16. package/dist/public/assets/{AccountSection-B5Akd_lT.js → AccountSection-Df6P_xbB.js} +1 -1
  17. package/dist/public/assets/{ActivityModeContent-D_PWtsd2.js → ActivityModeContent-Lmykn82f.js} +1 -1
  18. package/dist/public/assets/{AddPropertiesButton-CPmEiINR.js → AddPropertiesButton-DkoGq7Ha.js} +1 -1
  19. package/dist/public/assets/{AgentDiffPane-GH9VSfje.js → AgentDiffPane-jhAu0qwX.js} +1 -1
  20. package/dist/public/assets/{AttachmentsSection-De3luzw5.js → AttachmentsSection-B-b_hc4S.js} +1 -1
  21. package/dist/public/assets/{CodeMirrorPropInput-541INHEl.js → CodeMirrorPropInput-B1EXz6Fn.js} +42 -36
  22. package/dist/public/assets/{ContentRulesSection-DvspCgkN.js → ContentRulesSection-Bpt2GiY6.js} +1 -1
  23. package/dist/public/assets/{DocumentContext-BhDKYP3I.js → DocumentContext-CmexYbvB.js} +1 -1
  24. package/dist/public/assets/{EditorModeToggle-DcLCuSh1.js → EditorModeToggle-BJXNVGsx.js} +1 -1
  25. package/dist/public/assets/{ExcalidrawDocEditor-6bsvmnp4.js → ExcalidrawDocEditor-NW4UaLCG.js} +1 -1
  26. package/dist/public/assets/FeedbackForm-kMQ0wWlm.js +1 -0
  27. package/dist/public/assets/{ImportSkillDialog-D4baBg1I.js → ImportSkillDialog-CNzGNkY_.js} +1 -1
  28. package/dist/public/assets/{LinkPreviewsSection-BYLSlOtr.js → LinkPreviewsSection-Lj7YM2bN.js} +1 -1
  29. package/dist/public/assets/{LintConfigEditor-C0bykZjj.js → LintConfigEditor-DfcK1PUv.js} +1 -1
  30. package/dist/public/assets/{LintingSection-Dkw3Gy-L.js → LintingSection-PtbcOqZ-.js} +1 -1
  31. package/dist/public/assets/{ManagedArtifactProperties-DkLXqbca.js → ManagedArtifactProperties-DRzcKo1o.js} +1 -1
  32. package/dist/public/assets/ManagedArtifactProperties-IwKy6gB8.js +1 -0
  33. package/dist/public/assets/{MermaidDocEditor-DdKA5_sd.js → MermaidDocEditor-DWccj1FI.js} +1 -1
  34. package/dist/public/assets/{NetworkAccessSection-C9S4FV2h.js → NetworkAccessSection-DU5ByI9J.js} +1 -1
  35. package/dist/public/assets/{PropertyDisplayRow-BpyUE4rQ.js → PropertyDisplayRow-BXPmfsIa.js} +1 -1
  36. package/dist/public/assets/{PublishToGitHubDialog-B5IUZX4A.js → PublishToGitHubDialog-DEvK8Knm.js} +1 -1
  37. package/dist/public/assets/{SchemaConfigEditor-DjoiXTi6.js → SchemaConfigEditor-D88cIFbD.js} +1 -1
  38. package/dist/public/assets/{SearchSection-Z13NU7QH.js → SearchSection-DAJ1_dla.js} +1 -1
  39. package/dist/public/assets/{SessionsHost-CPF7ISZW.js → SessionsHost-CXHMOx1g.js} +2 -2
  40. package/dist/public/assets/{SettingsDialogBody-6x3yGlOk.js → SettingsDialogBody-CxgXkZER.js} +2 -2
  41. package/dist/public/assets/{ShareReceiveMissDialog-fQ2NCsxj.js → ShareReceiveMissDialog-D_ghV4c2.js} +1 -1
  42. package/dist/public/assets/{SkillToolbarControls-V_rtwpQB.js → SkillToolbarControls-miX28Wwt.js} +1 -1
  43. package/dist/public/assets/{SourceEditor-pAuA5Jbq.js → SourceEditor-5ixhr2uV.js} +1 -1
  44. package/dist/public/assets/{SyncSection-DSdmvKYA.js → SyncSection-CSpqxjDa.js} +1 -1
  45. package/dist/public/assets/{SyncStatusBadge-CmqR-dvk.js → SyncStatusBadge-eHCZhha8.js} +1 -1
  46. package/dist/public/assets/{TerminalSection-umX9YQiY.js → TerminalSection-b99TgIY6.js} +1 -1
  47. package/dist/public/assets/{TerminalWindowApp-BbSqFpI4.js → TerminalWindowApp-DNS9sol4.js} +1 -1
  48. package/dist/public/assets/{TextDocEditor-DbiJOi-9.js → TextDocEditor-rQd5hS10.js} +1 -1
  49. package/dist/public/assets/{ThreadView-DY-StT20.js → ThreadView-Sfxq-LPG.js} +1 -1
  50. package/dist/public/assets/{TimelineDiffPane-Dqif4LiO.js → TimelineDiffPane-DMWDGXU4.js} +1 -1
  51. package/dist/public/assets/{client-version-Bwkz2KKL.js → client-version-Bi7XZOS1.js} +1 -1
  52. package/dist/public/assets/{comment-chips-D0yLVwnq.js → comment-chips-git37WLc.js} +1 -1
  53. package/dist/public/assets/{config-provider-CKxggsEF.js → config-provider-DbZahXcw.js} +1 -1
  54. package/dist/public/assets/{doc-undo-manager-DDBrqZ8S.js → doc-undo-manager-C_N_q0_G.js} +1 -1
  55. package/dist/public/assets/globals-BddzEyvs.css +1 -0
  56. package/dist/public/assets/{index-KEo7R3RD.js → index-RazGf6Uc.js} +8 -8
  57. package/dist/public/assets/{lint-plugins-srBOr3VN.js → lint-plugins-BtOPh8Gl.js} +1 -1
  58. package/dist/public/assets/{pending-receive-nav-store-DSl8bhNh.js → pending-receive-nav-store-DeFr5cXd.js} +1 -1
  59. package/dist/public/assets/{preferred-session-events-CYm28hMK.js → preferred-session-events-CjyOKug5.js} +1 -1
  60. package/dist/public/assets/{progress-DFQn_hb4.js → progress-0qyXuaHT.js} +1 -1
  61. package/dist/public/assets/{selection-context-BksGkV1v.js → selection-context-CkSj29kx.js} +1 -1
  62. package/dist/public/assets/{src-msWh43qH.js → src-BsHJaK2N.js} +1 -1
  63. package/dist/public/assets/{telemetry-impl-CKc5wvGR.js → telemetry-impl-B4iNzQAQ.js} +1 -1
  64. package/dist/public/assets/{telemetry-startup-CZKMf_5M.js → telemetry-startup-G0pfyN_t.js} +1 -1
  65. package/dist/public/assets/{typing-burst-detector-DQ2h6sm2.js → typing-burst-detector-CpXz0zjV.js} +1 -1
  66. package/dist/public/assets/{uninstall-BvM8iYtm.js → uninstall-CnEEKVFb.js} +1 -1
  67. package/dist/public/assets/{use-activity-panel-682w4exD.js → use-activity-panel-j8bjl0FL.js} +1 -1
  68. package/dist/public/assets/{use-open-skill-BZu9ClPN.js → use-open-skill-DnaefJkm.js} +1 -1
  69. package/dist/public/assets/{use-terminal-enabled-D-gWAxuJ.js → use-terminal-enabled-DO31Ypkn.js} +1 -1
  70. package/dist/public/assets/{use-timeline-entry-diff-CKLWMEPL.js → use-timeline-entry-diff-DWum09BQ.js} +1 -1
  71. package/dist/public/index.html +20 -20
  72. package/dist/public/uninstall.html +3 -3
  73. package/dist/registry-probes-C7uxu4tM.mjs +17 -0
  74. package/dist/{removal-file-path-DXIJFyxw.mjs → removal-file-path-DZDrG3zb.mjs} +1 -1
  75. package/dist/{repair-launch-json-DCNJiOIo.mjs → repair-launch-json-S7Ro9IS4.mjs} +1 -1
  76. package/dist/{repair-mcp-configs-BISI44CH.mjs → repair-mcp-configs-BN4wPLWB.mjs} +1 -1
  77. package/dist/src-TUmzQrPO.mjs +16 -0
  78. package/dist/src-oGxozmX7.mjs +1 -0
  79. package/dist/start-BdUyii8P.mjs +1 -0
  80. package/dist/{start-D_u0K-Db.mjs → start-DpDSIaR1.mjs} +3 -3
  81. package/package.json +4 -4
  82. package/dist/constants-CvznkgU4.mjs +0 -1
  83. package/dist/dist-CqyT6Kac.mjs +0 -1
  84. package/dist/dist-qew1xYqg.mjs +0 -2212
  85. package/dist/init-CK3DgQiP.mjs +0 -1
  86. package/dist/loader-BwaFWYgH.mjs +0 -1
  87. package/dist/preview-DpN2RKRs.mjs +0 -1
  88. package/dist/public/assets/FeedbackForm-DR0XDvRa.js +0 -1
  89. package/dist/public/assets/ManagedArtifactProperties-DatL8HKW.js +0 -1
  90. package/dist/public/assets/globals-BOsVqbg9.css +0 -1
  91. package/dist/registry-probes-DXYESJWL.mjs +0 -17
  92. package/dist/src-CXbzpNvw.mjs +0 -1
  93. package/dist/src-e35-IXbd.mjs +0 -16
  94. package/dist/start-DnH8T2kW.mjs +0 -1
  95. /package/dist/public/assets/{globals-JnwKCLiW.js → globals-BfTv_Hnc.js} +0 -0
@@ -0,0 +1,16 @@
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{Cf as t,Ef as n,Fl as r,G as i,Il as a,Jc as o,Ju as s,Of as c,Tf as l,U as u,W as d,Wc as f,Yc as p,ba as m,bf as h,hf as g,l as ee,u as te,ya as _}from"./md-manager-BGnqyqi1-B6Vk34FK.mjs";import{$n as v,Ao as y,Ci as b,Ea as x,Er as S,Ri as C,Si as w,Ts as T,as as E,ci as D,hi as O,is as ne,jt as k,lr as re,m as A,ns as j,os as M,pr as ie,xi as N,zi as ae}from"./dist-CerHybyM.mjs";import{t as oe}from"./yazl-BBz29IQN.mjs";import{Ct as P,ot as F,st as se}from"./init-PHFeZ_1F.mjs";import{l as ce,w as le}from"./registry-probes-C7uxu4tM.mjs";import{c as ue}from"./colors-r_owlCuY.mjs";import{t as de}from"./is-object-BGze3w87.mjs";import{n as fe}from"./constants-owtVyfa1.mjs";import"./loader-CyiDGUuQ.mjs";import"./preview-4TMET2jL.mjs";import{execFile as pe,execSync as me,spawnSync as he}from"node:child_process";import{basename as I,dirname as L,isAbsolute as ge,join as R,relative as _e,resolve as z,sep as B,win32 as ve}from"node:path";import{closeSync as ye,cpSync as be,createWriteStream as xe,existsSync as V,lstatSync as Se,mkdirSync as H,mkdtempSync as Ce,openSync as we,readFileSync as U,readSync as Te,readdirSync as W,readlinkSync as Ee,realpathSync as De,rmSync as G,rmdirSync as Oe,statSync as ke,writeFileSync as K}from"node:fs";import{arch as Ae,freemem as je,homedir as q,hostname as Me,platform as Ne,release as Pe,tmpdir as Fe,totalmem as Ie,type as Le,uptime as Re}from"node:os";import{readFile as ze,readdir as Be,stat as Ve}from"node:fs/promises";import{createHash as He}from"node:crypto";function Ue(e,t){let n=t.map(e=>[T(e),e]);for(let t of e){let e=T(t);if(e===null)continue;let r=n.find(([t])=>t===e);if(r!==void 0)return r[1]}}function We(e){let{override:t,storedPreference:n,preferenceList:r,supportedLocales:i}=e,a=e.autoDetectableLocales??i;if(t!==void 0){let e=Ue([t],i);if(e!==void 0)return{locale:e,source:`override`}}if(n!==void 0&&n!==`system`&&i.includes(n))return{locale:n,source:`explicit`};let o=Ue(r,a);return o===void 0?{locale:`en`,source:`fallback`}:{locale:o,source:`system`}}function Ge(e,t=Date.now()){let n=Date.parse(e);if(!Number.isFinite(n))return`unknown`;let r=Math.floor(Math.max(0,t-n)/1e3);if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}const Ke=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`audit`,`deinit`,`auth`]);function qe(e,t,n=ie){if(e!==void 0&&!Ke.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Je=null;function Ye(e){Je=e}function Xe(){return Je??process.cwd()}const Ze=`Open Knowledge`;function Qe(e={}){let n=e.platformName??process.platform,r=e.productName??t().productName;return F(n).join(se({...e,platformName:n}),r)}function $e(e={}){let n=e.platformName??process.platform,r=e.home??q(),i=e.env??process.env,a=F(n),o;return o=n===`win32`?i.LOCALAPPDATA||a.join(r,`AppData`,`Local`):n===`darwin`?a.join(r,`Library`,`Caches`):i.XDG_CACHE_HOME||a.join(r,`.cache`),a.join(o,`${t().packageName.replaceAll(`/`,``)}-updater`)}function et(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 tt(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return et(n)??[]}function nt(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return et(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const rt=8192;function it(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 at(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const ot=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function st(e){return e.replace(ot,`$1"[REDACTED-DEVICE-ID]"`)}function ct(e){return st(at(e))}const lt=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function ut(e){if(typeof e!=`string`)return null;let t=lt.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 dt(e){let t=we(e,`r`);try{let e=Buffer.alloc(rt),n=0,r=!1;for(;n<rt;){let i=Te(t,e,n,rt-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{ye(t)}}function ft(e){try{let t=dt(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:ut(a)}}catch{return{kind:`unreadable`}}}function pt(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function mt(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=ke(n).mtimeMs}catch{continue}if(r<i)continue;let c=ft(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!pt(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`}}const ht=`state/os-termination-evidence.json`,gt=6048e5,_t=/openknowledge/i,vt=Object.values(h).map(n);function yt(e={}){return(t,n)=>new Promise(r=>{try{pe(t,n,{encoding:`utf8`,timeout:e.timeoutMs??15e3,maxBuffer:e.maxBuffer??16777216,windowsHide:!0},(e,t,n)=>{r({...bt(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function bt(e){return e===null?{status:0}:typeof e.code==`string`?{status:null,errorCode:e.code}:typeof e.code==`number`?{status:e.code}:e.killed===!0?{status:null,errorCode:`ETIMEDOUT`}:e.signal?{status:null,signal:e.signal}:{status:null}}function xt(e){if(e.errorCode!==void 0)return e.errorCode;if(e.signal!==void 0)return`signal ${e.signal}`;let t=(e.stderr.trim().split(`
2
+ `)[0]??``).replace(/\S*\/journal\/\S*/g,`<journal path>`).replace(/\b[0-9a-f]{32}\b/gi,`<id>`);return`exit ${e.status}${t===``?``:`: ${t}`}`}function J(e,t,n){return{schemaVersion:1,platform:e,source:t,outcome:`none-in-window`,readFrom:n,windowDays:7,foreignIgnored:0,unparseable:0,droppedOverCap:0,events:[]}}function St(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function Ct(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function wt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Tt(e,t){let n=t.indexOf(`
3
+ `);if(n===-1)return null;let r,i;try{r=wt(JSON.parse(t.slice(0,n))),i=wt(JSON.parse(t.slice(n+1)))}catch{return null}if(r===null||i===null||!Array.isArray(i.processes))return null;let a=[];for(let e of i.processes){let t=wt(e);t===null||typeof t.name!=`string`||!pt(t.name)||a.push({name:t.name,pid:Y(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:Y(t.rpages),lifetimeMaxPages:Y(t.lifetimeMax)})}let o=ut(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:Y(wt(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?pt(i.largestProcess):null,ownedProcesses:a}}const Et=/^JetsamEvent-.*\.ips$/;function Dt(e,t,n,r){let i=e.flatMap(({file:e,mtimeMs:n})=>n!==null&&n>=t?[{file:e,mtimeMs:n}]:[]);return i.sort((e,t)=>r===`newest-first`?t.mtimeMs-e.mtimeMs:e.mtimeMs-t.mtimeMs),{files:i.slice(0,n).map(({file:e})=>e),statFailed:e.filter(({mtimeMs:e})=>e===null).length,droppedOverCap:Math.max(0,i.length-n)}}async function Ot(e,t){let n=J(`darwin`,`macos-jetsam`,[R(e,`JetsamEvent-*.ips`)]),r;try{r=await Be(e)}catch(e){return St(n,e.code??`unknown`)}let i=Dt(await Promise.all(r.filter(e=>Et.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await Ve(R(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-gt,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=Tt(t,await ze(R(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return Ct(n)}const kt=[`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Out of memory|oom-kill|Killed process|Killed /|memory pressure`,`_TRANSPORT=kernel`,`+`,`_SYSTEMD_UNIT=systemd-oomd.service`],At=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],jt=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,Mt=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,Nt=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function Pt(e,t){let n=new Set,r;try{r=await Be(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!Nt.test(a))continue;let r=R(e,a);try{if(t.getTime()-(await Ve(r)).mtimeMs>gt)continue;for(let e of(await ze(r,`utf8`)).split(`
4
+ `)){if(!e.includes(`"event":"desktop.boot"`))continue;let t=/"pid":(\d+)/.exec(e)?.[1];t!==void 0&&n.add(Number(t))}}catch{i=!0}}return{pids:n,unreadable:i}}function Ft(e,t){if(e===`systemd-oomd`){let e=/^Killed (\S+)/.exec(t);if(e===null)return null;let n=e[1]?.split(`/`).pop()??``;return{origin:`systemd-oomd`,action:`oomd-kill`,pid:null,processName:null,unit:_t.test(n)?n:null,trigger:/swap used/.test(t)?`swap`:/memory pressure/.test(t)?`memory-pressure`:null}}if(e!==`kernel`)return null;let n=/Killed process (\d+) \(([^)]+)\)/.exec(t);if(n!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(n[1]),processName:n[2]??null,unit:null,trigger:null};let r=/task=([^,]+),pid=(\d+)/.exec(t);if(r!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(r[2]),processName:r[1]??null,unit:null,trigger:null};let i=/^(\S+) invoked oom-killer/.exec(t);return i===null?null:{origin:`kernel`,action:`oom-invoked`,pid:null,processName:i[1]??null,unit:null,trigger:null}}function It(e){let t=[],n=0,r=0;for(let i of e.split(`
5
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=jt.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!_t.test(s)){n+=1;continue}let c=Ft(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function Lt(e){let t=[],n=0,r=0;for(let i of e.split(`
6
+ `)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=jt.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=Mt.exec(o);if(s===null){n+=1;continue}t.push({at:a,pid:Number(s[1]),detail:(s[2]??``).slice(0,200)})}return{lines:t,foreignIgnored:n,unparseable:r}}async function Rt(e,t,n){let r=Lt(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await Pt(t,n),a=[],o=0;for(let e of r.lines){if(!i.pids.has(e.pid)){o+=1;continue}a.push({kind:`journal`,at:e.at,origin:`chromium`,action:`display-connection-lost`,pid:e.pid,processName:null,unit:null,trigger:/Wayland/.test(e.detail)?`wayland`:`x11`,detail:e.detail})}let s=i.pids.size>0&&!i.unreadable;if(o>0&&!s){let e=i.unreadable?`desktop logs unreadable`:`no desktop.boot pid in desktop logs`;return{events:a,foreignIgnored:r.foreignIgnored,unparseable:r.unparseable,unattributed:`${o} Chromium display line(s) not attributed, ${e}`}}return{events:a,foreignIgnored:r.foreignIgnored+o,unparseable:r.unparseable,unattributed:null}}function zt(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function Bt(e,t,n){let r=J(`linux`,`linux-journal`,[`journalctl ${kt.join(` `)}`,`journalctl ${At.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...kt]),e(`journalctl`,[...At])]),o=[];if(zt(i)){let e=It(i.stdout);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,/not seeing messages from other users/i.test(`${i.stdout}\n${i.stderr}`)&&(r.restrictedToCurrentUser=!0)}else o.push(`system journal: ${xt(i)}`);if(zt(a)){let e=await Rt(a.stdout,n,t);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,e.unattributed!==null&&o.push(`user journal: ${e.unattributed}`)}else o.push(`user journal: ${xt(a)}`);return o.length===2?St(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:Ct(r)}const Vt={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},Ht={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function Ut(e){return e===`System`?Vt:Ht}function Wt(e){let t=`System[(${Object.keys(Ut(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${gt}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${vt.map(e=>`Data='${e}'`).join(` or `)}]]`}function Gt(e){return[`qe`,e,`/q:${Wt(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function Kt(e){return ve.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function qt(e){return e.replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}function Jt(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function Yt(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>qt(e[1]??``).trim())}function Xt(e,t){let n=Ut(e),r=[],i=0,a=0;for(let o of t.match(/<Event[\s>][\s\S]*?<\/Event>/g)??[]){let t=/<Provider\s+Name=['"]([^'"]+)['"]/.exec(o)?.[1],s=Number(/<EventID[^>]*>(\d+)<\/EventID>/.exec(o)?.[1]),c=/<TimeCreated\s+SystemTime=['"]([^'"]+)['"]/.exec(o)?.[1];if(t===void 0||!Number.isInteger(s)||c===void 0){a+=1;continue}if(n[s]!==t){i+=1;continue}let l=Yt(o,`Data`),u=Yt(o,`Name`),d=[...l,...u].some(e=>_t.test(e));if(e===`Application`&&!d){i+=1;continue}r.push({kind:`windows-event`,at:c,log:e,provider:t,eventId:s,mentionsOpenKnowledge:d,data:e===`Application`?l.filter(e=>e!==``&&!Jt(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function Zt(e,t){let n=Kt(t),r=[`System`,`Application`],i=J(`win32`,`windows-event-log`,r.map(e=>`${n} ${Gt(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,Gt(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${xt(t)}`);continue}let n=Xt(e,t.stdout);i.droppedOverCap+=Math.max(0,n.events.length-50),i.events.push(...n.events.slice(0,50)),i.foreignIgnored+=n.foreignIgnored,i.unparseable+=n.unparseable}return o.length===r.length?St(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:Ct(i)}async function Qt(e={}){let t=e.platform??process.platform,n=e.runCommand??yt(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return Ot(e.macosReportsDir??`/Library/Logs/DiagnosticReports`,r);case`linux`:return Bt(n,r,e.desktopLogsDir??R(j(),`logs`));case`win32`:return Zt(n,e.systemRoot??process.env.SystemRoot);default:return{...J(t,null,[]),outcome:`unsupported`}}}const $t={schemaVersion:1,outcome:`not-collected`};function en(e){return`${JSON.stringify(e??$t,null,2)}\n`}const tn={"macos-jetsam":`macOS low-memory reports`,"linux-journal":`system and user journals`,"windows-event-log":`Windows event logs`};function nn(e){let t=[`${e.windowDays}d`,`${e.events.length} kept`,`${e.foreignIgnored} other-process record(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&t.push(`${e.droppedOverCap} older dropped over cap`);let n=e.source?` from ${tn[e.source]}`:``,r=e.unavailableReason?`, ${e.unavailableReason}`:``;return`${e.outcome}${n}${r} (${t.join(`; `)})`}function rn(){return R(j(),`bug-reports`)}function an(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=rn(),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 on(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function sn(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`))?He(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function cn(){let e={timestamp:new Date().toISOString(),platform:Ne(),osType:Le(),osRelease:Pe(),hostname:`[redacted]`,uptime:Re(),freeMem:je(),totalMem:Ie(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=me(`sw_vers -productVersion 2>/dev/null`,y({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 ln=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function un(e){let t=I(e);return ln.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function dn(e,t){return hn(e,t).files}const fn=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function pn(e,t=ce){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return fn.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 mn(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,-ee.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 hn(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(un),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=>!un(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function gn(e){let t=R(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,o,f].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function _n(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 vn(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#${He(`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 yn(e){let t=e.revealDocNames?e.content:vn(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=m(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function X(e){for(let t of e.files)try{let n=U(t,`utf8`);yn({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?ct(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 bn(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??R(j(),`logs`),s=t.projectDir?sn(t.projectDir,i):null;H(L(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=cn();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=hn(s,o),{files:d}=t.projectDir?gn(t.projectDir):{files:[]},{files:f}=t.projectDir?_n(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:ee}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new ee;X({zipfile:v,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:te,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i});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);let r=on(e,n);r!==null&&h.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&yn({zipfile:v,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,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)`:it(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`),yn({zipfile:v,name:ht,content:en(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:g,redactions:h});let S=JSON.stringify(c,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:s,files:g,redactions:h,sysinfo:c};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=>`${te}/${I(e)}`)),O=g.filter(e=>D.has(e)),ne=s?g.filter(e=>e.startsWith(`logs/`)&&!un(e)&&!T.has(e)):[],k=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.`]:[],re=k.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...k]:[`Redaction was disabled for this bundle; file contents are unmodified.`],A=[`# Bug Report Bundle`,``,`Generated: ${C.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${C.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...ne.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:`,...ne.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}`),``]:[],...(t.osTerminationEvidence?.events.length??0)>0?[`Termination records: read from the operating system's own logs, covering`,`the last 7 days, to explain an exit the app could not record itself. On`,`macOS: the memory-pressure (jetsam) reports`,`that list processes of this app, with each one's memory use and whether`,`it was killed. On Linux: kernel and systemd-oomd out-of-memory kills of`,`this app, as structured fields with the machine name, cgroup paths and`,`user id left out, plus display-connection errors this app's desktop`,`process wrote to the user's own journal, with Chromium's message cut to`,`200 characters. On Windows: crash and hang records for this app with`,`file paths left out, plus the time of every shutdown, restart, power`,`loss and low-memory warning on the machine, whatever caused it:`,`- ${ht}`,``]:[],...O.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...O.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${_.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.`,...k,``,`This bundle is safe to attach to a GitHub issue.`]:re].join(`
7
+ `);v.addBuffer(Buffer.from(A,`utf8`),`README.md`),v.end();let M=xe(r);return v.outputStream.pipe(M),await new Promise((e,t)=>{M.on(`close`,e),M.on(`error`,t)}),i?.info({bundlePath:r,fileCount:g.length,redactionCount:w},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:g,redactions:h,redactedLineCount:w,generatedAt:C.generatedAt}}}var xn=s(),Sn=e(oe(),1),Z=e(ue(),1);function Cn(e){let t=M(`user`,e,e);return ne({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function wn({home:e=q(),env:t=process.env}={}){let n=Cn(e),{override:i,preferenceList:o}=E(t),{locale:s,source:c}=We({override:i,storedPreference:n,supportedLocales:a,preferenceList:o,autoDetectableLocales:r});return{preference:n,locale:s,source:c,systemLanguages:o}}function Tn(e){let t=new Set([e]);try{t.add(De.native(e))}catch{return[e].filter(e=>e.length>0)}return[...t].filter(e=>e.length>0).sort((e,t)=>t.length-e.length)}function En(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function Dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function On(e,t){if(typeof e==`string`)return En(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>On(e,t));if(!Dn(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=On(i,t);return n}function kn(e,t){let n=U(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
8
+ `),i=n.split(`
9
+ `),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=On(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
10
+ `)}\n`:a.join(`
11
+ `);K(e,o)}function An(e,t){let n=U(e,`utf-8`);if(n.trim().length!==0)try{let r=On(JSON.parse(n),t),i=n.endsWith(`
12
+ `)?`
13
+ `:``;K(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=En(n,t.contentDirSpellings);r!==n&&K(e,r)}}function jn(e,t){let n=U(e,`utf-8`),r=En(n,t.contentDirSpellings);r!==n&&K(e,r)}function Mn(e){try{return W(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>R(e,t.name))}catch{return[]}}const Nn=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function Pn(e){return/\.log\.\d+$/.test(e)}function Fn(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||Pn(e)}const In=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function Ln(e){let t={contentDirSpellings:Tn(e.contentDir)};for(let n of In)for(let r of Mn(R(e.stagingDir,n)))Fn(r)?kn(r,t):r.endsWith(`.json`)?An(r,t):jn(r,t);for(let n of Mn(R(e.stagingDir,`state`))){let e=I(n);n.endsWith(`.jsonl`)?kn(n,t):Nn.has(e)?An(n,t):jn(n,t)}}const Rn=[`.ok`,`local`,`telemetry`],zn=[`.ok`,`local`,`logs`],Bn=[`.ok`,`local`,`loss-capture`],Vn=`spans-current.jsonl`,Hn=`spans-prev.jsonl`,Un=`server-current.jsonl`,Wn=`server-prev.jsonl`,Gn=`loss-current.jsonl`,Kn=`loss-prev.jsonl`;function qn(e){return R(e,...Rn,Vn)}function Jn(e){return R(e,...Rn,Hn)}function Yn(e){return R(e,...zn,Un)}function Xn(e){return R(e,...zn,Wn)}function Zn(e){return R(e,...Bn,Gn)}function Qn(e){return R(e,...Bn,Kn)}const $n=1e3;async function er(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout($n)});return t.ok?await t.text():null}catch{return null}}async function tr(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout($n)});return t.ok?await t.text():null}catch{return null}}async function nr(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout($n)});return t.ok?await t.text():null}catch{return null}}function rr(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(`
14
+ `)}\n`:null}catch{return null}}function ir(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=he(`git`,[`-C`,t,`log`,`--oneline`,`-50`],y({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function ar(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=he(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],y({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function or(){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 sr(){return{nodeVersion:process.version,platform:Ne(),arch:Ae()}}function cr(){return process.env.OTEL_SDK_DISABLED===`false`}function lr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ur(e){if(!V(e))return{};let t;try{t=(0,xn.parse)(U(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(!lr(t))return{};let n=t.telemetry;if(!lr(n))return{};let r=n.localSink;return lr(r)?r:{}}function dr(e){return typeof e==`boolean`?e:void 0}function fr(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function pr(e){if(lr(e))return fr(e.maxBytes)}function mr(e){let t=ur(M(`project`,e)),n=ur(M(`project-local`,e));return{enabled:dr(n.enabled)??dr(t.enabled)??!0,spansMaxBytes:pr(n.spans)??pr(t.spans)??52428800,logsMaxBytes:pr(n.logs)??pr(t.logs)??26214400}}function hr(e){return He(`sha256`).update(e).digest(`hex`)}function gr(e){let t=U(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const _r=[`"doc.name"`,`"docName"`];function vr(e){let t=U(e,`utf-8`),n=0;for(let e of _r){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Q(e,t){if(!V(e))return!1;try{return H(L(t),{recursive:!0}),e.endsWith(`.ips`)?K(t,ct(U(e,`utf-8`))):be(e,t),!0}catch{return!1}}function yr(e){let t=[],n=e=>{let r=W(e,{withFileTypes:!0});for(let i of r){let r=R(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const br=new Set([`.jsonl`]);function xr(e){let t=e.lastIndexOf(`.`);return t!==-1&&br.has(e.slice(t))}const Sr=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Cr(e){if(Pn(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Sr.has(e.slice(t))}function wr(e){let t=[];for(let n of yr(e)){let r=Tr(e,n);if(!Cr(r))continue;let{redacted:i,patterns:a,lineCount:o}=m(U(n,`utf-8`));a.length!==0&&(K(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function Tr(e,t){return _e(e,t).split(B).join(`/`)}async function Er(e){let t=z(e.contentDir),n=z(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??er,a=r.fetchAgentEffects??tr,s=r.fetchWatcherRecent??nr,c=r.readShadowHead??ir,l=r.readCheckpointRefs??ar,u=r.now??(()=>new Date),d=r.okVersion??(()=>fe),m=r.readDesktopEnv??or,h=r.readLanguage??wn,g=r.readRuntime??sr,ee=r.isOtlpPushEnabled??cr,_=Ce(R(Fe(),`ok-bundle-`));try{H(R(_,`telemetry`),{recursive:!0}),H(R(_,`logs`),{recursive:!0}),H(R(_,`state`),{recursive:!0}),Q(qn(n),R(_,`telemetry`,Vn)),Q(Jn(n),R(_,`telemetry`,Hn)),Q(Yn(n),R(_,`logs`,Un)),Q(Xn(n),R(_,`logs`,Wn));for(let t of e.userLogFiles??[])Q(t,R(_,`logs`,I(t)));for(let t of e.userStateFiles??[])Q(t,R(_,te,I(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Q(t,R(_,`diagnostic-reports`,I(t)))&&(v+=1);let y=R(n,`.ok`,`local`),b=R(y,`server.lock`),x=`not-running`,S=`no server.lock`,C=null;if(V(b)){Q(b,R(_,`state`,`server.lock`));try{let e=U(b,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?C=t.port:S=`lock present but no port`}catch{S=`lock present but unparseable`}}if(C!==null){let e=await i(C);e===null?S=`agent-presence endpoint at :${C} unreachable`:(K(R(_,`state`,`agent-presence.json`),e),x=`running`,S=``);let t=await a(C);t!==null&&K(R(_,`state`,`agent-effects.json`),t);let n=await s(C);if(n!==null){let e=rr(n);e!==null&&K(R(_,`state`,`watcher-recent.jsonl`),e)}}let w=c(t);w!==null&&K(R(_,`state`,`shadow-head.txt`),w);let T=l(t);T!==null&&K(R(_,`state`,`checkpoint-refs.txt`),T),Q(Zn(n),R(_,`state`,Gn)),Q(Qn(n),R(_,`state`,Kn)),Q(R(y,`last-spawn-error.log`),R(_,`state`,`last-spawn-error.log`)),Q(R(y,p),R(_,`state`,p)),Q(R(y,o),R(_,`state`,o)),Q(R(y,f),R(_,`state`,f));let E=g(),D=m(),O=h(),ne={ok:{version:d(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O}};K(R(_,`state`,`runtime.json`),`${JSON.stringify(ne,null,2)}\n`);let k=x===`running`?`running
15
+ `:`not-running (${S})\n`;K(R(_,`state`,`server-status.txt`),k);let re=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:it(e.diagnosticReports,v);if(K(R(_,`state`,`diagnostic-reports-status.txt`),`${re}\n`),K(R(_,ht),en(e.osTerminationEvidence)),e.processDir&&V(e.processDir)){let t=R(_,`process`);H(t,{recursive:!0}),be(e.processDir,t,{recursive:!0})}let A=e.redact===!0;A&&Ln({stagingDir:_,contentDir:t}),e.note&&K(R(_,`note.txt`),e.note);let j=null;e.scrubSecrets===!0&&(j=wr(_));for(let t of e.extraFiles??[]){let e=t.zipName??I(t.sourcePath);if(!Q(t.sourcePath,R(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=on(t,`extra/${e}`);n!==null&&(j??={redactions:[],redactedLineCount:0},j.redactions.push(n),j.redactedLineCount+=n.lineCount)}let M=mr(n),ie=yr(_),N=[],ae=0,oe=0;for(let e of ie){let t=Tr(_,e),n=ke(e).size,r=xr(t)?gr(e):0;N.push({path:t,bytes:n,lines:r}),ae+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(oe+=vr(e))}let P={applied:A};j!==null&&(P.secretScrub=j);let F={schemaVersion:2,createdAt:u().toISOString(),ok:{version:d(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O},contentDir:{pathSha256:hr(t),absolutePath:A?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:ee()},redaction:P,serverStatus:x,files:N};K(R(_,`manifest.json`),`${JSON.stringify(F,null,2)}\n`);let se=Tn(t),ce=ie.some(e=>{try{let t=U(e,`utf-8`);return se.some(e=>t.includes(e))}catch{return!1}}),le={stagedDiagnosticReports:v,totalBytes:ae,fileCount:N.length,docNameCount:oe,contentDirVisible:ce,redacted:A},ue=!1;return{stagingDir:_,manifest:F,summary:le,cleanup:()=>{ue||(ue=!0,G(_,{recursive:!0,force:!0}))}}}catch(e){throw G(_,{recursive:!0,force:!0}),e}}async function Dr(e){let{collected:t,outputPath:n}=e,r=L(n);if(!V(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new Sn.ZipFile,a=yr(t.stagingDir);for(let e of a){let n=Tr(t.stagingDir,e);i.addFile(e,n)}i.end();let o=xe(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 Or(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let t=(0,xn.parse)(U(n,`utf-8`)),r=de(t)?t.content:void 0,i=de(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return z(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 z(e)}async function kr(e,t,n,r,i,a){let o=sn(t,e.logger),s=await Er({contentDir:Or(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...dn(o,e.userLogsDir??R(j(),`logs`)),...pn(e.cachesDir??R(q(),`Library`,`Caches`))],userStateFiles:mn(e.bugReportsDir??rn()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{H(L(e.outputPath),{recursive:!0}),await Dr({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function Ar(e){let{projectDir:t}=e,n=e.readDesktopEnv??or,r=e.readLanguage??wn,i=()=>mt(e.diagnosticReportsDir??R(q(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return kr(e,t,n,r,i(),await Qt(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await bn({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:pn(e.cachesDir??R(q(),`Library`,`Caches`)),bugReportLedgerFiles:mn(e.bugReportsDir??rn()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await Qt(e.osTerminationEvidenceDeps):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}}}function $(e,t,n={}){let r=b(e,t),i;try{i=U(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r}}let o=a&&typeof a==`object`?a:{},s=`machineId`in o&&typeof o.machineId==`string`?o.machineId!==(n.machineId??S()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??Me());if(!a||typeof a!=`object`||!O(a.pid))return{status:`corrupt`,lockPath:r,...s?{foreignHost:!0}:{}};let c=a.pid,l=`machineId`in o&&typeof o.machineId==`string`||`hostname`in o&&typeof o.hostname==`string`;return s?{status:`foreign-host`,lockPath:r,lock:a}:(n.isAlive??D)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function jr(e){return e.status===`unverified-owner`?`Cannot verify shutdown: the server lock at ${e.lockPath} does not record its owning machine, and its recorded process ${e.pid} is still running on this machine. Check whether process ${e.pid} is an OpenKnowledge server. If it is, stop it and retry. Do not remove the lock file while that process is running.`:`Cannot verify shutdown: the server lock at ${e.lockPath} belongs to another machine. Stop OpenKnowledge on the owning machine. Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it. Only then remove the stale lock file at ${e.lockPath} and retry cleanup.`}function Mr(e){return e.replace(/:\d+$/,``)}function Nr(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Mr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Mr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Mr(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const Pr=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function Fr(e){return i(c(),e)}function Ir(){return d(c())}function Lr(){let e=c();if(e===`stable`)return Pr;let t=u(e);return RegExp(`^# >>> ${t} >>>\\n[\\s\\S]*?^# <<< ${t} <<<\\n?`,`m`)}const Rr={existsSync:e=>V(e),readFileSync:(e,t)=>U(e,t),lstatSync:e=>Se(e),readlinkSync:e=>Ee(e)};function zr(e,t=Rr){let n=Fr(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function Br(e){let t=e.replace(Lr(),``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function Vr(e,t,n=Rr){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const Hr=[{hostDir:`.adal`,pruneRoot:`.adal`},{hostDir:`.aider-desk`,pruneRoot:`.aider-desk`},{hostDir:`.astrbot/data`,pruneRoot:`.astrbot`},{hostDir:`.augment`,pruneRoot:`.augment`},{hostDir:`.autohand`,pruneRoot:`.autohand`},{hostDir:`.bob`,pruneRoot:`.bob`},{hostDir:`.codeartsdoer`,pruneRoot:`.codeartsdoer`},{hostDir:`.codebuddy`,pruneRoot:`.codebuddy`},{hostDir:`.codeium/windsurf`,pruneRoot:`.codeium`},{hostDir:`.codemaker`,pruneRoot:`.codemaker`},{hostDir:`.codestudio`,pruneRoot:`.codestudio`},{hostDir:`.commandcode`,pruneRoot:`.commandcode`},{hostDir:`.config/crush`,pruneRoot:`.config/crush`},{hostDir:`.config/devin`,pruneRoot:`.config/devin`},{hostDir:`.config/goose`,pruneRoot:`.config/goose`},{hostDir:`.config/kimchi/harness`,pruneRoot:`.config/kimchi`},{hostDir:`.continue`,pruneRoot:`.continue`},{hostDir:`.factory`,pruneRoot:`.factory`},{hostDir:`.forge`,pruneRoot:`.forge`},{hostDir:`.grok`,pruneRoot:`.grok`},{hostDir:`.iflow`,pruneRoot:`.iflow`},{hostDir:`.inferencesh`,pruneRoot:`.inferencesh`},{hostDir:`.jazz`,pruneRoot:`.jazz`},{hostDir:`.junie`,pruneRoot:`.junie`},{hostDir:`.kilocode`,pruneRoot:`.kilocode`},{hostDir:`.kiro`,pruneRoot:`.kiro`},{hostDir:`.kode`,pruneRoot:`.kode`},{hostDir:`.lingma`,pruneRoot:`.lingma`},{hostDir:`.mcpjam`,pruneRoot:`.mcpjam`},{hostDir:`.moxby`,pruneRoot:`.moxby`},{hostDir:`.mux`,pruneRoot:`.mux`},{hostDir:`.neovate`,pruneRoot:`.neovate`},{hostDir:`.ona`,pruneRoot:`.ona`},{hostDir:`.openhands`,pruneRoot:`.openhands`},{hostDir:`.pochi`,pruneRoot:`.pochi`},{hostDir:`.qoder`,pruneRoot:`.qoder`},{hostDir:`.qoder-cn`,pruneRoot:`.qoder-cn`},{hostDir:`.qwen`,pruneRoot:`.qwen`},{hostDir:`.reasonix`,pruneRoot:`.reasonix`},{hostDir:`.roo`,pruneRoot:`.roo`},{hostDir:`.rovodev`,pruneRoot:`.rovodev`},{hostDir:`.snowflake/cortex`,pruneRoot:`.snowflake`},{hostDir:`.tabnine/agent`,pruneRoot:`.tabnine`},{hostDir:`.terramind`,pruneRoot:`.terramind`},{hostDir:`.tinycloud`,pruneRoot:`.tinycloud`},{hostDir:`.trae`,pruneRoot:`.trae`},{hostDir:`.trae-cn`,pruneRoot:`.trae-cn`},{hostDir:`.vibe`,pruneRoot:`.vibe`},{hostDir:`.zcode`,pruneRoot:`.zcode`},{hostDir:`.zencoder`,pruneRoot:`.zencoder`}],Ur=[...k.map(e=>A[e]),`open-knowledge`];function Wr(e){if(!ge(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=z(e);if(t===B||L(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function Gr(e,t){let n=_e(e,t);if(n.startsWith(`..`)||ge(n))return!1;let r=e;for(let e of n.split(B)){r=R(r,e);try{if(!Se(r).isDirectory())return!1}catch{return!1}}return!0}function Kr(e,t){try{return W(e).every(n=>t.has(R(e,n)))}catch{return!1}}function qr(e){let t=Wr(e),n=[],r=[],i=new Set;for(let e of Hr){let a=R(t,e.hostDir,`skills`);if(!Gr(t,a))continue;let o=Ur.map(e=>R(a,e)).filter(e=>V(e));n.push(...o);for(let e of o)i.add(e);let s=R(t,e.pruneRoot),c=a;for(;Kr(c,i)&&(r.push(c),i.add(c),c!==s);){let e=L(c);if(e===c||e===t||!e.startsWith(t+B))break;c=e}}return{skillDirs:n,emptyDirs:r}}function Jr(e){try{if(!Se(e).isDirectory())return!1;let t=W(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function Yr(e){let t=new Set,n=new Set;for(let r of Hr){let i=R(e,r.hostDir,`skills`);for(let e of Ur)t.add(R(i,e));let a=R(e,r.pruneRoot),o=i;for(;n.add(o),o!==a;){let t=L(o);if(t===o||t===e||!t.startsWith(e+B))break;o=t}}return{skillDirs:t,emptyDirs:n}}function Xr(e,t){let n=Wr(e),r=Yr(n),i=[...t.skillDirs.filter(e=>!r.skillDirs.has(e)),...t.emptyDirs.filter(e=>!r.emptyDirs.has(e))];if(i.length>0)throw Error(`refusing skill cleanup — ${i.length} path(s) outside the known legacy set: ${i.join(`, `)}`);let a=[];for(let e of t.skillDirs)if(Gr(n,e)&&Jr(e))try{G(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Gr(n,e))try{Oe(e),a.push(e)}catch{}return a}function Zr(e){let t=Wr(e),n=[];for(let e of k){let r=A[e];n.push({path:R(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of g)n.push({path:R(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function Qr(e,t){let n=[];for(let r of Zr(e))if(r.bundleId===t)try{G(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function $r(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ei(e,t=Date.now()){if(e===null)return`—`;let n=Ge(e,t);return n===`unknown`?`—`:n}function ti(e){let t=L(e);return I(e)===`local`&&I(t)===`.ok`?L(t):I(e)===`.ok`?t:null}function ni(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:ti(e),server:{port:null,status:t.status,pid:t.pid,startedAt:null,usage:null},ui:null,hostname:null,lockPath:t.lockPath,binary:null,command:null,isDesktop:!1};let i=t.lock,a=t.status===`alive`&&N(i)?{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r}:null;return{directory:i.worktreeRoot,server:{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r},ui:a,hostname:i.hostname,lockPath:t.lockPath,binary:n==null?null:re(n),command:n,isDesktop:$r(n)}}function ri(e){let t=e.server.status;switch(t){case`unverified-owner`:return`unverified`;case`alive`:return e.isDesktop?`desktop`:`running`;case`foreign-host`:return e.isDesktop?`desktop`:`foreign`;case`dead-pid`:return`stale`;default:return t}}const ii=new Set([`running`,`desktop`,`foreign`,`unverified`]);function ai(e){switch(e){case`running`:return Z.default.green(e);case`desktop`:return Z.default.blue(e);case`foreign`:return Z.default.cyan(e);case`unverified`:case`stale`:return Z.default.yellow(e)}}function oi(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function si(e){return`${oi(e.server.usage)} | ${oi(e.ui?.usage??null)}`}function ci(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function li(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,ci(e),si(e),ri(e),String(e.server.pid),ei(e.server.startedAt),e.binary??`—`]),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=ai(ri(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=Z.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
16
+ `)}async function ui(e={}){let t=e.discover??v,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??C,a=e.resolveUsage??ae,o=await t(),s=[];for(let e of o){let t=n(e),r=ni(e,t,t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:a(t.lock.pid));r!=null&&s.push(r)}if(e.json){let e=s.map(e=>({...e,displayStatus:ri(e)}));r(JSON.stringify(e,null,2));return}r(li(e.all?s:s.filter(e=>ii.has(ri(e)))))}function di(){return new P(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale entries (foreign and unverified entries already show)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await ui({all:t.all===!0||e===`all`,json:t.json===!0})})}async function fi(e,t=le()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=w(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500),redirect:`manual`});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function pi(e,t={}){return{targets:gi(e,t.isAlive??D)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function mi(e){try{return c()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function hi(e){let t=e.inspect??(()=>$(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??fi,o=e.logger??le(),s=t(),c=pi(s,{isAlive:e.isAlive});if(c.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};let u=s.status===`alive`||s.status===`foreign-host`?s.lock.channel:void 0;if(e.force!==!0&&typeof u==`string`&&u.length>0){let t=e.selfChannel??mi(o);if(t!==void 0&&u!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${l(u)}. Stop it from that app or its CLI, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,holderChannel:u,selfChannel:t,pids:c.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:u}}}if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:c.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let d=[],f=[];for(let e of c.targets)try{n(e.pid,`SIGTERM`),d.push(e)}catch(t){f.push({target:e,error:t instanceof Error?t.message:String(t)})}return d.length>0&&r(`Stopped: ${d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0&&i(`Failed to stop: ${f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:d,failed:f,hadTargets:!0}}function gi(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function _i(e,t=D){let n=await v(),r=null;for(let i of n){let n=$(i,`server`);if(gi(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}async function vi(e,t){let n=await hi({lockDir:e,force:t});return(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1),n}function yi(e,t,n={}){return t===0?`Nothing was running for ${e}, and no other open-knowledge servers are running.`:`Nothing was running for ${e}. ${t} other open-knowledge server${t===1?` is`:`s are`} running${n.listingFollows===!0?``:" — run `ok ps` to list them"}.`}async function bi(e){let t=await v(),n=0;for(let r of t)r!==e&&gi($(r,`server`),D)&&n++;return n}function xi(e){return new P(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the enclosing project — run it from anywhere inside the project. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).option(`--force`,`Stop even when the server belongs to another OpenKnowledge app (Stable or Beta) or editor windows or agents are still connected to it`).action(async(t,n)=>{let r=n.force===!0,i=t.length===0?void 0:t.join(` `);if(i===void 0){e();let t=x(process.cwd()),n=await hi({lockDir:t,force:r,log:()=>{}});if(n.hadTargets){if(n.stopped.length>0){let e=n.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1)}else{let e=await bi(t);console.log(yi(process.cwd(),e,{listingFollows:e>0})),e>0&&await ui({})}return}if(i===`all`){let e=await v();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e)gi($(n,`server`),D)&&(await vi(n,r),t++);t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(i)){let e=Number.parseInt(i,10),t=await _i(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await vi(t,r);return}let a=z(Xe(),i),o=x(a),s=[],c=await hi({lockDir:o,force:r,log:e=>s.push(e)});if((c.failed.length>0||c.declined!==void 0)&&(process.exitCode=1),c.hadTargets)for(let e of s)console.log(e);else console.log(yi(a,await bi(o)))})}export{tt as A,Qt as C,Ze as D,it as E,Xe as M,Ye as N,$e as O,qe as P,rn as S,mt as T,$ as _,Xr as a,Dr as b,Zr as c,Fr as d,Ir as f,jr as g,Nr as h,di as i,nt as j,Qe as k,Pr as l,Br as m,hi as n,qr as o,zr as p,xi as r,Qr as s,fi as t,Vr as u,Ar as v,nn as w,an as x,Er as y};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-B6Vk34FK.mjs";import"./src-TUmzQrPO.mjs";import"./init-PHFeZ_1F.mjs";import"./registry-probes-C7uxu4tM.mjs";import"./start-DpDSIaR1.mjs";import{n as e}from"./loader-CyiDGUuQ.mjs";import"./preview-4TMET2jL.mjs";import"./repair-mcp-configs-BN4wPLWB.mjs";export{e as loadConfig};
@@ -0,0 +1 @@
1
+ import{S as e,m as t,p as n,r}from"./start-DpDSIaR1.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
@@ -1,5 +1,5 @@
1
- import{F as e,S as t,X as n,Z as r,_l as i,i as a,pd as o}from"./md-manager-BGnqyqi1-C80pMLi7.mjs";import{Ii as s,as as c,bi as l,ci as u,gs as d,k as f,rs as p,wi as m}from"./dist-qew1xYqg.mjs";import{Ct as h,L as g,Tt as _,X as v,b as y,ut as b,wt as x,y as S,z as C}from"./init-Cb5cGxKf.mjs";import{S as w,a as T,c as E,h as D,i as O,m as k,n as A,o as j,p as M,r as N,s as P,t as ee,u as F}from"./registry-probes-DXYESJWL.mjs";import{n as I}from"./constants-CvznkgU4.mjs";import{execFileSync as L,spawn as R}from"node:child_process";import{basename as z,dirname as B,resolve as V}from"node:path";import{existsSync as H,realpathSync as te}from"node:fs";import{homedir as ne,tmpdir as re}from"node:os";import{rm as ie}from"node:fs/promises";import{setTimeout as ae}from"node:timers/promises";const oe=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],se={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function ce(e,t={}){let{login:n}=t,r=t._exec??L,i=le(t._fileExists??H),a=e?[`--hostname`,e]:[];if(n){let e=U(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=U(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function le(e){return[`gh`,...oe.filter(e)]}function U(e,t,n){for(let r of t)try{let t=e(r,n,se).toString().trim();if(t.length>0)return t}catch{}}function W(e,t={}){let n=t._exec??L,r=le(t._fileExists??H),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=U(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=ue(a,e);if(t)return t}let o=U(n,r,i);if(o!==void 0){let e=he(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ue(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 de=/Logged in to \S+ account (\S+) \(/,fe=/(?:Failed to log in to|Timeout trying to log in to) \S+/,pe=/^\s*-\s*Active account:\s*true\s*$/,me=/\u001b\[[0-9;]*m/g;function he(e){let t=[],n;for(let r of e.split(`
2
- `)){let e=r.replace(me,``),i=de.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(fe.test(e)){n=void 0;continue}n&&pe.test(e)&&(n.active=!0)}return t}const ge={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){d(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function _e(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 ve(e,t,n,r,i){let a=v[e];try{let o=j(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&d(`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`),_e(o.kind)}catch(i){return d(`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 ye(e,t,n){if(v[e].scope!==`global`)return q();if(n===`absent`)return ve(e,``,t.home,void 0,t.env);let r=(await y({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 be(e,t,n){let r=v[e].projectConfigPath?.(t.cwd);if(r===void 0)return q();if(n===`absent`)return ve(e,t.cwd,t.home,r,t.env);let i=S(v[e],t.cwd,ge,void 0,r);switch(i.action){case`written`:case`overwritten`:return{action:i.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function xe(e,t,n){let r=t.home??ne();if(n===`absent`){let t=N(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 Se(e,t,n){if(n===`absent`){let n=g(v[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=C(v[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 Ce(e){return t=>{if(t.pathId===void 0)return Y();let n=o(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return ye(n.editor,e,t.desired);case`editor-project-config`:return be(n.editor,e,t.desired);case`editor-project-skill-root`:return Se(n.editor,e,t.desired);case`editor-user-skill-root`:return xe(n.editor,e,t.desired)}}}function we(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Te(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function Ee(e=H,t=import.meta.dirname??new URL(`.`,import.meta.url).pathname){let n=[V(t,`public`),V(t,`../../app/dist`),V(t,`../../../app/dist`)];return e(V(t,`../../app.asar`))&&n.push(V(t,`../../app`)),n.find(t=>e(t))}function De(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 Oe(e){if(e===`off`)return`off`;if(!i.test(e))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function ke(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Ae(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function je(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||ke(e.host))&&e.isTTY}function Me(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Ne(e){return Me(`--external-url`,e)}function Pe(e){let t=z(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 ${f}* 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??re,r=t.realpathFn??te,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?V(e):null}},a=V(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(B(a));o=e===null?null:V(e,z(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&B(o)===s&&z(o).startsWith(`ok-ephemeral-`)}function $(e,t,n=e=>ie(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 ${f}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Fe(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 Ie(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:c}=await import(`node:fs`),{basename:l,dirname:d,resolve:f}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:x}=await import(`./dist-CqyT6Kac.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,T=C?s(e.singleFile).canonicalFilePath:void 0,D=T?d(T):void 0,k=T?l(T):void 0,j,M=!1;if(D!==void 0){if(e.projectDir!==void 0){if(j=e.projectDir,!Q(j))throw new Z(j);o(f(j,`.ok`,`config.yml`))||y(j,D)}else j=h(D),M=!0}let N=async()=>{if(!(!M||j===void 0)){if(!Q(j)){S.warn({ephemeralProjectDir:j},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await ie(j,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:j},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},F=j;if(!C){if(!i&&!u(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-BISI44CH.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-DCNJiOIo.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let I=D??_(t,n);!C&&!o(I)&&(c(I,{recursive:!0}),S.info({contentDir:I},`Created content directory`));let L=w(),R=m(),z;try{{let e=v(j??n),t=Date.now(),r=await x(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`)}z=await p({config:t,contentDir:I,projectDir:j??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:ce,detectGhAccounts:W,tokenStore:L,embeddingsKeyStore:R,mcpTomlEditor:b(),...C?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>A(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:(e,t)=>P(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:j??n,home:ne(),env:process.env};return{probe:ee(e),execute:Ce(e),userSkillPresentAnywhere:O}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Fe(F===void 0?n:$(n,F),{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 N(),e}let B=z.destroy,V=M?async()=>{try{await B()}finally{await N()}}:B;return{httpServer:z.httpServer,destroy:V,lockDir:z.lockDir,contentDir:I,port:z.port,ready:z.ready,degraded:z.degraded}}function Le(e,t,n=()=>p({absPath:c(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Re(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function ze(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Be(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 Ve(i,o){let s=Le(i,o.singleFile),c=ze(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=Pe(m);let h;try{h=n(process.env)}catch(e){throw e instanceof a&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=t(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=r(g),S=v??(_||b===void 0?[...x.bind]:[b]);Ae({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=o.externalUrl,E=r(t(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=o.port===void 0?void 0:Number(o.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,k=D??O??s.server?.port,A=De({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:Ee}),j=A.dir;A.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 M;try{M=await Ie({config:s,cwd:m,host:C,port:k,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...j?{reactShellDistDir:j}:{},idleThresholdMs:e(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{},...o.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-CqyT6Kac.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)),We(e,t,m)){let e=t.resolveLockDir(m),n=null;try{n=await He({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ae(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]=Ue(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=Ge(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 N=!1,P=async e=>{if(N)return;N=!0;let[t,...n]=Be(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await M.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`,()=>{P(`SIGINT`)}),process.once(`SIGTERM`,()=>{P(`SIGTERM`)});let ee=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${M.port}`,F=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${M.port}`:void 0,L=ee;console.log(l({name:`open-knowledge`,version:I,localUrl:L,networkUrl:F,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let R={"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`};M.ready.then(async()=>{if(M.degraded.length>0){console.log();for(let e of M.degraded){let t=R[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(je({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:j!==void 0})){let{openBrowser:e}=await import(`./open-browser-DdYx0HOD.mjs`);e(L)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function He(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:l(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 Ue(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 We(e,t,n){let r=t.ServerLockCollisionError;if(r!==void 0&&e instanceof r)return!0;let i=t.ServerAuthorityCollisionError;if(i===void 0||!(e instanceof i))return!1;try{return e.existing.scope.kind===`tree`&&te.native(n)===e.existing.projectDir}catch{return!1}}function Ge(e,t,n){let r=n.ServerAuthorityCollisionError;if(r!==void 0&&e instanceof r)return e.message;let i=n.ServerAuthorityRegistryError;if(i!==void 0&&e instanceof i)return e.message;let a=n.ServerLockCollisionError;if(a===void 0||!(e instanceof a))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 Ke(e){return new h(`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)`,Te).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)`,Oe).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Re).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 _(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new _(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new _(`--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).`,Ne).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{C as e,I as t,Q as n,Z as r,i,md as a,vl as o}from"./md-manager-BGnqyqi1-B6Vk34FK.mjs";import{Li as s,Ti as c,_s as l,is as u,k as d,li as f,os as p,xi as m}from"./dist-CerHybyM.mjs";import{Ct as h,L as g,Tt as _,X as v,b as y,ut as b,wt as x,y as S,z as C}from"./init-PHFeZ_1F.mjs";import{S as w,a as T,c as E,h as D,i as O,m as k,n as A,o as j,p as M,r as N,s as P,t as ee,u as F}from"./registry-probes-C7uxu4tM.mjs";import{n as I}from"./constants-owtVyfa1.mjs";import{execFileSync as L,spawn as R}from"node:child_process";import{basename as z,dirname as B,resolve as V}from"node:path";import{existsSync as H,realpathSync as te}from"node:fs";import{homedir as ne,tmpdir as re}from"node:os";import{rm as ie}from"node:fs/promises";import{setTimeout as ae}from"node:timers/promises";const oe=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],se={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function ce(e,t={}){let{login:n}=t,r=t._exec??L,i=le(t._fileExists??H),a=e?[`--hostname`,e]:[];if(n){let e=U(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=U(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function le(e){return[`gh`,...oe.filter(e)]}function U(e,t,n){for(let r of t)try{let t=e(r,n,se).toString().trim();if(t.length>0)return t}catch{}}function W(e,t={}){let n=t._exec??L,r=le(t._fileExists??H),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=U(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=ue(a,e);if(t)return t}let o=U(n,r,i);if(o!==void 0){let e=he(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ue(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 de=/Logged in to \S+ account (\S+) \(/,fe=/(?:Failed to log in to|Timeout trying to log in to) \S+/,pe=/^\s*-\s*Active account:\s*true\s*$/,me=/\u001b\[[0-9;]*m/g;function he(e){let t=[],n;for(let r of e.split(`
2
+ `)){let e=r.replace(me,``),i=de.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(fe.test(e)){n=void 0;continue}n&&pe.test(e)&&(n.active=!0)}return t}const ge={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 _e(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 ve(e,t,n,r,i){let a=v[e];try{let o=j(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`),_e(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 ye(e,t,n){if(v[e].scope!==`global`)return q();if(n===`absent`)return ve(e,``,t.home,void 0,t.env);let r=(await y({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 be(e,t,n){let r=v[e].projectConfigPath?.(t.cwd);if(r===void 0)return q();if(n===`absent`)return ve(e,t.cwd,t.home,r,t.env);let i=S(v[e],t.cwd,ge,void 0,r);switch(i.action){case`written`:case`overwritten`:return{action:i.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function xe(e,t,n){let r=t.home??ne();if(n===`absent`){let t=N(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 Se(e,t,n){if(n===`absent`){let n=g(v[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=C(v[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 Ce(e){return t=>{if(t.pathId===void 0)return Y();let n=a(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return ye(n.editor,e,t.desired);case`editor-project-config`:return be(n.editor,e,t.desired);case`editor-project-skill-root`:return Se(n.editor,e,t.desired);case`editor-user-skill-root`:return xe(n.editor,e,t.desired)}}}function we(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function Te(e){if(e===`server`)return e;throw new x(`--only must be 'server'`)}function Ee(e=H,t=import.meta.dirname??new URL(`.`,import.meta.url).pathname){let n=[V(t,`public`),V(t,`../../app/dist`),V(t,`../../../app/dist`)];return e(V(t,`../../app.asar`))&&n.push(V(t,`../../app`)),n.find(t=>e(t))}function De(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 Oe(e){if(e===`off`)return`off`;if(!o.test(e))throw new x(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function ke(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Ae(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function je(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||ke(e.host))&&e.isTTY}function Me(e,t){let n;try{n=new URL(t)}catch{throw new x(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new x(`${e} must be an http(s) origin (got: ${t})`);return t}function Ne(e){return Me(`--external-url`,e)}function Pe(e){let t=z(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 ${d}* 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??re,r=t.realpathFn??te,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?V(e):null}},a=V(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(B(a));o=e===null?null:V(e,z(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&B(o)===s&&z(o).startsWith(`ok-ephemeral-`)}function $(e,t,n=e=>ie(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 ${d}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Fe(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 Ie(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:l}=await import(`node:fs`),{basename:u,dirname:d,resolve:p}=await import(`node:path`),{bootServer:m,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:x}=await import(`./dist-fzYMjYEW.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,T=C?s(e.singleFile).canonicalFilePath:void 0,D=T?d(T):void 0,k=T?u(T):void 0,j,M=!1;if(D!==void 0){if(e.projectDir!==void 0){if(j=e.projectDir,!Q(j))throw new Z(j);o(p(j,`.ok`,`config.yml`))||y(j,D)}else j=h(D),M=!0}let N=async()=>{if(!(!M||j===void 0)){if(!Q(j)){S.warn({ephemeralProjectDir:j},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await ie(j,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:j},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},F=j;if(!C){if(!i&&!f(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-BN4wPLWB.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-S7Ro9IS4.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let I=D??_(t,n);!C&&!o(I)&&(l(I,{recursive:!0}),S.info({contentDir:I},`Created content directory`));let L=w(),R=c(),z;try{{let e=v(j??n),t=Date.now(),r=await x(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`)}z=await m({config:t,contentDir:I,projectDir:j??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:ce,detectGhAccounts:W,tokenStore:L,embeddingsKeyStore:R,mcpTomlEditor:b(),...C?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>A(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:(e,t)=>P(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:j??n,home:ne(),env:process.env};return{probe:ee(e),execute:Ce(e),userSkillPresentAnywhere:O}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Fe(F===void 0?n:$(n,F),{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 N(),e}let B=z.destroy,V=M?async()=>{try{await B()}finally{await N()}}:B;return{httpServer:z.httpServer,destroy:V,lockDir:z.lockDir,contentDir:I,port:z.port,ready:z.ready,degraded:z.degraded}}function Le(e,t,n=()=>u({absPath:p(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Re(e){if(e===`browser`||e===`app`)return e;throw new x(`--mode must be 'browser' or 'app'`)}function ze(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Be(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 Ve(a,o){let s=Le(a,o.singleFile),c=ze(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=Pe(m);let h;try{h=r(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=e(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=n(g),S=v??(_||b===void 0?[...x.bind]:[b]);Ae({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=o.externalUrl,E=n(e(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=o.port===void 0?void 0:Number(o.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,k=D??O??s.server?.port,A=De({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:Ee}),j=A.dir;A.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 M;try{M=await Ie({config:s,cwd:m,host:C,port:k,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...j?{reactShellDistDir:j}:{},idleThresholdMs:t(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{},...o.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-fzYMjYEW.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)),We(e,t,m)){let e=t.resolveLockDir(m),n=null;try{n=await He({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ae(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]=Ue(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=Ge(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 N=!1,P=async e=>{if(N)return;N=!0;let[t,...n]=Be(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await M.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`,()=>{P(`SIGINT`)}),process.once(`SIGTERM`,()=>{P(`SIGTERM`)});let ee=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${M.port}`,F=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${M.port}`:void 0,L=ee;console.log(l({name:`open-knowledge`,version:I,localUrl:L,networkUrl:F,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let R={"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`};M.ready.then(async()=>{if(M.degraded.length>0){console.log();for(let e of M.degraded){let t=R[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(je({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:j!==void 0})){let{openBrowser:e}=await import(`./open-browser-BL65djdM.mjs`);e(L)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function He(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:m(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 Ue(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 We(e,t,n){let r=t.ServerLockCollisionError;if(r!==void 0&&e instanceof r)return!0;let i=t.ServerAuthorityCollisionError;if(i===void 0||!(e instanceof i))return!1;try{return e.existing.scope.kind===`tree`&&te.native(n)===e.existing.projectDir}catch{return!1}}function Ge(e,t,n){let r=n.ServerAuthorityCollisionError;if(r!==void 0&&e instanceof r)return e.message;let i=n.ServerAuthorityRegistryError;if(i!==void 0&&e instanceof i)return e.message;let a=n.ServerLockCollisionError;if(a===void 0||!(e instanceof a))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 Ke(e){return new h(`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)`,Te).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)`,Oe).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Re).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 _(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new _(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new _(`--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).`,Ne).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=M(F());if(n.available){k({spawn:R},n);return}console.error(D(n.reason)),process.exit(1)}await Ve(n,t)})}export{Ge as C,W as D,ce as E,Ke as S,Fe as T,ze as _,Ue as a,je as b,Q as c,Oe as d,Te as f,Le as g,He as h,Pe as i,We as l,we as m,X as n,Be as o,Ee as p,Ie as r,ke as s,Z as t,Ne as u,De as v,$ as w,Ae as x,Ve as y};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.86.12-beta.0",
3
+ "version": "0.86.13-beta.0",
4
4
  "description": "Local-first, agent-friendly Markdown knowledge base with a cross-platform CLI and web editor",
5
5
  "keywords": [
6
6
  "knowledge-base",
@@ -65,10 +65,10 @@
65
65
  "@parcel/watcher": "^2.5.6"
66
66
  },
67
67
  "devDependencies": {
68
- "@inkeep/open-knowledge-app": "0.86.12-beta.0",
69
- "@inkeep/open-knowledge-core": "0.86.12-beta.0",
68
+ "@inkeep/open-knowledge-app": "0.86.13-beta.0",
69
+ "@inkeep/open-knowledge-core": "0.86.13-beta.0",
70
70
  "@inkeep/open-knowledge-native-config": "0.0.0",
71
- "@inkeep/open-knowledge-server": "0.86.12-beta.0",
71
+ "@inkeep/open-knowledge-server": "0.86.13-beta.0",
72
72
  "@types/node": "^24.7.0",
73
73
  "@types/proper-lockfile": "^4.1.4",
74
74
  "@types/yazl": "^3.3.1",
@@ -1 +0,0 @@
1
- import"./md-manager-BGnqyqi1-C80pMLi7.mjs";var e=`0.86.12-beta.0`;const t=`config.yml`,n=e;export{n,t};
@@ -1 +0,0 @@
1
- import{Dt as e,Ka as t,Tt as n,Y as r,_c as i,ec as a,sc as o,v as s}from"./md-manager-BGnqyqi1-C80pMLi7.mjs";import{$ as c,$a as l,$i as u,$n as d,$r as f,$t as p,A as m,Aa as h,Ai as g,An as _,Ao as v,Ar as y,At as b,B as x,Ba as S,Bi as C,Bn as w,Br as T,Bt as E,C as D,Ca as O,Ci as k,Cn as A,Co as j,Cr as M,Ct as N,D as P,Da as F,Di as I,Dn as L,Do as R,Dr as z,Ds as B,Dt as V,E as H,Ea as U,Ei as W,En as G,Eo as K,Er as q,Es as J,Et as Y,F as X,Fa as Z,Fi as Q,Fn as $,Fo as ee,Fr as te,Ft as ne,G as re,Ga as ie,Gi as ae,Gn as oe,Gr as se,Gt as ce,H as le,Ha as ue,Hi as de,Hn as fe,Hr as pe,Ht as me,I as he,Ia as ge,Ii as _e,In as ve,Io as ye,Ir as be,It as xe,J as Se,Ja as Ce,Ji as we,Jn as Te,Jr as Ee,Jt as De,K as Oe,Ka as ke,Ki as Ae,Kn as je,Kr as Me,Kt as Ne,L as Pe,La as Fe,Li as Ie,Ln as Le,Lo as Re,Lr as ze,Lt as Be,M as Ve,Ma as He,Mi as Ue,Mn as We,Mo as Ge,Mr as Ke,Mt as qe,N as Je,Na as Ye,Ni as Xe,Nn as Ze,No as Qe,Nr as $e,Nt as et,O as tt,Oa as nt,Oi as rt,On as it,Oo as at,Or as ot,Os as st,Ot as ct,P as lt,Pa as ut,Pi as dt,Pn as ft,Po as pt,Pr as mt,Pt as ht,Q as gt,Qa as _t,Qi as vt,Qn as yt,Qr as bt,Qt as xt,R as St,Ra as Ct,Ri as wt,Rn as Tt,Rr as Et,Rt as Dt,S as Ot,Sa as kt,Si as At,Sn as jt,So as Mt,Sr as Nt,Ss as Pt,St as Ft,T as It,Ta as Lt,Ti as Rt,Tn as zt,To as Bt,Tr as Vt,Ts as Ht,Tt as Ut,U as Wt,Ua as Gt,Ui as Kt,Un as qt,Ur as Jt,Ut as Yt,V as Xt,Va as Zt,Vi as Qt,Vn as $t,Vr as en,Vt as tn,W as nn,Wa as rn,Wi as an,Wn as on,Wr as sn,Wt as cn,X as ln,Xa as un,Xi as dn,Xn as fn,Xr as pn,Xt as mn,Y as hn,Ya as gn,Yi as _n,Yn as vn,Yr as yn,Yt as bn,Z as xn,Za as Sn,Zi as Cn,Zn as wn,Zr as Tn,Zt as En,_ as Dn,_a as On,_i as kn,_n as An,_o as jn,_r as Mn,_s as Nn,_t as Pn,a as Fn,aa as In,ai as Ln,an as Rn,ao as zn,ar as Bn,at as Vn,b as Hn,ba as Un,bi as Wn,bn as Gn,bo as Kn,br as qn,bs as Jn,bt as Yn,c as Xn,ca as Zn,ci as Qn,cn as $n,co as er,cr as tr,ct as nr,d as rr,da as ir,di as ar,dn as or,do as sr,dr as cr,dt as lr,ea as ur,ei as dr,en as fr,eo as pr,er as mr,et as hr,f as gr,fa as _r,fi as vr,fn as yr,fo as br,fr as xr,ft as Sr,g as Cr,ga as wr,gi as Tr,gn as Er,go as Dr,gr as Or,gs as kr,gt as Ar,h as jr,ha as Mr,hi as Nr,hn as Pr,ho as Fr,hr as Ir,hs as Lr,ht as Rr,i as zr,ia as Br,ii as Vr,in as Hr,io as Ur,ir as Wr,it as Gr,j as Kr,ja as qr,ji as Jr,jn as Yr,jo as Xr,jr as Zr,jt as Qr,k as $r,ka as ei,ki as ti,kn as ni,ko as ri,kr as ii,kt as ai,l as oi,la as si,li as ci,ln as li,lo as ui,lr as di,ls as fi,lt as pi,m as mi,ma as hi,mi as gi,mn as _i,mo as vi,mr as yi,ms as bi,mt as xi,n as Si,na as Ci,ni as wi,nn as Ti,no as Ei,nr as Di,nt as Oi,o as ki,oa as Ai,oi as ji,on as Mi,oo as Ni,or as Pi,ot as Fi,p as Ii,pa as Li,pi as Ri,pn as zi,po as Bi,pr as Vi,pt as Hi,q as Ui,qa as Wi,qi as Gi,qn as Ki,qr as qi,qt as Ji,r as Yi,ra as Xi,ri as Zi,rn as Qi,ro as $i,rr as ea,rt as ta,s as na,sa as ra,si as ia,sn as aa,so as oa,sr as sa,st as ca,t as la,ta as ua,ti as da,tn as fa,to as pa,tr as ma,tt as ha,u as ga,ua as _a,ui as va,un as ya,uo as ba,ur as xa,us as Sa,ut as Ca,v as wa,va as Ta,vi as Ea,vn as Da,vo as Oa,vr as ka,vs as Aa,vt as ja,w as Ma,wa as Na,wi as Pa,wn as Fa,wo as Ia,wr as La,wt as Ra,x as za,xa as Ba,xi as Va,xn as Ha,xo as Ua,xr as Wa,xs as Ga,xt as Ka,y as qa,ya as Ja,yi as Ya,yn as Xa,yo as Za,yr as Qa,ys as $a,yt as eo,z as to,za as no,zi as ro,zn as io,zr as ao,zt as oo}from"./dist-qew1xYqg.mjs";export{la as AGENT_ID_MAX_LEN,Si as AGENT_ID_RE,Yi as AGENT_WRITE_ORIGIN,t as AUDIT_EMPTY_SCOPE_WARNING,zr as AcpPermissionStore,Fn as AcpRegistry,ki as AcpThreadManager,na as AgentFocusBroadcaster,Xn as AgentPresenceBroadcaster,oi as AgentSessionCapacityError,ga as AgentSessionManager,rr as AutoStartDisabledError,gr as BUNDLE_IDS,Ii as BUNDLE_SCOPE,mi as BUNDLE_SKILL_NAME,jr as BacklinkIndex,Cr as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Dn as CONCURRENT_REPLACE_WINDOW_MS,wa as CONFIG_FILENAME,qa as CONFLICT_MARKER_RE,Hn as CURSOR_BUNDLE_PATHS_BY_PLATFORM,za as ConfigSchema,Ot as ConflictAuthority,D as DEFAULT_CHECKPOINT_RETENTION,Ma as DEFAULT_EMBEDDINGS_DIMENSIONS,It as DEFAULT_PACK_ID,H as DocumentDurabilityState,P as DocumentDurabilityStateError,tt as EMBEDDINGS_API_KEY_ENV,$r as EPHEMERAL_PROJECT_DIR_PREFIX,m as ExposureConsentError,Kr as FEATURED_AGENT_IDS,Ve as FILE_SYSTEM_WRITER,Je as FILE_WATCHER_ORIGIN,lt as FileEmbeddingsBackend,X as FilesystemRootProjectError,he as GIT_PREFLIGHT_FAIL_SPAN_NAME,Pe as GIT_UPSTREAM_WRITER,fi as GitDirAccessError,St as GitNotAvailableError,to as GitTooOldError,x as HOCUSPOCUS_AUTH_REJECTION_REASONS,Xt as HocuspocusAuthRejection,le as HocuspocusAuthTokenSchema,Wt as HomeProjectRootError,nn as INSTALLED_AGENTS_SCHEMES,re as JSON_SCHEMA_DIALECT_2020_12,B as LINEAGE_EPOCH_KEY,Oe as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Ui as MANAGED_RENAME_ORIGIN,Se as MAX_ACP_THREADS,hn as MAX_AGENT_SESSIONS,ln as MCP_CONNECTION_ID_HEADER,a as MCP_SERVER_NAME,xn as MIN_EVICTABLE_IDLE_MS,gt as MIN_GIT_VERSION,c as MISSING_OK_CONFIG_MESSAGE,Sa as MalformedGitPointerError,hr as McpLogger,ha as MissingOkConfigError,Oi as OBSERVER_SYNC_ORIGIN,ta as OK_OKIGNORE_TEMPLATE,Gr as ONBOARDING_BUNDLE_IDS,Ht as ORPHAN_MODES,st as PROTOCOL_VERSION,bi as PinoLogger,Vn as ProcessLockCollisionError,Fi as ProjectGitInitError,ca as ROLLBACK_ORIGIN,nr as ROOT_GITIGNORE_TEMPLATE,pi as RUNTIME_VERSION,Ca as SERVICE_WRITER,lr as SKILL_INSTALL_EVENTS_FILENAME,s as SKILL_STATE_TARGETS,Sr as STARTER_FOLDER_FRONTMATTER_FILENAME,Hi as STARTER_PACKS,xi as STARTER_PACK_IDS,Rr as STATE_MANIFEST_FILENAME,Ar as STATE_SCHEMA_VERSION,Pn as SYMLINK_MERGE_MIN_GIT_LABEL,ja as SYMLINK_MERGE_MIN_GIT_VERSION,i as SYSTEM_DOC_NAME,eo as SeedPrerequisiteError,Yn as SeedRootDirError,Ka as ServerAuthorityCollisionError,Ft as ServerAuthorityRegistryError,N as ServerLockCollisionError,Ra as SingleFileNotAFileError,Ut as SingleFileNotFoundError,Y as SingleFileNotMarkdownError,V as SingleFileProjectOverrideError,ct as StateManifestError,ai as TagIndex,b as USER_GLOBAL_BUNDLE_IDS,Qr as UnsafeIncomingSymlinkError,qe as __getShowAllWalkStatsForTesting,et as __resetShowAllWalkStatsForTesting,ht as acpThreadStoreRoots,ne as acpThreadsDir,xe as acquireProcessLock,Be as acquireServerLock,Dt as applyAgentMarkdownWrite,oo as applyExternalChange,E as applySeed,tn as assertCheckoutSymlinksSafe,me as assertCompatibleStateManifest,Yt as assertGitAvailable,cn as assertIncomingSymlinksSafe,ce as assertMergeNameResolvesTo,Ne as assertNeverDiskEvent,Ji as assertRepoCheckoutSymlinksSafe,De as assertSafeProjectRoot,bn as attachAcpThreadSocket,mn as attachCollabClientCounter,En as attachIdleShutdown,xt as auditScopeNotFoundTitle,p as bindConflictAuthority,fr as bootServer,fa as buildAndOpenSkill,Ti as buildConfigYmlContent,Qi as buildExecResult,Hr as buildIngressPolicy,Rn as buildOkMcpStdioCommand,Mi as buildSkillZip,aa as buildStarterFolderFrontmatterYaml,$n as buildWipTree,li as bundleSkillMdPath,ya as canonicalProjectKey,or as canonicalizeForCompare,yr as classifyEvents,zi as classifyFsPath,_i as clearAllEmbeddingsKeys,Pr as coercePackId,Er as collectServerHostSnapshot,n as colorFromSeed,An as commitUpstreamImport,Da as commitWip,Xa as commitWipFromTree,Gn as compareSemver,Ha as composeEffectiveLinterConfig,jt as composeFrontmatterSchemasConfig,A as containsConflictMarkers,Fa as contentHash,zt as contributorCount,G as countShadowObjects,L as countStaleAgentWipRefs,it as countWipRefs,ni as createApiExtension,_ as createAssetServeMiddleware,Yr as createCollaborationHost,We as createContentFilter,Ze as createContentFilterAsync,ft as createEmbeddingsSecretStore,$ as createEphemeralProjectDir,ve as createExternalChangeHandler,Le as createFileLogger,Tt as createLiveDerivedIndexExtension,io as createMcpHttpHandler,w as createOsProbe,$t as createPersistenceExtension,fe as createProbeFailureReporter,qt as createServer,on as createServerObserverExtension,oe as createServerProbeResolver,je as createStreamingErrorWriter,Lr as createTestLogger,Ki as describeStoredEmbeddingsKey,Te as detectClaudeDesktopPresence,vn as detectGit,fn as detectProjectShape,wn as detectUserSkillHosts,yt as discoverLockDirs,d as discoverMarkdownlintConfig,mr as emitPreflightFailureSpan,ma as encodeDocName,Di as encodeFolderRoute,ea as encodeSkillRoute,Wr as ensureProjectGit,Bn as errorResponse,Pi as evictStaleTrackerEntries,sa as extractHeadings,tr as extractOkBinaryPath,di as extractWikiLinksFromMarkdown,xa as fallbackPaths,cr as findEnclosingGitRoot,xr as findEnclosingProjectRoot,Vi as findNativeMarkdownlintFile,yi as flushFileLogger,Ir as formatAuditBrokenLinkSuppressionLine,Or as formatAuthRejectionWire,Mn as formatContributorsFrom,ka as formatPackRationale,Qa as gcCheckpointRefs,qn as getCurrentMcpLogger,Wa as getIngressContext,Nt as getLocalDir,M as getLogFilePath,kr as getLogger,La as getLogsDir,Vt as getMachineId,q as getMeter,z as getMetrics,ot as getTracer,ii as handleCollabSocketError,y as handleSpawnCursor,Zr as hasForwardingHeaders,Ke as hasGcLogLatch,e as iconFromClientName,$e as incrementCollabSocketFilteredError,mt as incrementServerObserverFire,te as initContent,be as initShadowRepo,ze as initTelemetry,Et as initToleranceTelemetryWriter,ao as installJsonSchemaDialect,T as installPrettyZodErrors,Nn as installTestLoggers,en as installUserSkill,pe as isAllowedApiOrigin,Jt as isAllowedWorkspaceHostHeader,sn as isConfigDoc,se as isDefunctProcess,Me as isDocInConflict,qi as isFilesystemRoot,Ee as isHocuspocusAuthRejectionReason,yn as isHomeDir,pn as isHostAdmitted,Tn as isKnownPackId,bt as isLinkIndexExcludedDoc,f as isLockProcessRunning,dr as isLoopbackAddress,da as isManagedArtifactDoc,wi as isMintedThreadId,Zi as isOriginAdmitted,J as isOrphanMode,Vr as isPairedWriteOrigin,Ln as isPathWithinDir,ji as isPeerAdmitted,ia as isProcessAlive,Qn as isProjectRoot,ci as isReservedForUserTree,va as isSelfWrite,ar as isSkillInstallReportEnvOptOut,vr as isSystemDoc,Ri as isToleranceTelemetryEnabled,gi as isValidLockPid,Nr as lastKnownHash,Tr as listRescueCheckpoints,kn as listStarterPacks,Ea as loadCustomAgents,Ya as loadPrincipal,Wn as lockAdvertisesUi,Va as lockBaseUrl,At as lockFilePath,Aa as loggerFactory,k as loginShapedUserinfoUser,$a as logsCurrentPath,Jn as logsPreviousPath,Pa as makeLazyEmbeddingsKeyStore,Rt as markServerLockDraining,W as mountMcpAndApi,I as normalizeFsPath,rt as observeReadiness,ti as packageVersionMajorMinor,g as parseAuthRejectionWire,Jr as parseGitVersion,Ue as parseHocuspocusAuthToken,Xe as parseKeepaliveConnectionId,dt as pathToDocName,Q as planSeed,_e as prepareSingleFileOpen,Ie as processCommand,wt as processUsage,ro as readAgentBrowserTools,C as readAllTargets,Qt as readBundleDecision,de as readDeclaredGitHubHosts,Kt as readOriginCredentialHost,an as readOriginGitHubRepo,ae as readOwnNativeRules,Ae as readProcessLock,Gi as readProcessLockDetailed,we as readProcessState,_n as readProjectHeadState,dn as readProjectLocalSemanticConfig,Cn as readServerLock,vt as readServerPackageVersion,u as readSkillInstallStateSnapshot,ur as readStateManifest,ua as readTargetRecordedAt,Ci as readTargetVersion,Xi as reconcile,Br as recordContributor,In as recordSkillInstallEvent,Ai as redactShareSubprocessStderr,ra as registerAllTools,Zn as registerWrite,si as releaseProcessLock,_a as releaseServerLock,ir as removeLastKnownHash,_r as removeProjectSkillGitignoreBlock,Li as reportSkillInstall,hi as resetMetrics,Mr as resolveAuditScope,wr as resolveBuiltinSkillHosts,r as resolveBundleEnabled,On as resolveBundledSkillDir,Ta as resolveContentDir,Ja as resolveCursorBinaryDefault,Un as resolveCursorSpawnInvocation,Ba as resolveEffectiveLinterConfig,kt as resolveEmbeddingsCredential,O as resolveGitHubAccountFromUrl,Na as resolveGitHubAuthHost,Lt as resolveLockDir,U as resolveNativeConfigForDoc,F as resolveNativeMarkdownlintConfig,nt as resolvePack,ei as resolvePackageVersion,h as resolveSkillInstallReportSettings,qr as resolveUiInfo,He as restoreContributors,Ye as rewriteMarkdownLinksForDocumentRename,ut as rewriteWikiLinksForDocumentRename,Z as runAuthReposSubprocess,ge as runAuthStatusSubprocess,Fe as runCloneSubprocess,Ct as runDeviceFlowSubprocess,no as runWithMcpLogger,S as safeContentPath,Zt as safeSubdir,ue as safetyCheckpoint,Gt as sameGitHubLogin,rn as sanitizeClientName,ie as saveInMemoryCheckpoint,ke as saveVersion,Wi as scanLockProcesses,Ce as seedBasenameIndex,gn as seedEphemeralProjectDir,un as serializeError,Sn as setActiveSpanAttributes,_t as setupServerObservers,l as shadowGit,pr as shutdownTelemetry,Ga as spansCurrentPath,Pt as spansPreviousPath,pa as spawnDetached,Ei as splitMarkdownBlocks,$i as startWatcher,Ur as strategiesFor,zn as streamedChunkOf,Ni as streamingProblemEvent,oa as swapContributors,er as teardownToleranceTelemetryWriter,ui as toBroadcasterKey,ba as tracedAppendFileSync,sr as tracedLinkSync,br as tracedMkdir,Bi as tracedMkdirSync,vi as tracedRename,Fr as tracedRenameSync,Dr as tracedRmSync,jn as tracedRmdirSync,Oa as tracedUnlinkSync,Za as tracedWriteFile,Kn as tracedWriteFileSync,Ua as trustSystemCertificates,Mt as updateLastKnownHash,j as updateProcessLockPort,Ia as updateServerLockPort,Bt as validateAgentId,K as validateCloneInputs,R as validateSkillZip,at as waitForServerLockDrain,ri as withHiddenWindowsConsole,v as withSpan,Xr as withSpanSync,Ge as writeBundleDecision,Qe as writeMarkdownlintRule,pt as writeRootGitignoreForNewRepo,ee as writeStateManifest,ye as writeTargetVersion,Re as writeTracker};