@inkeep/open-knowledge 0.78.0-beta.3 → 0.78.0-beta.5

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 (48) hide show
  1. package/dist/cli.mjs +25 -25
  2. package/dist/constants-C_LhGnYS.mjs +1 -0
  3. package/dist/{dist-H727Mac0.mjs → dist-Bm-n9FIx.mjs} +1 -1
  4. package/dist/{dist-D0NB38wf.mjs → dist-C9hrA0xr.mjs} +491 -491
  5. package/dist/index.d.mts +2 -0
  6. package/dist/index.mjs +1 -1
  7. package/dist/{init-Dp4PGYjw.mjs → init-CMZ1xdkA.mjs} +6 -6
  8. package/dist/init-DCPTgvxB.mjs +1 -0
  9. package/dist/{launch-json-removal-BmAuG_jG.mjs → launch-json-removal-BuZBUdUh.mjs} +1 -1
  10. package/dist/loader-BXm1oZrQ.mjs +1 -0
  11. package/dist/{loader-DfDlNps8.mjs → loader-C96mSVCK.mjs} +1 -1
  12. package/dist/{md-manager-BGnqyqi1-XuN_2HH6.mjs → md-manager-BGnqyqi1-CTvRTh-G.mjs} +155 -155
  13. package/dist/{open-browser-BnVmN9HA.mjs → open-browser-CG-plfXw.mjs} +1 -1
  14. package/dist/parse-worker.mjs +1 -1
  15. package/dist/{preview-7AGXsowO.mjs → preview-BGznaTo5.mjs} +1 -1
  16. package/dist/preview-qA7eAGIs.mjs +1 -0
  17. package/dist/public/assets/{AgentThreadClientBinder-B_EgL186.js → AgentThreadClientBinder-DCNH3zpd.js} +1 -1
  18. package/dist/public/assets/FeedbackForm-W-GjgDzG.js +1 -0
  19. package/dist/public/assets/SessionsHost-D9ZVPtHV.js +2 -0
  20. package/dist/public/assets/{TerminalPanel-B72jSABs.js → TerminalPanel-BOgEc32H.js} +2 -2
  21. package/dist/public/assets/{TerminalWindowApp-BBh9BN3G.js → TerminalWindowApp-Ct6qN_dO.js} +1 -1
  22. package/dist/public/assets/ThreadView-eUlv8dQ1.js +21 -0
  23. package/dist/public/assets/{index-CEN6HBkt.js → index--MkvkIJ3.js} +7 -7
  24. package/dist/public/assets/{preferred-session-events-BRTAOH0T.js → preferred-session-events-CXVw_3pf.js} +1 -1
  25. package/dist/public/assets/{progress-C8UCGQRe.js → progress-W-vIN-1-.js} +1 -1
  26. package/dist/public/assets/{launch-agent-thread--2IQ94Jw.js → sign-in-terminal-events-fDClI0Ap.js} +1 -1
  27. package/dist/public/assets/{terminal-launch-events-CXy7fHCR.js → terminal-launch-events-BBQ_c0On.js} +1 -1
  28. package/dist/public/assets/thread-client-D1YauXa3.js +3 -0
  29. package/dist/public/index.html +5 -5
  30. package/dist/{registry-probes-BzBX71vv.mjs → registry-probes-CHLJIRQ4.mjs} +2 -2
  31. package/dist/{removal-file-path-CMyXYCOR.mjs → removal-file-path-Db5k0FY2.mjs} +1 -1
  32. package/dist/{repair-launch-json-D7lAfSDj.mjs → repair-launch-json-deR6M_1O.mjs} +1 -1
  33. package/dist/{repair-mcp-configs-PSGELPq4.mjs → repair-mcp-configs-Heu6oO75.mjs} +1 -1
  34. package/dist/{src-1TB4Nw4k.mjs → src-DtEzWpk5.mjs} +4 -4
  35. package/dist/src-x20mMyjG.mjs +1 -0
  36. package/dist/start-u8_lFdEN.mjs +1 -0
  37. package/dist/{start-CwtZ_BnR.mjs → start-ufRM13rZ.mjs} +3 -3
  38. package/package.json +4 -4
  39. package/dist/constants-DbysIMPf.mjs +0 -1
  40. package/dist/init-O-lh1wdP.mjs +0 -1
  41. package/dist/loader-CPL0b4Ru.mjs +0 -1
  42. package/dist/preview-Dwh_DKhf.mjs +0 -1
  43. package/dist/public/assets/FeedbackForm-CBP1A2Tx.js +0 -1
  44. package/dist/public/assets/SessionsHost-7KYn79Jy.js +0 -2
  45. package/dist/public/assets/ThreadView-CeGUJ4X2.js +0 -21
  46. package/dist/public/assets/thread-client-Cpl5iQ-N.js +0 -3
  47. package/dist/src-DbACWJHw.mjs +0 -1
  48. package/dist/start-CPbpuluW.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{Bn as t,Cc as n,Ds as r,Eo as i,Jc as a,Mn as o,Qd as s,Rs as c,Yc as l,Zc as u,jn as d,xc as ee,zu as te}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{$n as f,Fo as p,Io as m,Kr as h,Lo as g,Qr as _,Si as v,Tt as y,Yn as b,ai as x,fr as S,ii as C,lo as w,m as T,oa as E,oi as D,xi as O,zn as k}from"./dist-D0NB38wf.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{Ct as ne,ot as j,st as M}from"./init-Dp4PGYjw.mjs";import{b as re,l as ie}from"./registry-probes-BzBX71vv.mjs";import{c as N}from"./colors-r_owlCuY.mjs";import{t as P}from"./is-object-BGze3w87.mjs";import{n as ae}from"./constants-DbysIMPf.mjs";import"./loader-DfDlNps8.mjs";import"./preview-7AGXsowO.mjs";import{execSync as oe,spawnSync as F}from"node:child_process";import{basename as I,dirname as L,isAbsolute as se,join as R,relative as ce,resolve as z,sep as B}from"node:path";import{closeSync as le,cpSync as ue,createWriteStream as de,existsSync as V,lstatSync as fe,mkdirSync as H,mkdtempSync as pe,openSync as me,readFileSync as U,readSync as he,readdirSync as W,rmSync as G,rmdirSync as ge,statSync as _e,writeFileSync as K}from"node:fs";import{arch as ve,freemem as ye,homedir as q,hostname as be,platform as xe,release as Se,tmpdir as Ce,totalmem as we,type as Te,uptime as Ee}from"node:os";import"node:fs/promises";import{createHash as De}from"node:crypto";const Oe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function ke(e,t,n=f){if(e!==void 0&&!Oe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ae=null;function je(e){Ae=e}function Me(){return Ae??process.cwd()}const Ne=`Open Knowledge`;function Pe(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return j(t).join(M({...e,platformName:t}),n)}function Fe(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=j(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`@inkeepopen-knowledge-desktop-updater`)}function Ie(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Le(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return Ie(n)??[]}function Re(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return Ie(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const ze=8192;function Be(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function Ve(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const He=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ue(e){return e.replace(He,`$1"[REDACTED-DEVICE-ID]"`)}function We(e){return Ue(Ve(e))}const Ge=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ke(e){if(typeof e!=`string`)return null;let t=Ge.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function qe(e){let t=me(e,`r`);try{let e=Buffer.alloc(ze),n=0,r=!1;for(;n<ze;){let i=he(t,e,n,ze-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{le(t)}}function Je(e){try{let t=qe(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Ke(a)}}catch{return{kind:`unreadable`}}}function Ye(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function Xe(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=W(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=R(e,t.name),r;try{r=_e(n).mtimeMs}catch{continue}if(r<i)continue;let c=Je(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Ye(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function J(){return R(q(),`.ok`,`bug-reports`)}function Ze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=R(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=R(n,`${r}-${e}.zip`);return i}function Qe(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let e=U(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return V(R(e,`.ok`))?De(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function $e(){let e={timestamp:new Date().toISOString(),platform:xe(),osType:Te(),osRelease:Se(),hostname:`[redacted]`,uptime:Ee(),freeMem:ye(),totalMem:we(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=oe(`sw_vers -productVersion 2>/dev/null`,w({encoding:`utf8`})).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const et=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function tt(e){let t=I(e);return et.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function nt(e,t){return ot(e,t).files}const rt=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function it(e,t=ie){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return rt.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>R(n,e.entry)))}function at(e){if(!V(e))return[];try{let t=new Map;for(let n of W(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-d.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>R(e,t))}catch{return[]}}function ot(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(tt),i=[],a=r.filter(t=>{try{return U(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!tt(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function st(e){let t=R(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,a,ee].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function ct(e){let t=R(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function lt(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${De(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function ut(e){let t=e.revealDocNames?e.content:lt(e.content).text;if(e.redact){let{redacted:n,patterns:i,lineCount:a}=r(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),i.length>0&&e.redactions.push({file:e.name,lineCount:a,patterns:i})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function Y(e){for(let t of e.files)try{let n=U(t,`utf8`);ut({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?We(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function dt(n){let{redact:r,outputPath:i,logger:a}=n,s=n.revealDocNames??!1,c=n.userLogsDir??R(q(),`.ok`,`logs`),l=n.projectDir?Qe(n.projectDir,a):null;H(L(i),{recursive:!0}),a?.info({projectSlug:l},`gathering diagnostic data`);let u=$e();u.desktop=n.desktop??null,u.language=n.language??null;let{files:d,excludedByProjectSlug:ee}=ot(l,c),{files:te}=n.projectDir?st(n.projectDir):{files:[]},{files:f}=n.projectDir?ct(n.projectDir):{files:[]},p=n.shipItLogFiles??[],m=n.diagnosticReports?.files??[];a?.info({logFileCount:d.length,logFilesExcludedByProjectSlug:ee,lockFileCount:te.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:_}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new _;Y({zipfile:v,files:[...d,...p],prefix:`logs`,redact:r,revealDocNames:s,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:te,prefix:`lockdir`,redact:r,revealDocNames:s,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:r,revealDocNames:s,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:n.bugReportLedgerFiles??[],prefix:o,redact:r,revealDocNames:s,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:r,revealDocNames:s,bundleFiles:g,redactions:h,logger:a});for(let e of n.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??I(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}n.note&&ut({zipfile:v,name:`note.txt`,content:n.note,redact:r,revealDocNames:s,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${I(e)}`)),b=g.filter(e=>y.has(e)),x=n.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(n.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`);let S=JSON.stringify(u,null,2);v.addBuffer(Buffer.from(S,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let C={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:l,files:g,redactions:h,sysinfo:u};v.addBuffer(Buffer.from(JSON.stringify(C,null,2),`utf8`),`MANIFEST.json`);let w=h.reduce((e,t)=>e+t.lineCount,0),T=new Set(p.map(e=>`logs/${I(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((n.bugReportLedgerFiles??[]).map(e=>`${o}/${I(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!tt(e)&&!T.has(e)):[],A=b.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ne=A.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...A]:[`Redaction was disabled for this bundle; file contents are unmodified.`],j=[`# Bug Report Bundle`,``,`Generated: ${C.generatedAt}`,`Project: ${l??`(unscoped)`}`,`Discipline version: ${C.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...k.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...k.map(e=>`- ${e}`),``]:[],...E.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...E.map(e=>`- ${e}`),``]:[],...b.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...b.map(e=>`- ${e}`),``]:[],...O.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...O.map(e=>`- ${e}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${t.join(`, `)}`,w>0?`${w} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...A,``,`This bundle is safe to attach to a GitHub issue.`]:ne].join(`
2
- `);v.addBuffer(Buffer.from(j,`utf8`),`README.md`),v.end();let M=de(i);return v.outputStream.pipe(M),await new Promise((e,t)=>{M.on(`close`,e),M.on(`error`,t)}),a?.info({bundlePath:i,fileCount:g.length,redactionCount:w},`bundle written`),{zipPath:i,summary:{projectSlug:l,files:g,redactions:h,redactedLineCount:w,generatedAt:C.generatedAt}}}var ft=te(),pt=e(A(),1),X=e(N(),1);function mt(e){let t=g(`user`,e,e);return p({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function ht({home:e=q(),env:t=process.env}={}){let r=mt(e),{override:i,preferenceList:a}=m(t),{locale:o,source:s}=c({override:i,storedPreference:r,supportedLocales:u,preferenceList:a,autoDetectableLocales:n});return{preference:r,locale:o,source:s,systemLanguages:a}}function gt(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function _t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vt(e,t){if(typeof e==`string`)return gt(e,t.contentDir);if(Array.isArray(e))return e.map(e=>vt(e,t));if(!_t(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=vt(i,t);return n}function yt(e,t){let n=U(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1
+ import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$d as t,Bn as n,Cc as r,Ds as i,Eo as a,Jc as o,Mn as s,Rs as c,Yc as l,Zc as u,jn as d,xc as ee,zu as te}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{$n as f,Fo as p,Io as m,Kr as h,Lo as g,Qr as _,Si as v,Tt as y,Yn as b,ai as x,fr as S,ii as C,lo as w,m as T,oa as E,oi as D,xi as O,zn as k}from"./dist-C9hrA0xr.mjs";import{t as A}from"./yazl-BBz29IQN.mjs";import{Ct as ne,ot as j,st as M}from"./init-CMZ1xdkA.mjs";import{b as re,l as ie}from"./registry-probes-CHLJIRQ4.mjs";import{c as N}from"./colors-r_owlCuY.mjs";import{t as P}from"./is-object-BGze3w87.mjs";import{n as ae}from"./constants-C_LhGnYS.mjs";import"./loader-C96mSVCK.mjs";import"./preview-BGznaTo5.mjs";import{execSync as oe,spawnSync as F}from"node:child_process";import{basename as I,dirname as L,isAbsolute as se,join as R,relative as ce,resolve as z,sep as B}from"node:path";import{closeSync as le,cpSync as ue,createWriteStream as de,existsSync as V,lstatSync as fe,mkdirSync as H,mkdtempSync as pe,openSync as me,readFileSync as U,readSync as he,readdirSync as W,rmSync as G,rmdirSync as ge,statSync as _e,writeFileSync as K}from"node:fs";import{arch as ve,freemem as ye,homedir as q,hostname as be,platform as xe,release as Se,tmpdir as Ce,totalmem as we,type as Te,uptime as Ee}from"node:os";import"node:fs/promises";import{createHash as De}from"node:crypto";const Oe=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`deinit`,`auth`]);function ke(e,t,n=f){if(e!==void 0&&!Oe.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ae=null;function je(e){Ae=e}function Me(){return Ae??process.cwd()}const Ne=`Open Knowledge`;function Pe(e={}){let t=e.platformName??process.platform,n=e.productName??`OpenKnowledge`;return j(t).join(M({...e,platformName:t}),n)}function Fe(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=j(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`@inkeepopen-knowledge-desktop-updater`)}function Ie(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function Le(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return Ie(n)??[]}function Re(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return Ie(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const ze=8192;function Be(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function Ve(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const He=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function Ue(e){return e.replace(He,`$1"[REDACTED-DEVICE-ID]"`)}function We(e){return Ue(Ve(e))}const Ge=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Ke(e){if(typeof e!=`string`)return null;let t=Ge.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function qe(e){let t=me(e,`r`);try{let e=Buffer.alloc(ze),n=0,r=!1;for(;n<ze;){let i=he(t,e,n,ze-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{le(t)}}function Je(e){try{let t=qe(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:Ke(a)}}catch{return{kind:`unreadable`}}}function Ye(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function Xe(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=W(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=R(e,t.name),r;try{r=_e(n).mtimeMs}catch{continue}if(r<i)continue;let c=Je(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!Ye(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function J(){return R(q(),`.ok`,`bug-reports`)}function Ze(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=J(),r=`${t}-bugreport`,i=R(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=R(n,`${r}-${e}.zip`);return i}function Qe(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let e=U(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return V(R(e,`.ok`))?De(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function $e(){let e={timestamp:new Date().toISOString(),platform:xe(),osType:Te(),osRelease:Se(),hostname:`[redacted]`,uptime:Ee(),freeMem:ye(),totalMem:we(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=oe(`sw_vers -productVersion 2>/dev/null`,w({encoding:`utf8`})).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const et=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function tt(e){let t=I(e);return et.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function nt(e,t){return ot(e,t).files}const rt=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function it(e,t=ie){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return rt.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>R(n,e.entry)))}function at(e){if(!V(e))return[];try{let t=new Map;for(let n of W(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-d.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>R(e,t))}catch{return[]}}function ot(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(tt),i=[],a=r.filter(t=>{try{return U(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!tt(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function st(e){let t=R(e,`.ok`,`local`);return V(t)?{files:[`server.lock`,`last-spawn-error.log`,o,ee].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function ct(e){let t=R(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function lt(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${De(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function ut(e){let t=e.revealDocNames?e.content:lt(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:a}=i(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:a,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function Y(e){for(let t of e.files)try{let n=U(t,`utf8`);ut({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?We(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function dt(t){let{redact:r,outputPath:i,logger:a}=t,o=t.revealDocNames??!1,c=t.userLogsDir??R(q(),`.ok`,`logs`),l=t.projectDir?Qe(t.projectDir,a):null;H(L(i),{recursive:!0}),a?.info({projectSlug:l},`gathering diagnostic data`);let u=$e();u.desktop=t.desktop??null,u.language=t.language??null;let{files:d,excludedByProjectSlug:ee}=ot(l,c),{files:te}=t.projectDir?st(t.projectDir):{files:[]},{files:f}=t.projectDir?ct(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];a?.info({logFileCount:d.length,logFilesExcludedByProjectSlug:ee,lockFileCount:te.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:_}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),v=new _;Y({zipfile:v,files:[...d,...p],prefix:`logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:te,prefix:`lockdir`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:f,prefix:`local-logs`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:t.bugReportLedgerFiles??[],prefix:s,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a}),Y({zipfile:v,files:m,prefix:`diagnostic-reports`,redact:r,revealDocNames:o,bundleFiles:g,redactions:h,logger:a});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??I(e.sourcePath)}`;v.addBuffer(t,n),g.push(n)}catch(t){a?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&ut({zipfile:v,name:`note.txt`,content:t.note,redact:r,revealDocNames:o,bundleFiles:g,redactions:h});let y=new Set(m.map(e=>`diagnostic-reports/${I(e)}`)),b=g.filter(e=>y.has(e)),x=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(t.diagnosticReports,b.length);v.addBuffer(Buffer.from(`${x}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`);let S=JSON.stringify(u,null,2);v.addBuffer(Buffer.from(S,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let C={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:l,files:g,redactions:h,sysinfo:u};v.addBuffer(Buffer.from(JSON.stringify(C,null,2),`utf8`),`MANIFEST.json`);let w=h.reduce((e,t)=>e+t.lineCount,0),T=new Set(p.map(e=>`logs/${I(e)}`)),E=g.filter(e=>T.has(e)),D=new Set((t.bugReportLedgerFiles??[]).map(e=>`${s}/${I(e)}`)),O=g.filter(e=>D.has(e)),k=l?g.filter(e=>e.startsWith(`logs/`)&&!tt(e)&&!T.has(e)):[],A=b.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ne=A.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...A]:[`Redaction was disabled for this bundle; file contents are unmodified.`],j=[`# Bug Report Bundle`,``,`Generated: ${C.generatedAt}`,`Project: ${l??`(unscoped)`}`,`Discipline version: ${C.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...k.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...k.map(e=>`- ${e}`),``]:[],...E.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...E.map(e=>`- ${e}`),``]:[],...b.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...b.map(e=>`- ${e}`),``]:[],...O.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...O.map(e=>`- ${e}`),``]:[],...r?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${n.join(`, `)}`,w>0?`${w} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...A,``,`This bundle is safe to attach to a GitHub issue.`]:ne].join(`
2
+ `);v.addBuffer(Buffer.from(j,`utf8`),`README.md`),v.end();let M=de(i);return v.outputStream.pipe(M),await new Promise((e,t)=>{M.on(`close`,e),M.on(`error`,t)}),a?.info({bundlePath:i,fileCount:g.length,redactionCount:w},`bundle written`),{zipPath:i,summary:{projectSlug:l,files:g,redactions:h,redactedLineCount:w,generatedAt:C.generatedAt}}}var ft=te(),pt=e(A(),1),X=e(N(),1);function mt(e){let t=g(`user`,e,e);return p({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function ht({home:e=q(),env:t=process.env}={}){let n=mt(e),{override:i,preferenceList:a}=m(t),{locale:o,source:s}=c({override:i,storedPreference:n,supportedLocales:u,preferenceList:a,autoDetectableLocales:r});return{preference:n,locale:o,source:s,systemLanguages:a}}function gt(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function _t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vt(e,t){if(typeof e==`string`)return gt(e,t.contentDir);if(Array.isArray(e))return e.map(e=>vt(e,t));if(!_t(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=vt(i,t);return n}function yt(e,t){let n=U(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
3
3
  `),i=n.split(`
4
4
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(e!==i.length-1||n!==``){if(n.length===0){a.push(``);continue}try{let e=vt(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
5
5
  `)}\n`:a.join(`
6
6
  `);K(e,o)}function bt(e,t){let n=U(e,`utf-8`);if(n.trim().length!==0)try{let r=vt(JSON.parse(n),t),i=n.endsWith(`
7
7
  `)?`
8
8
  `:``;K(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=gt(n,t.contentDir);r!==n&&K(e,r)}}function xt(e,t){let n=U(e,`utf-8`),r=gt(n,t.contentDir);r!==n&&K(e,r)}function St(e){try{return W(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>R(e,t.name))}catch{return[]}}const Ct=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function wt(e){return/\.log\.\d+$/.test(e)}function Tt(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||wt(e)}const Et=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function Dt(e){let t={contentDir:e.contentDir};for(let n of Et)for(let r of St(R(e.stagingDir,n)))Tt(r)?yt(r,t):r.endsWith(`.json`)?bt(r,t):xt(r,t);for(let n of St(R(e.stagingDir,`state`))){let e=I(n);n.endsWith(`.jsonl`)?yt(n,t):Ct.has(e)?bt(n,t):xt(n,t)}}const Ot=[`.ok`,`local`,`telemetry`],kt=[`.ok`,`local`,`logs`],At=[`.ok`,`local`,`loss-capture`],jt=`spans-current.jsonl`,Mt=`spans-prev.jsonl`,Nt=`server-current.jsonl`,Pt=`server-prev.jsonl`,Ft=`loss-current.jsonl`,It=`loss-prev.jsonl`;function Lt(e){return R(e,...Ot,jt)}function Rt(e){return R(e,...Ot,Mt)}function zt(e){return R(e,...kt,Nt)}function Bt(e){return R(e,...kt,Pt)}function Vt(e){return R(e,...At,Ft)}function Ht(e){return R(e,...At,It)}const Ut=1e3;async function Wt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(Ut)});return t.ok?await t.text():null}catch{return null}}async function Gt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(Ut)});return t.ok?await t.text():null}catch{return null}}async function Kt(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(Ut)});return t.ok?await t.text():null}catch{return null}}function qt(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(`
9
- `)}\n`:null}catch{return null}}function Jt(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=F(`git`,[`-C`,t,`log`,`--oneline`,`-50`],w({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Yt(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=F(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],w({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Xt(){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 Zt(){return{nodeVersion:process.version,platform:xe(),arch:ve()}}function Qt(){return process.env.OTEL_SDK_DISABLED===`false`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e){if(!V(e))return{};let t;try{t=(0,ft.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(!Z(t))return{};let n=t.telemetry;if(!Z(n))return{};let r=n.localSink;return Z(r)?r:{}}function en(e){return typeof e==`boolean`?e:void 0}function tn(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function nn(e){if(Z(e))return tn(e.maxBytes)}function rn(e){let t=$t(g(`project`,e)),n=$t(g(`project-local`,e));return{enabled:en(n.enabled)??en(t.enabled)??!0,spansMaxBytes:nn(n.spans)??nn(t.spans)??52428800,logsMaxBytes:nn(n.logs)??nn(t.logs)??26214400}}function an(e){return De(`sha256`).update(e).digest(`hex`)}function on(e){let t=U(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const sn=[`"doc.name"`,`"docName"`];function cn(e){let t=U(e,`utf-8`),n=0;for(let e of sn){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,We(U(e,`utf-8`))):ue(e,t),!0}catch{return!1}}function ln(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 un=new Set([`.jsonl`]);function dn(e){let t=e.lastIndexOf(`.`);return t!==-1&&un.has(e.slice(t))}const fn=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function pn(e){if(wt(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&fn.has(e.slice(t))}function mn(e){let t=[];for(let n of ln(e)){let i=hn(e,n);if(!pn(i))continue;let{redacted:a,patterns:o,lineCount:s}=r(U(n,`utf-8`));o.length!==0&&(K(n,a),t.push({file:i,lineCount:s,patterns:o}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function hn(e,t){return ce(e,t).split(B).join(`/`)}async function gn(e){let t=z(e.contentDir),n=z(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Wt,s=r.fetchAgentEffects??Gt,c=r.fetchWatcherRecent??Kt,u=r.readShadowHead??Jt,d=r.readCheckpointRefs??Yt,te=r.now??(()=>new Date),f=r.okVersion??(()=>ae),p=r.readDesktopEnv??Xt,m=r.readLanguage??ht,h=r.readRuntime??Zt,g=r.isOtlpPushEnabled??Qt,_=pe(R(Ce(),`ok-bundle-`));try{H(R(_,`telemetry`),{recursive:!0}),H(R(_,`logs`),{recursive:!0}),H(R(_,`state`),{recursive:!0}),Q(Lt(n),R(_,`telemetry`,jt)),Q(Rt(n),R(_,`telemetry`,Mt)),Q(zt(n),R(_,`logs`,Nt)),Q(Bt(n),R(_,`logs`,Pt));for(let t of e.userLogFiles??[])Q(t,R(_,`logs`,I(t)));for(let t of e.userStateFiles??[])Q(t,R(_,o,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 s(C);t!==null&&K(R(_,`state`,`agent-effects.json`),t);let n=await c(C);if(n!==null){let e=qt(n);e!==null&&K(R(_,`state`,`watcher-recent.jsonl`),e)}}let w=u(t);w!==null&&K(R(_,`state`,`shadow-head.txt`),w);let T=d(t);T!==null&&K(R(_,`state`,`checkpoint-refs.txt`),T),Q(Vt(n),R(_,`state`,Ft)),Q(Ht(n),R(_,`state`,It)),Q(R(y,`last-spawn-error.log`),R(_,`state`,`last-spawn-error.log`)),Q(R(y,l),R(_,`state`,l)),Q(R(y,a),R(_,`state`,a)),Q(R(y,ee),R(_,`state`,ee));let E=h(),D=p(),O=m(),k={ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O}};K(R(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let A=x===`running`?`running
10
- `:`not-running (${S})\n`;K(R(_,`state`,`server-status.txt`),A);let ne=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(e.diagnosticReports,v);if(K(R(_,`state`,`diagnostic-reports-status.txt`),`${ne}\n`),e.processDir&&V(e.processDir)){let t=R(_,`process`);H(t,{recursive:!0}),ue(e.processDir,t,{recursive:!0})}let j=e.redact===!0;j&&Dt({stagingDir:_,contentDir:t}),e.note&&K(R(_,`note.txt`),e.note);let M=null;e.scrubSecrets===!0&&(M=mn(_));for(let t of e.extraFiles??[])Q(t.sourcePath,R(_,`extra`,t.zipName??I(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let re=rn(n),ie=ln(_),N=[],P=0,ae=0;for(let e of ie){let t=hn(_,e),n=_e(e).size,r=dn(t)?on(e):0;N.push({path:t,bytes:n,lines:r}),P+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(ae+=cn(e))}let oe={applied:j};M!==null&&(oe.secretScrub=M);let F={schemaVersion:2,createdAt:te().toISOString(),ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O},contentDir:{pathSha256:an(t),absolutePath:j?`<CONTENT_DIR>`:t},telemetry:{localSink:re,otlpPushEnabled:g()},redaction:oe,serverStatus:x,files:N};K(R(_,`manifest.json`),`${JSON.stringify(F,null,2)}\n`);let L=ie.some(e=>{try{return U(e,`utf-8`).includes(t)}catch{return!1}}),se={stagedDiagnosticReports:v,totalBytes:P,fileCount:N.length,docNameCount:ae,contentDirVisible:L,redacted:j},ce=!1;return{stagingDir:_,manifest:F,summary:se,cleanup:()=>{ce||(ce=!0,G(_,{recursive:!0,force:!0}))}}}catch(e){throw G(_,{recursive:!0,force:!0}),e}}async function _n(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 pt.ZipFile,a=ln(t.stagingDir);for(let e of a){let n=hn(t.stagingDir,e);i.addFile(e,n)}i.end();let o=de(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function vn(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let t=(0,ft.parse)(U(n,`utf-8`)),r=P(t)?t.content:void 0,i=P(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 yn(e,t,n,r,i){let a=Qe(t,e.logger),o=await gn({contentDir:vn(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...nt(a,e.userLogsDir??R(q(),`.ok`,`logs`)),...it(e.cachesDir??R(q(),`Library`,`Caches`))],userStateFiles:at(e.bugReportsDir??J()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{H(L(e.outputPath),{recursive:!0}),await _n({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function bn(e){let{projectDir:t}=e,n=e.readDesktopEnv??Xt,r=e.readLanguage??ht,i=()=>Xe(e.diagnosticReportsDir??R(q(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return yn(e,t,n,r,i());let{zipPath:a,summary:o}=await dt({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:it(e.cachesDir??R(q(),`Library`,`Caches`)),bugReportLedgerFiles:at(e.bugReportsDir??J()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=D(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??be());if(!a||typeof a!=`object`||!_(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??h)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function xn(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 Sn(e){return e.replace(/:\d+$/,``)}function Cn(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Sn(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Sn(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Sn(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 wn=[{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`}],Tn=[...y.map(e=>T[e]),`open-knowledge`];function En(e){if(!se(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 Dn(e,t){let n=ce(e,t);if(n.startsWith(`..`)||se(n))return!1;let r=e;for(let e of n.split(B)){r=R(r,e);try{if(!fe(r).isDirectory())return!1}catch{return!1}}return!0}function On(e,t){try{return W(e).every(n=>t.has(R(e,n)))}catch{return!1}}function kn(e){let t=En(e),n=[],r=[],i=new Set;for(let e of wn){let a=R(t,e.hostDir,`skills`);if(!Dn(t,a))continue;let o=Tn.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(;On(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 An(e){try{if(!fe(e).isDirectory())return!1;let t=W(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function jn(e){let t=new Set,n=new Set;for(let r of wn){let i=R(e,r.hostDir,`skills`);for(let e of Tn)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 Mn(e,t){let n=En(e),r=jn(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(Dn(n,e)&&An(e))try{G(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Dn(n,e))try{ge(e),a.push(e)}catch{}return a}function Nn(e){let t=En(e),n=[];for(let e of y){let r=T[e];n.push({path:R(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of s)n.push({path:R(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function Pn(e,t){let n=[];for(let r of Nn(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 Fn(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function In(e,t=Date.now()){if(e===null)return`—`;let n=i(e,t);return n===`unknown`?`—`:n}function Ln(e){let t=L(e);return I(e)===`local`&&I(t)===`.ok`?L(t):I(e)===`.ok`?t:null}function Rn(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:Ln(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`&&C(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:b(n),command:n,isDesktop:Fn(n)}}function zn(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 Bn=new Set([`running`,`desktop`,`foreign`,`unverified`]);function Vn(e){switch(e){case`running`:return X.default.green(e);case`desktop`:return X.default.blue(e);case`foreign`:return X.default.cyan(e);case`unverified`:case`stale`:return X.default.yellow(e)}}function Hn(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Un(e){return`${Hn(e.server.usage)} | ${Hn(e.ui?.usage??null)}`}function Wn(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function Gn(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,Wn(e),Un(e),zn(e),String(e.server.pid),In(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=Vn(zn(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=X.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
9
+ `)}\n`:null}catch{return null}}function Jt(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=F(`git`,[`-C`,t,`log`,`--oneline`,`-50`],w({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Yt(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=F(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],w({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function Xt(){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 Zt(){return{nodeVersion:process.version,platform:xe(),arch:ve()}}function Qt(){return process.env.OTEL_SDK_DISABLED===`false`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e){if(!V(e))return{};let t;try{t=(0,ft.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(!Z(t))return{};let n=t.telemetry;if(!Z(n))return{};let r=n.localSink;return Z(r)?r:{}}function en(e){return typeof e==`boolean`?e:void 0}function tn(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function nn(e){if(Z(e))return tn(e.maxBytes)}function rn(e){let t=$t(g(`project`,e)),n=$t(g(`project-local`,e));return{enabled:en(n.enabled)??en(t.enabled)??!0,spansMaxBytes:nn(n.spans)??nn(t.spans)??52428800,logsMaxBytes:nn(n.logs)??nn(t.logs)??26214400}}function an(e){return De(`sha256`).update(e).digest(`hex`)}function on(e){let t=U(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const sn=[`"doc.name"`,`"docName"`];function cn(e){let t=U(e,`utf-8`),n=0;for(let e of sn){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,We(U(e,`utf-8`))):ue(e,t),!0}catch{return!1}}function ln(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 un=new Set([`.jsonl`]);function dn(e){let t=e.lastIndexOf(`.`);return t!==-1&&un.has(e.slice(t))}const fn=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function pn(e){if(wt(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&fn.has(e.slice(t))}function mn(e){let t=[];for(let n of ln(e)){let r=hn(e,n);if(!pn(r))continue;let{redacted:a,patterns:o,lineCount:s}=i(U(n,`utf-8`));o.length!==0&&(K(n,a),t.push({file:r,lineCount:s,patterns:o}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function hn(e,t){return ce(e,t).split(B).join(`/`)}async function gn(e){let t=z(e.contentDir),n=z(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??Wt,a=r.fetchAgentEffects??Gt,c=r.fetchWatcherRecent??Kt,u=r.readShadowHead??Jt,d=r.readCheckpointRefs??Yt,te=r.now??(()=>new Date),f=r.okVersion??(()=>ae),p=r.readDesktopEnv??Xt,m=r.readLanguage??ht,h=r.readRuntime??Zt,g=r.isOtlpPushEnabled??Qt,_=pe(R(Ce(),`ok-bundle-`));try{H(R(_,`telemetry`),{recursive:!0}),H(R(_,`logs`),{recursive:!0}),H(R(_,`state`),{recursive:!0}),Q(Lt(n),R(_,`telemetry`,jt)),Q(Rt(n),R(_,`telemetry`,Mt)),Q(zt(n),R(_,`logs`,Nt)),Q(Bt(n),R(_,`logs`,Pt));for(let t of e.userLogFiles??[])Q(t,R(_,`logs`,I(t)));for(let t of e.userStateFiles??[])Q(t,R(_,s,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 c(C);if(n!==null){let e=qt(n);e!==null&&K(R(_,`state`,`watcher-recent.jsonl`),e)}}let w=u(t);w!==null&&K(R(_,`state`,`shadow-head.txt`),w);let T=d(t);T!==null&&K(R(_,`state`,`checkpoint-refs.txt`),T),Q(Vt(n),R(_,`state`,Ft)),Q(Ht(n),R(_,`state`,It)),Q(R(y,`last-spawn-error.log`),R(_,`state`,`last-spawn-error.log`)),Q(R(y,l),R(_,`state`,l)),Q(R(y,o),R(_,`state`,o)),Q(R(y,ee),R(_,`state`,ee));let E=h(),D=p(),O=m(),k={ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O}};K(R(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let A=x===`running`?`running
10
+ `:`not-running (${S})\n`;K(R(_,`state`,`server-status.txt`),A);let ne=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:Be(e.diagnosticReports,v);if(K(R(_,`state`,`diagnostic-reports-status.txt`),`${ne}\n`),e.processDir&&V(e.processDir)){let t=R(_,`process`);H(t,{recursive:!0}),ue(e.processDir,t,{recursive:!0})}let j=e.redact===!0;j&&Dt({stagingDir:_,contentDir:t}),e.note&&K(R(_,`note.txt`),e.note);let M=null;e.scrubSecrets===!0&&(M=mn(_));for(let t of e.extraFiles??[])Q(t.sourcePath,R(_,`extra`,t.zipName??I(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let re=rn(n),ie=ln(_),N=[],P=0,ae=0;for(let e of ie){let t=hn(_,e),n=_e(e).size,r=dn(t)?on(e):0;N.push({path:t,bytes:n,lines:r}),P+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(ae+=cn(e))}let oe={applied:j};M!==null&&(oe.secretScrub=M);let F={schemaVersion:2,createdAt:te().toISOString(),ok:{version:f(),nodeVersion:E.nodeVersion,platform:E.platform,arch:E.arch},host:{desktop:D,language:O},contentDir:{pathSha256:an(t),absolutePath:j?`<CONTENT_DIR>`:t},telemetry:{localSink:re,otlpPushEnabled:g()},redaction:oe,serverStatus:x,files:N};K(R(_,`manifest.json`),`${JSON.stringify(F,null,2)}\n`);let L=ie.some(e=>{try{return U(e,`utf-8`).includes(t)}catch{return!1}}),se={stagedDiagnosticReports:v,totalBytes:P,fileCount:N.length,docNameCount:ae,contentDirVisible:L,redacted:j},ce=!1;return{stagingDir:_,manifest:F,summary:se,cleanup:()=>{ce||(ce=!0,G(_,{recursive:!0,force:!0}))}}}catch(e){throw G(_,{recursive:!0,force:!0}),e}}async function _n(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 pt.ZipFile,a=ln(t.stagingDir);for(let e of a){let n=hn(t.stagingDir,e);i.addFile(e,n)}i.end();let o=de(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function vn(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let t=(0,ft.parse)(U(n,`utf-8`)),r=P(t)?t.content:void 0,i=P(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 yn(e,t,n,r,i){let a=Qe(t,e.logger),o=await gn({contentDir:vn(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...nt(a,e.userLogsDir??R(q(),`.ok`,`logs`)),...it(e.cachesDir??R(q(),`Library`,`Caches`))],userStateFiles:at(e.bugReportsDir??J()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{H(L(e.outputPath),{recursive:!0}),await _n({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function bn(e){let{projectDir:t}=e,n=e.readDesktopEnv??Xt,r=e.readLanguage??ht,i=()=>Xe(e.diagnosticReportsDir??R(q(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return yn(e,t,n,r,i());let{zipPath:a,summary:o}=await dt({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:it(e.cachesDir??R(q(),`Library`,`Caches`)),bugReportLedgerFiles:at(e.bugReportsDir??J()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=D(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??be());if(!a||typeof a!=`object`||!_(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??h)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function xn(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 Sn(e){return e.replace(/:\d+$/,``)}function Cn(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Sn(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Sn(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Sn(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 wn=[{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`}],Tn=[...y.map(e=>T[e]),`open-knowledge`];function En(e){if(!se(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 Dn(e,t){let n=ce(e,t);if(n.startsWith(`..`)||se(n))return!1;let r=e;for(let e of n.split(B)){r=R(r,e);try{if(!fe(r).isDirectory())return!1}catch{return!1}}return!0}function On(e,t){try{return W(e).every(n=>t.has(R(e,n)))}catch{return!1}}function kn(e){let t=En(e),n=[],r=[],i=new Set;for(let e of wn){let a=R(t,e.hostDir,`skills`);if(!Dn(t,a))continue;let o=Tn.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(;On(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 An(e){try{if(!fe(e).isDirectory())return!1;let t=W(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function jn(e){let t=new Set,n=new Set;for(let r of wn){let i=R(e,r.hostDir,`skills`);for(let e of Tn)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 Mn(e,t){let n=En(e),r=jn(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(Dn(n,e)&&An(e))try{G(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Dn(n,e))try{ge(e),a.push(e)}catch{}return a}function Nn(e){let n=En(e),r=[];for(let e of y){let i=T[e];r.push({path:R(n,`.agents`,`skills`,i),bundleId:e,scope:`central`});for(let a of t)r.push({path:R(n,a.skillsRoot,i),bundleId:e,scope:`host`,hostDir:a.hostDir})}return r}function Pn(e,t){let n=[];for(let r of Nn(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 Fn(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function In(e,t=Date.now()){if(e===null)return`—`;let n=a(e,t);return n===`unknown`?`—`:n}function Ln(e){let t=L(e);return I(e)===`local`&&I(t)===`.ok`?L(t):I(e)===`.ok`?t:null}function Rn(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:Ln(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`&&C(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:b(n),command:n,isDesktop:Fn(n)}}function zn(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 Bn=new Set([`running`,`desktop`,`foreign`,`unverified`]);function Vn(e){switch(e){case`running`:return X.default.green(e);case`desktop`:return X.default.blue(e);case`foreign`:return X.default.cyan(e);case`unverified`:case`stale`:return X.default.yellow(e)}}function Hn(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Un(e){return`${Hn(e.server.usage)} | ${Hn(e.ui?.usage??null)}`}function Wn(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function Gn(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,Wn(e),Un(e),zn(e),String(e.server.pid),In(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=Vn(zn(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=X.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
11
11
  `)}async function Kn(e={}){let t=e.discover??k,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??O,a=e.resolveUsage??v,o=await t(),s=[];for(let e of o){let t=n(e),r=Rn(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:zn(e)}));r(JSON.stringify(e,null,2));return}r(Gn(e.all?s:s.filter(e=>Bn.has(zn(e)))))}function qn(){return new ne(`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 Kn({all:t.all===!0||e===`all`,json:t.json===!0})})}async function Jn(e,t=re()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=x(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 Yn(e,t={}){return{targets:Zn(e,t.isAlive??h)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}async function Xn(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??Jn,o=e.logger??re(),s=Yn(t(),{isAlive:e.isAlive});if(s.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:s.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let c=[],l=[];for(let e of s.targets)try{n(e.pid,`SIGTERM`),c.push(e)}catch(t){l.push({target:e,error:t instanceof Error?t.message:String(t)})}return c.length>0&&r(`Stopped: ${c.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:c.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:l.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),l.length>0&&i(`Failed to stop: ${l.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:c,failed:l,hadTargets:!0}}function Zn(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function Qn(e,t=h){let n=await k(),r=null;for(let i of n){let n=$(i,`server`);if(Zn(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}async function $n(e,t){let n=await Xn({lockDir:e,force:t});return(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1),n}function er(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 tr(e){let t=await k(),n=0;for(let r of t)r!==e&&Zn($(r,`server`),h)&&n++;return n}function nr(e){return new ne(`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 editor windows or agents are still connected to the server`).action(async(t,n)=>{let r=n.force===!0,i=t.length===0?void 0:t.join(` `);if(i===void 0){e();let t=E(process.cwd()),n=await Xn({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 tr(t);console.log(er(process.cwd(),e,{listingFollows:e>0})),e>0&&await Kn({})}return}if(i===`all`){let e=await k();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e)Zn($(n,`server`),h)&&(await $n(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 Qn(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await $n(t,r);return}let a=z(Me(),i),o=E(a),s=[],c=await Xn({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(er(a,await tr(o)))})}export{Re as C,ke as E,Le as S,je as T,Xe as _,Mn as a,Fe as b,Nn as c,$ as d,bn as f,J as g,Ze as h,qn as i,Cn as l,_n as m,Xn as n,kn as o,gn as p,nr as r,Pn as s,Jn as t,xn as u,Be as v,Me as w,Pe as x,Ne as y};
@@ -0,0 +1 @@
1
+ import"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import"./init-CMZ1xdkA.mjs";import"./registry-probes-CHLJIRQ4.mjs";import"./src-DtEzWpk5.mjs";import"./start-ufRM13rZ.mjs";import{n as e}from"./loader-C96mSVCK.mjs";import"./preview-BGznaTo5.mjs";import"./cli.mjs";import"./repair-mcp-configs-Heu6oO75.mjs";export{e as loadConfig};
@@ -0,0 +1 @@
1
+ import{S as e,m as t,p as n,r}from"./start-ufRM13rZ.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
@@ -1,5 +1,5 @@
1
- import{Hd as e,Is as t,Po as n,_t as r,qu as i,ua as a,zc as o,zs as s}from"./md-manager-BGnqyqi1-XuN_2HH6.mjs";import{Fo as c,Jo as l,Lo as u,bi as d,ci as f,ii as p,k as m,qr as h}from"./dist-D0NB38wf.mjs";import{Ct as g,L as _,Tt as v,X as y,b,ut as x,wt as S,y as C,z as w}from"./init-Dp4PGYjw.mjs";import{a as T,c as E,d as D,f as O,i as ee,n as k,o as A,p as j,r as M,s as N,t as te,u as P,v as F}from"./registry-probes-BzBX71vv.mjs";import{n as ne}from"./constants-DbysIMPf.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,join as re,resolve as B}from"node:path";import{existsSync as V,realpathSync as ie}from"node:fs";import{homedir as ae,tmpdir as oe}from"node:os";import{rm as se}from"node:fs/promises";import{setTimeout as ce}from"node:timers/promises";const le=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function H(e,t={}){let{login:n}=t,r=t._exec??I,i=U(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=W(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=W(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function U(e){return[`gh`,...le.filter(e)]}function W(e,t,n){for(let r of t)try{let t=e(r,n,ue).toString().trim();if(t.length>0)return t}catch{}}function de(e,t={}){let n=t._exec??I,r=U(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=W(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=fe(a,e);if(t)return t}let o=W(n,r,i);if(o!==void 0){let e=_e(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function fe(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const pe=/Logged in to \S+ account (\S+) \(/,me=/(?:Failed to log in to|Timeout trying to log in to) \S+/,he=/^\s*-\s*Active account:\s*true\s*$/,ge=/\u001b\[[0-9;]*m/g;function _e(e){let t=[],n;for(let r of e.split(`
2
- `)){let e=r.replace(ge,``),i=pe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(me.test(e)){n=void 0;continue}n&&he.test(e)&&(n.active=!0)}return t}const ve={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){l(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function ye(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}function be(e,t,n,r,i){let a=y[e];try{let o=A(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),ye(o.kind)}catch(i){return l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function xe(e,t,n){if(y[e].scope!==`global`)return q();if(n===`absent`)return be(e,``,t.home,void 0,t.env);let r=(await b({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function Se(t,n,r){let i=e[t];if(i===null)return q();let a=re(n.cwd,i);if(r===`absent`)return be(t,n.cwd,n.home,a,n.env);let o=C(y[t],n.cwd,ve,void 0,a);switch(o.action){case`written`:case`overwritten`:return{action:o.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function Ce(e,t,n){let r=t.home??ae();if(n===`absent`){let t=M(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=T(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function we(e,t,n){if(n===`absent`){let n=_(y[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=w(y[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function Te(e){return t=>{if(t.pathId===void 0)return Y();let n=i(t.pathId);if(n===null||n.kind===`central-skill-store`)return Y();switch(n.kind){case`editor-user-config`:return xe(n.editor,e,t.desired);case`editor-project-config`:return Se(n.editor,e,t.desired);case`editor-project-skill-root`:return we(n.editor,e,t.desired);case`editor-user-skill-root`:return Ce(n.editor,e,t.desired)}}}function Ee(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function De(e){if(e===`server`)return e;throw new S(`--only must be 'server'`)}function Oe(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function ke(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function Ae(e){if(e===`off`)return`off`;if(!o.test(e))throw new S(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function je(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Me(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Ne(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||je(e.host))&&e.isTTY}function Pe(e,t){let n;try{n=new URL(t)}catch{throw new S(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new S(`${e} must be an http(s) origin (got: ${t})`);return t}function Fe(e){return Pe(`--external-url`,e)}function Ie(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${m}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??oe,r=t.realpathFn??ie,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function Le(e,t,n=e=>se(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${m}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function $(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Re(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:m,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-H727Mac0.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?d(e.singleFile).canonicalFilePath:void 0,T=w?l(w):void 0,D=w?c(w):void 0,O,A=!1;if(T!==void 0){if(e.projectDir!==void 0){if(O=e.projectDir,!Q(O))throw new Z(O);o(u(O,`.ok`,`config.yml`))||y(O,T)}else O=m(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){S.warn({ephemeralProjectDir:O},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await se(O,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!C){if(!i&&!h(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-PSGELPq4.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-D7lAfSDj.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!C&&!o(P)&&(s(P,{recursive:!0}),S.info({contentDir:P},`Created content directory`));let ne=F(),I=f(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&S.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}L=await p({config:t,contentDir:P,projectDir:O??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:x(),...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>k(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:(e,t)=>N(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:O??n,home:ae(),env:process.env};return{probe:te(e),execute:Te(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return $(M===void 0?n:Le(n,M),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}})}catch(e){throw await j(),e}let R=L.destroy,z=A?async()=>{try{await R()}finally{await j()}}:R;return{httpServer:L.httpServer,destroy:z,lockDir:L.lockDir,contentDir:P,port:L.port,ready:L.ready,degraded:L.degraded}}function ze(e,t,n=()=>c({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Be(e){if(e===`browser`||e===`app`)return e;throw new S(`--mode must be 'browser' or 'app'`)}function Ve(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function He(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Ue(e,i){let o=ze(e,i.singleFile),c=Ve(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Ie(m);let h;try{h=t(process.env)}catch(e){throw e instanceof r&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=a(o,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=i.bind!==void 0&&i.bind.length>0?i.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=s(g),S=v??(_||b===void 0?[...x.bind]:[b]);Me({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=i.externalUrl,E=s(a(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
3
- `)))}let D=i.port===void 0?void 0:Number(i.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,ee=D??O??o.server?.port,k=ke({explicitDir:i.reactShellDistDir,only:i.only,findBundledDir:Oe}),A=k.dir;k.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let j;try{j=await Re({config:o,cwd:m,host:C,port:ee,bind:w,...i.serveContentAssets===void 0?{}:{serveContentAssets:i.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:n(i.idleShutdown??E.idleShutdown),serverRuntime:E,...i.singleFile?{singleFile:i.singleFile}:{},...i.projectDir?{projectDir:i.projectDir}:{}})}catch(e){e instanceof X&&(console.error(f(e.message)),process.exit(1)),e instanceof Z&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-H727Mac0.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),(e instanceof t.MissingOkConfigError||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),Ke(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await We({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ce(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=Ge(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=qe(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let M=!1,N=async e=>{if(M)return;M=!0;let[t,...n]=He(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await j.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{N(`SIGINT`)}),process.once(`SIGTERM`,()=>{N(`SIGTERM`)});let te=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${j.port}`,P=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${j.port}`:void 0,F=te;console.log(l({name:`open-knowledge`,version:ne,localUrl:F,networkUrl:P,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let I={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};j.ready.then(async()=>{if(j.degraded.length>0){console.log();for(let e of j.degraded){let t=I[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(Ne({openBrowser:i.openBrowser!==!1&&E.openBrowser,explicitOn:i.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:i.singleFile!==void 0,only:i.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-BnVmN9HA.mjs`);e(F)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function We(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:p(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function Ge(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function Ke(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function qe(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function Je(e){return new g(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,De).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,Ae).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Be).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new v(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new v(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Fe).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
1
+ import{Is as e,Ju as t,Po as n,Ud as r,_t as i,ua as a,zc as o,zs as s}from"./md-manager-BGnqyqi1-CTvRTh-G.mjs";import{Fo as c,Jo as l,Lo as u,bi as d,ci as f,ii as p,k as m,qr as h}from"./dist-C9hrA0xr.mjs";import{Ct as g,L as _,Tt as v,X as y,b,ut as x,wt as S,y as C,z as w}from"./init-CMZ1xdkA.mjs";import{a as T,c as E,d as D,f as O,i as ee,n as k,o as A,p as j,r as M,s as N,t as te,u as P,v as F}from"./registry-probes-CHLJIRQ4.mjs";import{n as ne}from"./constants-C_LhGnYS.mjs";import{execFileSync as I,spawn as L}from"node:child_process";import{basename as R,dirname as z,join as re,resolve as B}from"node:path";import{existsSync as V,realpathSync as ie}from"node:fs";import{homedir as ae,tmpdir as oe}from"node:os";import{rm as se}from"node:fs/promises";import{setTimeout as ce}from"node:timers/promises";const le=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function H(e,t={}){let{login:n}=t,r=t._exec??I,i=U(t._fileExists??V),a=e?[`--hostname`,e]:[];if(n){let e=W(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=W(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function U(e){return[`gh`,...le.filter(e)]}function W(e,t,n){for(let r of t)try{let t=e(r,n,ue).toString().trim();if(t.length>0)return t}catch{}}function de(e,t={}){let n=t._exec??I,r=U(t._fileExists??V),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=W(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=fe(a,e);if(t)return t}let o=W(n,r,i);if(o!==void 0){let e=_e(o);if(e.length>0)return e}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function fe(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=G(G(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=G(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const pe=/Logged in to \S+ account (\S+) \(/,me=/(?:Failed to log in to|Timeout trying to log in to) \S+/,he=/^\s*-\s*Active account:\s*true\s*$/,ge=/\u001b\[[0-9;]*m/g;function _e(e){let t=[],n;for(let r of e.split(`
2
+ `)){let e=r.replace(ge,``),i=pe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(me.test(e)){n=void 0;continue}n&&he.test(e)&&(n.active=!0)}return t}const ve={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function K(){return{action:`failed`,errorId:`write-failed`}}function q(){return{action:`skipped-missing`,errorId:`surface-missing`}}function J(e,t,n){l(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function Y(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function ye(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}function be(e,t,n,r,i){let a=y[e];try{let o=A(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),ye(o.kind)}catch(i){return l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),K()}}async function xe(e,t,n){if(y[e].scope!==`global`)return q();if(n===`absent`)return be(e,``,t.home,void 0,t.env);let r=(await b({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return K();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return q();case`skipped-flag`:return Y();default:return K()}}function Se(e,t,n){let i=r[e];if(i===null)return q();let a=re(t.cwd,i);if(n===`absent`)return be(e,t.cwd,t.home,a,t.env);let o=C(y[e],t.cwd,ve,void 0,a);switch(o.action){case`written`:case`overwritten`:return{action:o.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return K()}}function Ce(e,t,n){let r=t.home??ae();if(n===`absent`){let t=M(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,t.path,t.error),K()}}let i=T(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`failed`:return J(e,i.path,i.error),K()}}function we(e,t,n){if(n===`absent`){let n=_(y[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return q();case`failed`:return J(e,n.path,n.error),K()}}let r=w(y[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return q();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return J(e,r.path,r.error),K()}}function Te(e){return n=>{if(n.pathId===void 0)return Y();let r=t(n.pathId);if(r===null||r.kind===`central-skill-store`)return Y();switch(r.kind){case`editor-user-config`:return xe(r.editor,e,n.desired);case`editor-project-config`:return Se(r.editor,e,n.desired);case`editor-project-skill-root`:return we(r.editor,e,n.desired);case`editor-user-skill-root`:return Ce(r.editor,e,n.desired)}}}function Ee(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function De(e){if(e===`server`)return e;throw new S(`--only must be 'server'`)}function Oe(e=V){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(t,`public`),B(t,`../../app/dist`),B(t,`../../../app/dist`)].find(t=>e(t))}function ke(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function Ae(e){if(e===`off`)return`off`;if(!o.test(e))throw new S(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function je(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Me(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Ne(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||je(e.host))&&e.isTTY}function Pe(e,t){let n;try{n=new URL(t)}catch{throw new S(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new S(`${e} must be an http(s) origin (got: ${t})`);return t}function Fe(e){return Pe(`--external-url`,e)}function Ie(e){let t=R(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var X=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}},Z=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${m}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Q(e,t={}){let n=t.tmpdirFn??oe,r=t.realpathFn??ie,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?B(e):null}},a=B(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(z(a));o=e===null?null:B(e,R(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&z(o)===s&&R(o).startsWith(`ok-ephemeral-`)}function Le(e,t,n=e=>se(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Q(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${m}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function $(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Re(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:c,dirname:l,resolve:u}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:m,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-Bm-n9FIx.mjs`),S=e.log??g(`start`),C=e.singleFile!==void 0,w=C?d(e.singleFile).canonicalFilePath:void 0,T=w?l(w):void 0,D=w?c(w):void 0,O,A=!1;if(T!==void 0){if(e.projectDir!==void 0){if(O=e.projectDir,!Q(O))throw new Z(O);o(u(O,`.ok`,`config.yml`))||y(O,T)}else O=m(T),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Q(O)){S.warn({ephemeralProjectDir:O},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await se(O,{recursive:!0,force:!0})}catch(e){S.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!C){if(!i&&!h(n))throw new X(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?S.debug({event:e},`[start] reclaim sweep event`):S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-Heu6oO75.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-deR6M_1O.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=T??_(t,n);!C&&!o(P)&&(s(P,{recursive:!0}),S.info({contentDir:P},`Created content directory`));let ne=F(),I=f(),L;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&S.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}L=await p({config:t,contentDir:P,projectDir:O??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:H,detectGhAccounts:de,tokenStore:ne,embeddingsKeyStore:I,mcpTomlEditor:x(),...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>k(e,t),probePiAcpBridge:e=>E(e),ensurePiAcpBridge:(e,t)=>N(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:O??n,home:ae(),env:process.env};return{probe:te(e),execute:Te(e),userSkillPresentAnywhere:ee}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return $(M===void 0?n:Le(n,M),{log:S,exit:e.idleExit})},log:S,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}catch(e){throw await j(),e}let R=L.destroy,z=A?async()=>{try{await R()}finally{await j()}}:R;return{httpServer:L.httpServer,destroy:z,lockDir:L.lockDir,contentDir:P,port:L.port,ready:L.ready,degraded:L.degraded}}function ze(e,t,n=()=>c({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Be(e){if(e===`browser`||e===`app`)return e;throw new S(`--mode must be 'browser' or 'app'`)}function Ve(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function He(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Ue(t,r){let o=ze(t,r.singleFile),c=Ve(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Ie(m);let h;try{h=e(process.env)}catch(e){throw e instanceof i&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=a(o,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=r.bind!==void 0&&r.bind.length>0?r.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=s(g),S=v??(_||b===void 0?[...x.bind]:[b]);Me({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=r.externalUrl,E=s(a(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
3
+ `)))}let D=r.port===void 0?void 0:Number(r.port),O=h.overrides.find(e=>e.envVar===`PORT`)?.value,ee=D??O??o.server?.port,k=ke({explicitDir:r.reactShellDistDir,only:r.only,findBundledDir:Oe}),A=k.dir;k.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let j;try{j=await Re({config:o,cwd:m,host:C,port:ee,bind:w,...r.serveContentAssets===void 0?{}:{serveContentAssets:r.serveContentAssets},...A?{reactShellDistDir:A}:{},idleThresholdMs:n(r.idleShutdown??E.idleShutdown),serverRuntime:E,...r.singleFile?{singleFile:r.singleFile}:{},...r.projectDir?{projectDir:r.projectDir}:{},...r.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}catch(e){e instanceof X&&(console.error(f(e.message)),process.exit(1)),e instanceof Z&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-Bm-n9FIx.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),(e instanceof t.MissingOkConfigError||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),Ke(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await We({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ce(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=Ge(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=qe(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let M=!1,N=async e=>{if(M)return;M=!0;let[t,...n]=He(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await j.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{N(`SIGINT`)}),process.once(`SIGTERM`,()=>{N(`SIGTERM`)});let te=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${j.port}`,P=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${j.port}`:void 0,F=te;console.log(l({name:`open-knowledge`,version:ne,localUrl:F,networkUrl:P,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let I={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};j.ready.then(async()=>{if(j.degraded.length>0){console.log();for(let e of j.degraded){let t=I[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(Ne({openBrowser:r.openBrowser!==!1&&E.openBrowser,explicitOn:r.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:r.singleFile!==void 0,only:r.only,servesUi:A!==void 0})){let{openBrowser:e}=await import(`./open-browser-CG-plfXw.mjs`);e(F)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function We(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:p(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function Ge(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function Ke(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function qe(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function Je(e){return new g(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,De).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,Ae).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Be).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new v(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new v(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new v(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Fe).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
4
4
  `),process.exit(2)),t.projectDir!==void 0&&t.singleFile===void 0&&(process.stderr.write(`error: option '--project-dir' requires '--single-file'
5
5
  `),process.exit(2)),t.mode===`app`){let e=[];if(t.port!==void 0&&e.push(`--port`),t.bind!==void 0&&e.push(`--bind`),t.only!==void 0&&e.push(`--only`),t.idleShutdown!==void 0&&e.push(`--idle-shutdown`),t.openBrowser===!1&&e.push(`--no-open-browser`),t.externalUrl!==void 0&&e.push(`--external-url`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=D(P());if(n.available){O({spawn:L},n);return}console.error(j(n.reason)),process.exit(1)}await Ue(n,t)})}export{qe as C,de as D,H as E,Je as S,$ as T,Ve as _,Ge as a,Ne as b,Q as c,Ae as d,De as f,ze as g,We as h,Ie as i,Ke as l,Ee as m,X as n,He as o,Oe as p,Re as r,je as s,Z as t,Fe as u,ke as v,Le as w,Me as x,Ue as y};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.78.0-beta.3",
3
+ "version": "0.78.0-beta.5",
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",
@@ -72,10 +72,10 @@
72
72
  "ajv-formats": "^3.0.1",
73
73
  "tsdown": "^0.22.14",
74
74
  "typescript": "~7.0.2",
75
- "@inkeep/open-knowledge-app": "0.78.0-beta.3",
75
+ "@inkeep/open-knowledge-app": "0.78.0-beta.5",
76
+ "@inkeep/open-knowledge-core": "0.78.0-beta.5",
76
77
  "@inkeep/open-knowledge-native-config": "0.0.0",
77
- "@inkeep/open-knowledge-core": "0.78.0-beta.3",
78
- "@inkeep/open-knowledge-server": "0.78.0-beta.3"
78
+ "@inkeep/open-knowledge-server": "0.78.0-beta.5"
79
79
  },
80
80
  "scripts": {
81
81
  "build:cli": "rm -rf dist && tsdown",
@@ -1 +0,0 @@
1
- import"./md-manager-BGnqyqi1-XuN_2HH6.mjs";var e=`0.78.0-beta.3`;const t=`config.yml`,n=e;export{n,t};
@@ -1 +0,0 @@
1
- import"./dist-D0NB38wf.mjs";import{_ as e}from"./init-Dp4PGYjw.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-DfDlNps8.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-7AGXsowO.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{t as e}from"./index-CEN6HBkt.js";export{e as FeedbackForm};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TerminalPanel-B72jSABs.js","./chunk-CYidjpOJ.js","./dist-BBWka618.js","./preload-helper-Chd9yIcd.js","./trace-api-BP9dN1Hz.js","./lib-CPkc7nK4.js","./html-void-elements-zEl0KGqf.js","./lib-DmueaA5E.js","./markdownit-CugClK-K.js","./w3c-keyname-C7Rznu6R.js","./dist-Nvb76hAm.js","./jsx-runtime-BUgB2tll.js","./react-f2sANaYj.js","./button-HKX9wT1K.js","./dist-BHv-mziD.js","./bundle-mjs-SHeFpKGC.js","./compiler-runtime-BfE3aGVn.js","./utils-CPqDy6Hr.js","./triangle-alert-CCeXtPLU.js","./createLucideIcon-B6ULg5PN.js","./x-DIayTyoR.js","./dist-PQ5KMVDh.js","./TerminalStartingNotice-DaOP2MEM.js","./spinner-Bp2_BYkl.js","./file-tree-adapter-DLjG7Vd1.js","./file-tree-rename-validation-C0aGoscw.js","./file-tree-utils-xLkLWRXE.js","./navigation-targets-CQRRzWZU.js","./doc-paths-Cchodm9a.js","./terminal-command-events-B_odljGI.js","./agent-connection-status-BpmHdteI.js","./dist-Cr4-nBVI.js","./alert-dialog-BJIyfEVh.js","./dist-BcvirUWL.js","./react-dom-DPxgxlDT.js","./electron-drag-strip-BgiQs0O3.js","./dist-DRO03ovd.js","./es2015-B9_uRFGw.js","./checkbox-Crs_F_Np.js","./dist-Bd_yyADX.js","./dist-BDna-dOq.js","./check-BzfGb3KU.js","./minus-cd1ERTPg.js","./label-D-K3fWtj.js","./tooltip-DVBVVaAs.js","./dist-DYso7MCm.js","./floating-ui.dom-CDtYEnEj.js","./folder-C4F4ia-z.js","./info-CilGMBpP.js","./monitor-BZlB-tXl.js","./sparkles-CKoBZZKl.js","./AgentIconCluster-D4c5FBAw.js","./OpenInAgentMenuItem-AxhfRLpc.js","./dropdown-menu-raSZ06x1.js","./dist-BX7qfUal.js","./dist-tLQ-ULW1.js","./dist-Bn0BEeMP.js","./dist-Dhtu02232.js","./chevron-right-C-g4JuT4.js","./cursor-4hw-hwX-.js","./copilot-Cm5ODIkW.js","./mascot-outline-CtS592mc.js","./badge-EmKkAvTN.js","./dialog-Cv_pRVgB.js","./field-CKJVhgvN.js","./separator-CcvvqzEJ.js","./tool-list-format-C-Zu064J.js","./use-live-xterm-theme-BFttHtXj.js","./css-color-to-hex-CdrQ_PIL.js","./use-apply-config-theme-B5w38X1P.js","./page-list-cache-DzovwSp2.js","./TerminalPanel-BrP-ENHg.css","./ThreadView-CeGUJ4X2.js","./progress-C8UCGQRe.js","./DocumentContext-D5M6KGbp.js","./dist-BVlXaanp.js","./dist-AflZtDqw.js","./dist-DzgSQ1Ui.js","./dist-CoHX6EXK.js","./dist-BrW_Vaw8.js","./dist-CVYbGDxf.js","./dist-Dt26oMwk.js","./dist-DD23qI37.js","./dist-CKx7qIeD.js","./dist-DQmlLKXk.js","./stex-D_W9RRx2.js","./config-provider-BUgrvKtX.js","./use-apply-config-language-CcGDxTum.js","./dist-CJhtNlOm2.js","./messages-DbeSi0ES.js","./client-version-Ca-8OF05.js","./propagation-api-DC5404fy.js","./context-api-dUnlgSJr.js","./select-D_BhUvh8.js","./chevron-down-Dloks0wp.js","./collapsible-DYySK8La.js","./switch-iwBsEWej.js","./CodeMirrorPropInput-BxpqNYRy.js","./folder-open-dlosmFj2.js","./trash-2-B9Flu-41.js","./with-selector-PRoyWQiu.js","./cm-theme-CwmFYVNi.js","./external-link-iDv4MHBU.js","./documents-fetch-BN5vQY0e.js","./note-window-mode-CsmLTxU_.js","./git-branch-B_QTfwFA.js","./Mermaid-CBJnefqy.js","./maximize-2-DaY3HCwc.js","./circle-alert-Czw40trT.js","./prop-types-Dr9qeaU4.js","./documents-events-4ANG-YM5.js","./parse-api-error-BtEdpaFC.js","./startup-marks-CP0XYWYE.js","./diagnostic-breadcrumb-ZzsGTt1a.js","./eye-BtMXolFK.js","./hash-d98LeeWB.js","./local-menu-action-bus-DaoT7_kL.js","./paperclip-C8NmE81Z.js","./react-error-boundary-6ac6QM6R.js","./input-6HnhfmYW.js","./popover-BQOia0v4.js","./dist-zcYT-cpc.js","./use-collab-url-BEoSkrry.js","./excalidraw-scene-BStZkHyn.js","./known-skill-dirs-BZ8lUpY6.js","./skill-scope-CDgG3_a5.js","./skills-api-CpXGHi5r.js","./use-workspace-JzehlodO.js","./DocumentContext-B0sQn39F.css","./comment-chips-v9i2WFp7.js","./thread-client-Cpl5iQ-N.js","./image-attachment-m6wAdtfg.js","./workspace-paths-Dczkx4vn.js","./libesm-BBCvJbEY.js","./chunk-BO2N2NFS-8plYX3pZ.js","./RegisteredAgentIcon-KQW6AEu6.js","./terminal-launch-events-CXy7fHCR.js","./list-plus-BmoxCvSM.js","./rotate-ccw-B05K_aam.js","./square-pen-BhqhPrdL.js","./terminal-DGmaW797.js","./wrench-Cjhn9plF.js","./skeleton-BkL5nKOO.js","./textarea-D9PjrPjk.js","./use-installed-clis-DYoBxFbg.js","./launch-agent-thread--2IQ94Jw.js","./agent-presence-YJt1D8a4.js","./ok-syntax-theme-BmDz5WQQ.js","./overlay-layers-Bj-TVfKw.js","./clipboard-adapter-DJc-vDVF.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./preload-helper-Chd9yIcd.js";import{t as n}from"./jsx-runtime-BUgB2tll.js";import{t as r}from"./react-f2sANaYj.js";import{n as i,r as a}from"./dist-Nvb76hAm.js";import{t as o}from"./react-dom-DPxgxlDT.js";import{t as s}from"./compiler-runtime-BfE3aGVn.js";import{t as c}from"./react-error-boundary-6ac6QM6R.js";import{t as l}from"./utils-CPqDy6Hr.js";import{t as u}from"./overlay-layers-Bj-TVfKw.js";import{t as d}from"./button-HKX9wT1K.js";import{i as f,n as p,t as m}from"./tooltip-DVBVVaAs.js";import{t as h}from"./alert-dialog-BJIyfEVh.js";import{a as g,f as _,g as v,m as y,n as b,t as x,v as ee,y as te}from"./RegisteredAgentIcon-KQW6AEu6.js";import{r as S,s as ne}from"./terminal-telemetry-GDbpPMTk.js";import{bc as C}from"./dist-BBWka618.js";import{n as w}from"./dist-CJhtNlOm2.js";import{a as T,x as E}from"./use-settings-route-Dq8G3ePM.js";import{t as D}from"./dist-Cr4-nBVI.js";import{a as O,i as k,n as re,o as A,r as ie}from"./local-menu-action-bus-DaoT7_kL.js";import{$ as ae,A as oe,C as se,D as ce,E as j,F as M,G as N,K as P,M as F,N as I,O as L,P as le,S as R,T as z,Y as B,Z as ue,at as de,c as V,ct as H,et as fe,h as U,i as W,it as G,k as pe,l as K,lt as me,n as he,nt as ge,ot as _e,r as ve,rt as ye,tt as be,u as xe,ut as Se,x as Ce}from"./preferred-session-events-BRTAOH0T.js";import{b as we,d as Te,f as Ee,g as De,i as Oe,m as ke,o as Ae,p as je,t as Me,u as Ne,v as Pe}from"./terminal-launch-events-CXy7fHCR.js";import{t as Fe}from"./OpenInAgentMenuItem-AxhfRLpc.js";import{t as Ie}from"./createLucideIcon-B6ULg5PN.js";import{t as Le}from"./check-BzfGb3KU.js";import{t as Re}from"./chevron-left-BTZYHMSf.js";import{t as ze}from"./chevron-down-Dloks0wp.js";import{t as Be}from"./chevron-right-C-g4JuT4.js";import{a as Ve,h as He,i as Ue,o as We,r as Ge,t as Ke,u as q}from"./dropdown-menu-raSZ06x1.js";import{t as qe}from"./spinner-Bp2_BYkl.js";import{t as Je}from"./trash-2-B9Flu-41.js";import{t as J}from"./x-DIayTyoR.js";import{t as Ye}from"./diagnostic-breadcrumb-ZzsGTt1a.js";import{t as Xe}from"./input-6HnhfmYW.js";import{c as Ze,i as Qe,m as $e,n as Y,o as X,r as et,s as tt,t as nt}from"./DeleteConfirmationDialog-MTriAXRX.js";import{a as rt,d as it,g as at,h as ot,n as st,r as ct,s as lt,t as ut}from"./sortable.esm-CglQ4Z6u.js";import{i as dt,n as ft,r as pt,t as mt}from"./input-group-DCx8EIXX.js";import{d as ht,f as gt,h as _t,i as vt,l as yt,p as bt,s as xt,u as St}from"./thread-client-Cpl5iQ-N.js";import{i as Ct,n as wt,r as Tt,t as Et}from"./tabs-B9Fehvlq.js";import{i as Dt,n as Ot,o as kt,r as At,t as jt}from"./launch-agent-thread--2IQ94Jw.js";import{n as Mt,t as Nt}from"./use-terminal-enabled-DTm-rbQh.js";import{t as Pt}from"./TerminalStartingNotice-DaOP2MEM.js";var Ft=Ie(`panel-bottom`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M3 15h18`,key:`5xshup`}]]),It=e(o(),1),Lt=s(),Z=e(r(),1),Q=n(),Rt=3e4,zt=(0,Z.createContext)(null);function Bt(e){let t=(0,Lt.c)(8),{scope:n,children:r}=e,[i,a]=(0,Z.useState)(``),o;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>{a(``)},t[0]=o):o=t[0];let s;t[1]===n?s=t[2]:(s=[n],t[1]=n,t[2]=s),(0,Z.useEffect)(o,s);let c;t[3]===i?c=t[4]:(c={query:i,setQuery:a},t[3]=i,t[4]=c);let l;return t[5]!==r||t[6]!==c?(l=(0,Q.jsx)(zt,{value:c,children:r}),t[5]=r,t[6]=c,t[7]=l):l=t[7],l}function Vt(e){let t=(0,Lt.c)(19),{open:n,panelId:r,triggerRef:i,onOpenChange:o}=e,{_:s}=a(),c;t[0]===s?c=t[1]:(c=s({id:`Sdv6pQ`}),t[0]=s,t[1]=c);let l;t[2]!==o||t[3]!==n?(l=()=>o(!n),t[2]=o,t[3]=n,t[4]=l):l=t[4];let u;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,Q.jsx)(De,{"aria-hidden":`true`}),t[5]=u):u=t[5];let h;t[6]!==n||t[7]!==r||t[8]!==c||t[9]!==l||t[10]!==i?(h=(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsx)(d,{ref:i,type:`button`,variant:`ghost`,size:`icon-xs`,className:`shrink-0 cursor-pointer text-muted-foreground hover:text-foreground`,"aria-label":c,"aria-expanded":n,"aria-controls":r,"data-testid":`agent-thread-history`,onClick:l,children:u})}),t[6]=n,t[7]=r,t[8]=c,t[9]=l,t[10]=i,t[11]=h):h=t[11];let g;t[12]===s?g=t[13]:(g=s({id:`Sdv6pQ`}),t[12]=s,t[13]=g);let _;t[14]===g?_=t[15]:(_=(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:g}),t[14]=g,t[15]=_);let v;return t[16]!==h||t[17]!==_?(v=(0,Q.jsxs)(m,{children:[h,_]}),t[16]=h,t[17]=_,t[18]=v):v=t[18],v}function Ht(e){let t=(0,Lt.c)(11),{controllerRef:n}=e,{_:r}=a(),[i,o]=(0,Z.useState)(null),s,c;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>({open:o}),c=[],t[0]=s,t[1]=c):(s=t[0],c=t[1]),(0,Z.useImperativeHandle)(n,s,c),i===null)return null;let l;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(l=e=>{e||o(null)},t[2]=l):l=t[2];let u=i.title,d;t[3]===r?d=t[4]:(d=r({id:`IgkKDg`}),t[3]=r,t[4]=d);let f;t[5]===i.threadId?f=t[6]:(f=()=>{vt().deleteThread(i.threadId),o(null)},t[5]=i.threadId,t[6]=f);let p;return t[7]!==d||t[8]!==f||t[9]!==i.title?(p=(0,Q.jsx)(h,{open:!0,onOpenChange:l,children:(0,Q.jsx)(nt,{itemName:u,customTitle:d,isSubmitting:!1,onDelete:f})}),t[7]=d,t[8]=f,t[9]=i.title,t[10]=p):p=t[10],p}function Ut(e){let t=(0,Lt.c)(96),{thread:n,openAsTab:r,active:i,mode:o,now:s,reasonId:c,openTabReason:u,deleteDialogRef:h,onSelectThread:g,onDismiss:_}=e,{_:v}=a(),[y,b]=(0,Z.useState)(null),ee=(0,Z.useRef)(!1);if(y!==null){let e;t[0]!==y||t[1]!==n?(e=()=>{let e=y.trim();!ee.current&&e!==``&&e!==n.title&&vt().renameThread(n.threadId,e),ee.current=!1,b(null)},t[0]=y,t[1]=n,t[2]=e):e=t[2];let r=e,i;t[3]===v?i=t[4]:(i=v({id:`tDlhkF`}),t[3]=v,t[4]=i);let a,o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(a=e=>b(e.target.value),o=e=>{e.nativeEvent.isComposing||(e.key===`Enter`&&(e.preventDefault(),e.currentTarget.blur()),e.key===`Escape`&&(e.preventDefault(),ee.current=!0,e.currentTarget.blur()))},t[5]=a,t[6]=o):(a=t[5],o=t[6]);let s;return t[7]!==y||t[8]!==r||t[9]!==i?(s=(0,Q.jsx)(M,{className:`[contain-intrinsic-size:auto_2.25rem] [content-visibility:auto]`,children:(0,Q.jsx)(`div`,{className:`rounded-md bg-sidebar-accent p-1`,"data-testid":`agent-thread-history-rename`,children:(0,Q.jsx)(Xe,{autoFocus:!0,value:y,"aria-label":i,className:`h-7 min-w-0 text-sm`,onChange:a,onKeyDown:o,onBlur:r,"data-testid":`agent-thread-history-rename-input`})})}),t[7]=y,t[8]=r,t[9]=i,t[10]=s):s=t[10],s}let te=`${c}-${n.threadId}`,S=r||n.archived!==!0,ne=i?`bg-[var(--thread-row-bg)] [--thread-row-bg:var(--sidebar-selected)] [--thread-row-destructive-foreground:var(--sidebar-selected-destructive-foreground)] [--thread-row-foreground:var(--sidebar-selected-foreground)] [--thread-row-muted-foreground:var(--sidebar-selected-muted-foreground)]`:`hover:bg-[var(--thread-row-bg)] focus-within:bg-[var(--thread-row-bg)] [--thread-row-bg:var(--sidebar-hover)]`,C;t[11]===ne?C=t[12]:(C=l(`rounded-md [--thread-row-destructive-foreground:var(--sidebar-hover-destructive-foreground)] [--thread-row-foreground:var(--sidebar-hover-foreground)] [--thread-row-muted-foreground:var(--sidebar-hover-muted-foreground)] [contain-intrinsic-size:auto_2.25rem] [content-visibility:auto]`,ne),t[11]=ne,t[12]=C);let w=i?`true`:void 0,T;t[13]!==o||t[14]!==_||t[15]!==g||t[16]!==n.threadId?(T=()=>{g(n.threadId),o===`cover`&&_(`selection`)},t[13]=o,t[14]=_,t[15]=g,t[16]=n.threadId,t[17]=T):T=t[17];let E=`agent-thread-history-open-${n.threadId}`,D;t[18]!==n.agent.iconUrl||t[19]!==n.agent.id?(D=(0,Q.jsx)(x,{agentId:n.agent.id,iconUrl:n.agent.iconUrl,className:`size-4 shrink-0`}),t[18]=n.agent.iconUrl,t[19]=n.agent.id,t[20]=D):D=t[20];let O;t[21]===n.title?O=t[22]:(O=(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-start`,children:n.title}),t[21]=n.title,t[22]=O);let k;t[23]!==s||t[24]!==n.lastActivityAt?(k=Jt(n.lastActivityAt,s),t[23]=s,t[24]=n.lastActivityAt,t[25]=k):k=t[25];let re;t[26]===k?re=t[27]:(re=(0,Q.jsx)(`span`,{className:`shrink-0 text-2xs text-[var(--thread-row-muted-foreground)] motion-safe:transition-opacity group-focus-within/menu-item:opacity-0 group-hover/menu-item:opacity-0`,children:k}),t[26]=k,t[27]=re);let ie;t[28]!==i||t[29]!==w||t[30]!==T||t[31]!==E||t[32]!==D||t[33]!==O||t[34]!==re?(ie=(0,Q.jsxs)(le,{type:`button`,size:`default`,isActive:i,"aria-current":w,className:`h-9 bg-transparent pr-2! text-sidebar-foreground hover:bg-transparent hover:text-[var(--thread-row-foreground)] active:bg-transparent data-active:bg-transparent data-active:text-[var(--thread-row-foreground)] data-active:hover:bg-transparent group-focus-within/menu-item:text-[var(--thread-row-foreground)] group-hover/menu-item:text-[var(--thread-row-foreground)]`,onClick:T,"data-testid":E,children:[D,O,re]}),t[28]=i,t[29]=w,t[30]=T,t[31]=E,t[32]=D,t[33]=O,t[34]=re,t[35]=ie):ie=t[35];let ae;t[36]!==v||t[37]!==n.title?(ae=v({id:`0TnCvC`,values:{0:n.title}}),t[36]=v,t[37]=n.title,t[38]=ae):ae=t[38];let oe;t[39]===n.title?oe=t[40]:(oe=()=>{ee.current=!1,b(n.title)},t[39]=n.title,t[40]=oe);let se=`agent-thread-history-rename-${n.threadId}`,ce;t[41]===Symbol.for(`react.memo_cache_sentinel`)?(ce=(0,Q.jsx)(A,{className:`size-3`,"aria-hidden":`true`}),t[41]=ce):ce=t[41];let j;t[42]!==ae||t[43]!==oe||t[44]!==se?(j=(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":ae,className:`rounded-sm bg-transparent text-[var(--thread-row-muted-foreground)] shadow-none hover:bg-transparent hover:text-[var(--thread-row-foreground)]`,onClick:oe,"data-testid":se,children:ce})}),t[42]=ae,t[43]=oe,t[44]=se,t[45]=j):j=t[45];let N;t[46]===v?N=t[47]:(N=v({id:`6PsaMr`}),t[46]=v,t[47]=N);let P;t[48]===N?P=t[49]:(P=(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:N}),t[48]=N,t[49]=P);let F;t[50]!==j||t[51]!==P?(F=(0,Q.jsxs)(m,{children:[j,P]}),t[50]=j,t[51]=P,t[52]=F):F=t[52];let L=S&&`cursor-not-allowed`,R;t[53]===L?R=t[54]:(R=l(`inline-flex`,L),t[53]=L,t[54]=R);let z;t[55]!==v||t[56]!==n.title?(z=v({id:`Y2tU6I`,values:{0:n.title}}),t[55]=v,t[56]=n.title,t[57]=z):z=t[57];let B=S||void 0,ue=S?te:void 0,de=S?`pointer-events-none cursor-not-allowed bg-transparent text-muted-foreground/35 shadow-none hover:bg-transparent hover:text-muted-foreground/35 active:translate-y-0`:`rounded-sm bg-transparent text-[var(--thread-row-muted-foreground)] shadow-none hover:bg-transparent hover:text-[var(--thread-row-destructive-foreground)]`,V;t[58]===de?V=t[59]:(V=l(de),t[58]=de,t[59]=V);let H;t[60]!==S||t[61]!==h||t[62]!==n?(H=()=>{S||h.current?.open(n)},t[60]=S,t[61]=h,t[62]=n,t[63]=H):H=t[63];let fe=`agent-thread-history-delete-${n.threadId}`,U;t[64]===Symbol.for(`react.memo_cache_sentinel`)?(U=(0,Q.jsx)(Je,{className:`size-3`,"aria-hidden":`true`}),t[64]=U):U=t[64];let W;t[65]!==z||t[66]!==B||t[67]!==ue||t[68]!==V||t[69]!==H||t[70]!==fe?(W=(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":z,"aria-disabled":B,"aria-describedby":ue,className:V,onClick:H,"data-testid":fe,children:U}),t[65]=z,t[66]=B,t[67]=ue,t[68]=V,t[69]=H,t[70]=fe,t[71]=W):W=t[71];let G;t[72]!==S||t[73]!==u||t[74]!==te?(G=S?(0,Q.jsx)(`span`,{id:te,className:`sr-only`,children:u}):null,t[72]=S,t[73]=u,t[74]=te,t[75]=G):G=t[75];let pe;t[76]!==R||t[77]!==W||t[78]!==G?(pe=(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsxs)(`span`,{className:R,children:[W,G]})}),t[76]=R,t[77]=W,t[78]=G,t[79]=pe):pe=t[79];let K;t[80]!==v||t[81]!==S||t[82]!==u?(K=S?u:v({id:`YFpLoV`}),t[80]=v,t[81]=S,t[82]=u,t[83]=K):K=t[83];let me;t[84]===K?me=t[85]:(me=(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:K}),t[84]=K,t[85]=me);let he;t[86]!==pe||t[87]!==me?(he=(0,Q.jsxs)(m,{children:[pe,me]}),t[86]=pe,t[87]=me,t[88]=he):he=t[88];let ge;t[89]!==F||t[90]!==he?(ge=(0,Q.jsx)(I,{asChild:!0,showOnHover:!0,className:`pointer-events-none inset-y-0 top-0! end-0! z-10 aspect-auto h-auto w-auto overflow-visible rounded-none rounded-e-md bg-[var(--thread-row-bg)] p-1 opacity-0 shadow-none before:pointer-events-none before:absolute before:inset-y-0 before:end-full before:w-8 before:bg-[linear-gradient(to_right,transparent,var(--thread-row-bg))] after:hidden hover:bg-[var(--thread-row-bg)] group-focus-within/menu-item:pointer-events-auto group-hover/menu-item:pointer-events-auto rtl:before:bg-[linear-gradient(to_left,transparent,var(--thread-row-bg))]`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[F,he]})}),t[89]=F,t[90]=he,t[91]=ge):ge=t[91];let _e;return t[92]!==ie||t[93]!==C||t[94]!==ge?(_e=(0,Q.jsxs)(M,{className:C,children:[ie,ge]}),t[92]=ie,t[93]=C,t[94]=ge,t[95]=_e):_e=t[95],_e}function Wt(e){let t=(0,Lt.c)(54),{threads:n,openThreadIds:r,activeThreadId:i,onSelectThread:o,mode:s,panelId:c,onDismiss:l,newChatControl:u}=e,{_:h}=a(),g=(0,Z.use)(zt);if(g===null)throw Error(`ThreadHistoryPanel requires ThreadHistorySearchProvider`);let{query:_,setQuery:v}=g,[y,b]=(0,Z.useState)(Gt),x=(0,Z.useRef)(null),ee=(0,Z.useRef)(null),te=(0,Z.useRef)(s),S=(0,Z.useId)(),ne=h({id:`V0mbgd`}),C=_.trim().toLowerCase(),w=n.filter(e=>e.title.toLowerCase().includes(C)).sort(Kt),T=w.filter(e=>qt(e.lastActivityAt,y)),E=w.filter(e=>!qt(e.lastActivityAt,y)),D=[{key:`today`,label:h({id:`ecUA8p`}),threads:T},{key:`older`,label:h({id:`_fwE6J`}),threads:E}].filter($),O;t[0]===v?O=t[1]:(O=()=>{v(``),ee.current?.focus()},t[0]=v,t[1]=O);let re=O,A,ie;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(A=()=>{let e=setInterval(()=>b(Date.now()),Rt);return()=>clearInterval(e)},ie=[],t[2]=A,t[3]=ie):(A=t[2],ie=t[3]),(0,Z.useEffect)(A,ie);let ae,se;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(ae=()=>{ee.current?.focus({preventScroll:te.current===`cover`})},se=[],t[4]=ae,t[5]=se):(ae=t[4],se=t[5]),(0,Z.useEffect)(ae,se);let M;t[6]===h?M=t[7]:(M=h({id:`Sdv6pQ`}),t[6]=h,t[7]=M);let N;t[8]===l?N=t[9]:(N=e=>{e.key!==`Escape`||e.nativeEvent.isComposing||e.defaultPrevented||(e.preventDefault(),l(`explicit`))},t[8]=l,t[9]=N);let I;t[10]!==h||t[11]!==s||t[12]!==l?(I=s===`cover`?(0,Q.jsxs)(`div`,{className:`mb-2 flex h-8 items-center gap-1`,children:[(0,Q.jsxs)(m,{children:[(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":h({id:`iH8pgl`}),"data-testid":`agent-thread-history-back`,onClick:()=>l(`explicit`),children:(0,Q.jsx)(Re,{"aria-hidden":`true`})})}),(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:h({id:`iH8pgl`})})]}),(0,Q.jsx)(`h2`,{className:`font-mono text-xs font-normal uppercase tracking-wide text-muted-foreground`,children:h({id:`Sdv6pQ`})})]}):null,t[10]=h,t[11]=s,t[12]=l,t[13]=I):I=t[13];let le;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,Q.jsx)(ft,{children:(0,Q.jsx)(k,{"aria-hidden":`true`})}),t[14]=le):le=t[14];let R;t[15]===h?R=t[16]:(R=h({id:`eKGK4A`}),t[15]=h,t[16]=R);let de;t[17]===h?de=t[18]:(de=h({id:`a4xYoA`}),t[17]=h,t[18]=de);let V;t[19]===v?V=t[20]:(V=e=>v(e.target.value),t[19]=v,t[20]=V);let H;t[21]!==_||t[22]!==R||t[23]!==de||t[24]!==V?(H=(0,Q.jsx)(dt,{ref:ee,type:`search`,className:`[&::-webkit-search-cancel-button]:hidden`,name:`chat-history-search`,autoComplete:`off`,spellCheck:!1,value:_,"aria-label":R,placeholder:de,onChange:V}),t[21]=_,t[22]=R,t[23]=de,t[24]=V,t[25]=H):H=t[25];let fe;t[26]!==h||t[27]!==re||t[28]!==_?(fe=_===``?null:(0,Q.jsx)(ft,{align:`inline-end`,children:(0,Q.jsx)(pt,{size:`icon-xs`,"aria-label":h({id:`8SVvE7`}),onClick:re,children:(0,Q.jsx)(J,{"aria-hidden":`true`})})}),t[26]=h,t[27]=re,t[28]=_,t[29]=fe):fe=t[29];let U;t[30]!==H||t[31]!==fe?(U=(0,Q.jsxs)(mt,{className:`border-none bg-muted-foreground/5`,children:[le,H,fe]}),t[30]=H,t[31]=fe,t[32]=U):U=t[32];let W;t[33]!==I||t[34]!==U?(W=(0,Q.jsxs)(oe,{className:`shrink-0 gap-0`,children:[I,U]}),t[33]=I,t[34]=U,t[35]=W):W=t[35];let G=z,K=n.length===0?`flex min-h-0 flex-1 flex-col`:void 0,me=n.length===0?(0,Q.jsx)(P,{className:`min-h-32 p-4`,children:(0,Q.jsx)(B,{children:(0,Q.jsx)(ue,{className:`font-normal text-muted-foreground`,asChild:!0,children:(0,Q.jsx)(`h2`,{children:h({id:`r3iaI0`})})})})}):w.length===0?(0,Q.jsx)(`h2`,{className:`px-4 py-6 text-center text-sm font-normal text-muted-foreground`,children:h({id:`cnR7h2`})}):null,he;t[36]!==K||t[37]!==me?(he=(0,Q.jsx)(`div`,{role:`status`,"aria-atomic":`true`,className:K,children:me}),t[36]=K,t[37]=me,t[38]=he):he=t[38];let ge=D.map(e=>(0,Q.jsxs)(ce,{className:`mt-1 p-0 first:mt-0`,children:[(0,Q.jsx)(pe,{asChild:!0,className:`text-xs text-muted-foreground font-normal uppercase tracking-wide font-mono`,children:(0,Q.jsx)(`h2`,{id:`${S}-${e.key}`,children:e.label})}),(0,Q.jsx)(L,{children:(0,Q.jsx)(F,{"aria-labelledby":`${S}-${e.key}`,children:e.threads.map(e=>(0,Q.jsx)(Ut,{thread:e,openAsTab:r.has(e.threadId),active:i===e.threadId,mode:s,now:y,reasonId:S,openTabReason:ne,deleteDialogRef:x,onSelectThread:o,onDismiss:l},e.threadId))})})]},e.key)),_e;t[39]!==G||t[40]!==he||t[41]!==ge?(_e=(0,Q.jsxs)(G,{className:`px-1 pb-1 scroll-fade-mask`,children:[he,ge]}),t[39]=G,t[40]=he,t[41]=ge,t[42]=_e):_e=t[42];let ve;t[43]===u?ve=t[44]:(ve=u==null?null:(0,Q.jsx)(j,{className:`shrink-0 gap-0`,children:u}),t[43]=u,t[44]=ve);let ye;t[45]===Symbol.for(`react.memo_cache_sentinel`)?(ye=(0,Q.jsx)(Ht,{controllerRef:x}),t[45]=ye):ye=t[45];let be;return t[46]!==s||t[47]!==c||t[48]!==W||t[49]!==_e||t[50]!==ve||t[51]!==M||t[52]!==N?(be=(0,Q.jsxs)(`aside`,{id:c,"aria-label":M,className:`flex h-full min-h-0 w-full flex-col bg-muted/20 text-sidebar-foreground [--sidebar-accent-foreground:var(--foreground)]`,"data-testid":`agent-thread-history-panel`,"data-history-mode":s,onKeyDown:N,children:[W,_e,ve,ye]}),t[46]=s,t[47]=c,t[48]=W,t[49]=_e,t[50]=ve,t[51]=M,t[52]=N,t[53]=be):be=t[53],be}function $(e){return e.threads.length>0}function Gt(){return Date.now()}function Kt(e,t){return e.lastActivityAt===t.lastActivityAt?e.threadId<t.threadId?-1:+(e.threadId>t.threadId):t.lastActivityAt-e.lastActivityAt}function qt(e,t){let n=new Date(e),r=new Date(t);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate()}function Jt(e,t){let n=Math.max(0,t-e);if(n<6e4)return D._({id:`xOTzt5`});if(n<36e5){let e=Math.round(n/6e4);return D._({id:`_rP3HI`,values:{minutes:e}})}if(n<864e5){let e=Math.round(n/36e5);return D._({id:`nYeBmY`,values:{hours:e}})}let r=Math.round(n/864e5);return D._({id:`LPAv9E`,values:{days:r}})}var Yt=300,Xt=1;function Zt(e){return e>=248+Yt+Xt?`docked`:`cover`}function Qt(e,t){let n=(0,Lt.c)(9),[r,i]=(0,Z.useState)(`cover`),a,o;n[0]!==e||n[1]!==t?(a=()=>{if(!t||e==null)return;let n=0,r=()=>{window.cancelAnimationFrame(n),n=window.requestAnimationFrame(()=>{i(Zt(e.getBoundingClientRect().width))})};r();let a=new ResizeObserver(r);return a.observe(e),()=>{window.cancelAnimationFrame(n),a.disconnect()}},o=[e,t],n[0]=e,n[1]=t,n[2]=a,n[3]=o):(a=n[2],o=n[3]),(0,Z.useLayoutEffect)(a,o);let s;n[4]===e?s=n[5]:(s=()=>{e!=null&&i(Zt(e.getBoundingClientRect().width))},n[4]=e,n[5]=s);let c;return n[6]!==r||n[7]!==s?(c={mode:r,remeasure:s},n[6]=r,n[7]=s,n[8]=c):c=n[8],c}var $t=`ok-terminal-new-tab-bare-v1`;function en(e){try{return(e??localStorage).getItem($t)===`1`}catch{return!1}}function tn(e,t){try{let n=t??localStorage;e?n.setItem($t,`1`):n.removeItem($t)}catch{}for(let e of nn)e()}var nn=new Set;function rn(){return cn()}function an(){for(let e of nn)e()}typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`storage`,e=>{(e.key===`ok-terminal-new-tab-bare-v1`||e.key===null)&&an()});function on(e){return nn.add(e),()=>nn.delete(e)}function sn(){return(0,Z.useSyncExternalStore)(on,rn,rn)}function cn(){try{return typeof localStorage>`u`?!1:en()}catch{return!1}}var ln=N(()=>t(()=>import(`./TerminalPanel-B72jSABs.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71]),import.meta.url));function un(e){let t=(0,Lt.c)(24),{bridge:n,onClose:r,onTitleChange:i,launch:o,commandId:s,adoptPtyId:l,onPtyId:u}=e,d=o===void 0?null:o,f=s===void 0?null:s,p=l===void 0?null:l,{enabled:m,synced:h}=Nt(),g=Mt(),{_}=a(),v;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(v={enabled:null,hasSynced:!1},t[0]=v):v=t[0];let[y,b]=(0,Z.useState)(v),x,ee;t[1]!==m||t[2]!==h?(x=()=>{h&&b(e=>e.hasSynced&&e.enabled===m?e:{enabled:m,hasSynced:!0})},ee=[m,h],t[1]=m,t[2]=h,t[3]=x,t[4]=ee):(x=t[3],ee=t[4]),(0,Z.useEffect)(x,ee);let te=h||y.hasSynced,S=h?m:y.enabled,ne=te&&S===!1,C,T;t[5]===ne?(C=t[6],T=t[7]):(C=()=>{ne||ln.preload()},T=[ne],t[5]=ne,t[6]=C,t[7]=T),(0,Z.useEffect)(C,T);let E;t[8]!==_||t[9]!==g?(E=function(){if(g===null){w.error(_({id:`V_6bJ4`}));return}let e=g(!0);e.ok||w.error(_({id:`jKd3AP`,values:{0:e.error}}))},t[8]=_,t[9]=g,t[10]=E):E=t[10];let D=E;if(te&&!ne){let e;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(Pt,{}),t[11]=e):e=t[11];let a;return t[12]!==p||t[13]!==n||t[14]!==f||t[15]!==d||t[16]!==r||t[17]!==u||t[18]!==i?(a=(0,Q.jsx)(c,{fallbackRender:fn,onError:dn,children:(0,Q.jsx)(Z.Suspense,{fallback:e,children:(0,Q.jsx)(ln,{bridge:n,className:`h-full`,onClose:r,onTitleChange:i,launch:d,commandId:f,adoptPtyId:p,onPtyId:u})})}),t[12]=p,t[13]=n,t[14]=f,t[15]=d,t[16]=r,t[17]=u,t[18]=i,t[19]=a):a=t[19],a}let O;return t[20]!==D||t[21]!==ne||t[22]!==g?(O=ne?(0,Q.jsx)(hn,{enableDisabled:g===null,onEnable:D}):(0,Q.jsx)(Pt,{}),t[20]=D,t[21]=ne,t[22]=g,t[23]=O):O=t[23],O}function dn(e,t){console.error(`[TerminalGate] rendered fallback for the terminal panel`,e,t.componentStack)}function fn(e){return(0,Q.jsx)(pn,{...e})}function pn(e){let t=(0,Lt.c)(15),{error:n}=e,{_:r}=a(),i;t[0]!==r||t[1]!==n?(i=n instanceof Error&&/dynamically imported module|Failed to fetch/i.test(n.message)?r({id:`Y8ViJx`}):r({id:`fbsiBw`}),t[0]=r,t[1]=n,t[2]=i):i=t[2];let o=i,s;t[3]===r?s=t[4]:(s=r({id:`6MnZEC`}),t[3]=r,t[4]=s);let c;t[5]===o?c=t[6]:(c=(0,Q.jsx)(`p`,{className:`max-w-sm text-sm text-foreground`,children:o}),t[5]=o,t[6]=c);let l;t[7]===r?l=t[8]:(l=r({id:`HpK_8d`}),t[7]=r,t[8]=l);let u;t[9]===l?u=t[10]:(u=(0,Q.jsx)(d,{onClick:mn,children:l}),t[9]=l,t[10]=u);let f;return t[11]!==s||t[12]!==c||t[13]!==u?(f=(0,Q.jsxs)(`section`,{"aria-label":s,className:`flex h-full w-full flex-col items-center justify-center gap-3 bg-background p-6 text-center`,role:`alert`,children:[c,u]}),t[11]=s,t[12]=c,t[13]=u,t[14]=f):f=t[14],f}function mn(){return window.location.reload()}function hn(e){let t=(0,Lt.c)(27),{enableDisabled:n,onEnable:r}=e,{_:i}=a(),o=(0,Z.useId)(),s;t[0]===i?s=t[1]:(s=i({id:`_XWY2J`}),t[0]=i,t[1]=s);let c;t[2]===i?c=t[3]:(c=i({id:`oYepHb`}),t[2]=i,t[3]=c);let l;t[4]===c?l=t[5]:(l=(0,Q.jsx)(`p`,{className:`max-w-sm text-sm text-foreground`,children:c}),t[4]=c,t[5]=l);let u=n?o:void 0,f;t[6]===i?f=t[7]:(f=i({id:`v2ZW0K`}),t[6]=i,t[7]=f);let p;t[8]!==n||t[9]!==r||t[10]!==u||t[11]!==f?(p=(0,Q.jsx)(d,{disabled:n,"aria-describedby":u,onClick:r,children:f}),t[8]=n,t[9]=r,t[10]=u,t[11]=f,t[12]=p):p=t[12];let m;t[13]!==i||t[14]!==n||t[15]!==o?(m=n?(0,Q.jsx)(`p`,{id:o,className:`text-xs text-muted-foreground`,children:i({id:`V_6bJ4`})}):null,t[13]=i,t[14]=n,t[15]=o,t[16]=m):m=t[16];let h;t[17]===i?h=t[18]:(h=i({id:`ICoNYz`}),t[17]=i,t[18]=h);let g;t[19]===h?g=t[20]:(g=(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:h}),t[19]=h,t[20]=g);let _;return t[21]!==s||t[22]!==l||t[23]!==p||t[24]!==m||t[25]!==g?(_=(0,Q.jsxs)(`section`,{"aria-label":s,className:`flex h-full w-full flex-col items-center justify-center gap-3 bg-background p-6 text-center`,children:[l,p,m,g]}),t[21]=s,t[22]=l,t[23]=p,t[24]=m,t[25]=g,t[26]=_):_=t[26],_}function gn(e){let t=(0,Lt.c)(118),{selected:n,onLaunchSelected:r,showAgents:o,registeredAgents:s,onPickAgent:c,onOpenSettings:u,liveThreadCount:h,agentPickPending:g,showClis:_,onPickCli:v,onPickTerminal:y,visibleClis:b,className:ee,presentation:te}=e,S=g===void 0?!1:g,w=b===void 0?Y:b,T=te===void 0?`toolbar`:te,{_:E}=a(),[D,k]=(0,Z.useState)(!1),re=h>=(ne(D&&o).data?.maxThreads??8),A=re||S,ae=o||_,oe=T===`panel`,se=n.kind===`agent`?n.agent?.name:void 0,ce;t[0]!==E||t[1]!==se||t[2]!==n.cli||t[3]!==n.kind?(ce=n.kind===`terminal`?E({id:`AB4qw9`}):n.kind===`cli`?E({id:`nP-KFo`,values:{0:C[n.cli].displayName}}):E(se===void 0?{id:`G7bn_N`}:{id:`iSguIe`,values:{agentName:se}}),t[0]=E,t[1]=se,t[2]=n.cli,t[3]=n.kind,t[4]=ce):ce=t[4];let j=ce,M;t[5]!==E||t[6]!==se||t[7]!==oe||t[8]!==j?(M=oe&&se!==void 0?E({id:`hIQkLb`}):j,t[5]=E,t[6]=se,t[7]=oe,t[8]=j,t[9]=M):M=t[9];let N=M;if(oe){let e;t[10]===ee?e=t[11]:(e=l(`w-full`,ee),t[10]=ee,t[11]=e);let a;t[12]===n?a=t[13]:(a=n.kind===`terminal`?null:(0,Q.jsx)(bn,{selected:n,className:`size-4`}),t[12]=n,t[13]=a);let d;t[14]===N?d=t[15]:(d=(0,Q.jsx)(`span`,{className:`truncate`,children:N}),t[14]=N,t[15]=d);let f;t[16]!==a||t[17]!==d?(f=(0,Q.jsxs)(Q.Fragment,{children:[a,d]}),t[16]=a,t[17]=d,t[18]=f):f=t[18];let p;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(p=[],t[19]=p):p=t[19];let m;t[20]!==A||t[21]!==c||t[22]!==s||t[23]!==n.agent?.id||t[24]!==n.agent?.source||t[25]!==n.kind||t[26]!==o?(m=o?s.map(e=>({key:`${e.source}:${e.id}`,id:e.id,name:e.name,...e.iconUrl===void 0?{}:{iconUrl:e.iconUrl},selected:n.kind===`agent`&&n.agent?.source===e.source&&n.agent?.id===e.id,disabled:A,onSelect:()=>c(e)})):void 0,t[20]=A,t[21]=c,t[22]=s,t[23]=n.agent?.id,t[24]=n.agent?.source,t[25]=n.kind,t[26]=o,t[27]=m):m=t[27];let h;t[28]===re?h=t[29]:(h=re?(0,Q.jsx)(We,{className:`py-1 font-normal text-muted-foreground text-xs`,"data-testid":`terminal-new-chat-cap`,children:(0,Q.jsx)(i,{id:`0QVrvp`})}):void 0,t[28]=re,t[29]=h);let g;t[30]!==E||t[31]!==v||t[32]!==n.cli||t[33]!==n.kind||t[34]!==_||t[35]!==w?(g=_?w.map(e=>({cli:e,label:C[e].displayName,ariaLabel:E({id:`yxH4Gs`,values:{0:C[e].displayName}}),selected:n.kind===`cli`&&n.cli===e,onSelect:()=>v(e)})):void 0,t[30]=E,t[31]=v,t[32]=n.cli,t[33]=n.kind,t[34]=_,t[35]=w,t[36]=g):g=t[36];let b;t[37]!==E||t[38]!==y||t[39]!==n.kind||t[40]!==_?(b=_?{selected:n.kind===`terminal`,onSelect:y,label:E({id:`ALhMYW`}),icon:(0,Q.jsx)(H,{"aria-hidden":`true`,className:`size-4`}),ariaLabel:E({id:`ALhMYW`}),testId:`terminal-new-chat-terminal`}:void 0,t[37]=E,t[38]=y,t[39]=n.kind,t[40]=_,t[41]=b):b=t[41];let x;t[42]===E?x=t[43]:(x=E({id:`gzaLgh`}),t[42]=E,t[43]=x);let te;t[44]===s?te=t[45]:(te={primary:`terminal-new-chat`,trigger:`terminal-new-chat-menu`,menu:`terminal-new-chat-menu-content`,option:vn,terminal:_n,threadAgent:e=>`terminal-new-chat-agent-${s.find(t=>`${t.source}:${t.id}`===e)?.id??e}`,settings:`terminal-new-chat-settings`},t[44]=s,t[45]=te);let S;return t[46]!==r||t[47]!==u||t[48]!==j||t[49]!==m||t[50]!==h||t[51]!==g||t[52]!==b||t[53]!==x||t[54]!==te||t[55]!==e||t[56]!==f?(S=(0,Q.jsx)(fe,{className:e,primaryClassName:`min-w-0 flex-1 justify-start`,primary:f,primaryAriaLabel:j,onPrimary:r,enabledTargets:p,selectedTargetId:null,onSelectTarget:yn,threadAgents:m,threadAgentsFooter:h,terminals:g,terminal:b,onOpenSettings:u,onMenuOpenChange:k,menuAlign:`start`,triggerAriaLabel:x,testIds:te}),t[46]=r,t[47]=u,t[48]=j,t[49]=m,t[50]=h,t[51]=g,t[52]=b,t[53]=x,t[54]=te,t[55]=e,t[56]=f,t[57]=S):S=t[57],S}let P;t[58]===ee?P=t[59]:(P=l(`flex shrink-0 items-center`,ee),t[58]=ee,t[59]=P);let F=ae&&`rounded-r-none`,I;t[60]===F?I=t[61]:(I=l(`cursor-pointer gap-0.5 px-1.5 text-muted-foreground hover:text-foreground`,F),t[60]=F,t[61]=I);let L;t[62]===n?L=t[63]:(L=n.kind===`terminal`?null:(0,Q.jsx)(bn,{selected:n,className:`size-3.5`}),t[62]=n,t[63]=L);let le;t[64]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,Q.jsx)(O,{"aria-hidden":`true`,className:`size-3`}),t[64]=le):le=t[64];let R;t[65]!==r||t[66]!==j||t[67]!==I||t[68]!==L?(R=(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsxs)(d,{type:`button`,variant:`ghost`,size:`xs`,"aria-label":j,"data-testid":`terminal-new-chat`,className:I,onClick:r,children:[L,le]})}),t[65]=r,t[66]=j,t[67]=I,t[68]=L,t[69]=R):R=t[69];let z;t[70]===j?z=t[71]:(z=(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:j}),t[70]=j,t[71]=z);let B;t[72]!==R||t[73]!==z?(B=(0,Q.jsxs)(m,{children:[R,z]}),t[72]=R,t[73]=z,t[74]=B):B=t[74];let ue;t[75]!==E||t[76]!==ae?(ue=ae?(0,Q.jsx)(He,{asChild:!0,children:(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":E({id:`l87Deg`}),"data-testid":`terminal-new-chat-menu`,className:`cursor-pointer rounded-s-none text-muted-foreground hover:text-foreground`,children:(0,Q.jsx)(ze,{"aria-hidden":`true`,className:`size-3`})})}):null,t[75]=E,t[76]=ae,t[77]=ue):ue=t[77];let de;t[78]!==E||t[79]!==A||t[80]!==re||t[81]!==c||t[82]!==s||t[83]!==n.agent?.id||t[84]!==n.agent?.source||t[85]!==n.kind||t[86]!==o?(de=o&&s.length>0?(0,Q.jsxs)(Ue,{"aria-label":E({id:`RXEbZy`}),children:[(0,Q.jsx)(We,{children:(0,Q.jsx)(i,{id:`RXEbZy`})}),s.map(e=>{let t=n.kind===`agent`&&n.agent?.source===e.source&&n.agent?.id===e.id;return(0,Q.jsxs)(Ve,{onSelect:()=>c(e),disabled:A,"data-testid":`terminal-new-chat-agent-${e.id}`,"aria-current":t?`true`:void 0,children:[(0,Q.jsx)(x,{agentId:e.id,iconUrl:e.iconUrl,className:`size-4`}),(0,Q.jsx)(`span`,{className:`flex-1 truncate`,children:e.name}),t?(0,Q.jsx)(Le,{"aria-hidden":`true`,className:`size-4 text-muted-foreground`}):null]},`${e.source}:${e.id}`)}),re?(0,Q.jsx)(We,{className:`py-1 font-normal text-muted-foreground text-xs`,"data-testid":`terminal-new-chat-cap`,children:(0,Q.jsx)(i,{id:`0QVrvp`})}):null]}):null,t[78]=E,t[79]=A,t[80]=re,t[81]=c,t[82]=s,t[83]=n.agent?.id,t[84]=n.agent?.source,t[85]=n.kind,t[86]=o,t[87]=de):de=t[87];let V;t[88]!==s||t[89]!==o||t[90]!==_?(V=o&&s.length>0&&_?(0,Q.jsx)(q,{}):null,t[88]=s,t[89]=o,t[90]=_,t[91]=V):V=t[91];let U;t[92]!==E||t[93]!==v||t[94]!==y||t[95]!==n.cli||t[96]!==n.kind||t[97]!==_||t[98]!==w?(U=_?(0,Q.jsxs)(Ue,{"aria-label":E({id:`ALhMYW`}),children:[(0,Q.jsx)(We,{children:(0,Q.jsx)(i,{id:`ALhMYW`})}),w.map(e=>{let{displayName:t}=C[e],r=n.kind===`cli`&&n.cli===e;return(0,Q.jsxs)(Ve,{onSelect:()=>v(e),"data-testid":`terminal-new-chat-cli-${e}`,"aria-label":E({id:`9mEZeD`,values:{name:t}}),"aria-current":r?`true`:void 0,children:[(0,Q.jsx)(Fe,{id:et(e),className:`size-4`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`flex-1`,children:t}),r?(0,Q.jsx)(Le,{"aria-hidden":`true`,className:`size-4 text-muted-foreground`}):null]},e)}),(0,Q.jsxs)(Ve,{onSelect:y,"data-testid":`terminal-new-chat-terminal`,"aria-current":n.kind===`terminal`?`true`:void 0,children:[(0,Q.jsx)(H,{"aria-hidden":`true`,className:`size-4`}),(0,Q.jsx)(`span`,{className:`flex-1`,children:(0,Q.jsx)(i,{id:`ALhMYW`})}),n.kind===`terminal`?(0,Q.jsx)(Le,{"aria-hidden":`true`,className:`size-4 text-muted-foreground`}):null]})]}):null,t[92]=E,t[93]=v,t[94]=y,t[95]=n.cli,t[96]=n.kind,t[97]=_,t[98]=w,t[99]=U):U=t[99];let W;t[100]!==u||t[101]!==s||t[102]!==o||t[103]!==_?(W=o?(0,Q.jsxs)(Q.Fragment,{children:[s.length>0||_?(0,Q.jsx)(q,{}):null,(0,Q.jsxs)(Ve,{onSelect:u,"data-testid":`terminal-new-chat-settings`,children:[(0,Q.jsx)(ie,{"aria-hidden":`true`,className:`size-4 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`flex-1`,children:(0,Q.jsx)(i,{id:`jRAGrQ`})})]})]}):null,t[100]=u,t[101]=s,t[102]=o,t[103]=_,t[104]=W):W=t[104];let G;t[105]!==de||t[106]!==V||t[107]!==U||t[108]!==W?(G=(0,Q.jsxs)(Ge,{align:`start`,className:`max-h-80 min-w-[200px]`,children:[de,V,U,W]}),t[105]=de,t[106]=V,t[107]=U,t[108]=W,t[109]=G):G=t[109];let pe;t[110]!==D||t[111]!==ue||t[112]!==G?(pe=(0,Q.jsxs)(Ke,{open:D,onOpenChange:k,children:[ue,G]}),t[110]=D,t[111]=ue,t[112]=G,t[113]=pe):pe=t[113];let K;return t[114]!==B||t[115]!==pe||t[116]!==P?(K=(0,Q.jsxs)(`div`,{className:P,children:[B,pe]}),t[114]=B,t[115]=pe,t[116]=P,t[117]=K):K=t[117],K}function _n(e){return`terminal-new-chat-cli-${e}`}function vn(e){return`terminal-new-chat-option-${e}`}function yn(){}function bn(e){let t=(0,Lt.c)(13),{selected:n,className:r}=e;if(n.kind===`terminal`){let e;return t[0]===r?e=t[1]:(e=(0,Q.jsx)(H,{"aria-hidden":`true`,className:r}),t[0]=r,t[1]=e),e}if(n.kind===`cli`){let e;t[2]===n.cli?e=t[3]:(e=et(n.cli),t[2]=n.cli,t[3]=e);let i;return t[4]!==r||t[5]!==e?(i=(0,Q.jsx)(Fe,{id:e,className:r,"aria-hidden":`true`}),t[4]=r,t[5]=e,t[6]=i):i=t[6],i}if(n.agent!==null){let e;return t[7]!==r||t[8]!==n.agent.iconUrl||t[9]!==n.agent.id?(e=(0,Q.jsx)(x,{agentId:n.agent.id,iconUrl:n.agent.iconUrl,className:r}),t[7]=r,t[8]=n.agent.iconUrl,t[9]=n.agent.id,t[10]=e):e=t[10],e}let i;return t[11]===r?i=t[12]:(i=(0,Q.jsx)(b,{"aria-hidden":`true`,className:r}),t[11]=r,t[12]=i),i}var xn=`[data-terminal-tab-sortable]`;function Sn(e){let t=(0,Lt.c)(11),{id:n,disabled:r,children:i}=e,a;t[0]!==r||t[1]!==n?(a={id:n,disabled:r},t[0]=r,t[1]=n,t[2]=a):a=t[2];let{setNodeRef:o,listeners:s,rect:c,transform:l,transition:u,isDragging:d}=rt(a),f;return t[3]!==i||t[4]!==d||t[5]!==s||t[6]!==c.current?.width||t[7]!==o||t[8]!==l||t[9]!==u?(f=i({setNodeRef:o,listeners:s,style:U({activeWidth:c.current?.width,isDragging:d,transform:l,transition:u})}),t[3]=i,t[4]=d,t[5]=s,t[6]=c.current?.width,t[7]=o,t[8]=l,t[9]=u,t[10]=f):f=t[10],f}function Cn(e){let t=(0,Lt.c)(11),{children:n,onMoveRight:r}=e,a=(0,Z.useRef)(null);if(r==null)return n;let o;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=e=>{if(!R(e))return;e.preventDefault(),a.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=e.currentTarget.getBoundingClientRect();e.currentTarget.dispatchEvent(new MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,clientX:t.left,clientY:t.bottom}))},t[0]=o):o=t[0];let s;t[1]===n?s=t[2]:(s=(0,Q.jsx)($e,{asChild:!0,onKeyDown:o,children:n}),t[1]=n,t[2]=s);let c;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>{a.current!=null&&(e.preventDefault(),a.current.focus(),a.current=null)},t[3]=c):c=t[3];let l,u;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,Q.jsx)(me,{"aria-hidden":`true`}),u=(0,Q.jsx)(i,{id:`jcEoUi`}),t[4]=l,t[5]=u):(l=t[4],u=t[5]);let d;t[6]===r?d=t[7]:(d=(0,Q.jsx)(X,{onCloseAutoFocus:c,children:(0,Q.jsx)(tt,{children:(0,Q.jsxs)(Ze,{onSelect:r,children:[l,u]})})}),t[6]=r,t[7]=d);let f;return t[8]!==s||t[9]!==d?(f=(0,Q.jsxs)(Qe,{children:[s,d]}),t[8]=s,t[9]=d,t[10]=f):f=t[10],f}function wn(e){let t=(0,Lt.c)(111),{sessions:n,sessionKind:r,activeSessionId:o,onSelect:s,onTabActivate:c,newButton:u,trailingControls:h,onClose:g,onRename:_,onReorder:v,onDragActiveChange:y,edge:b,onPlacementChange:x,reserveRightRevealTabGutter:ee,onCollapse:te,children:S,className:ne,draggable:C}=e,{_:w}=a(),T=b===`right`,E=T?`bottom`:`right`,D;t[0]!==w||t[1]!==T?(D=w(T?{id:`Tofsyo`}:{id:`PrWQiT`}),t[0]=w,t[1]=T,t[2]=D):D=t[2];let O=D,k;t[3]!==b||t[4]!==x||t[5]!==r?(k=r===`terminal`&&b===`bottom`&&x!=null?()=>x(`right`):void 0,t[3]=b,t[4]=x,t[5]=r,t[6]=k):k=t[6];let re=k,[A,ie]=(0,Z.useState)(null),[ae,oe]=(0,Z.useState)(``),[ce,j]=(0,Z.useState)(null),M=(0,Z.useRef)(null),N=(0,Z.useRef)(!1),P=_!=null,F,I;t[7]===A?(F=t[8],I=t[9]):(F=()=>{A!=null&&(M.current?.focus(),M.current?.select())},I=[A],t[7]=A,t[8]=F,t[9]=I),(0,Z.useEffect)(F,I);let L,le;t[10]!==A||t[11]!==n?(L=()=>{A!=null&&!n.some(e=>e.id===A)&&(N.current=!1,ie(null),oe(``))},le=[n,A],t[10]=A,t[11]=n,t[12]=L,t[13]=le):(L=t[12],le=t[13]),(0,Z.useEffect)(L,le);let R=function(e){P&&(N.current=!1,ie(e.id),oe(e.label))},z;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(z=function(e){let t=typeof CSS<`u`&&CSS.escape?CSS.escape(e):e;queueMicrotask(()=>{document.querySelector(`[role="tab"][data-tab-id="${t}"]`)?.focus()})},t[14]=z):z=t[14];let B=z,ue=function(e){N.current||_?.(e,ae.trim()),N.current=!1,ie(null),oe(``),B(e)},de=(0,Z.useRef)(null),H=(0,Z.useRef)(null),[fe,U]=(0,Z.useState)(null),G;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(G={activationConstraint:{distance:8}},t[15]=G):G=t[15];let pe=at(ot(it,G)),he=v!=null,ge;t[16]===fe?ge=t[17]:(ge=xe(fe),t[16]=fe,t[17]=ge);let _e;t[18]===ge?_e=t[19]:(_e=[ge],t[18]=ge,t[19]=_e);let ye=_e,be;t[20]!==o||t[21]!==n?(be=o===``?null:`${o}\u0000${n.map(Dn).join(`\0`)}`,t[20]=o,t[21]=n,t[22]=be):be=t[22];let Se=be,we,Te;t[23]===Se?(we=t[24],Te=t[25]):(we=()=>{if(Se===null)return;let[e]=Se.split(`\0`,1),t=typeof CSS<`u`&&CSS.escape?CSS.escape(e):e;H.current?.querySelector(`[data-tab-id="${t}"]`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},Te=[Se],t[23]=Se,t[24]=we,t[25]=Te),(0,Z.useEffect)(we,Te);let Ee;t[26]===y?Ee=t[27]:(Ee=function(){U(Ce(de.current,xn)),y?.(!0)},t[26]=y,t[27]=Ee);let De=Ee,Oe;t[28]!==y||t[29]!==v||t[30]!==n?(Oe=function(e){U(null),y?.(!1);let t=String(e.active.id),r=e.over?String(e.over.id):null;if(!r||t===r)return;let i=n.map(En),a=i.indexOf(t),o=i.indexOf(r);a<0||o<0||a===o||v?.(st(i,a,o))},t[28]=y,t[29]=v,t[30]=n,t[31]=Oe):Oe=t[31];let ke=Oe,Ae;t[32]===y?Ae=t[33]:(Ae=function(){U(null),y?.(!1)},t[32]=y,t[33]=Ae);let je=Ae,Me=Et,Ne;t[34]===ne?Ne=t[35]:(Ne=l(`flex min-h-0 min-w-0 flex-1 flex-col`,ne),t[34]=ne,t[35]=Ne);let Pe=Cn,Fe=C?``:void 0,Ie=T&&ee&&`pr-9`,Le=C&&`h-[62px] [-webkit-app-region:drag] pr-[22px] pl-[calc(var(--ok-titlebar-reserve-left,1rem)+0.75rem)]`,Re;t[36]!==Ie||t[37]!==Le?(Re=l(`flex shrink-0 flex-row items-center gap-1 px-1.5 py-1`,Ie,Le),t[36]=Ie,t[37]=Le,t[38]=Re):Re=t[38];let Ve=lt,He=se,Ue;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(Ue={container:typeof document<`u`?document.body:void 0},t[39]=Ue):Ue=t[39];let We=ut,Ge;t[40]===n?Ge=t[41]:(Ge=n.map(Tn),t[40]=n,t[41]=Ge);let Ke=ct,q=ve,qe=C&&`[-webkit-app-region:no-drag]`,Je;t[42]===qe?Je=t[43]:(Je=l(`grid h-auto w-fit max-w-full min-w-0 grid-flow-col items-center justify-start gap-0.5 overflow-x-auto overflow-y-hidden [grid-auto-columns:minmax(8rem,9rem)] [scrollbar-width:none] scroll-fade-mask-x`,qe),t[42]=qe,t[43]=Je);let Ye;t[44]!==w||t[45]!==r?(Ye=w(r===`agent`?{id:`GjsGAu`}:{id:`1MGRQl`}),t[44]=w,t[45]=r,t[46]=Ye):Ye=t[46];let Xe=n.map((e,t)=>{let n=e.id===o,r=ce===e.id,i=A===e.id;return(0,Q.jsx)(Sn,{id:e.id,disabled:!he||A!=null,children:a=>{let{setNodeRef:o,listeners:s,style:u}=a;return(0,Q.jsxs)(m,{children:[(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsxs)(Ct,{ref:o,value:e.id,"data-terminal-tab-sortable":``,"data-tab-id":e.id,style:{...u,gridColumn:t+1,gridRow:1},...s,onMouseEnter:()=>j(e.id),onMouseLeave:()=>j(null),onClick:t=>{t.detail>=2||c?.(e.id)},onDoubleClick:()=>R(e),onKeyDown:t=>{t.key===`F2`&&(t.preventDefault(),R(e))},className:l(`h-7 flex-none justify-start gap-1.5 rounded-md py-0 pr-7 pl-2 text-left text-1sm transition-colors motion-reduce:transition-none`,n?V:r&&`bg-sidebar-hover! text-sidebar-hover-foreground!`,i&&`w-full opacity-0`,C&&`[-webkit-app-region:no-drag]`),children:[e.icon,(0,Q.jsx)(`span`,{className:l(`min-w-0 flex-1`,n||r?K:`truncate`),children:e.label})]})}),(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:e.label})]})}},e.id)}),Ze;t[47]!==Ye||t[48]!==Xe?(Ze=(0,Q.jsx)(Tt,{ref:H,variant:`line`,"aria-label":Ye,className:`contents`,children:Xe}),t[47]=Ye,t[48]=Xe,t[49]=Ze):Ze=t[49];let Qe=n.map((e,t)=>{let n=e.id===o;return A===e.id?(0,Q.jsx)(mt,{style:{gridColumn:t+1,gridRow:1},className:l(`z-20 h-7 w-full rounded-md border-0 bg-transparent dark:bg-transparent`,C&&`[-webkit-app-region:no-drag]`),children:(0,Q.jsx)(dt,{ref:M,value:ae,"aria-label":w({id:`0TnCvC`,values:{0:e.label}}),"data-testid":`terminal-tab-rename-input`,className:`h-7 px-2 text-1sm`,onChange:e=>oe(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),M.current?.blur()):e.key===`Escape`&&(e.preventDefault(),N.current=!0,M.current?.blur())},onBlur:()=>ue(e.id)})},e.id):(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":w({id:`nzHlj8`,values:{0:e.label}}),tabIndex:n?0:-1,style:{gridColumn:t+1,gridRow:1},className:l(W,`z-20 mr-0.5 justify-self-end opacity-0 transition-opacity focus-visible:opacity-100`,(n||ce===e.id)&&`opacity-100`,fe!=null&&`pointer-events-none opacity-0`,C&&`[-webkit-app-region:no-drag]`),onMouseEnter:()=>j(e.id),onMouseLeave:()=>j(null),onClick:t=>{t.stopPropagation(),g(e.id)},children:(0,Q.jsx)(J,{"aria-hidden":`true`})},e.id)}),$e;t[50]===Qe?$e=t[51]:($e=(0,Q.jsx)(`div`,{className:`contents`,children:Qe}),t[50]=Qe,t[51]=$e);let Y;t[52]!==q||t[53]!==Je||t[54]!==Ze||t[55]!==$e?(Y=(0,Q.jsxs)(`div`,{onWheel:q,className:Je,children:[Ze,$e]}),t[52]=q,t[53]=Je,t[54]=Ze,t[55]=$e,t[56]=Y):Y=t[56];let X;t[57]!==We||t[58]!==Ge||t[59]!==Ke||t[60]!==Y?(X=(0,Q.jsx)(We,{items:Ge,strategy:Ke,children:Y}),t[57]=We,t[58]=Ge,t[59]=Ke,t[60]=Y,t[61]=X):X=t[61];let et;t[62]!==Ve||t[63]!==je||t[64]!==ke||t[65]!==De||t[66]!==ye||t[67]!==pe||t[68]!==!1||t[69]!==He||t[70]!==Ue||t[71]!==X?(et=(0,Q.jsx)(Ve,{sensors:pe,autoScroll:!1,collisionDetection:He,modifiers:ye,onDragStart:De,onDragEnd:ke,onDragCancel:je,accessibility:Ue,children:X}),t[62]=Ve,t[63]=je,t[64]=ke,t[65]=De,t[66]=ye,t[67]=pe,t[68]=!1,t[69]=He,t[70]=Ue,t[71]=X,t[72]=et):et=t[72];let tt;t[73]!==C||t[74]!==u?(tt=u==null?null:(0,Q.jsx)(`div`,{className:l(`shrink-0`,C&&`[-webkit-app-region:no-drag]`),children:u}),t[73]=C,t[74]=u,t[75]=tt):tt=t[75];let nt;t[76]===Symbol.for(`react.memo_cache_sentinel`)?(nt=(0,Q.jsx)(`div`,{className:`flex-1`}),t[76]=nt):nt=t[76];let rt;t[77]!==C||t[78]!==h?(rt=h==null?null:(0,Q.jsx)(`div`,{className:l(`shrink-0`,C&&`[-webkit-app-region:no-drag]`),children:h}),t[77]=C,t[78]=h,t[79]=rt):rt=t[79];let ft;t[80]!==b||t[81]!==x||t[82]!==O||t[83]!==E||t[84]!==T||t[85]!==r?(ft=r===`terminal`&&b!=null&&x!=null?(0,Q.jsxs)(m,{children:[(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":O,className:`shrink-0 cursor-pointer text-muted-foreground hover:text-foreground`,onClick:()=>x(E),children:T?(0,Q.jsx)(Ft,{"aria-hidden":`true`}):(0,Q.jsx)(me,{"aria-hidden":`true`})})}),(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:O})]}):null,t[80]=b,t[81]=x,t[82]=O,t[83]=E,t[84]=T,t[85]=r,t[86]=ft):ft=t[86];let pt;t[87]!==w||t[88]!==te||t[89]!==T||t[90]!==r?(pt=te==null?null:(0,Q.jsxs)(m,{children:[(0,Q.jsx)(f,{asChild:!0,children:(0,Q.jsx)(d,{type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":w(r===`terminal`?{id:`MU_NVW`}:{id:`g5V4_P`}),className:`shrink-0 cursor-pointer text-muted-foreground hover:text-foreground`,onClick:te,children:T?(0,Q.jsx)(Be,{"aria-hidden":`true`}):(0,Q.jsx)(ze,{"aria-hidden":`true`})})}),(0,Q.jsx)(p,{side:`bottom`,sideOffset:8,children:r===`terminal`?(0,Q.jsx)(i,{id:`MU_NVW`}):(0,Q.jsx)(i,{id:`g5V4_P`})})]}),t[87]=w,t[88]=te,t[89]=T,t[90]=r,t[91]=pt):pt=t[91];let ht;t[92]!==Fe||t[93]!==Re||t[94]!==et||t[95]!==tt||t[96]!==rt||t[97]!==ft||t[98]!==pt?(ht=(0,Q.jsxs)(`div`,{ref:de,"data-terminal-tab-row":``,"data-electron-drag":Fe,className:Re,children:[et,tt,nt,rt,ft,pt]}),t[92]=Fe,t[93]=Re,t[94]=et,t[95]=tt,t[96]=rt,t[97]=ft,t[98]=pt,t[99]=ht):ht=t[99];let gt;t[100]!==Pe||t[101]!==re||t[102]!==ht?(gt=(0,Q.jsx)(Pe,{onMoveRight:re,children:ht}),t[100]=Pe,t[101]=re,t[102]=ht,t[103]=gt):gt=t[103];let _t;return t[104]!==Me||t[105]!==o||t[106]!==S||t[107]!==s||t[108]!==Ne||t[109]!==gt?(_t=(0,Q.jsxs)(Me,{value:o,onValueChange:s,className:Ne,children:[gt,S]}),t[104]=Me,t[105]=o,t[106]=S,t[107]=s,t[108]=Ne,t[109]=gt,t[110]=_t):_t=t[110],_t}function Tn(e){return e.id}function En(e){return e.id}function Dn(e){return e.id}var On=(0,Z.lazy)(()=>t(()=>import(`./ThreadView-CeGUJ4X2.js`).then(e=>({default:e.ThreadView})),__vite__mapDeps([72,1,3,2,4,5,6,7,8,9,31,10,11,12,73,33,14,34,44,45,46,40,36,16,17,15,74,75,76,77,78,79,80,81,82,83,84,85,86,21,87,88,89,90,68,69,91,92,93,56,37,39,19,41,94,95,35,96,97,98,99,100,27,26,28,101,70,102,103,104,13,105,106,107,18,63,20,58,108,109,110,111,112,113,114,115,48,23,42,116,117,50,118,25,62,119,120,121,122,123,124,125,126,127,128,53,54,55,57,129,24,130,131,132,133,134,135,59,136,65,137,138,139,140,141,61,142,143,144,145,146,147,148,149,66]),import.meta.url));function kn(e,t){if(t.length!==e.length)return null;let n=new Map(e.map(e=>[e.id,e])),r=[];for(let e of t){let t=n.get(e);if(t==null)return null;r.push(t)}return r.every((t,n)=>t===e[n])?null:r}function An(e){return`terminal-session-${e}`}function jn(e){return typeof CSS<`u`&&CSS.escape?CSS.escape(e):e}function Mn(e){return`[data-terminal-session="${jn(e)}"] .xterm-helper-textarea`}function Nn(e){return`[data-session-id="${jn(e)}"] [data-testid="agent-thread-composer"]`}function Pn(e){if(e===``)return!1;let t=document.querySelector(Mn(e));return t?.focus(),t!=null&&document.activeElement===t}function Fn(e){let t=typeof CSS<`u`&&CSS.escape?CSS.escape(e):e;return document.querySelector(`[role="tab"][data-tab-id="${t}"]`)}function In(e){if(e===``)return!1;let t=document.querySelector(Nn(e));return t?.focus(),t!=null&&document.activeElement===t?!0:(Fn(e)?.focus(),!1)}function Ln(e){return e.kind===`terminal`?Pn(e.id):In(e.id)}function Rn(e){return e.kind===`thread`?Fn(e.id):null}function zn(e){return e?.contains(document.activeElement)??!1}function Bn(e){if(e==null||e.disabled||e.tabIndex<0||!e.isConnected||e.closest(`[aria-disabled="true"], [hidden], [inert], [aria-hidden="true"]`)!=null)return null;let t=e;for(;t!=null;){let e=window.getComputedStyle(t);if(e.display===`none`||e.visibility===`hidden`)return null;t=t.parentElement}return e.focus(),document.activeElement===e?e:null}function Vn(e){return e.querySelector(`[data-testid="terminal-new-chat"]`)}function Hn(e,t){return t||zn(e)}function Un(e){switch(e){case`running`:return`bg-amber-500 animate-pulse`;case`installing`:case`spawning`:case`authenticating`:return`bg-sky-500 animate-pulse`;case`auth_required`:case`awaiting_permission`:return`bg-amber-500`;case`ready`:return`bg-emerald-500`;case`error`:return`bg-red-500`;default:return`bg-muted-foreground`}}function Wn(){return(0,Q.jsx)(H,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`})}var Gn=[`ring-violet-400/60`,`ring-fuchsia-400/60`,`ring-pink-400/60`,`ring-cyan-400/60`,`ring-teal-400/60`,`ring-lime-400/60`,`ring-yellow-400/60`,`ring-stone-400/60`];function Kn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return Gn[t%Gn.length]??`ring-transparent`}function qn(e){let t=(0,Lt.c)(12),{info:n,threadId:r}=e,i=St(r),a;t[0]===r?a=t[1]:(a=l(`relative inline-flex shrink-0 rounded-full ring-1`,Kn(r)),t[0]=r,t[1]=a);let o=n?.agent.id??``,s=n?.agent.iconUrl,c;t[2]!==o||t[3]!==s?(c=(0,Q.jsx)(x,{agentId:o,iconUrl:s,className:`size-3.5`}),t[2]=o,t[3]=s,t[4]=c):c=t[4];let u;t[5]!==n||t[6]!==i?(u=n==null?null:(0,Q.jsx)(`span`,{className:l(`-right-0.5 -bottom-0.5 absolute size-1.5 rounded-full ring-1 ring-background`,Un(n.status),i&&n.status===`ready`&&`animate-pulse`),"aria-hidden":`true`}),t[5]=n,t[6]=i,t[7]=u):u=t[7];let d;return t[8]!==a||t[9]!==c||t[10]!==u?(d=(0,Q.jsxs)(`span`,{className:a,children:[c,u]}),t[8]=a,t[9]=c,t[10]=u,t[11]=d):d=t[11],d}var Jn=5e3,Yn={cli:!0,terminal:!0,desktop:!0};function Xn(e,t,n,r){let i=t===`always`||t===`if-panel-focused`&&document.getElementById(n)?.contains(document.activeElement)===!0;e(!1),i&&queueMicrotask(()=>r.current?.focus())}var Zn=20;function Qn(e){let t=(0,Lt.c)(210),{bridge:n,terminalCapable:r,surface:i,terminalPlacement:o,onTerminalPlacementChange:s,reserveRightRevealTabGutter:c,terminalRestoreRevealNonce:d,visible:f,onVisibleChange:p,agentsVisibilityRestoreSettled:m,launch:h,commandLaunch:b,threadLaunch:x,installedClis:D,container:O,isShowing:k,onRequestEditorFocus:A}=e,ie=r===void 0?!1:r,oe=o===void 0?`bottom`:o,se=d===void 0?0:d,ce=h===void 0?null:h,j=b===void 0?null:b,M=x===void 0?null:x,{_:N}=a(),P=i===`terminal-window`,F=i===`agents-panel`,I=!F,L=I&&ie&&n?.terminal!=null,le=F?`right`:oe,R=F?`agents`:`terminal`,z=F&&f,B=!P,ue=n?.platform===`darwin`?`mac`:n?.platform===`linux`||n?.platform===`win32`?`windowsLinux`:void 0,[V]=(0,Z.useState)(Tr),[H,fe]=(0,Z.useState)(null),U=(0,Z.useRef)(0),W,pe;t[0]!==O||t[1]!==V?(W=()=>{V==null||O==null||(V.parentElement!==O&&O.appendChild(V),fe(V))},pe=[V,O],t[0]=O,t[1]=V,t[2]=W,t[3]=pe):(W=t[2],pe=t[3]),(0,Z.useLayoutEffect)(W,pe);let[K,me]=(0,Z.useState)(!1),{mode:ve,remeasure:xe}=Qt(O,F),Ce=(0,Z.useId)(),De=(0,Z.useRef)(null),Fe=(0,Z.useRef)(ve),Ie,Le;t[4]!==ve||t[5]!==K||t[6]!==Ce?(Le=()=>{let e=Fe.current;Fe.current=ve,K&&e===`docked`&&ve===`cover`&&Xn(me,`if-panel-focused`,Ce,De)},Ie=[ve,K,Ce],t[4]=ve,t[5]=K,t[6]=Ce,t[7]=Ie,t[8]=Le):(Ie=t[7],Le=t[8]),(0,Z.useLayoutEffect)(Le,Ie);let Re=I&&typeof n?.terminal?.list==`function`,ze=F&&typeof n?.terminal?.getDockState==`function`,Be=!Re&&L&&f,Ve;t[9]!==n?.terminal?.getDockState||t[10]!==Re||t[11]!==Be||t[12]!==R||t[13]!==B?(Ve=()=>Re||!B||Be||typeof n?.terminal?.getDockState==`function`?null:ye(R),t[9]=n?.terminal?.getDockState,t[10]=Re,t[11]=Be,t[12]=R,t[13]=B,t[14]=Ve):Ve=t[14];let[He]=(0,Z.useState)(Ve),Ue;t[15]===He?.order?Ue=t[16]:(Ue=He?.order??[],t[15]=He?.order,t[16]=Ue);let We=(0,Z.useRef)(Ue),Ge=(0,Z.useRef)(He?.activeKey??null),Ke;t[17]!==Be||t[18]!==ce?(Ke=()=>Be?[{kind:`terminal`,id:An(1),launch:ce,commandId:null,title:null,customLabel:null,ordinal:1,adoptPtyId:null}]:[],t[17]=Be,t[18]=ce,t[19]=Ke):Ke=t[19];let[q,qe]=(0,Z.useState)(Ke),Je;t[20]===Be?Je=t[21]:(Je=()=>Be?An(1):``,t[20]=Be,t[21]=Je);let[J,Xe]=(0,Z.useState)(Je),[Ze,Qe]=(0,Z.useState)(!Re&&!ze),$e=(0,Z.useRef)(!1),Y=(0,Z.useRef)(J),X=(0,Z.useRef)(q),et=(0,Z.useRef)(+!!Be),tt=(0,Z.useRef)(Be&&ce?ce.nonce:null),nt=(0,Z.useRef)(null),rt=(0,Z.useRef)(null),it=(0,Z.useRef)(!1),at=(0,Z.useRef)(!1),[ot,st]=(0,Z.useState)(`idle`),ct=(0,Z.useRef)(null),lt=(0,Z.useRef)(null),ut=(0,Z.useRef)(null),dt=(0,Z.useRef)(null),ft=(0,Z.useRef)(!1),pt=(0,Z.useRef)(!1),mt=(0,Z.useRef)(!1),St=(0,Z.useRef)(!1),Ct=(0,Z.useRef)(!1),Tt=(0,Z.useRef)(!1),Et=(0,Z.useRef)(!1),Mt=(0,Z.useRef)(wr),Nt=(0,Z.useRef)(null),Pt=(0,Z.useRef)(P?!1:f),Ft=(0,Z.useRef)(se),Rt=(0,Z.useRef)(new Map),zt=(0,Z.useRef)(0),Ht,Ut;t[22]===k?(Ht=t[23],Ut=t[24]):(Ht=()=>{let e=k&&!ft.current;ft.current=k,e&&(dt.current={pendingThreadId:null}),k||(dt.current=null)},Ut=[k],t[22]=k,t[23]=Ht,t[24]=Ut),(0,Z.useLayoutEffect)(Ht,Ut);let $=bt(),Gt=ht(),Kt=yt(),qt=xt(),Jt;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Jt=()=>{at.current=!1,ct.current=null,lt.current=null,pt.current=!1,st(`idle`)},t[25]=Jt):Jt=t[25];let Yt;t[26]===Kt?Yt=t[27]:(Yt=[Kt],t[26]=Kt,t[27]=Yt),(0,Z.useEffect)(Jt,Yt);let Xt,Zt;t[28]===ot?(Xt=t[29],Zt=t[30]):(Xt=()=>{if(!pt.current||ot!==`failed`&&ot!==`deduped`)return;let e=window.requestAnimationFrame(()=>{pt.current=!1,ut.current?.focus()});return()=>window.cancelAnimationFrame(e)},Zt=[ot],t[28]=ot,t[29]=Xt,t[30]=Zt),(0,Z.useEffect)(Xt,Zt);let $t,en;t[31]!==K||t[32]!==Ce||t[33]!==F||t[34]!==f?($t=()=>{F&&!f&&K&&Xn(me,`never`,Ce,De)},en=[K,Ce,F,f],t[31]=K,t[32]=Ce,t[33]=F,t[34]=f,t[35]=$t,t[36]=en):($t=t[35],en=t[36]),(0,Z.useEffect)($t,en);let nn=qt===`connecting`||qt===`closed`,rn=ne(F),an=te(),on=_(),cn;t[37]===on?cn=t[38]:(cn=e=>g(on,e.source,e.id,!0,e.supported),t[37]=on,t[38]=cn);let ln=an.filter(cn),dn=y(ln,ee()),fn=new Set(an.map(Cr)),pn=S(rn.data?.agents??[]).some(e=>!fn.has(`${e.source}:${e.id}`)),mn;t[39]===rn?mn=t[40]:(mn=()=>{rn.refetch()},t[39]=rn,t[40]=mn);let hn=mn,_n=rn.isError,vn=!rn.isLoading&&!pn,yn;t[41]===$?yn=t[42]:(yn=$.filter(Sr),t[41]=$,t[42]=yn);let bn=yn.length,xn=new Map($.map(xr)),Sn=new Set(xn.keys()),Cn=function(e){mi(),Ge.current=null;let t=X.current.find(t=>t.kind===`thread`&&t.threadId===e);if(t!=null){Xe(t.id),queueMicrotask(()=>Ln(t));return}vt().openArchivedThread(e)},Tn;t[43]===Ce?Tn=t[44]:(Tn=function(e){Xn(me,e===`explicit`?`always`:`never`,Ce,De)},t[43]=Ce,t[44]=Tn);let En=Tn,Dn;t[45]===xe?Dn=t[46]:(Dn=function(e){e&&xe(),me(e)},t[45]=xe,t[46]=Dn);let On=Dn,jn=function(){F&&K&&ve===`cover`&&Xn(me,`never`,Ce,De)},Mn=function(){return!B||!Ze?!0:St.current&&!Ct.current?(Et.current||(Et.current=!0,console.warn(`[${F?`agents`:`terminal`}] dock persistence withheld: the restore did not complete, so the saved tab set is left untouched`)),!0):!1},Nn=function(){if(Mn())return;let e=Rt.current,t=X.current.map(t=>Fr(t,e)).filter(br),r=X.current.find(e=>e.id===Y.current),i=r==null?null:Fr(r,e),a=Ir(X.current,Y.current);F?(de(n,`agents`,{order:t,activeKey:i},a),G(n,f)):de(n,`terminal`,{order:t,activeKey:i},a)},Fn=function(e,t){if(t===null){Rt.current.delete(e),$r(X.current,Y.current);return}Rt.current.set(e,t),$r(X.current,Y.current);let r=X.current.find(t=>t.id===e);r!=null&&r.kind===`terminal`&&n?.terminal?.setMeta?.(t,{ordinal:r.ordinal,customLabel:r.customLabel}),Nn()},Un=function(e,t,n){let r=t===void 0?null:t;n===`user`&&mi(),Ge.current=null,et.current+=1;let i=An(et.current);qe(t=>[...t,{kind:`terminal`,id:i,launch:e,commandId:r,title:null,customLabel:null,ordinal:et.current,adoptPtyId:null}]),Xe(i)},Gn=ke(),Kn=sn(),Qn;t[47]===D?Qn=t[48]:(Qn=D??{},t[47]=D,t[48]=Qn);let Dr;t[49]===D?Dr=t[50]:(Dr=D??{},t[49]=D,t[50]=Dr);let Mr=Ae({sticky:Gn,effectiveThreadAgent:dn,enabledClis:Oe(on,Qn),enabledDesktopTargets:[],installedClis:Dr,terminalAvailable:L,threadsAvailable:F,desktopSelectable:!1,preferBareTerminal:Kn,bareTerminalFallback:!0}),Pr=Ne(Gn),Rr=Mr.kind===`thread`?{kind:`agent`,agent:Mr.agent}:Mr.kind===`cli`?Mr.cli===Pr?{kind:`cli`,cli:Mr.cli}:{kind:`terminal`}:Mr.kind===`terminal`?{kind:`terminal`}:{kind:`agent`,agent:null},zr=function(e,t){zt.current+=1,Un({prompt:null,cli:e,nonce:zt.current},null,t)},Br=function(e){let{agent:t,prompt:n,docName:r,titleHint:i,stageDraft:a,attachments:o}=e,s=n===void 0?null:n,c=r===void 0?null:r,l=i===void 0?null:i,u=a===void 0?null:a,d=F&&X.current.length===0,f=ct.current;return d&&(ct.current=e,st(`launching`)),Ot({source:t.source,id:t.id},s,c,l,u,o).then(t=>{if(t===`deduped`&&w.error(N({id:`eCOktA`})),!d||X.current.length>0||ct.current!==e)return t;switch(t){case`failed`:return ct.current=null,lt.current=e,st(`failed`),t;case`deduped`:return f===null?(ct.current=null,lt.current=e,st(`deduped`)):(ct.current=f,st(`launching`)),t;case`started`:return t;default:return jr(t)}})},Vr=function(){jn(),pt.current=!0;let e=lt.current;if(e===null){Hr();return}Br(e)};function Hr(){jn(),Rr.kind===`terminal`?Un(null,null,`user`):Rr.kind===`cli`?zr(Rr.cli,`user`):Rr.kind===`agent`&&Rr.agent!=null?Br({agent:Rr.agent}):T()}let Ur=function(){return F?Rr.kind!==`agent`||Rr.agent==null?!1:(Br({agent:Rr.agent}),!0):(Rr.kind===`terminal`?Un(null,null,`restore-seed`):Rr.kind===`cli`&&zr(Rr.cli,`restore-seed`),!0)},Wr;t[51]===D?Wr=t[52]:(Wr=D??{},t[51]=D,t[52]=Wr);let Gr;t[53]===D?Gr=t[54]:(Gr=D??{},t[53]=D,t[54]=Gr);let Kr=Ae({sticky:Gn,effectiveThreadAgent:dn,enabledClis:Oe(on,Wr),enabledDesktopTargets:[],installedClis:Gr,terminalAvailable:ie,threadsAvailable:!P,desktopSelectable:!1,preferBareTerminal:!1,bareTerminalFallback:!1}),qr=Ae({sticky:Gn,effectiveThreadAgent:dn,enabledClis:[],enabledDesktopTargets:[],installedClis:{},terminalAvailable:!1,threadsAvailable:F,desktopSelectable:!1,preferBareTerminal:!1,bareTerminalFallback:!1}),Jr;t[55]===D?Jr=t[56]:(Jr=D??{},t[55]=D,t[56]=Jr);let Yr;t[57]===D?Yr=t[58]:(Yr=D??{},t[57]=D,t[58]=Yr);let Xr=Ae({sticky:Gn,effectiveThreadAgent:dn,enabledClis:Oe(on,Jr),enabledDesktopTargets:[],installedClis:Yr,terminalAvailable:ie,threadsAvailable:!P,desktopSelectable:!1,preferBareTerminal:Kn,bareTerminalFallback:!0}),Zr;t[59]!==F||t[60]!==P?(Zr=function(e){return P?!0:F?e===`thread`||e===`none`:e in Yn},t[59]=F,t[60]=P,t[61]=Zr):Zr=t[61];let Qr=Zr;function $r(e,t){let r=e.find(e=>e.id===t);if(r==null){Se(R,null);return}if(r.kind===`thread`){let e=xn.get(r.threadId);Se(R,{id:r.id,kind:`thread`,label:e?.agent.name??N({id:`bcm0pR`}),agentId:e?.agent.id??``,iconUrl:e?.agent.iconUrl});return}let i=Rt.current.get(r.id),a=r.launch?.cli;if(i==null||n?.terminal==null||a==null){Se(R,null);return}Se(R,{id:r.id,kind:`terminal`,label:C[a].displayName,cli:a})}let ei;t[62]!==J||t[63]!==$||t[64]!==q?(ei=[J,q,$],t[62]=J,t[63]=$,t[64]=q,t[65]=ei):ei=t[65],(0,Z.useEffect)(()=>{$r(q,J)},ei);let ti=function(){jn(),f||p(!0)},ni=function(e){let{text:t,newTab:r,submit:i,target:a}=e,o=a===`agents`?qr:Kr;if(a===`agents`){if(!F)return}else if(!Qr(o.kind))return;f||p(!0),jn();let s=Y.current,c=X.current.find(e=>e.id===s);if(!r&&c!=null){if(c.kind===`thread`){kt(c.threadId,t),ti(),queueMicrotask(()=>Ln(c));return}let e=Rt.current.get(c.id),r=n?.terminal;if(e!=null&&r!=null&&c.launch?.cli!=null){r.input(e,t),ti(),queueMicrotask(()=>Pn(s));return}}if(o.kind===`thread`){let e={source:o.agent.source,id:o.agent.id};Br(i?{agent:e,prompt:t}:{agent:e,stageDraft:t})}else o.kind===`cli`?Me(t,o.cli,{stage:!i}):T()},ri=function(e){jn(),tn(!1),Te(Ee(e)),zr(e,`user`)},ii=function(){jn(),tn(!0),Un(null,null,`user`)},ai=function(){let e=X.current.find(e=>e.id===Y.current);if(e==null||e.kind!==`thread`)return null;let t=xn.get(e.threadId);if(t===void 0||t.archived===!0)return null;let n=vt().getThreadModel(e.threadId);return n===null||_t(n)?null:{threadId:e.threadId,agent:t.agent}},oi=function(e){let t=ai();if(t!==null&&Ai.has(t.threadId))return;if(jn(),v(e),tn(!1),Te(je(e)),t===null||t.agent.source===e.source&&t.agent.id===e.id){Br({agent:e});return}let n=Dt(t.threadId);if(n?.uploadsPending===!0){Br({agent:e});return}let r=n!==null&&!At(n)&&n.doc!==null?{agent:e,stageDraft:{doc:n.doc,attachments:n.attachments}}:{agent:e},i=t.threadId;ji(e=>new Set(e).add(i)),Br(r).then(e=>{ji(e=>{if(!e.has(i))return e;let t=new Set(e);return t.delete(i),t}),e===`started`&&vt().closeThread(i)})},si;t[66]===Symbol.for(`react.memo_cache_sentinel`)?(si=function(e,t){let n=t.trim()===``?null:t.trim();qe(t=>t.some(t=>t.id===e&&t.kind===`terminal`&&t.title!==n)?t.map(t=>t.id===e&&t.kind===`terminal`?{...t,title:n}:t):t)},t[66]=si):si=t[66];let ci=si,li=function(e,t){let r=X.current.find(t=>t.id===e);if(r==null)return;if(r.kind===`thread`){vt().renameThread(r.threadId,t);return}let i=t.trim()===``?null:t.trim();qe(t=>t.some(t=>t.id===e&&t.kind===`terminal`&&t.customLabel!==i)?t.map(t=>t.id===e&&t.kind===`terminal`?{...t,customLabel:i}:t):t);let a=Rt.current.get(e);a!=null&&n?.terminal?.setMeta?.(a,{customLabel:i})},ui=function(e){return e.kind===`terminal`?e.customLabel??e.title??N({id:`OVjNeX`,values:{0:e.ordinal}}):xn.get(e.threadId)?.title??N({id:`iEQQyu`})},di=(0,Z.useRef)(!1),fi=(0,Z.useRef)(null),pi=(0,Z.useRef)(null);function mi(){Et.current&&console.warn(`[${F?`agents`:`terminal`}] dock persistence resumed: a user arrangement established the tab set the restore did not`),Ct.current=!0,Et.current=!1}let hi=function(e){kn(X.current,e)!=null&&mi(),qe(t=>kn(t,e)??t);let t=e.map(e=>Rt.current.get(e)).filter(yr);t.length>0&&n?.terminal?.setOrder?.(t)},gi=function(e){let t=X.current,n=t.findIndex(e=>e.id===Y.current);if(n<0)return null;let r=n+e;if(r<0||r>=t.length)return null;let i=t.map(vr),[a]=i.splice(n,1);return i.splice(r,0,a),hi(i),{label:ui(t[n]),position:r+1,total:t.length}},_i=function(){Qr(Xr.kind)&&(f||p(!0),Hr())},vi=(0,Z.useRef)(mi),yi=(0,Z.useRef)(gi),bi=(0,Z.useRef)(Un),xi=(0,Z.useRef)(Ur),Si=(0,Z.useRef)(Br),Ci=(0,Z.useRef)(ni),wi=(0,Z.useRef)(ti),Ti=(0,Z.useRef)(_i),Ei=function(e){let t=X.current,n=t.findIndex(t=>t.id===e);if(n===-1)return;mi();let r=t[n],i=t.length===1;if(Ge.current=null,e===Y.current){let e=t[n-1]??t[n+1];Xe(e?.id??``),e!=null&&queueMicrotask(()=>Ln(e))}r.kind===`thread`?vt().closeThread(r.threadId):qe(t.filter(t=>t.id!==e)),i&&(p(!1),A())},Di=(0,Z.useRef)(_r),[Oi,ki]=(0,Z.useState)(gr),Ai=Oi,ji=ki;(0,Z.useEffect)(()=>{Mt.current=Mn,bi.current=Un,xi.current=Ur,Si.current=Br,Ci.current=ni,wi.current=ti,Ti.current=_i,vi.current=mi,yi.current=gi,Y.current=J,X.current=q,q.length>0&&(Tt.current=!0),Di.current=()=>{let e=X.current.find(e=>e.id===Y.current);if(e?.kind===`terminal`){Ei(e.id);return}let t=[...X.current].reverse().find(hr);t!=null&&Ei(t.id)}});let Mi,Ni;t[67]===q.length?(Mi=t[68],Ni=t[69]):(Mi=()=>{q.length!==0&&(ct.current=null,lt.current=null,pt.current=!1,st(`idle`))},Ni=[q.length],t[67]=q.length,t[68]=Mi,t[69]=Ni),(0,Z.useEffect)(Mi,Ni);let Pi=gt(),Fi;t[70]!==J||t[71]!==n||t[72]!==F||t[73]!==Pi||t[74]!==z||t[75]!==B||t[76]!==Ze||t[77]!==q?(Fi=[q,J,B,n,Ze,z,F,Pi],t[70]=J,t[71]=n,t[72]=F,t[73]=Pi,t[74]=z,t[75]=B,t[76]=Ze,t[77]=q,t[78]=Fi):Fi=t[78],(0,Z.useEffect)(()=>{if(!B||!Ze||Mt.current())return;if(F&&q.length===0&&!Tt.current&&(Pi===null||Pi.size>0)){G(n,z);return}let e=Rt.current,t=q.map(t=>Fr(t,e)).filter(mr),r=q.find(e=>e.id===J),i=r==null?null:Fr(r,e),a=Ir(q,J);F?(de(n,`agents`,{order:t,activeKey:i},a),G(n,z)):de(n,`terminal`,{order:t,activeKey:i},a)},Fi);let Ii;t[79]!==F||t[80]!==$?(Ii=[$,F],t[79]=F,t[80]=$,t[81]=Ii):Ii=t[81],(0,Z.useEffect)(()=>{if(!F)return;let e=new Set($.map(pr)),t=X.current,n=new Set(t.filter(fr).map(dr)),r=[];for(let e of $)n.has(e.threadId)||(et.current+=1,r.push({kind:`thread`,id:e.threadId,threadId:e.threadId,ordinal:et.current}));let i=t.some(t=>t.kind===`thread`&&!e.has(t.threadId));r.length===0&&!i||qe(t=>{let n=t.filter(t=>t.kind!==`thread`||e.has(t.threadId)),i=new Set(n.filter(ur).map(lr)),a=r.filter(e=>!i.has(e.threadId)),o=Rt.current,s=a.length>0?Lr(n,a,We.current,e=>Fr(e,o)):n;return s.length===t.length&&s.every((e,n)=>e===t[n])?t:s})},Ii);let Li;t[82]===Symbol.for(`react.memo_cache_sentinel`)?(Li=[],t[82]=Li):Li=t[82];let Ri=(0,Z.useRef)(Li),zi,Bi;t[83]!==F||t[84]!==$?(zi=()=>{if(!F)return;let e=$.map(cr),t=Ri.current;if(Ri.current=e,Ge.current!=null)return;let n=e.filter(e=>!t.includes(e)),r=n[n.length-1];r!=null&&(Xe(r),dt.current==null?queueMicrotask(()=>In(r)):dt.current.pendingThreadId=r)},Bi=[$,F],t[83]=F,t[84]=$,t[85]=zi,t[86]=Bi):(zi=t[85],Bi=t[86]),(0,Z.useEffect)(zi,Bi);let Vi;t[87]===$?Vi=t[88]:(Vi=$.filter(sr).map(or),t[87]=$,t[88]=Vi);let Hi=Vi,Ui=(0,Z.useRef)(Hi),Wi,Gi;t[89]!==m||t[90]!==F||t[91]!==Pi||t[92]!==Hi||t[93]!==p||t[94]!==f?(Wi=()=>{if(!F||!m)return;let e=Ui.current;Ui.current=Hi;let t=Hi.filter(t=>!e.includes(t));t.length===0||f||t.every(e=>Pi?.has(e)===!0)||p(!0)},Gi=[Hi,F,m,f,Pi,p],t[89]=m,t[90]=F,t[91]=Pi,t[92]=Hi,t[93]=p,t[94]=f,t[95]=Wi,t[96]=Gi):(Wi=t[95],Gi=t[96]),(0,Z.useEffect)(Wi,Gi);let Ki;t[97]!==J||t[98]!==q?(Ki=[q,J],t[97]=J,t[98]=q,t[99]=Ki):Ki=t[99],(0,Z.useEffect)(()=>{let e=Ge.current;if(e!=null){let t=Rt.current,n=q.find(n=>Fr(n,t)===e);if(n!=null){Ge.current=null,Xe(n.id);return}if(q.some(e=>e.id===J))return}if(!(J!==``&&q.some(e=>e.id===J))){if(q.length===0){J!==``&&Xe(``);return}Xe(q[q.length-1].id)}},Ki),(0,Z.useEffect)(()=>{if(!Ze)return;let e=Pt.current;if(Pt.current=f,ce!=null&&ce.nonce!==tt.current){tt.current=ce.nonce,bi.current(ce,null,`user`);return}if(j!=null&&j.nonce!==Nt.current){Nt.current=j.nonce,bi.current(null,j.id,`user`);return}let t=F&&M!=null&&M.nonce!==nt.current,n=I&&se!==Ft.current;if(n&&(Ft.current=se),f&&!e&&q.length===0&&!t&&!(F&&jt())){if(n&&!mt.current)return;it.current=!xi.current();return}if(F&&f&&e&&!at.current&&Pi!==null){at.current=!0,$.length===0&&q.length===0&&!t&&!jt()&&(it.current=!xi.current());return}if(it.current){if(!f||q.length>0||t){it.current=!1;return}F&&dn===null||xi.current()&&(it.current=!1)}},[f,ce,j,M,q.length,Ze,F,dn,Pi,$.length,I,se]);let qi;t[100]!==dn||t[101]!==F||t[102]!==M?(qi=[M,F,dn],t[100]=dn,t[101]=F,t[102]=M,t[103]=qi):qi=t[103],(0,Z.useEffect)(()=>{if(!F||M==null||M.nonce===nt.current)return;let e=M.agentId===``?null:{source:M.agentSource,id:M.agentId};if(e===null&&dn!==null&&(e={source:dn.source,id:dn.id}),e===null){rt.current!==M.nonce&&(rt.current=M.nonce,T());return}nt.current=M.nonce,Si.current({agent:e,prompt:M.prompt,docName:M.docName,titleHint:M.titleHint,attachments:M.attachments??void 0})},qi);let Ji;t[104]!==n||t[105]!==I||t[106]!==R?(Ji=[n,I,R],t[104]=n,t[105]=I,t[106]=R,t[107]=Ji):Ji=t[107],(0,Z.useEffect)(()=>{if(!I||typeof n?.terminal?.list!=`function`||$e.current)return;$e.current=!0;let e=!1,t=!1,r=()=>{e||Qe(!0)},i=window.setTimeout(()=>{t=!0,console.warn(`[terminal] dock restore exceeded its ${be}ms bound; cold-starting instead of waiting`),mt.current=!0,St.current=!0,it.current=!0,r()},be),a=()=>{window.clearTimeout(i),t||r()};return(async()=>{try{let{sessionOrder:r,terminalSnapshot:i,failed:o}=await ge(n,R);if(e||t)return;o&&(St.current=!0),r!=null&&(We.current=r.order,Ge.current=r.activeKey);let s=null;try{s=await n.terminal.list()??[]}catch(e){let t=e;St.current=!0,console.error(`[terminal] reload session list() failed; the surviving shells are unknown: ${String(t)}`)}if(e)return;if(t){let e=(s??[]).map(ar);e.length>0&&console.warn(`[terminal] dock restore was abandoned before list() resolved; these PTYs stay running unadopted: ${e.join(`, `)}`);return}if(s!=null&&s.length>0){let e=We.current,t=t=>{let n=e.indexOf(t);return n===-1?1/0:n},n=s.map(ir).sort((e,n)=>{let r=t(e.adoptPtyId),i=t(n.adoptPtyId);return r===i?0:r-i});et.current=Math.max(n.length,...n.map(rr)),qe(n)}else if(s!=null&&i!=null&&i.tabs.length>0){let e=i.tabs.map(nr);et.current=Math.max(e.length,...e.map(tr)),Ge.current=null,qe(e);let t=e.find(e=>e.ordinal===i?.activeOrdinal);t!=null&&Xe(t.id)}else s!=null&&(mt.current=!0,it.current=!0);window.setTimeout(()=>{e||(Ge.current=null)},9e3),a()}catch(e){let t=e;St.current=!0,mt.current=!0,it.current=!0,console.error(`[terminal] dock rehydration failed; cold-starting: ${t instanceof Error?t.stack??t.message:String(t)}`),a()}})(),()=>{e=!0,t=!0,window.clearTimeout(i),$e.current=!1,mt.current=!1,St.current=!1,Ct.current=!1,it.current=!1,Et.current=!1}},Ji);let Yi,Xi;t[108]!==n||t[109]!==Re||t[110]!==R||t[111]!==B?(Yi=()=>{if(Re||!B||typeof n?.terminal?.getDockState!=`function`)return;let e=!1,t=!1,r=()=>{e||Qe(!0)},i=window.setTimeout(()=>{t=!0,console.warn(`[agents] dock order restore exceeded its ${be}ms bound; the saved tab set is left untouched`),St.current=!0,r()},be);return ge(n,R).then(n=>{let{sessionOrder:r,failed:i}=n;e||t||(i&&(St.current=!0),r!=null&&(We.current=r.order,Ge.current===null&&(Ge.current=r.activeKey)))}).finally(()=>{window.clearTimeout(i),r()}),()=>{e=!0,window.clearTimeout(i),St.current=!1,Ct.current=!1,Et.current=!1}},Xi=[n,Re,B,R],t[108]=n,t[109]=Re,t[110]=R,t[111]=B,t[112]=Yi,t[113]=Xi):(Yi=t[112],Xi=t[113]),(0,Z.useEffect)(Yi,Xi);let Zi,Qi;t[114]===Re?(Zi=t[115],Qi=t[116]):(Zi=()=>{if(Re)return;let e=window.setTimeout(()=>{Ge.current=null},9e3);return()=>window.clearTimeout(e)},Qi=[Re],t[114]=Re,t[115]=Zi,t[116]=Qi),(0,Z.useEffect)(Zi,Qi);let $i;t[117]!==F||t[118]!==L?($i=[L,F],t[117]=F,t[118]=L,t[119]=$i):$i=t[119],(0,Z.useEffect)(()=>{if(!(!L&&!F))return ae(e=>Ci.current(e))},$i);let ea;t[120]===F?ea=t[121]:(ea=[F],t[120]=F,t[121]=ea),(0,Z.useEffect)(()=>{if(F)return we(e=>{let{threadIds:t}=e,n=Y.current,r=X.current.find(e=>e.id===n);r?.kind===`thread`&&(Pe(r.threadId,t),wi.current(),queueMicrotask(()=>Ln(r)))})},ea);let ta;t[122]===Symbol.for(`react.memo_cache_sentinel`)?(ta=[],t[122]=ta):ta=t[122],(0,Z.useEffect)(()=>he(()=>Ti.current()),ta);let na;t[123]!==I||t[124]!==P||t[125]!==L?(na=[P,I,L],t[123]=I,t[124]=P,t[125]=L,t[126]=na):na=t[126],(0,Z.useEffect)(()=>{if(I)return re(e=>{e===`new-terminal`?L&&bi.current(null,null,`user`):(e===`kill-terminal`||e===`close-active-tab-or-window`&&P)&&Di.current()})},na);let ra;t[127]!==V||t[128]!==P||t[129]!==ue?(ra=[V,P,ue],t[127]=V,t[128]=P,t[129]=ue,t[130]=ra):ra=t[130],(0,Z.useEffect)(()=>{let e=function(e){if(!E(e,ue)||e.altKey||e.shiftKey||!/^[1-9]$/.test(e.key)||!Hn(V,P)||u())return;let t=X.current[Number(e.key)-1];t!=null&&(e.preventDefault(),e.stopPropagation(),t.id!==Y.current&&vi.current(),Xe(t.id),queueMicrotask(()=>Ln(t)))};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},ra);let ia;t[131]!==N||t[132]!==V||t[133]!==P||t[134]!==ue?(ia=[V,P,ue,N],t[131]=N,t[132]=V,t[133]=P,t[134]=ue,t[135]=ia):ia=t[135],(0,Z.useEffect)(()=>{let e=function(e){if(!E(e,ue)||!e.shiftKey||e.altKey)return;let t=e.key===`ArrowLeft`?-1:+(e.key===`ArrowRight`);if(t===0||!Hn(V,P)||u()||di.current)return;let n=e.target;if(n?.tagName===`INPUT`||n?.isContentEditable)return;let r=yi.current(t);if(r==null)return;e.preventDefault(),e.stopPropagation();let i=Y.current,a=X.current.find(e=>e.id===i);a!=null&&queueMicrotask(()=>Ln(a));let o=N({id:`CoHvYd`,values:{0:r.label,1:r.position,2:r.total}});pi.current!=null&&window.clearTimeout(pi.current),pi.current=window.setTimeout(()=>{pi.current=null,fi.current!=null&&(fi.current.textContent=o)},60)};return window.addEventListener(`keydown`,e,{capture:!0}),()=>{window.removeEventListener(`keydown`,e,{capture:!0}),pi.current!=null&&(window.clearTimeout(pi.current),pi.current=null)}},ia);let aa;t[136]!==n?.editor||t[137]!==I||t[138]!==q?(aa=()=>{if(!I)return;let e=q.some(er);_e({terminalLive:e}),n?.editor.notifyViewMenuStateChanged({terminalLive:e})},t[136]=n?.editor,t[137]=I,t[138]=q,t[139]=aa):aa=t[139];let oa;t[140]!==n||t[141]!==I||t[142]!==q?(oa=[n,q,I],t[140]=n,t[141]=I,t[142]=q,t[143]=oa):oa=t[143],(0,Z.useEffect)(aa,oa);let sa=(0,Z.useRef)(!1),ca,la;t[144]===V?(ca=t[145],la=t[146]):(ca=()=>{if(V==null)return;let e=()=>{sa.current=zn(V)};return document.addEventListener(`focusin`,e,!0),e(),()=>document.removeEventListener(`focusin`,e,!0)},la=[V],t[144]=V,t[145]=ca,t[146]=la),(0,Z.useEffect)(ca,la);let ua,da;t[147]!==k||t[148]!==A||t[149]!==f?(ua=()=>{k||f||sa.current&&(sa.current=!1,A())},da=[k,f,A],t[147]=k,t[148]=A,t[149]=f,t[150]=ua,t[151]=da):(ua=t[150],da=t[151]),(0,Z.useLayoutEffect)(ua,da);let fa;t[152]!==H||t[153]!==F||t[154]!==k?(fa=[k,H,F],t[152]=H,t[153]=F,t[154]=k,t[155]=fa):fa=t[155],(0,Z.useEffect)(()=>{if(!k||H==null)return;let e=document.activeElement,t=dt.current?.pendingThreadId??Y.current,n=X.current.find(e=>e.id===t),r=!1;if(n!=null){let e=Rn(n);if(Ln(n)){dt.current=null;return}r=e!=null&&document.activeElement===e}let i=F&&n==null?Bn(ut.current)??Bn(Vn(H)):null;dt.current={pendingThreadId:dt.current?.pendingThreadId??null};let a=r,o=null,s=null,c=!1,l=e=>{e.target===o&&(a=!0)},u=()=>{if(s=null,c)return;let t=dt.current?.pendingThreadId??Y.current,n=X.current.find(e=>e.id===t);if(n==null)return;let r=document.activeElement,l=Rn(n);if(r!=null&&r!==document.body&&r!==e&&r!==l&&r!==i){a=!0,dt.current=null;return}a=!1,o=l;let u=Ln(n);o=null,a=u||a||l!=null&&document.activeElement===l,u&&(dt.current=null,f.disconnect())},d=()=>{c||s!==null||(s=window.requestAnimationFrame(u))};document.addEventListener(`focusin`,l,!0);let f=new MutationObserver(()=>{u(),a||d()});f.observe(H,{subtree:!0,childList:!0}),d();let p=window.setTimeout(()=>{c=!0,s!=null&&window.cancelAnimationFrame(s),s=null,f.disconnect(),dt.current=null;let e=document.activeElement==null||document.activeElement===document.body,t=X.current.find(e=>e.id===Y.current);!a&&e&&t!=null&&console.warn(`[${F?`agents`:`terminal`}] reveal focus did not land within its ${Jn}ms bound`)},Jn);return()=>{c=!0,dt.current=null,document.removeEventListener(`focusin`,l,!0),f.disconnect(),s!=null&&window.cancelAnimationFrame(s),window.clearTimeout(p)}},fa);let pa;if(t[156]!==J||t[157]!==q){let e;t[159]===J?e=t[160]:(e=e=>e.id===J,t[159]=J,t[160]=e),pa=q.find(e),t[156]=J,t[157]=q,t[158]=pa}else pa=t[158];let ma=pa,ha=ma?.kind===`thread`?ma.threadId:null,ga=ha===null?void 0:xn.get(ha),_a=ga?.lastActivityAt??null,va=ga?.status??null,ya=F&&K&&ve===`cover`,ba;t[161]!==ha||t[162]!==ya||t[163]!==k?(ba=()=>{!k||ya||ha===null||vt().markThreadViewed(ha)},t[161]=ha,t[162]=ya,t[163]=k,t[164]=ba):ba=t[164];let xa;t[165]!==_a||t[166]!==ha||t[167]!==va||t[168]!==ya||t[169]!==k?(xa=[ha,_a,va,ya,k],t[165]=_a,t[166]=ha,t[167]=va,t[168]=ya,t[169]=k,t[170]=xa):xa=t[170],(0,Z.useEffect)(ba,xa);let Sa=q.map(e=>({id:e.id,label:ui(e),icon:e.kind===`terminal`?Wn():(0,Q.jsx)(qn,{info:xn.get(e.threadId),threadId:e.threadId})})),Ca=[...q].sort($n),wa=q.some(e=>e.id===J&&e.kind===`thread`&&Ai.has(e.threadId)),Ta=Hr,Ea;t[171]===D?Ea=t[172]:(Ea=D??{},t[171]=D,t[172]=Ea);let Da;t[173]!==on||t[174]!==Ea?(Da=Oe(on,Ea),t[173]=on,t[174]=Ea,t[175]=Da):Da=t[175];let Oa=(0,Q.jsx)(gn,{selected:Rr,onLaunchSelected:Ta,showAgents:F,registeredAgents:ln,onPickAgent:oi,agentPickPending:wa,onOpenSettings:T,liveThreadCount:bn,showClis:L,onPickCli:ri,onPickTerminal:ii,visibleClis:Da}),ka=F?(0,Q.jsx)(gn,{selected:Rr,onLaunchSelected:Hr,showAgents:!0,registeredAgents:ln,onPickAgent:oi,agentPickPending:wa,onOpenSettings:T,liveThreadCount:bn,showClis:L,onPickCli:ri,onPickTerminal:ii,visibleClis:Oe(on,D??{}),presentation:`panel`}):null,Aa;t[176]!==K||t[177]!==Ce||t[178]!==F||t[179]!==On?(Aa=F?(0,Q.jsx)(Vt,{open:K,panelId:Ce,triggerRef:De,onOpenChange:On}):null,t[176]=K,t[177]=Ce,t[178]=F,t[179]=On,t[180]=Aa):Aa=t[180];let ja=Aa,Ma=q.length>0||f&&!P,Na,Pa;t[181]!==H||t[182]!==O||t[183]!==V||t[184]!==I||t[185]!==q.length||t[186]!==Ma||t[187]!==i||t[188]!==f?(Na=()=>{I&&(U.current>=Zn||(U.current+=1,Ye(`ok-terminal-sessions-host-state`,{surface:i,sessions:q.length,hostConnected:V?.isConnected===!0,hasContainer:O!=null,attached:H!=null,terminalVisible:f,showStrip:Ma,tabs:V?.querySelectorAll(`[role="tab"]`).length??0})))},Pa=[I,i,q.length,V,O,H,f,Ma],t[181]=H,t[182]=O,t[183]=V,t[184]=I,t[185]=q.length,t[186]=Ma,t[187]=i,t[188]=f,t[189]=Na,t[190]=Pa):(Na=t[189],Pa=t[190]),(0,Z.useEffect)(Na,Pa);let Fa;t[191]===Symbol.for(`react.memo_cache_sentinel`)?(Fa=Ar(),t[191]=Fa):Fa=t[191];let Ia=Fa,La=Ia??(Pi===null||dn===null&&!vn?`loading`:dn===null?_n?`agents-unavailable`:`no-agents`:Nr(ot)),Ra=F&&(q.length===0||Ia!==null)?(0,Q.jsx)(kr,{state:La,onConfigureAgents:T,onRetry:La===`agents-unavailable`?hn:Vr,actionButtonRef:ut}):q.length===0?L?null:(0,Q.jsx)(Or,{}):Ca.map(e=>(0,Q.jsx)(wt,{value:e.id,forceMount:!0,"data-session-id":e.id,...e.kind===`terminal`?{"data-terminal-session":e.id}:{},className:l(`m-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden`,P&&`px-[22px] pb-[22px]`),children:e.kind===`terminal`?n!=null&&L?(0,Q.jsx)(un,{bridge:n,launch:e.launch,commandId:e.commandId,adoptPtyId:e.adoptPtyId,onPtyId:t=>Fn(e.id,t),onTitleChange:t=>ci(e.id,t),onClose:()=>Ei(e.id)}):null:(0,Q.jsx)(Er,{threadId:e.threadId,info:xn.get(e.threadId),showConnectionBanner:nn&&e.id===J,active:f&&!ya&&e.id===J})},e.id)),za=K?(0,Q.jsx)(Wt,{threads:Gt,openThreadIds:Sn,activeThreadId:ha,onSelectThread:Cn,mode:ve,panelId:Ce,onDismiss:En,newChatControl:ka}):null,Ba;t[192]!==Y||t[193]!==mi?(Ba=e=>{e!==Y.current&&mi(),Ge.current=null,Xe(e)},t[192]=Y,t[193]=mi,t[194]=Ba):Ba=t[194];let Va;t[195]===X?Va=t[196]:(Va=e=>{let t=X.current.find(t=>t.id===e);t!=null&&queueMicrotask(()=>Ln(t))},t[195]=X,t[196]=Va);let Ha;t[197]===Symbol.for(`react.memo_cache_sentinel`)?(Ha=e=>{di.current=e},t[197]=Ha):Ha=t[197];let Ua;t[198]!==P||t[199]!==A||t[200]!==p?(Ua=P?void 0:()=>{p(!1),A()},t[198]=P,t[199]=A,t[200]=p,t[201]=Ua):Ua=t[201];let Wa;t[202]!==F||t[203]!==Ra?(Wa=F?(0,Q.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:Ra}):Ra,t[202]=F,t[203]=Ra,t[204]=Wa):Wa=t[204];let Ga=(0,Q.jsx)(wn,{sessions:Sa,sessionKind:F?`agent`:`terminal`,activeSessionId:J,onSelect:Ba,onTabActivate:Va,newButton:Oa,trailingControls:ja,onClose:Ei,onRename:li,onReorder:hi,onDragActiveChange:Ha,edge:le,onPlacementChange:i===`terminal-dock`?s:void 0,reserveRightRevealTabGutter:c,onCollapse:Ua,draggable:P,className:`h-full`,children:Wa}),Ka=Ma?F?(0,Q.jsx)(Bt,{scope:Kt,children:(0,Q.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 overflow-hidden`,"data-testid":`agent-panel-layout`,children:[(0,Q.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,"data-testid":`agent-panel-session-surface`,inert:ya?!0:void 0,children:Ga}),K?(0,Q.jsx)(`div`,{className:l(`z-20 h-full max-w-full bg-background`,ve===`cover`?`absolute inset-0 w-full shadow-xl`:`w-(--history-panel-width) shrink-0 border-s`),style:{"--history-panel-width":`248px`},"data-testid":`agent-thread-history-surface`,children:za}):null]})}):Ga:null,qa;t[205]!==H||t[206]!==Ka?(qa=H==null?null:(0,It.createPortal)((0,Q.jsxs)(Q.Fragment,{children:[Ka,(0,Q.jsx)(`span`,{ref:fi,"aria-live":`polite`,"aria-atomic":`true`,className:`sr-only`,"data-testid":`terminal-reorder-announcer`})]}),H),t[205]=H,t[206]=Ka,t[207]=qa):qa=t[207];let Ja;return t[208]===qa?Ja=t[209]:(Ja=(0,Q.jsx)(Q.Fragment,{children:qa}),t[208]=qa,t[209]=Ja),Ja}function $n(e,t){return e.ordinal-t.ordinal}function er(e){return e.kind===`terminal`}function tr(e){return e.ordinal}function nr(e,t){return{kind:`terminal`,commandId:null,id:An(t+1),launch:null,title:null,customLabel:e.customLabel,ordinal:e.ordinal,adoptPtyId:null}}function rr(e){return e.ordinal}function ir(e,t){return{kind:`terminal`,commandId:null,id:An(t+1),launch:null,title:null,customLabel:e.customLabel??null,ordinal:e.ordinal??t+1,adoptPtyId:e.ptyId}}function ar(e){return e.ptyId}function or(e){return e.threadId}function sr(e){return e.archived!==!0}function cr(e){return e.threadId}function lr(e){return e.threadId}function ur(e){return e.kind===`thread`}function dr(e){return e.threadId}function fr(e){return e.kind===`thread`}function pr(e){return e.threadId}function mr(e){return e!=null}function hr(e){return e.kind===`terminal`}function gr(){return new Set}function _r(){}function vr(e){return e.id}function yr(e){return e!=null}function br(e){return e!=null}function xr(e){return[e.threadId,e]}function Sr(e){return e.archived!==!0}function Cr(e){return`${e.source}:${e.id}`}function wr(){return!1}function Tr(){if(typeof document>`u`)return null;let e=document.createElement(`div`);return e.className=`flex min-h-0 flex-1 flex-col overflow-hidden`,e}function Er(e){let t=(0,Lt.c)(10),{threadId:n,info:r,showConnectionBanner:i,active:a}=e;if(r===void 0)return null;let o;t[0]===i?o=t[1]:(o=i?(0,Q.jsx)(Dr,{}):null,t[0]=i,t[1]=o);let s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,Q.jsx)(`div`,{role:`status`,"aria-busy":`true`,className:`flex min-h-0 flex-1 items-center justify-center text-muted-foreground`,children:(0,Q.jsx)(qe,{className:`size-5`,"aria-hidden":`true`})}),t[2]=s):s=t[2];let c;t[3]!==a||t[4]!==r||t[5]!==n?(c=(0,Q.jsx)(Z.Suspense,{fallback:s,children:(0,Q.jsx)(On,{info:r,active:a},n)}),t[3]=a,t[4]=r,t[5]=n,t[6]=c):c=t[6];let l;return t[7]!==o||t[8]!==c?(l=(0,Q.jsxs)(Q.Fragment,{children:[o,c]}),t[7]=o,t[8]=c,t[9]=l):l=t[9],l}function Dr(){let e=(0,Lt.c)(4),{_:t}=a(),n;e[0]===t?n=e[1]:(n=t({id:`k0dL2I`}),e[0]=t,e[1]=n);let r;return e[2]===n?r=e[3]:(r=(0,Q.jsx)(`div`,{className:`shrink-0 border-amber-500/30 border-b bg-amber-500/5 px-3 py-1 text-amber-700 text-xs dark:text-amber-400`,"data-testid":`agent-thread-reconnecting`,children:n}),e[2]=n,e[3]=r),r}function Or(){let e=(0,Lt.c)(4),{_:t}=a(),n;e[0]===t?n=e[1]:(n=t({id:`-l6jM7`}),e[0]=t,e[1]=n);let r;return e[2]===n?r=e[3]:(r=(0,Q.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-6 text-center text-muted-foreground text-sm`,"data-testid":`sessions-dock-empty`,children:n}),e[2]=n,e[3]=r),r}function kr(e){let t=(0,Lt.c)(62),{state:n,onConfigureAgents:r,onRetry:i,actionButtonRef:o}=e,{_:s}=a(),c;bb0:switch(n){case`idle`:c=null;break bb0;case`loading`:case`starting`:{let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(qe,{className:`size-4`})}),t[0]=e):e=t[0];let r;t[1]!==s||t[2]!==n?(r=s(n===`loading`?{id:`ucXZ0k`}:{id:`l3zD7w`}),t[1]=s,t[2]=n,t[3]=r):r=t[3];let i;t[4]===r?i=t[5]:(i=(0,Q.jsxs)(`div`,{role:`status`,"aria-busy":`true`,className:`flex items-center gap-2`,"data-testid":`sessions-dock-loading`,children:[e,(0,Q.jsx)(`span`,{children:r})]}),t[4]=r,t[5]=i),c=i;break bb0}case`no-agents`:{let e;t[6]===s?e=t[7]:(e=s({id:`jAQCRf`}),t[6]=s,t[7]=e);let n;t[8]===e?n=t[9]:(n=(0,Q.jsx)(`p`,{children:e}),t[8]=e,t[9]=n);let i;t[10]===s?i=t[11]:(i=s({id:`jRAGrQ`}),t[10]=s,t[11]=i);let a;t[12]!==o||t[13]!==r||t[14]!==i?(a=(0,Q.jsx)(d,{ref:o,type:`button`,size:`sm`,onClick:r,children:i}),t[12]=o,t[13]=r,t[14]=i,t[15]=a):a=t[15];let l;t[16]!==n||t[17]!==a?(l=(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,"data-testid":`sessions-dock-no-agents`,children:[n,a]}),t[16]=n,t[17]=a,t[18]=l):l=t[18],c=l;break bb0}case`agents-unavailable`:{let e;t[19]===s?e=t[20]:(e=s({id:`Jrwm42`}),t[19]=s,t[20]=e);let n;t[21]===e?n=t[22]:(n=(0,Q.jsx)(`p`,{children:e}),t[21]=e,t[22]=n);let r;t[23]===s?r=t[24]:(r=s({id:`KDw4GX`}),t[23]=s,t[24]=r);let a;t[25]!==o||t[26]!==i||t[27]!==r?(a=(0,Q.jsx)(d,{ref:o,type:`button`,size:`sm`,onClick:i,children:r}),t[25]=o,t[26]=i,t[27]=r,t[28]=a):a=t[28];let l;t[29]!==n||t[30]!==a?(l=(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,"data-testid":`sessions-dock-agents-unavailable`,children:[n,a]}),t[29]=n,t[30]=a,t[31]=l):l=t[31],c=l;break bb0}case`failed`:{let e;t[32]===s?e=t[33]:(e=s({id:`WC8Mr6`}),t[32]=s,t[33]=e);let n;t[34]===e?n=t[35]:(n=(0,Q.jsx)(`p`,{children:e}),t[34]=e,t[35]=n);let r;t[36]===s?r=t[37]:(r=s({id:`KDw4GX`}),t[36]=s,t[37]=r);let a;t[38]!==o||t[39]!==i||t[40]!==r?(a=(0,Q.jsx)(d,{ref:o,type:`button`,size:`sm`,onClick:i,children:r}),t[38]=o,t[39]=i,t[40]=r,t[41]=a):a=t[41];let l;t[42]!==n||t[43]!==a?(l=(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,"data-testid":`sessions-dock-launch-failed`,children:[n,a]}),t[42]=n,t[43]=a,t[44]=l):l=t[44],c=l;break bb0}case`deduped`:{let e;t[45]===s?e=t[46]:(e=s({id:`eCOktA`}),t[45]=s,t[46]=e);let n;t[47]===e?n=t[48]:(n=(0,Q.jsx)(`p`,{children:e}),t[47]=e,t[48]=n);let r;t[49]===s?r=t[50]:(r=s({id:`KDw4GX`}),t[49]=s,t[50]=r);let a;t[51]!==o||t[52]!==i||t[53]!==r?(a=(0,Q.jsx)(d,{ref:o,type:`button`,size:`sm`,onClick:i,children:r}),t[51]=o,t[52]=i,t[53]=r,t[54]=a):a=t[54];let l;t[55]!==n||t[56]!==a?(l=(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,"data-testid":`sessions-dock-launch-deduped`,children:[n,a]}),t[55]=n,t[56]=a,t[57]=l):l=t[57],c=l;break bb0}default:{let e;t[58]===n?e=t[59]:(e=Mr(n),t[58]=n,t[59]=e),c=e}}let l;return t[60]===c?l=t[61]:(l=(0,Q.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center px-6 text-center text-muted-foreground text-sm`,"data-testid":`sessions-dock-empty`,children:c}),t[60]=c,t[61]=l),l}function Ar(){return null}function jr(e){throw Error(`unhandled thread launch outcome: ${String(e)}`)}function Mr(e){throw Error(`unhandled empty agent state: ${String(e)}`)}function Nr(e){switch(e){case`idle`:return`idle`;case`launching`:return`starting`;case`deduped`:return`deduped`;case`failed`:return`failed`;default:return Pr(e)}}function Pr(e){throw Error(`unhandled empty agent launch state: ${String(e)}`)}function Fr(e,t){return e.kind===`thread`?e.threadId:e.adoptPtyId??t.get(e.id)??null}function Ir(e,t){let n=e.filter(e=>e.kind===`terminal`),r=n.find(e=>e.id===t);return{tabs:n.map(e=>({ordinal:e.ordinal,customLabel:e.customLabel})),activeOrdinal:r?.ordinal??null}}function Lr(e,t,n,r){let i=e=>{let t=r(e);if(t==null)return 1/0;let i=n.indexOf(t);return i===-1?1/0:i},a=[...e];for(let e of t){let t=i(e);if(t===1/0){a.push(e);continue}let n=a.length;for(let e=0;e<a.length;e++)if(i(a[e])>t){n=e;break}a.splice(n,0,e)}return a}export{Qn as SessionsHost};