@inkeep/open-knowledge 0.19.0-beta.0 → 0.19.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +6 -6
  4. package/dist/constants-DRZYaWtr.mjs +2 -0
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-CHlwzxSA.mjs → init-BMT_3l9F.mjs} +3 -3
  7. package/dist/init-Cz9Xc6e4.mjs +1 -0
  8. package/dist/loader-Bhq-VNS_.mjs +1 -0
  9. package/dist/{loader-CjrRykwH.mjs → loader-D4wC401d.mjs} +2 -2
  10. package/dist/{preview-Cv6HcQ_e.mjs → preview-BGMRorsT.mjs} +2 -2
  11. package/dist/preview-DWfgcb6s.mjs +1 -0
  12. package/dist/public/assets/{ActivityModeContent-4WkJ4YsY.js → ActivityModeContent-viVPzw3Y.js} +1 -1
  13. package/dist/public/assets/{DocumentContext-md7jH47y.js → DocumentContext-D8cckXN4.js} +19 -19
  14. package/dist/public/assets/{SettingsDialogBody-qFgxGdKj.js → SettingsDialogBody-CeLLdSxI.js} +1 -1
  15. package/dist/public/assets/{SourceEditor-Da2JfgzJ.js → SourceEditor-DTMRToUF.js} +2 -2
  16. package/dist/public/assets/{config-validation-events-DygY3HvV.js → config-validation-events-3FV56Hzw.js} +1 -1
  17. package/dist/public/assets/{index-Cbh9CKOu.js → index-DuPo-pVa.js} +5 -5
  18. package/dist/public/assets/index-RaWglp98.css +1 -0
  19. package/dist/public/assets/{typing-burst-detector-Xp_EnyFS.js → typing-burst-detector-D_u2E6Id.js} +1 -1
  20. package/dist/public/index.html +5 -5
  21. package/dist/{repair-launch-json-0Hl3ctn-.mjs → repair-launch-json-Ak_vMWlE.mjs} +2 -2
  22. package/dist/{repair-mcp-configs-C2XinSeJ.mjs → repair-mcp-configs-CnhOJEv-.mjs} +2 -2
  23. package/dist/{src-CABDPvtm.mjs → src-ANkvjof-.mjs} +2 -2
  24. package/dist/{start-F1c6hHGL.mjs → start-BTUBLJch.mjs} +2 -2
  25. package/dist/start-Uo8BaBLY.mjs +1 -0
  26. package/package.json +1 -1
  27. package/dist/constants-BiXELTVf.mjs +0 -2
  28. package/dist/init-BP843Mwl.mjs +0 -1
  29. package/dist/loader-CL1cBJAY.mjs +0 -1
  30. package/dist/preview-BcwxW8Jz.mjs +0 -1
  31. package/dist/public/assets/index-Dr6njkuY.css +0 -1
  32. package/dist/start-B3JghErx.mjs +0 -1
@@ -3,7 +3,7 @@ name: open-knowledge-discovery
3
3
  description: "Read when the user asks what Open Knowledge is, wants to install it on a repository, wants to share an Open Knowledge project with collaborators, or asks how `ok init` / `ok install-skill` / OK Desktop set up a project. Do NOT load to perform Open Knowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs. If the user appears to be editing markdown inside a `.ok/` project and this is the only OK skill loaded, advise them to re-run `ok init` to install the project-local skill."
4
4
  compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
5
5
  metadata:
6
- version: "0.19.0-beta.0"
6
+ version: "0.19.0-beta.2"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "MUST invoke before reading or editing any `.md` / `.mdx` file, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, and the rest). This skill is installed into the repository by `ok init`, so its presence alone means this is an Open Knowledge project — its runtime contract governs every markdown file here, with no need to probe for a `.ok/` directory. Authoritative agent-runtime contract for working inside this Open Knowledge project."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.19.0-beta.0"
6
+ version: "0.19.0-beta.2"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{Bi as n,Fa as r,Pa as i,Qr as a,Wi as o,Yr as s,Zi as c,_a as l,ba as u,bn as d,ca as f,f as p,la as m,ma as h,n as g,na as _,ra as v,s as y,sa as ee,ta as b,ua as x,wr as S,xr as te,yi as C,zi as ne}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{a as re,n as ie,r as ae,t as oe}from"./gh-detect-DLds_L3H.mjs";import{r as w}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$n as se,Br as ce,Bt as le,Cn as ue,En as de,F as fe,Fn as pe,Gi as me,Hn as he,Ht as ge,Ji as _e,Ki as ve,Kr as ye,P as be,Pr as xe,Q as Se,Qi as Ce,Rn as we,T as Te,Ur as Ee,Vt as De,Wi as Oe,Xt as ke,Yi as Ae,Z as je,_ as Me,_t as Ne,aa as Pe,ai as Fe,an as Ie,at as Le,br as Re,c as ze,dn as Be,ea as Ve,it as He,jt as Ue,mt as We,na as Ge,qi as Ke,qt as qe,ra as Je,rt as Ye,ta as Xe,tt as Ze,un as Qe,v as $e,w as et,wr as tt,xt as nt,yn as rt,yr as it}from"./dist-CWv9hwiJ.mjs";import{t as at}from"./yazl-Docqgl6q.mjs";import{n as ot,r as st,t as ct}from"./dist-bundle-D75dREX-.mjs";import{A as lt,C as ut,D as dt,E as ft,F as pt,I as mt,L as ht,M as gt,N as _t,O as vt,P as yt,S as bt,T as xt,b as St,j as Ct,k as wt,u as Tt,v as Et,w as Dt}from"./init-CHlwzxSA.mjs";import{a as Ot,c as kt,h as At,i as jt,l as Mt,m as Nt,o as Pt,s as Ft,u as It}from"./src-CABDPvtm.mjs";import{n as Lt,t as Rt}from"./constants-BiXELTVf.mjs";import{n as zt,t as Bt}from"./loader-CjrRykwH.mjs";import{S as Vt,_ as Ht,b as Ut,m as Wt,x as Gt,y as Kt}from"./start-F1c6hHGL.mjs";import{c as qt,i as T,n as E,o as D,r as O,s as k,t as A}from"./colors-CBY1ibtz.mjs";import{n as Jt}from"./repair-skills-BNYzyMnZ.mjs";import{execFile as Yt,execSync as Xt,spawn as j,spawnSync as M}from"node:child_process";import{accessSync as Zt,closeSync as Qt,constants as $t,cpSync as en,createWriteStream as tn,existsSync as N,mkdirSync as P,mkdtempSync as nn,openSync as rn,readFileSync as F,readdirSync as an,realpathSync as on,rmSync as sn,statSync as cn,unlinkSync as ln,writeFileSync as I}from"node:fs";import un,{basename as L,dirname as dn,join as R,relative as fn,resolve as z,sep as pn}from"node:path";import mn from"node:process";import{arch as hn,freemem as gn,homedir as _n,platform as vn,release as yn,tmpdir as bn,totalmem as xn,type as Sn,uptime as Cn}from"node:os";import{fileURLToPath as wn}from"node:url";import{rm as Tn}from"node:fs/promises";import{createHash as En,randomUUID as Dn}from"node:crypto";import{setTimeout as On}from"node:timers/promises";import{promisify as kn,stripVTControlCharacters as An,styleText as B}from"node:util";import{AsyncLocalStorage as jn,AsyncResource as Mn}from"node:async_hooks";import*as Nn from"node:readline";import{createInterface as Pn}from"node:readline/promises";const Fn={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var In;(function(e){})(In||={});function Ln(e){return u(c,e)}async function Rn(e,t,n,r){let i=zn(await Bn(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function zn(e){let t={};for(let n of e.split(`
2
+ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{Bi as n,Fa as r,Pa as i,Qr as a,Wi as o,Yr as s,Zi as c,_a as l,ba as u,bn as d,ca as f,f as p,la as m,ma as h,n as g,na as _,ra as v,s as y,sa as ee,ta as b,ua as x,wr as S,xr as te,yi as C,zi as ne}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{a as re,n as ie,r as ae,t as oe}from"./gh-detect-DLds_L3H.mjs";import{r as w}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$n as se,Br as ce,Bt as le,Cn as ue,En as de,F as fe,Fn as pe,Gi as me,Hn as he,Ht as ge,Ji as _e,Ki as ve,Kr as ye,P as be,Pr as xe,Q as Se,Qi as Ce,Rn as we,T as Te,Ur as Ee,Vt as De,Wi as Oe,Xt as ke,Yi as Ae,Z as je,_ as Me,_t as Ne,aa as Pe,ai as Fe,an as Ie,at as Le,br as Re,c as ze,dn as Be,ea as Ve,it as He,jt as Ue,mt as We,na as Ge,qi as Ke,qt as qe,ra as Je,rt as Ye,ta as Xe,tt as Ze,un as Qe,v as $e,w as et,wr as tt,xt as nt,yn as rt,yr as it}from"./dist-CWv9hwiJ.mjs";import{t as at}from"./yazl-Docqgl6q.mjs";import{n as ot,r as st,t as ct}from"./dist-bundle-D75dREX-.mjs";import{A as lt,C as ut,D as dt,E as ft,F as pt,I as mt,L as ht,M as gt,N as _t,O as vt,P as yt,S as bt,T as xt,b as St,j as Ct,k as wt,u as Tt,v as Et,w as Dt}from"./init-BMT_3l9F.mjs";import{a as Ot,c as kt,h as At,i as jt,l as Mt,m as Nt,o as Pt,s as Ft,u as It}from"./src-ANkvjof-.mjs";import{n as Lt,t as Rt}from"./constants-DRZYaWtr.mjs";import{n as zt,t as Bt}from"./loader-D4wC401d.mjs";import{S as Vt,_ as Ht,b as Ut,m as Wt,x as Gt,y as Kt}from"./start-BTUBLJch.mjs";import{c as qt,i as T,n as E,o as D,r as O,s as k,t as A}from"./colors-CBY1ibtz.mjs";import{n as Jt}from"./repair-skills-BNYzyMnZ.mjs";import{execFile as Yt,execSync as Xt,spawn as j,spawnSync as M}from"node:child_process";import{accessSync as Zt,closeSync as Qt,constants as $t,cpSync as en,createWriteStream as tn,existsSync as N,mkdirSync as P,mkdtempSync as nn,openSync as rn,readFileSync as F,readdirSync as an,realpathSync as on,rmSync as sn,statSync as cn,unlinkSync as ln,writeFileSync as I}from"node:fs";import un,{basename as L,dirname as dn,join as R,relative as fn,resolve as z,sep as pn}from"node:path";import mn from"node:process";import{arch as hn,freemem as gn,homedir as _n,platform as vn,release as yn,tmpdir as bn,totalmem as xn,type as Sn,uptime as Cn}from"node:os";import{fileURLToPath as wn}from"node:url";import{rm as Tn}from"node:fs/promises";import{createHash as En,randomUUID as Dn}from"node:crypto";import{setTimeout as On}from"node:timers/promises";import{promisify as kn,stripVTControlCharacters as An,styleText as B}from"node:util";import{AsyncLocalStorage as jn,AsyncResource as Mn}from"node:async_hooks";import*as Nn from"node:readline";import{createInterface as Pn}from"node:readline/promises";const Fn={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var In;(function(e){})(In||={});function Ln(e){return u(c,e)}async function Rn(e,t,n,r){let i=zn(await Bn(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function zn(e){let t={};for(let n of e.split(`
3
3
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function Bn(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Vn(e,n){let r=new t(`git-credential`);return r.description(`Git credential helper (git credential-helper protocol)`),r.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=n?.();try{let n,r=await e({onKeychainRead:e=>{n=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&t?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await Rn(process.stdin,process.stdout,r,{log:t,getDiag:()=>n});await rt(t),process.exit(i)}catch(e){t?.error({error:e instanceof Error?e.message:String(e)},`[auth] git-credential get: unexpected error`),await rt(t),process.exit(1)}}),r}function Hn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Un(e,t,n){let r={baseUrl:Hn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ot(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Wn(e){let t=e.request||ct,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Un(t,`POST /login/device/code`,n)}async function Gn(e){let t=await Un(e.request||ct,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Kn(e,t.data.expires_in),n.refreshTokenExpiresAt=Kn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Kn(e,t){return new Date(e+t*1e3).toISOString()}async function qn(e,t){let n=Jn(e,t.auth);if(n)return n;let{data:r}=await Wn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Xn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Jn(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Yn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Xn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Gn({...i,clientType:`oauth-app`}):await Gn({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Yn(r.interval),Xn(e,t,n,r);if(a===`slow_down`)return await Yn(r.interval+7),Xn(e,t,n,r);throw i}}async function Zn(e,t){return qn(e,{auth:t})}async function Qn(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await qn(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var $n=`0.0.0-development`;function er(e){let t=e.request||ct.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${$n} ${st()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Zn.bind(null,i),{hook:Qn.bind(null,i)})}async function tr(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=er({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BnlRWriT.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function nr(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const rr=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function V(e){let t=e.toLowerCase().replace(/:\d+$/,``);rr.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function ir(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function ar(e,t,n=tr){let r=nr(),{host:i,json:a}=e;V(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?ir(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?ir(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function or(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await ar(t,await e())})}const sr=e=>e.name===`enter`||e.name===`return`;var cr=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},lr=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},ur=class extends Error{name=`ExitPromptError`},dr=class extends Error{name=`HookError`},fr=class extends Error{name=`ValidationError`};const pr=new jn;function mr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function hr(e,t){let n=mr(e);return pr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function H(){let e=pr.getStore();if(!e)throw new dr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function gr(){return H().rl}function _r(e){return Mn.bind((...t)=>{let n=H(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function vr(e){let t=H(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function yr(){H().handleChange()}const br={queue(e){let t=H(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(gr());if(r!=null&&typeof r!=`function`)throw new fr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=H();_r(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=H();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function xr(e){return typeof e==`function`}function U(e){return vr(t=>{let n=Mn.bind(function(e){t.get()!==e&&(t.set(e),yr())});if(t.initialized)return[t.get(),n];let r=xr(e)?e():e;return t.set(r),[r,n]})}function Sr(e,t){vr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&br.queue(e),n.set(t)})}const Cr={prefix:{idle:B(`blue`,`?`),done:B(`green`,ht.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>B(`yellow`,e))},style:{answer:e=>B(`cyan`,e),message:e=>B(`bold`,e),error:e=>B(`red`,`> ${e}`),defaultAnswer:e=>B(`dim`,`(${e})`),help:e=>B(`dim`,e),highlight:e=>B(`cyan`,e),key:e=>B(`cyan`,B(`bold`,`<${e}>`))}};function wr(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Tr(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=wr(n)&&wr(r)?Tr(n,r):r}return t}function Er(...e){return Tr(Cr,...e.filter(e=>e!=null))}function Dr({status:e=`idle`,theme:t}){let[n,r]=U(!1),[i,a]=U(0),{prefix:o,spinner:s}=Er(t);return Sr(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function Or(e){return U({current:e})[0]}function kr(e){let t=Or(e);t.current=e,Sr(e=>{let n=!1,r=_r((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var Ar=e(mt(),1);function jr(e,t){return e.split(`
4
4
  `).flatMap(e=>pt(e,t,{trim:!1,hard:!0}).split(`
5
5
  `).map(e=>e.trimEnd())).join(`
@@ -19,9 +19,9 @@ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";impor
19
19
  `),patterns:[...t],lineCount:n}}const Zi=R(_n(),`.ok`,`logs`),Qi=R(_n(),`.ok`,`bug-reports`);function $i(e){let t=R(e,`.ok`,`config.yml`);if(N(t))try{let e=F(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return N(R(e,`.ok`))?En(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function ea(){let e={timestamp:new Date().toISOString(),platform:vn(),osType:Sn(),osRelease:yn(),hostname:`[redacted]`,uptime:Cn(),freeMem:gn(),totalMem:xn(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Xt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);N(t)&&(e.okVersion=JSON.parse(F(t,`utf8`)).version)}catch{}return e}function ta(e){if(!N(Zi))return{files:[],dir:Zi};let t=an(Zi).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(Zi,e));if(e&&t.length>0){let n=t.filter(t=>{try{return F(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:Zi}}function na(e){let t=R(e,`.ok`,`local`);return N(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>R(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}function ra(e){let t=R(e,`.ok`,`local`,`logs`);return N(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>N(e)),dir:t}:{files:[],dir:null}}async function ia(t){let n=Uu();P(Qi,{recursive:!0});let r=R(Qi,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=ea(),{files:a}=ta(t.projectSlug),{files:o}=na(t.cwd),{files:s}=ra(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CQSNnbvt.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Xi(F(e,`utf8`)),i=`logs/${L(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of o)try{let{redacted:t,patterns:n,lineCount:r}=Xi(F(e,`utf8`)),i=`lockdir/${L(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of s)try{let{redacted:t,patterns:n,lineCount:r}=Xi(F(e,`utf8`)),i=`local-logs/${L(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}let f=JSON.stringify(i,null,2);d.addBuffer(Buffer.from(f,`utf8`),`sysinfo.json`),l.push(`sysinfo.json`);let p={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:t.projectSlug,files:l,redactions:c,sysinfo:i};d.addBuffer(Buffer.from(JSON.stringify(p,null,2),`utf8`),`MANIFEST.json`);let m=c.reduce((e,t)=>e+t.lineCount,0),h=[`# Bug Report Bundle`,``,`Generated: ${p.generatedAt}`,`Project: ${t.projectSlug??`(unscoped)`}`,`Discipline version: ${p.disciplineVersion}`,``,`## Contents`,``,...l.map(e=>`- ${e}`),``,`## Privacy`,``,`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Yi.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
20
20
  `);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=tn(r);if(d.outputStream.pipe(g),await new Promise((e,t)=>{g.on(`close`,e),g.on(`error`,t)}),n?.info({bundlePath:r,fileCount:l.length,redactionCount:m},`bundle written`),process.stdout.write(`${r}\n`),m>0&&process.stderr.write(`ok bug-report: ${m} line(s) auto-redacted across ${c.length} file(s)\n`),!t.noReveal&&vn()===`darwin`)try{j(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function aa(){return new t(`bug-report`).description(`Generate a diagnostic bundle for bug reporting`).option(`--reveal`,`Reveal the bundle in Finder (default: true)`,!0).option(`--no-reveal`,`Do not reveal the bundle in Finder`).action(async e=>{let t=process.cwd(),n=$i(t);try{await ia({projectSlug:n,cwd:t,noReveal:!e.reveal})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`ok bug-report: failed — ${t}\n`),process.exitCode=1}})}function oa(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function sa(e){let t=e.inspect??(t=>At(e.lockDir,t)),n=e.unlink??(e=>ln(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=oa(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function ca(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),sa({lockDir:Ee(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function la(e,t,n={},r=oe){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}async function ua(e,t,n=fetch){let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{return(await n(`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{signal:r.signal,headers:{"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}})).status===200}catch{return!1}finally{clearTimeout(i)}}const da=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function fa(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of da)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function K(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function pa(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t.GIT_TERMINAL_PROMPT=`0`,t.LANG=`C`,t.LC_ALL=`C`,t}function ma(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const ha=s;async function ga(e){try{return await e.clone(ma(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&ha(t))return e.onFallback(e.branch),await e.clone(ma(null)),{fellBack:!0};throw t}}function _a(e,t){return{baseDir:e,config:t,unsafe:{allowUnsafeCredentialHelper:!0,allowUnsafePager:!0,allowUnsafeSshCommand:!0,allowUnsafeAskPass:!0}}}function va(e,t,n){return e===`https`&&t===`github.com`&&n}function ya(e,t){let n=`${t.owner}/${t.name}`;return e===n||e===`${n}.git`?`https://${t.hostname}/${n}`:e}async function ba(e,t,n,r=process.cwd()){let i=Nt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=ya(e,i),o=t.dir?z(r,t.dir):z(r,i.name);if(N(o)&&an(o).length>0)throw Error(`Target directory is not empty: ${o}`);let s=re(),c=i.protocol===`https`&&i.hostname===`github.com`?await ua(i.owner,i.name):!1,l=va(i.protocol,i.hostname,c)?{tier:`none`,credentialArgs:[]}:await la(i.hostname,s,{}),u=pa(),d=w(_a(r,l.credentialArgs.length>=2?[l.credentialArgs[1]]:[])).env(u),f=-1;d.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
21
21
  `)){let n=fa(e);n&&n.pct!==f&&(f=n.pct,K(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await ga({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:e=>d.clone(a,o,e),onFallback:e=>{K(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
22
- `);try{let{runInit:e}=await import(`./init-BP843Mwl.mjs`),n=await e({cwd:o,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?K(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{xa(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function xa(e){let t=St(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const Sa=/^[A-Za-z0-9._/:@-]+$/;function Ca(e){return Sa.test(e)?e:C(e)}function wa(e,t){let n=typeof t==`string`&&t.length>0?` -b ${Ca(t)}`:``;return`ok clone ${Ca(e)}${n}`}function Ta(e){let t=te(e.error);if(t.kind!==`auth`)return null;if(a(t)){let t=wa(e.url,e.branch);return[`✗ Couldn't clone ${e.url} — authentication is required.`,``,` To fix:`,` 1. Run: ok auth login`,` 2. Then re-run: ${t}`].join(`
22
+ `);try{let{runInit:e}=await import(`./init-Cz9Xc6e4.mjs`),n=await e({cwd:o,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?K(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{xa(o)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?K(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return o}function xa(e){let t=St(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}const Sa=/^[A-Za-z0-9._/:@-]+$/;function Ca(e){return Sa.test(e)?e:C(e)}function wa(e,t){let n=typeof t==`string`&&t.length>0?` -b ${Ca(t)}`:``;return`ok clone ${Ca(e)}${n}`}function Ta(e){let t=te(e.error);if(t.kind!==`auth`)return null;if(a(t)){let t=wa(e.url,e.branch);return[`✗ Couldn't clone ${e.url} — authentication is required.`,``,` To fix:`,` 1. Run: ok auth login`,` 2. Then re-run: ${t}`].join(`
23
23
  `)}if(t.subclass===`403`){let t=typeof e.principal==`string`&&e.principal.length>0?` (signed in as @${e.principal} — may lack access)`:``;return`✗ Access denied when cloning ${e.url}${t}. Check that your account has access to the repository.`}return t.subclass===`ssh-auth`?`✗ Couldn't clone ${e.url} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`:["✗ Your GitHub token is missing required OAuth scopes — likely the `repo` scope.",``,` To fix:`," 1. Create a token with `repo` scope at https://github.com/settings/tokens",` 2. Run: ok auth pat`,` 3. Then re-run: ${wa(e.url,e.branch)}`].join(`
24
- `)}function Ea(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Ta({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Da(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function Oa(e){let t=te(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=Nt(e.url);t&&(n=await(e.resolvePrincipal??(e=>Da(re(),e)))(t.hostname))}Ea({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function ka(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await ba(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)K(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-B3JghErx.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){await Oa({error:e,url:t,branch:r.branch??null,json:r.json,emit:e=>K(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var Aa=r();const ja=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...n.map(e=>e.path)];function Ma(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??zt;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Na(e){let t=(0,Aa.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of ja)t.hasIn(e)&&n.push(e.join(`.`));return n}function Pa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Pa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ia(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Ve,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:Ce(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:Ce(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!N(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Na(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:a,scope:t,patch:Fa(ja.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:o(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function La(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Ma({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ia({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Ra=e(at(),1),q=e(qt(),1);const za=new Set([`doc.name`]);function Ba(e){return`doc:${En(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function Va(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function Ha(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Ba(e);return t.originalToHashed.set(e,r),Va(t,e,r),r}function Ua(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function Wa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ga(e,t){if(typeof e==`string`)return Ua(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Ga(e,t));if(!Wa(e))return e;let n=typeof e.key==`string`&&za.has(e.key)&&Wa(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&Wa(a)){let e=Ha(n,t);r[i]={...a,stringValue:e}}else za.has(i)&&typeof a==`string`?r[i]=Ha(a,t):r[i]=Ga(a,t);return r}function Ka(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function qa(e,t){let n=F(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
24
+ `)}function Ea(e){let t=e.error instanceof Error?e.error.message:String(e.error);if(e.json){e.emit({type:`error`,message:t});return}let n=Ta({error:e.error,url:e.url,branch:e.branch,principal:e.principal});e.printStderr(`${n??`✗ ${t}`}\n`)}async function Da(e,t){let n=(await e.get(t))?.login;return n&&n!==`unknown`?n:null}async function Oa(e){let t=te(e.error),n=null;if(!e.json&&t.kind===`auth`&&t.subclass===`403`){let t=Nt(e.url);t&&(n=await(e.resolvePrincipal??(e=>Da(re(),e)))(t.hostname))}Ea({error:e.error,url:e.url,branch:e.branch,json:e.json,principal:n,emit:e.emit,printStderr:e.printStderr})}function ka(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await ba(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)K(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-Uo8BaBLY.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){await Oa({error:e,url:t,branch:r.branch??null,json:r.json,emit:e=>K(!0,e),printStderr:e=>process.stderr.write(e)}),process.exitCode=1}})}var Aa=r();const ja=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...n.map(e=>e.path)];function Ma(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??zt;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function Na(e){let t=(0,Aa.parseDocument)(F(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of ja)t.hasIn(e)&&n.push(e.join(`.`));return n}function Pa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=Pa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ia(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),s=e.writeConfigPatchFn??Ve,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:Ce(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:Ce(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!N(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=Na(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:a,scope:t,patch:Fa(ja.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:o(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function La(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{Ma({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ia({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Ra=e(at(),1),q=e(qt(),1);const za=new Set([`doc.name`]);function Ba(e){return`doc:${En(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function Va(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function Ha(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Ba(e);return t.originalToHashed.set(e,r),Va(t,e,r),r}function Ua(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function Wa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ga(e,t){if(typeof e==`string`)return Ua(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Ga(e,t));if(!Wa(e))return e;let n=typeof e.key==`string`&&za.has(e.key)&&Wa(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&Wa(a)){let e=Ha(n,t);r[i]={...a,stringValue:e}}else za.has(i)&&typeof a==`string`?r[i]=Ha(a,t):r[i]=Ga(a,t);return r}function Ka(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function qa(e,t){let n=F(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
25
25
  `),i=n.split(`
26
26
  `),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=Ga(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}I(e,r?`${a.join(`
27
27
  `)}\n`:a.join(`
@@ -52,7 +52,7 @@ ws.addEventListener('error', () => process.exit(1));
52
52
  setTimeout(() => process.exit(2), ${t+1e4});
53
53
  `),r}async function is(e,t,n,r,i){let a=rs(e,t,R(r,`cpu.cpuprofile`)),o=!1,s=j(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=$o(n);e&&i(e)},1e3);await new Promise(e=>{s.once(`close`,t=>{o=t===0,e()}),setTimeout(()=>{s.kill(),e()},t+12e3)}),clearInterval(c);try{sn(R(a,`..`),{recursive:!0,force:!0})}catch{}return o}function as(e){let t;try{t=JSON.parse(e)}catch{return`(could not parse profile)`}let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map;for(let e of t.nodes)for(let t of e.children??[])r.set(t,e.id);let i=new Map;for(let e of t.samples??[])i.set(e,(i.get(e)??0)+1);let a=t.samples?.length??0,o=t.endTime!=null&&t.startTime!=null?((t.endTime-t.startTime)/1e3).toFixed(2):`?`,s=[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10),c=[`samples ${a} duration_ms ${o}`,``,`Top leaf nodes`];for(let[e,t]of s){let r=n.get(e);if(!r)continue;let i=a>0?(t/a*100).toFixed(1):`0.0`,{functionName:o,url:s,lineNumber:l,columnNumber:u}=r.callFrame;c.push(` ${t} ${i}% id=${e} ${o||`(anonymous)`} ${s}:${l}:${u} hit=${r.hitCount??0}`)}c.push(``,`Top stacks`);let l=e=>{let t=[],i=e;for(;i!=null;){let e=n.get(i);if(!e)break;let{functionName:a,url:o,lineNumber:s,columnNumber:c}=e.callFrame;t.unshift(` ${a||`(anonymous)`} ${o} ${s} ${c}`),i=r.get(i)}return t};for(let[e,t]of s.slice(0,5)){let n=a>0?(t/a*100).toFixed(1):`0.0`;c.push(``,`--- ${t} ${n}%`,...l(e))}return c.join(`
54
54
  `)}async function os(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??kt,s=t.inspect??At,c=t.resolveCommand??Mt,l=t.resolveUsage??It,u=t.collectLsofFn??es,d=t.getEndpoints??ns,f=t.profiler??is,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(q.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let ee=new Date().toISOString().replace(/[:.]/g,`-`),b=e.output?e.output:v?R(v,`.ok`,`local`,`diagnostics`,`process-${n}-${ee}`):R(process.cwd(),`ok-diagnose-${n}-${ee}`);try{P(b,{recursive:!0})}catch(e){a(q.default.red(`Cannot create output directory ${b}: ${e.message}`));return}a(q.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${b}`),a(``);let x=(e,t)=>{I(R(b,e),t),a(` wrote ${e}`)},S=c(n),te=l(n);x(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:S,usage:te,lockInfo:y},null,2)),a(` sampling lsof`);let C=u(n);if(C&&x(`lsof.txt`,C),!i){let e=C?ts(C).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(q.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){x(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,b,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(q.default.yellow(` CPU profile capture failed`)),t.length>0&&x(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
55
- `)}\n`);try{x(`stacks.txt`,as(F(R(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(q.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(q.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(q.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${q.default.bold(b)}`)}async function ss(e){let t=Pn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function cs(e){let t=nn(R(bn(),`ok-bundle-process-`));return await os({pid:e,output:t}),t}function ls(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function us(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function ds(e,t,n){let{summary:r,manifest:i}=t;e(``),e(q.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${ls(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function fs(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??ss,i=t.runProcessDiagnose??cs,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=dn(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=R(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=R(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(q.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Oo({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(q.default.yellow(` server not running — live state unavailable`)),ds(n,c,o),e.yes!==!0&&!us(await r(`Write bundle? [y/N]: `))?(n(q.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await ko({collected:c,outputPath:o}),n(q.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{sn(s,{recursive:!0,force:!0})}catch{}}}function ps(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(q.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(q.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await os({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Qo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(q.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-CL1cBJAY.mjs`),{resolveContentDir:r}=await import(`./dist-Y_CEziF9.mjs`),i=process.cwd(),{config:a}=n(i);await fs({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(q.default.red(t)),process.exit(1)}}),e}async function ms(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Hr({message:`Enter OpenAI embeddings API key:`})).trim()}function hs(e){return tt(e)}async function gs(){return(await Ie()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function _s(e){try{let t=p(Ee(e));if(!t||t.port<=0||!y(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function vs(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await ms();if(!e){process.stderr.write(`No key provided.
55
+ `)}\n`);try{x(`stacks.txt`,as(F(R(b,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(q.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(q.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(q.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${q.default.bold(b)}`)}async function ss(e){let t=Pn({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function cs(e){let t=nn(R(bn(),`ok-bundle-process-`));return await os({pid:e,output:t}),t}function ls(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function us(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function ds(e,t,n){let{summary:r,manifest:i}=t;e(``),e(q.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${ls(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function fs(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??ss,i=t.runProcessDiagnose??cs,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=dn(o);if(!N(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=R(e.contentDir,`.ok`,`local`,`diagnostics`);P(n,{recursive:!0}),o=R(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(q.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await Oo({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(q.default.yellow(` server not running — live state unavailable`)),ds(n,c,o),e.yes!==!0&&!us(await r(`Write bundle? [y/N]: `))?(n(q.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await ko({collected:c,outputPath:o}),n(q.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{sn(s,{recursive:!0,force:!0})}catch{}}}function ps(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(q.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(q.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await os({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Qo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(q.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-Bhq-VNS_.mjs`),{resolveContentDir:r}=await import(`./dist-Y_CEziF9.mjs`),i=process.cwd(),{config:a}=n(i);await fs({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(q.default.red(t)),process.exit(1)}}),e}async function ms(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Hr({message:`Enter OpenAI embeddings API key:`})).trim()}function hs(e){return tt(e)}async function gs(){return(await Ie()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function _s(e){try{let t=p(Ee(e));if(!t||t.port<=0||!y(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function vs(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await ms();if(!e){process.stderr.write(`No key provided.
56
56
  `),process.exitCode=1;return}await qe().set(e),process.stderr.write(`✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).
57
57
  Now enable it per project — the easiest path is OK Desktop → Settings → This
58
58
  project → Search (a toggle with an egress-confirmation prompt), or run
@@ -72,7 +72,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
72
72
  `).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function Nl(e){let t=z(e);for(;;){if(se(t))return t;let n=dn(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${ne}\`).`);t=n}}function Pl(e){try{let t=new URL(e);return t.protocol===`file:`?wn(t):void 0}catch{return}}async function Fl(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Pl(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Il(e,t,n,r=Nl){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function Ll(e){let t=process.stderr,n=e.spawnTimeoutMs??hl(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=Bt({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new Oe({name:fe,version:g});he(a);let o=Dn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=de(e),r=s.current,i=Ls({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Dl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>Fl({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d,f=!1,p=async e=>{if(f)return;f=!0;let n=await Ml(e);if(n<=1){f=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${n} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{t.write(`[mcp] ${r}\n`),await a.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},m=async e=>{let t=await Il(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&p(t.projectDir),t.projectDir},h=async e=>{let t=await Il(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)return;t.viaRootGuess&&p(t.projectDir);let a=t.projectDir,o=await i(a),s=await El({lockDir:de(a),contentDir:ce(o,a),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(a),s.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Fe(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},xe(a,{serverUrl:h,resolveCwd:m,config:i,identityRef:s});let _=new Vs,v=!1,y,ee,b=async()=>{if(v)return;v=!0,y?.stop(),ee?.stop();for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),_.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await a.connect(_),t.write(`[mcp] global stdio server ready (per-call project routing)
73
73
  `);let x=!1,S=()=>{x||(x=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
74
74
  `),process.exit(1)},5e3).unref(),b().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,S),process.once(`SIGTERM`,S),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
75
- `),S()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),S()}),ee=Gs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),S()}}),Ks({log:e=>t.write(`${e}\n`),transport:_,process,stdin:process.stdin}),process.platform===`darwin`){let e=Ws(Al,{realpathSync:on,statInoSync:e=>cn(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${g}\n`);let{resolvedPath:n,inode:r}=e;y=Us({detect:()=>Hs({bundleAnchorPath:Al,currentInode:r,platform:process.platform,realpath:on,statInode:e=>cn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${g} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:b}}function Rl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=hl(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await kl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Ps(process.env,i,process.platform);if(a.proxy){let e=Ns(process.platform,_n(),{existsSync:N});if(e===null)Fs({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Is({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Fs({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Fs({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Ll({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function zl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Bl(e=()=>Gt(Ut())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ye({lockDir:Ee(e)}).baseUrl,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:zl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Vl(e,t,n){let r=z(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Be(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Hl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Vl(e,t,Bl())})}function Ul(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-BcwxW8Jz.mjs`),r=e(),i=process.cwd(),a=ce(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Wl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Gl(e,t,n=process.cwd()){let r=e.op??`sync`,i=p(Ee(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...S({kind:`cli`,runtimeVersion:g})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Wl(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=w({baseDir:n});if(r===`sync`||r===`pull`){Wl(e.json,{type:`step`,step:`pull`});let t=await a.pull();Wl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Wl(e.json,{type:`step`,step:`push`}),await a.push(),Wl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
75
+ `),S()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),S()}),ee=Gs({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),S()}}),Ks({log:e=>t.write(`${e}\n`),transport:_,process,stdin:process.stdin}),process.platform===`darwin`){let e=Ws(Al,{realpathSync:on,statInoSync:e=>cn(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${g}\n`);let{resolvedPath:n,inode:r}=e;y=Us({detect:()=>Hs({bundleAnchorPath:Al,currentInode:r,platform:process.platform,realpath:on,statInode:e=>cn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${g} — exiting for host respawn\n`),S()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:b}}function Rl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=hl(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await kl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Ps(process.env,i,process.platform);if(a.proxy){let e=Ns(process.platform,_n(),{existsSync:N});if(e===null)Fs({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await Is({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Fs({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Fs({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await Ll({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function zl(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function Bl(e=()=>Gt(Ut())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>ye({lockDir:Ee(e)}).baseUrl,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:zl(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Vl(e,t,n){let r=z(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Be(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Qe(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function Hl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Vl(e,t,Bl())})}function Ul(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DWfgcb6s.mjs`),r=e(),i=process.cwd(),a=ce(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Wl(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Gl(e,t,n=process.cwd()){let r=e.op??`sync`,i=p(Ee(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...S({kind:`cli`,runtimeVersion:g})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Wl(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=w({baseDir:n});if(r===`sync`||r===`pull`){Wl(e.json,{type:`step`,step:`pull`});let t=await a.pull();Wl(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Wl(e.json,{type:`step`,step:`push`}),await a.push(),Wl(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
76
76
  `)),Wl(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Kl(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Gl({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function ql(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Gl({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Jl(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Gl({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function Yl(e){return typeof e==`string`&&Se.includes(e)}async function Xl(e={}){let t=z(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!je[n])return{status:`failed`,message:`${O(`Error:`)} Unknown pack "${n}". Available: ${Se.join(`, `)}`,exitCode:1};let r;try{r=await it({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ze?{status:`prerequisite-missing`,message:`${O(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${O(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=je[n].name;return{status:`no-op`,message:`${D(`Your ${e} pack is already seeded.`)}\n${E(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun){let e=ue(je[n]);return{status:`dry-run`,message:`${A(`Reference this pack for inspiration (dry-run — no changes made):`)}\n\n${e}\n\n${A(`Plan:`)}\n\n${Ql(r,t)}`,plan:r,exitCode:0}}if(!e.yes&&!await $l(`${A(`Plan:`)}\n\n${Ql(r,t)}\n\n${A(`Apply?`)} ${E(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:E(`Cancelled.`),plan:r,exitCode:0};let i=await We(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${O(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${k(`Applied`)} ${i.applied} entries, ${k(String(i.errors.length))} error(s):`,...e].join(`
77
77
  `),plan:r,exitCode:1}}let a=je[n].name,o=i.packSkillsInstalled.length>0?`\n${E(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${D(`✓ Seeded ${a}`)} ${E(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function Zl(){let e=[A(`Available packs:`)];for(let t of Se){let n=je[t];e.push(` ${D(t)} ${E(`—`)} ${n.name}: ${n.description}`)}return e.join(`
78
78
  `)}function Ql(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(A(`Folders to create:`));for(let e of r)n.push(` ${D(`+`)} ${T(fn(t,z(t,e.path))||e.path)}${E(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(A(`Files to create:`));for(let e of i)n.push(` ${D(`+`)} ${T(fn(t,z(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(E(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${E(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(k(`Warnings:`));for(let t of e.warnings)n.push(` ${k(`!`)} ${t}`)}return n.join(`
@@ -81,7 +81,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
81
81
  `);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function ru(e){return new t(`name-check`).description(`Check if owner/name is available on GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await nu(t,await e())})}async function iu(e){try{let t=[],n=await e.users.getAuthenticated();t.push({login:n.data.login,kind:`user`,avatarUrl:n.data.avatar_url});for await(let n of e.paginate.iterator(e.orgs.listMembershipsForAuthenticatedUser,{state:`active`,per_page:100}))for(let e of n.data)(e.permissions?.can_create_repository===!0||e.role===`admin`)&&t.push({login:e.organization.login,kind:`org`,avatarUrl:e.organization.avatar_url??void 0});return{kind:`ok`,owners:t}}catch(e){return e.status===401?{kind:`auth-required`}:{kind:`network`}}}async function au(e,t){let{host:n,json:r}=e;V(n);let i=await Ri(n,t);if(i==null){if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=await iu(new G({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function ou(e){return new t(`owners`).description(`List GitHub owners eligible to host a new repository`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await au(t,await e())})}function su(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
82
82
  `)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function cu(e){let{octokit:t,ownerLogin:n,ownerKind:r,name:i,visibility:a,description:o}=e,s=a===`private`;if(r===`user`){let{data:e}=await t.repos.createForAuthenticatedUser({name:i,private:s,...o?{description:o}:{}});return{cloneUrl:e.clone_url,defaultBranch:e.default_branch??`main`}}let{data:c}=await t.repos.createInOrg({org:n,name:i,visibility:a,...o?{description:o}:{}});return{cloneUrl:c.clone_url,defaultBranch:c.default_branch??`main`}}async function lu(e,t,n){try{let{data:r}=await e.repos.get({owner:t,repo:n});return{cloneUrl:r.clone_url,defaultBranch:r.default_branch??`main`}}catch{return null}}async function uu(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function du(e){return w({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function fu(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const pu={ensureOkScaffold:e=>{we(e)},gitFactory:du};async function mu(e){let t={...pu,...e.deps},n=z(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await uu(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:su(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!N(R(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await cu({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(su(t)===`name-conflict`){let t=await lu(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:su(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=fu(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function hu(e,t){if(!e){t.kind===`ok`?process.stdout.write(`✓ Published ${t.value.cloneUrl}\n`):(process.stderr.write(`✗ share publish failed: ${t.code}\n`),process.exit(1));return}if(t.kind===`ok`){process.stdout.write(`${JSON.stringify({type:`publish`,...t.value})}\n`);return}process.stdout.write(`${JSON.stringify({type:`error`,code:t.code})}\n`)}async function gu(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;V(n);let l=await Ri(n,t);if(l==null){hu(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new G({auth:l,...u?{baseUrl:u}:{}});try{Xt(`git config user.email`,{cwd:s,stdio:`ignore`})}catch{process.env.GIT_AUTHOR_NAME??=`Open Knowledge`,process.env.GIT_AUTHOR_EMAIL??=`noreply@inkeep.com`,process.env.GIT_COMMITTER_NAME??=`Open Knowledge`,process.env.GIT_COMMITTER_EMAIL??=`noreply@inkeep.com`}hu(c,await mu({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function _u(e){return new t(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
83
83
  `),process.exit(1)),await gu(t,await e())})}function vu(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>ae();return e.addCommand(ou(n)),e.addCommand(ru(n)),e.addCommand(_u(n)),e}function yu(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=z(e.project??process.cwd()),n=xt(t),r=ft(t,ut(t));if(r.kind===`no-exclude`){bu(e.json,t,r.reason);return}let i=xt(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${T(`Sharing mode is already`)} ${A(`shared`)} ${T(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${A(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function bu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${k({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function xu(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=z(e.project??process.cwd()),n=xt(t),r=[...bt(t)],i=Dt(t,ut(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`Open Knowledge sharing mode: ${Su(n)}`),a.push(``),a.push(`Excluded from git via ${A(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${T(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
84
- `)}\n`)})}function Su(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return k(`no-git (not a git repository)`)}}function Cu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=z(e.project??process.cwd()),n=St(t,ut(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){wu(e.json,t,n.reason);return}let r=xt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${A(`Sharing mode is already`)} ${D(`local-only`)} ${A(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${A(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function wu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${k({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Tu(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(yu()),e.addCommand(Cu()),e.addCommand(xu()),e}const Eu=new Set([`--cwd`,`--log-level`]);function Du(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){Eu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Ou(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ku(e){return/\.(md|mdx)$/i.test(e)}function Au(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function ju(e=()=>Gt(Ut())){return{prepare:Re,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Au(process.env)}).unref()},runProjectOpen:(e,t)=>Vl(e,{project:t},Bl()),runBrowserOpen:e=>Pu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Mu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof He||e instanceof Ye||e instanceof Le)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function Nu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[z(e,`public`),z(e,`../../app/dist`),z(e,`../../../app/dist`)].find(e=>N(e))}async function Pu(e){let{createEphemeralProjectDir:t}=await import(`./dist-Y_CEziF9.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-B3JghErx.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=Nu();o||(process.stderr.write("Open Knowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await Tn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Qe(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
84
+ `)}\n`)})}function Su(e){switch(e){case`shared`:return D(`shared`);case`local-only`:return D(`local-only`);case`no-git`:return k(`no-git (not a git repository)`)}}function Cu(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=z(e.project??process.cwd()),n=St(t,ut(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){wu(e.json,t,n.reason);return}let r=xt(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${A(`Sharing mode is already`)} ${D(`local-only`)} ${A(`— nothing to do.`)}\n`);return}process.stderr.write(`${D(`✓`)} ${A(`Sharing mode set to`)} ${D(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${A(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function wu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${k({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function Tu(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(yu()),e.addCommand(Cu()),e.addCommand(xu()),e}const Eu=new Set([`--cwd`,`--log-level`]);function Du(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){Eu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function Ou(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function ku(e){return/\.(md|mdx)$/i.test(e)}function Au(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function ju(e=()=>Gt(Ut())){return{prepare:Re,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{j(`open`,[e],{detached:!0,stdio:`ignore`,env:Au(process.env)}).unref()},runProjectOpen:(e,t)=>Vl(e,{project:t},Bl()),runBrowserOpen:e=>Pu(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function Mu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof He||e instanceof Ye||e instanceof Le)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function Nu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[z(e,`public`),z(e,`../../app/dist`),z(e,`../../../app/dist`)].find(e=>N(e))}async function Pu(e){let{createEphemeralProjectDir:t}=await import(`./dist-Y_CEziF9.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-Uo8BaBLY.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=Nu();o||(process.stderr.write("Open Knowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await Tn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Qe(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
85
85
  `),a(m),await new Promise(()=>{})}function Fu(e,t){return{server:Iu(`server`,e),ui:Iu(`ui`,t)}}function Iu(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Lu(e){return`${Ru(e.server)}\n${Ru(e.ui)}`}function Ru(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function zu(e){let t=e.inspect??(t=>At(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Fu(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Lu(r)),r}function Bu(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),zu({lockDir:Ee(process.cwd()),json:t.json===!0})})}function Vu(e){return[e,`Copyright (C) 2026 Inkeep, Inc.`,`License GPL-3.0-or-later: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.`,`This is free software: you are free to change and redistribute it.`,`There is NO WARRANTY, to the extent permitted by law.`].join(`
86
86
  `)}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $,Hu;function Uu(){return Hu}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(Vu(Lt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=Pt(n,process.cwd());r!==null&&(Ot(process.cwd()),process.chdir(r),console.error(`[ok] Using Open Knowledge project at ${r}`));let{config:i}=zt(r??t);$=i;let a=e.args?.[0]??e.name()??`cli`;Hu=ke({name:`cli`,project:i.project?.name??void 0}),Hu.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Gt(Ut()).available){Vt({spawn:j});return}await Wt($,{})});const Wu=Ht(()=>$);Q.addCommand(Wu);const Gu=Rl(()=>$);Q.addCommand(Gu),Q.addCommand(Tt()),Q.addCommand(eu()),Q.addCommand(As()),Q.addCommand(Jt());const Ku=Ul(()=>$);Q.addCommand(Ku);const qu=Et(()=>$);Q.addCommand(qu),Q.addCommand(Hl()),Q.addCommand(jt(()=>$)),Q.addCommand(ca(()=>$)),Q.addCommand(Bu(()=>$)),Q.addCommand(Ft()),Q.addCommand(ps()),Q.addCommand(aa()),Q.addCommand(La()),Q.addCommand(qi(Uu)),Q.addCommand(Ss()),Q.addCommand(ka(()=>$)),Q.addCommand(Kl(()=>$)),Q.addCommand(Jl(()=>$)),Q.addCommand(ql(()=>$)),Q.addCommand(vu()),Q.addCommand(Tu()),Q.addHelpText(`after`,`
87
87
  Examples:
@@ -0,0 +1,2 @@
1
+ import"./server-lock-BpjJj3OD-dsDEfapU.mjs";var e=`0.19.0-beta.2`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-DRZYaWtr.mjs.map
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{i as e,r as t,t as n}from"./gh-detect-DLds_L3H.mjs";import{C as r,E as i,S as a,T as o,_ as s,b as c,d as l,g as u,h as d,i as f,o as p,r as m,s as h,t as g,w as _,x as v,y}from"./init-CHlwzxSA.mjs";import{d as b,f as x,m as S,n as C,p as w,r as T,t as E}from"./src-CABDPvtm.mjs";import{a as D,c as O,o as k,r as A,s as j,t as M}from"./write-project-skill-Bn8zRlMF.mjs";import{n as N}from"./loader-CjrRykwH.mjs";import{n as P}from"./preview-Cv6HcQ_e.mjs";import{n as F,t as I}from"./mcp-migrate-event-D0NrGjvc.mjs";export{A as ALL_EDITOR_IDS,D as EDITOR_LABELS,k as EDITOR_TARGETS,g as LAUNCH_CONFIG_NAME,m as LAUNCH_UI_CHAIN_SENTINEL,f as LAUNCH_UI_CHAIN_V1,c as addOkPathsToGitExclude,M as assertProjectPathSafe,j as buildManagedServerEntry,I as buildMcpConfigMigrateEvent,p as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,h as detectInstalledEditors,v as formatTrackedRemediation,a as getExcludedOkPaths,r as getOkArtifactPaths,O as isEntryUpToDate,N as loadConfig,e as makeLazyProbeTokenStore,b as parseGitHubBlobUrl,x as parseGitHubShareUrl,w as parseGitHubTreeUrl,S as parseGitUrl,P as previewContent,_ as probeTrackedOkPaths,l as readExistingMcpEntry,o as readSharingMode,i as removeOkPathsFromGitExclude,y as resolveProjectRoot,T as runStop,d as scaffoldLaunchJson,F as truncatePriorEntry,C as validateLocalFolderForShare,u as writeEditorMcpConfig,E as writeProjectAiIntegrations,s as writeUserMcpConfigs};
1
+ import{i as e,r as t,t as n}from"./gh-detect-DLds_L3H.mjs";import{C as r,E as i,S as a,T as o,_ as s,b as c,d as l,g as u,h as d,i as f,o as p,r as m,s as h,t as g,w as _,x as v,y}from"./init-BMT_3l9F.mjs";import{d as b,f as x,m as S,n as C,p as w,r as T,t as E}from"./src-ANkvjof-.mjs";import{a as D,c as O,o as k,r as A,s as j,t as M}from"./write-project-skill-Bn8zRlMF.mjs";import{n as N}from"./loader-D4wC401d.mjs";import{n as P}from"./preview-BGMRorsT.mjs";import{n as F,t as I}from"./mcp-migrate-event-D0NrGjvc.mjs";export{A as ALL_EDITOR_IDS,D as EDITOR_LABELS,k as EDITOR_TARGETS,g as LAUNCH_CONFIG_NAME,m as LAUNCH_UI_CHAIN_SENTINEL,f as LAUNCH_UI_CHAIN_V1,c as addOkPathsToGitExclude,M as assertProjectPathSafe,j as buildManagedServerEntry,I as buildMcpConfigMigrateEvent,p as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,h as detectInstalledEditors,v as formatTrackedRemediation,a as getExcludedOkPaths,r as getOkArtifactPaths,O as isEntryUpToDate,N as loadConfig,e as makeLazyProbeTokenStore,b as parseGitHubBlobUrl,x as parseGitHubShareUrl,w as parseGitHubTreeUrl,S as parseGitUrl,P as previewContent,_ as probeTrackedOkPaths,l as readExistingMcpEntry,o as readSharingMode,i as removeOkPathsFromGitExclude,y as resolveProjectRoot,T as runStop,d as scaffoldLaunchJson,F as truncatePriorEntry,C as validateLocalFolderForShare,u as writeEditorMcpConfig,E as writeProjectAiIntegrations,s as writeUserMcpConfigs};
@@ -1,4 +1,4 @@
1
- import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{r,t as i}from"./esm-BLMtE3s6.mjs";import{Ft as a,Mr as o,St as s,ln as c,y as l}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{$i as u,$n as d,Bi as f,Gn as p,Kn as m,Rn as h,W as g,Wn as _,Xi as v,Xn as y,fn as b,ia as x,on as S}from"./dist-CWv9hwiJ.mjs";import"./constants-BiXELTVf.mjs";import{l as C,n as w,o as T,r as E,t as D,u as ee}from"./write-project-skill-Bn8zRlMF.mjs";import{t as O}from"./is-object-Cg453afR.mjs";import{i as k,o as A,r as te,s as j,t as M}from"./colors-CBY1ibtz.mjs";import{t as N}from"./preview-Cv6HcQ_e.mjs";import{execFileSync as ne}from"node:child_process";import{existsSync as P,mkdirSync as re,readFileSync as F,realpathSync as ie,writeFileSync as I}from"node:fs";import L,{dirname as ae,isAbsolute as oe,join as R,relative as z,resolve as B,sep as se}from"node:path";import V from"node:process";import{homedir as ce}from"node:os";import{randomUUID as le}from"node:crypto";import{stripVTControlCharacters as ue,styleText as H}from"node:util";import{AsyncLocalStorage as de,AsyncResource as U}from"node:async_hooks";import{createServer as fe,request as pe}from"node:http";import*as me from"node:readline";import{connect as he}from"node:net";function ge(){return V.platform.startsWith(`win`)?!!V.env.CI||!!V.env.WT_SESSION||!!V.env.TERMINUS_SUBLIME||V.env.ConEmuTask===`{cmd::Cmder}`||V.env.TERM_PROGRAM===`Terminus-Sublime`||V.env.TERM_PROGRAM===`vscode`||V.env.TERM===`xterm-256color`||V.env.TERM===`alacritty`||V.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:V.env.TERM!==`linux`}const _e={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},ve={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ye={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},be={..._e,...ve},xe={..._e,...ye},W=ge()?be:xe;Object.entries(ve);var Se=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Ce=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),we=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Te=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ee=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,De=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Oe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ke=/\t{1,1000}/y,Ae=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,je=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Me=/\p{M}+/gu,Ne={limit:1/0,ellipsis:``},Pe=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Pe(i,Ne,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[je,l],[Ee,0],[De,o],[ke,s],[Ae,c],[Oe,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Me,``)){let t=e.codePointAt(0)||0;if(S=we(t)?2:Te(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Oe?Ce(e.slice(p,n.lastIndex)):n===Ae?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Fe={limit:1/0,ellipsis:``,ellipsisWidth:0},G=(e,t={})=>Pe(e,Fe,t).width,Ie=`]8;;`,Le=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ie}(?<uri>.*))`,`y`),Re=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ze=e=>`[${e}m`,Be=e=>`${Ie}${e}`,Ve=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:G(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=G(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ie,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},He=e=>{let t=e.split(` `),n=t.length;for(;n&&!G(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ue=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=G(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=G(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ve(s,r,t),c=G(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ve(s,r,t),c=G(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ve(s,r,t),c=G(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>He(e)));let l=s.join(`
1
+ import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{r,t as i}from"./esm-BLMtE3s6.mjs";import{Ft as a,Mr as o,St as s,ln as c,y as l}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{$i as u,$n as d,Bi as f,Gn as p,Kn as m,Rn as h,W as g,Wn as _,Xi as v,Xn as y,fn as b,ia as x,on as S}from"./dist-CWv9hwiJ.mjs";import"./constants-DRZYaWtr.mjs";import{l as C,n as w,o as T,r as E,t as D,u as ee}from"./write-project-skill-Bn8zRlMF.mjs";import{t as O}from"./is-object-Cg453afR.mjs";import{i as k,o as A,r as te,s as j,t as M}from"./colors-CBY1ibtz.mjs";import{t as N}from"./preview-BGMRorsT.mjs";import{execFileSync as ne}from"node:child_process";import{existsSync as P,mkdirSync as re,readFileSync as F,realpathSync as ie,writeFileSync as I}from"node:fs";import L,{dirname as ae,isAbsolute as oe,join as R,relative as z,resolve as B,sep as se}from"node:path";import V from"node:process";import{homedir as ce}from"node:os";import{randomUUID as le}from"node:crypto";import{stripVTControlCharacters as ue,styleText as H}from"node:util";import{AsyncLocalStorage as de,AsyncResource as U}from"node:async_hooks";import{createServer as fe,request as pe}from"node:http";import*as me from"node:readline";import{connect as he}from"node:net";function ge(){return V.platform.startsWith(`win`)?!!V.env.CI||!!V.env.WT_SESSION||!!V.env.TERMINUS_SUBLIME||V.env.ConEmuTask===`{cmd::Cmder}`||V.env.TERM_PROGRAM===`Terminus-Sublime`||V.env.TERM_PROGRAM===`vscode`||V.env.TERM===`xterm-256color`||V.env.TERM===`alacritty`||V.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:V.env.TERM!==`linux`}const _e={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},ve={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ye={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},be={..._e,...ve},xe={..._e,...ye},W=ge()?be:xe;Object.entries(ve);var Se=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Ce=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),we=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Te=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ee=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,De=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Oe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ke=/\t{1,1000}/y,Ae=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,je=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Me=/\p{M}+/gu,Ne={limit:1/0,ellipsis:``},Pe=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Pe(i,Ne,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[je,l],[Ee,0],[De,o],[ke,s],[Ae,c],[Oe,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Me,``)){let t=e.codePointAt(0)||0;if(S=we(t)?2:Te(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Oe?Ce(e.slice(p,n.lastIndex)):n===Ae?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Fe={limit:1/0,ellipsis:``,ellipsisWidth:0},G=(e,t={})=>Pe(e,Fe,t).width,Ie=`]8;;`,Le=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ie}(?<uri>.*))`,`y`),Re=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ze=e=>`[${e}m`,Be=e=>`${Ie}${e}`,Ve=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:G(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=G(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ie,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},He=e=>{let t=e.split(` `),n=t.length;for(;n&&!G(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ue=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=G(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=G(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ve(s,r,t),c=G(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ve(s,r,t),c=G(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ve(s,r,t),c=G(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>He(e)));let l=s.join(`
2
2
  `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){Le.lastIndex=e+1;let t=Le.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
3
3
  `){a&&(r+=Be(``));let e=i?Re(i):void 0;i&&e&&(r+=ze(e))}else t===`
4
4
  `&&(i&&Re(i)&&(r+=ze(i)),a&&(r+=Be(a)))}return r},We=/\r?\n/;function Ge(e,t,n){return String(e).normalize().split(We).map(e=>Ue(e,t,n)).join(`
@@ -300,6 +300,6 @@ UIPORT="\${PORT:-${Di}}"
300
300
  unset PORT
301
301
  exec node "${C()}" start --ui-port "$UIPORT"`],port:Di,autoPort:!0}:{name:Ki,runtimeExecutable:`/bin/sh`,runtimeArgs:[`-l`,`-c`,Yi],port:Di,autoPort:!0};try{if(D(n,e),!P(n))return re(ae(n),{recursive:!0}),I(n,`${JSON.stringify({version:Gi,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=F(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!O(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>O(e)&&e.name===`open-knowledge-ui`);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Gi,configurations:a};return I(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Zi(e,t,n){try{return P(e.detectPath?.(t,n)??ae(e.configPath(t,n)))}catch{return!1}}function Qi(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!Zi(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{D(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{re(ae(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let c,l;try{u(`${o}.lock`,()=>{let t=e.format===`toml`?Ii(o):Fi(o),n=t[e.topLevelKey]??{};c=n[a];let r={...t,[e.topLevelKey]:{...n,[a]:s}};e.format===`toml`?Ri(o,r):Li(o,r)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){l=e instanceof Error?e:Error(String(e))}return l?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:l.message,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:c===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function $i(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!P(n)))return{editorId:e.id,label:e.label,path:n}}async function ea(e){let t=ee(e.editors),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>Qi(t,``,n,e.home))}function ta(e,t,n,r){let i=na(e,t,n,r);return i.kind===`present`?i.entry:null}function na(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!P(i))return{kind:`absent`};let a;try{a=F(i,`utf-8`)}catch(e){return{kind:`corrupt`,error:e instanceof Error?e.message:String(e)}}if(a.trim()===``)return{kind:`corrupt`,error:`file is empty`};let o;try{o=e.format===`toml`?Ii(i):Fi(i)}catch(e){return{kind:`corrupt`,error:e instanceof Error?e.message:String(e)}}let s=o[e.topLevelKey];if(!O(s))return{kind:`no-entry`};let c=s[e.serverName(t)];return O(c)?{kind:`present`,entry:c}:{kind:`no-entry`}}async function ra(e={}){let t=B(e.cwd??process.cwd()),n=gi(t,{homeDir:e.home}),r=n.projectRoot,i=!P(R(r,`.ok`));n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&console.log(`[ok] Initialized OK at ${r} — opened parent of ${z(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await b(r),s;try{s=h(r,{contentDir:n.defaultContentDir})}catch(t){let n=T.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:o.didInit,rootGitignoreCreated:!1,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:n,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let c=!1;if(o.didInit)try{c=f(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}let l=await Hi({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),u=e.editors??sa(r,e.home),d=e.editors??E.filter(e=>T[e].projectConfigPath!==void 0),p=ee(u),m=ee(d),g=e.mcp===!1||l===null,v=Array.from(new Map([...p,...g?[]:m].map(e=>[e.id,e])).values()),y=p.filter(t=>Zi(t,r,e.home)),x=[],C=[],D=new Set;for(let t of v){if(g){let n=``;try{n=t.configPath(r,e.home)}catch{}x.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(zi(l)&&p.includes(t)&&x.push(Qi(t,r,a,e.home)),Bi(l)&&m.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Qi(t,r,a,e.home,n);x.push(i),(i.action===`written`||i.action===`overwritten`)&&D.add(n)}}for(let e of m)e.projectSkillPath&&C.push(w(e,r));let O=!g&&l!==null&&Bi(l)?m.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,k=g?[]:y.map(e=>$i(e,r)).filter(e=>e!==void 0).filter(e=>!D.has(e.path)),A=y.some(e=>e.id===`claude`)&&!g?Xi(r,a):void 0,te=await(e.installUserSkill??_)({home:e.home}),j=S({home:e.home}),M=g?`skipped-flag`:`skipped-missing`,N=x.find(e=>e.editorId===`claude`)??x[0]??{action:M,configPath:T.claude.configPath(r,e.home)},ne=await ia({projectRoot:r,desiredMode:await Wi({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:s.created,contentUpdated:s.updated,contentSkipped:s.skipped,editors:x,projectSkills:C,legacyProjectConfigs:k,launchJson:A,skillInstall:te,didGitInit:o.didInit,rootGitignoreCreated:c,claudeDesktopDetected:j,mcpAction:N.action,mcpPath:N.configPath,mcpError:`error`in N?N.error:void 0,projectScopeUnsupportedLabels:O,sharing:ne}}async function ia(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=_t(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=mt(t);if(n===`local-only`){let e=ht(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:aa(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=gt(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:aa(t,o,`remove`)}function aa(e,t,n){let r=_t(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:[]}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function oa(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?z(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let c=R(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(M(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(M(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(M(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(M(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(M(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?z(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${A(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${A(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${te(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(M(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?z(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${A(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${A(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${te(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${z(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(M(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${A(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${A(`already installed at current version`)}`);break;case`failed`:n.push(` ${j(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${j(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${M(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(N(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...la(e.sharing,t)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${A(`✓`)} ${M(`Next steps:`)}`),n.push(` 1. Open your editor (${k(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${k(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${k(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${k(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${k(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${k(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
302
302
  `)}function sa(e,t){let n=[];for(let r of E)Zi(T[r],e,t)&&n.push(r);return n}function ca(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new r(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new r(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r;try{r=await ra({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n})}catch(e){if(e instanceof g){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
303
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-BcwxW8Jz.mjs`),{loadConfig:t}=await import(`./loader-CL1cBJAY.mjs`),{resolveContentDir:n}=await import(`./dist-Y_CEziF9.mjs`),{config:i}=t(r.projectRoot),a=n(i,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:a})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${oa(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}function la(e,t){let n=[];switch(e.kind){case`applied`:return n.push(M(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?n.push(` ${A(`local-only`)} — appended ${e.appended.length} path(s) to ${M(`${t}/.git/info/exclude`)} (per-clone, not committed).`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${A(`local-only`)} — already excluded; nothing to do.`):n.push(` ${A(`local-only`)}`):e.action===`removed`?n.push(` ${A(`shared`)} — removed OK paths from ${M(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${A(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(j(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
303
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DWfgcb6s.mjs`),{loadConfig:t}=await import(`./loader-Bhq-VNS_.mjs`),{resolveContentDir:n}=await import(`./dist-Y_CEziF9.mjs`),{config:i}=t(r.projectRoot),a=n(i,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:a})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${oa(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}function la(e,t){let n=[];switch(e.kind){case`applied`:return n.push(M(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?n.push(` ${A(`local-only`)} — appended ${e.appended.length} path(s) to ${M(`${t}/.git/info/exclude`)} (per-clone, not committed).`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${A(`local-only`)} — already excluded; nothing to do.`):n.push(` ${A(`local-only`)}`):e.action===`removed`?n.push(` ${A(`shared`)} — removed OK paths from ${M(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${A(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(j(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
304
304
  `))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${k(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(j(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${k(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${k(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(j(`Sharing mode unavailable: ${e.reason}.`));return n}}export{dt as A,mt as C,ut as D,gt as E,Ge as F,Se as I,W as L,pt as M,it as N,st as O,Ke as P,vt as S,_t as T,ea as _,ia as a,ht as b,oa as c,ta as d,Hi as f,Qi as g,Xi as h,Yi as i,lt as j,ct as k,la as l,ra as m,qi as n,na as o,Wi as p,Ji as r,sa as s,Ki as t,ca as u,Ni as v,yt as w,bt as x,gi as y};
305
- //# sourceMappingURL=init-CHlwzxSA.mjs.map
305
+ //# sourceMappingURL=init-BMT_3l9F.mjs.map
@@ -0,0 +1 @@
1
+ import{m as e}from"./init-BMT_3l9F.mjs";export{e as runInit};
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-D4wC401d.mjs";export{e as loadConfig};
@@ -1,4 +1,4 @@
1
- import{Fa as e,Ki as t,Ui as n,Wi as r}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{Qi as i,Zi as a,m as o}from"./dist-CWv9hwiJ.mjs";import{t as s}from"./constants-BiXELTVf.mjs";import{t as c}from"./is-object-Cg453afR.mjs";import{existsSync as l,readFileSync as u}from"node:fs";import{resolve as d}from"node:path";import{realpath as f}from"node:fs/promises";async function p(e){let t=d(e);try{return await f(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var m=e();function h(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];c(a)&&c(i)?n[r]=h(i,a):a!==void 0&&(n[r]=a)}return n}function g(e){if(!l(e))return{value:null,path:e,source:null,doc:null};let t;try{t=u(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,m.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return c(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function _(e,n){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(n.doc!==null&&n.source!==null){let e=t({file:n.path,source:n.source,doc:n.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function v(e){let t=e??process.cwd(),c=[],l=i(`user`,t),u=a({absPath:l}),f={};u.valid&&u.source!==void 0?(f=h(f,u.value),c.push(l)):u.valid;let p=d(t,`.ok`,s),m=g(p);if(m.value!==null){let e=n({value:m.value,file:m.path,source:m.source,doc:m.doc});if(e.length>0)throw Error(e.map(r).join(`
1
+ import{Fa as e,Ki as t,Ui as n,Wi as r}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{Qi as i,Zi as a,m as o}from"./dist-CWv9hwiJ.mjs";import{t as s}from"./constants-DRZYaWtr.mjs";import{t as c}from"./is-object-Cg453afR.mjs";import{existsSync as l,readFileSync as u}from"node:fs";import{resolve as d}from"node:path";import{realpath as f}from"node:fs/promises";async function p(e){let t=d(e);try{return await f(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var m=e();function h(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];c(a)&&c(i)?n[r]=h(i,a):a!==void 0&&(n[r]=a)}return n}function g(e){if(!l(e))return{value:null,path:e,source:null,doc:null};let t;try{t=u(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,m.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return c(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function _(e,n){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(n.doc!==null&&n.source!==null){let e=t({file:n.path,source:n.source,doc:n.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function v(e){let t=e??process.cwd(),c=[],l=i(`user`,t),u=a({absPath:l}),f={};u.valid&&u.source!==void 0?(f=h(f,u.value),c.push(l)):u.valid;let p=d(t,`.ok`,s),m=g(p);if(m.value!==null){let e=n({value:m.value,file:m.path,source:m.source,doc:m.doc});if(e.length>0)throw Error(e.map(r).join(`
2
2
 
3
3
  `));f=h(f,m.value),c.push(p)}let v=o.safeParse(f);if(!v.success){let e={code:`SCHEMA_INVALID`,issues:_(v.error.issues,m)};throw Error(r(e))}return{config:v.data,sources:c}}function y(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??v,r=new Map,i=new Map,a=p(e.startupCwd);return async o=>{let s=await p(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{v as n,y as t};
4
- //# sourceMappingURL=loader-CjrRykwH.mjs.map
4
+ //# sourceMappingURL=loader-D4wC401d.mjs.map
@@ -1,3 +1,3 @@
1
- import{Gt as e}from"./dist-CWv9hwiJ.mjs";import"./constants-BiXELTVf.mjs";import{existsSync as t,lstatSync as n,readdirSync as r,realpathSync as i,statSync as a}from"node:fs";import{join as o,relative as s}from"node:path";function c(t){let{projectDir:c,contentDir:l,sampleCap:u=5}=t,d=[],f=[];try{n(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=r(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${s(l,e)||`.`}: ${n}`);return}for(let n of t){let t=o(e,n.name);if(n.isSymbolicLink()){let e;try{e=i(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${s(l,t)}`):d.push(`cannot resolve symlink ${s(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=a(e)}catch{continue}if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,n){let r=[],i=s(n,e.contentDir),a=i===``?`./`:`./${i}`;if(r.push(`Content:`),r.push(` Found ${e.totalCount} markdown files in ${a}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;r.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)r.push(` Warning: ${t}`);return r.push(``),t(o(n,`.ok`,`config.yml`))?(r.push(` To adjust scope, add patterns to .okignore at the project root.`),r.push(` To change the content root, edit .ok/config.yml → content.dir.`)):r.push(" Run `open-knowledge init` to scaffold config + .okignore."),r.push(``),r.push(` Re-check anytime: open-knowledge preview`),r.join(`
1
+ import{Gt as e}from"./dist-CWv9hwiJ.mjs";import"./constants-DRZYaWtr.mjs";import{existsSync as t,lstatSync as n,readdirSync as r,realpathSync as i,statSync as a}from"node:fs";import{join as o,relative as s}from"node:path";function c(t){let{projectDir:c,contentDir:l,sampleCap:u=5}=t,d=[],f=[];try{n(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=r(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${s(l,e)||`.`}: ${n}`);return}for(let n of t){let t=o(e,n.name);if(n.isSymbolicLink()){let e;try{e=i(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${s(l,t)}`):d.push(`cannot resolve symlink ${s(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=a(e)}catch{continue}if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(n.isDirectory()){let e=s(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=s(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,n){let r=[],i=s(n,e.contentDir),a=i===``?`./`:`./${i}`;if(r.push(`Content:`),r.push(` Found ${e.totalCount} markdown files in ${a}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;r.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)r.push(` Warning: ${t}`);return r.push(``),t(o(n,`.ok`,`config.yml`))?(r.push(` To adjust scope, add patterns to .okignore at the project root.`),r.push(` To change the content root, edit .ok/config.yml → content.dir.`)):r.push(" Run `open-knowledge init` to scaffold config + .okignore."),r.push(``),r.push(` Re-check anytime: open-knowledge preview`),r.join(`
2
2
  `)}export{c as n,l as t};
3
- //# sourceMappingURL=preview-Cv6HcQ_e.mjs.map
3
+ //# sourceMappingURL=preview-BGMRorsT.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-BGMRorsT.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ActivityPanelDiffView-InYkbArk.js","./chunk-CFjPhJqf.js","./compiler-runtime-Cs91PcD2.js","./ActivityPanelDiffView-legcy4jI.css"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{a as n,i as r,o as i,r as a,t as o}from"./compiler-runtime-Cs91PcD2.js";import{Sr as s,Xn as c,n as l,r as u,ut as d,wr as f}from"./DocumentContext-md7jH47y.js";import{at as p,o as m,s as h}from"./dist-8N_b2j7p.js";import{t as g,u as _}from"./button-CmLxDlCv.js";import{f as v,i as y,m as b,r as x,t as S}from"./agent-presence-DYKkeiBZ.js";import{a as C,c as w,i as T,o as E,s as D,t as O}from"./dialog-uOgi9SAD.js";import{o as ee}from"./collapsible-BzkAcCLq.js";import{_ as k,i as A,l as j,z as M}from"./prop-types-C-Qh8A_7.js";import{n as N}from"./dist-DuNRfJxD.js";import{i as te,n as ne,t as re}from"./tooltip-DjrmDp0P.js";var ie=_(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),P=o(),F=e(n(),1),ae=500,I=64;async function oe(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t),r;try{r=await n.json()}catch(e){throw new d(`Could not parse /api/agent-activity response.`,{cause:e,status:n.status})}if(!n.ok){let e=p.safeParse(r);throw e.success?Error(e.data.title):new d(`/api/agent-activity returned a non-RFC-9457 error response.`,{cause:e.error,status:n.status})}let i=m.safeParse(r);if(!i.success)throw new d(`/api/agent-activity returned a body that did not match AgentActivitySuccessSchema.`,{cause:i.error,status:n.status});return i.data}async function se(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r),a;try{a=await i.json()}catch(e){throw new d(`Could not parse /api/agent-burst-diff response.`,{cause:e,status:i.status})}if(!i.ok){let e=p.safeParse(a);throw e.success?Error(e.data.title):new d(`/api/agent-burst-diff returned a non-RFC-9457 error response.`,{cause:e.error,status:i.status})}let o=h.safeParse(a);if(!o.success)throw new d(`/api/agent-burst-diff returned a body that did not match AgentBurstDiffSuccessSchema.`,{cause:o.error,status:i.status});return o.data.diff}function ce(e){let t=(0,P.c)(23),{systemProvider:n}=l(),[r,i]=(0,F.useState)(null),[a,o]=(0,F.useState)(`idle`),[s,c]=(0,F.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new y(I),t[0]=u):u=t[0];let d=(0,F.useRef)(u),f=(0,F.useRef)(0),p;t[1]===n?p=t[2]:(p=e=>{let t=f.current+=1;o(`loading`),c(null),oe(e).then(r=>{if(f.current!==t)return;let a=ue(n,e);i({...r,writingDocs:a}),o(`ready`)}).catch(e=>{f.current===t&&(c(e instanceof Error?e.message:String(e)),o(`error`))})},t[1]=n,t[2]=p);let m=p,h;t[3]!==e||t[4]!==m?(h=()=>{if(!e){f.current+=1,i(null),o(`idle`),c(null),d.current.clear();return}d.current.clear(),m(e);let t=null,n=k(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,m(e)},ae))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=m,t[5]=h):h=t[5];let g;t[6]===e?g=t[7]:(g=[e],t[6]=e,t[7]=g),(0,F.useEffect)(h,g);let _,v;t[8]!==e||t[9]!==n?(_=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ue(n,e);i(e=>!e||le(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},v=[e,n],t[8]=e,t[9]=n,t[10]=_,t[11]=v):(_=t[10],v=t[11]),(0,F.useEffect)(_,v);let b;t[12]===e?b=t[13]:(b=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await se(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=b);let x=b,S;t[14]!==e||t[15]!==m?(S=()=>{e&&m(e)},t[14]=e,t[15]=m,t[16]=S):S=t[16];let C=S,w;return t[17]!==r||t[18]!==s||t[19]!==x||t[20]!==C||t[21]!==a?(w={data:r,status:a,error:s,reload:C,fetchBurstDiff:x},t[17]=r,t[18]=s,t[19]=x,t[20]=C,t[21]=a,t[22]=w):w=t[22],w}function le(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ue(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!S(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var L=i(),de=(0,F.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-InYkbArk.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function fe(e,t){let n=Math.max(0,t-e);if(n<6e4){let e=Math.round(n/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(n<36e5){let e=Math.round(n/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}return new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function pe(e){let t=(0,P.c)(42),{burst:n,docName:i,fetchBurstDiff:o}=e,{_:s}=r(),[c,l]=(0,F.useState)(!1),[u,d]=(0,F.useState)(null),[p,m]=(0,F.useState)(null),[h,g]=(0,F.useState)(!1),[_,v]=(0,F.useState)(R),y,b;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(y=()=>{let e=setInterval(()=>v(Date.now()),3e4);return()=>clearInterval(e)},b=[],t[0]=y,t[1]=b):(y=t[0],b=t[1]),(0,F.useEffect)(y,b);let x;t[2]!==n.stackIndex||t[3]!==u||t[4]!==i||t[5]!==c||t[6]!==o||t[7]!==h?(x=()=>{let e=!c;l(e),e&&u===null&&!h&&(g(!0),m(null),o(i,n.stackIndex).then(e=>{d(e),g(!1)}).catch(e=>{m(e instanceof Error?e.message:String(e)),g(!1)}))},t[2]=n.stackIndex,t[3]=u,t[4]=i,t[5]=c,t[6]=o,t[7]=h,t[8]=x):x=t[8];let S=x,C=n.stackIndex+1,w;t[9]!==s||t[10]!==C||t[11]!==c?(w=s(c?{id:`-i7ik4`,values:{burstNumber:C}}:{id:`EeRZnZ`,values:{burstNumber:C}}),t[9]=s,t[10]=C,t[11]=c,t[12]=w):w=t[12];let T;t[13]===c?T=t[14]:(T=c?(0,L.jsx)(f,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,L.jsx)(ee,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[13]=c,t[14]=T);let E;t[15]!==n.ts||t[16]!==_?(E=fe(n.ts,_),t[15]=n.ts,t[16]=_,t[17]=E):E=t[17];let D;t[18]===E?D=t[19]:(D=(0,L.jsx)(`span`,{className:`font-mono`,children:E}),t[18]=E,t[19]=D);let O;t[20]===n.additions?O=t[21]:(O=(0,L.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[20]=n.additions,t[21]=O);let k;t[22]===n.deletions?k=t[23]:(k=(0,L.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[22]=n.deletions,t[23]=k);let A;t[24]!==O||t[25]!==k?(A=(0,L.jsxs)(`span`,{className:`ml-auto font-mono`,children:[O,` `,k]}),t[24]=O,t[25]=k,t[26]=A):A=t[26];let j;t[27]!==c||t[28]!==A||t[29]!==w||t[30]!==T||t[31]!==D||t[32]!==S?(j=(0,L.jsxs)(`button`,{type:`button`,onClick:S,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":c,"aria-label":w,children:[T,D,A]}),t[27]=c,t[28]=A,t[29]=w,t[30]=T,t[31]=D,t[32]=S,t[33]=j):j=t[33];let M;t[34]!==u||t[35]!==c||t[36]!==p||t[37]!==h?(M=c?(0,L.jsx)(`div`,{className:`bg-muted/20`,children:h?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`38foVZ`})}):p?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:(0,L.jsx)(a,{id:`pmKdif`,values:{loadError:p}})}):u===null?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`iNFKkm`})}):(0,L.jsx)(F.Suspense,{fallback:(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`38foVZ`})}),children:(0,L.jsx)(de,{diff:u})})}):null,t[34]=u,t[35]=c,t[36]=p,t[37]=h,t[38]=M):M=t[38];let N;return t[39]!==j||t[40]!==M?(N=(0,L.jsxs)(`div`,{className:`border-t border-border/50`,children:[j,M]}),t[39]=j,t[40]=M,t[41]=N):N=t[41],N}function R(){return Date.now()}function me(e,t){let n=Math.max(0,t-e);if(n<6e4){let e=Math.round(n/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(n<36e5){let e=Math.round(n/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}let r=Math.round(n/36e5);return M._({id:`nYeBmY`,values:{hours:r}})}function z(e){let t=(0,P.c)(118),{file:n,sessionAlive:i,isWriting:o,onNavigate:s,onUndoLast:c,onUndoAll:l,fetchBurstDiff:u}=e,{_:d}=r(),{docName:p}=n,[m,h]=(0,F.useState)(!1),[_,y]=(0,F.useState)(!1),[b,x]=(0,F.useState)(!1),[S,k]=(0,F.useState)(ge),A,j;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(A=()=>{let e=setInterval(()=>k(Date.now()),3e4);return()=>clearInterval(e)},j=[],t[0]=A,t[1]=j):(A=t[0],j=t[1]),(0,F.useEffect)(A,j),n.bursts.length===0)return null;let M=!i||n.bursts.length===0||b,N=n.bursts.length,ae;t[2]!==d||t[3]!==n.bursts.length||t[4]!==i?(ae=i?n.bursts.length===0?d({id:`2fkdnR`}):null:d({id:`NzFvyK`}),t[2]=d,t[3]=n.bursts.length,t[4]=i,t[5]=ae):ae=t[5];let I=ae,oe;t[6]!==M||t[7]!==n.docName||t[8]!==c?(oe=e=>{e.stopPropagation(),!M&&(x(!0),Promise.resolve(c(n.docName)).finally(()=>x(!1)))},t[6]=M,t[7]=n.docName,t[8]=c,t[9]=oe):oe=t[9];let se=oe,ce;t[10]===M?ce=t[11]:(ce=e=>{e.stopPropagation(),!M&&y(!0)},t[10]=M,t[11]=ce);let le=ce,ue;t[12]!==M||t[13]!==n.docName||t[14]!==l?(ue=()=>{y(!1),!M&&(x(!0),Promise.resolve(l(n.docName)).finally(()=>x(!1)))},t[12]=M,t[13]=n.docName,t[14]=l,t[15]=ue):ue=t[15];let de=ue,fe;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(fe=()=>h(he),t[16]=fe):fe=t[16];let R;t[17]!==d||t[18]!==p||t[19]!==m?(R=d(m?{id:`rVgSRB`,values:{docName:p}}:{id:`tW_yvQ`,values:{docName:p}}),t[17]=d,t[18]=p,t[19]=m,t[20]=R):R=t[20];let z;t[21]===m?z=t[22]:(z=m?(0,L.jsx)(f,{className:`size-4`,"aria-hidden":`true`}):(0,L.jsx)(ee,{className:`size-4`,"aria-hidden":`true`}),t[21]=m,t[22]=z);let B;t[23]!==m||t[24]!==R||t[25]!==z?(B=(0,L.jsx)(`button`,{type:`button`,onClick:fe,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":m,"aria-label":R,"data-testid":`activity-panel-file-row-carrot`,children:z}),t[23]=m,t[24]=R,t[25]=z,t[26]=B):B=t[26];let V;t[27]!==n.docName||t[28]!==s?(V=()=>s(n.docName),t[27]=n.docName,t[28]=s,t[29]=V):V=t[29];let H;t[30]!==d||t[31]!==p?(H=d({id:`QcpeeE`,values:{docName:p}}),t[30]=d,t[31]=p,t[32]=H):H=t[32];let U;t[33]!==n.docName||t[34]!==V||t[35]!==H?(U=(0,L.jsx)(`button`,{type:`button`,onClick:V,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":H,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[33]=n.docName,t[34]=V,t[35]=H,t[36]=U):U=t[36];let W;t[37]!==d||t[38]!==p?(W=d({id:`m4v3XT`,values:{docName:p}}),t[37]=d,t[38]=p,t[39]=W):W=t[39];let _e;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(_e=(0,L.jsx)(v,{className:`size-3.5`,"aria-hidden":`true`}),t[40]=_e):_e=t[40];let G;t[41]!==M||t[42]!==se||t[43]!==W?(G=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:se,disabled:M,"aria-label":W,"data-testid":`activity-panel-undo-last`,children:_e})}),t[41]=M,t[42]=se,t[43]=W,t[44]=G):G=t[44];let K;t[45]!==d||t[46]!==I?(K=I??d({id:`ArBWJf`}),t[45]=d,t[46]=I,t[47]=K):K=t[47];let q;t[48]===K?q=t[49]:(q=(0,L.jsx)(ne,{side:`bottom`,children:K}),t[48]=K,t[49]=q);let J;t[50]!==G||t[51]!==q?(J=(0,L.jsxs)(re,{children:[G,q]}),t[50]=G,t[51]=q,t[52]=J):J=t[52];let Y;t[53]!==d||t[54]!==p?(Y=d({id:`J2MgzQ`,values:{docName:p}}),t[53]=d,t[54]=p,t[55]=Y):Y=t[55];let ve;t[56]===Symbol.for(`react.memo_cache_sentinel`)?(ve=(0,L.jsx)(ie,{className:`size-3.5`,"aria-hidden":`true`}),t[56]=ve):ve=t[56];let X;t[57]!==M||t[58]!==le||t[59]!==Y?(X=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:le,disabled:M,"aria-label":Y,"data-testid":`activity-panel-undo-all`,children:ve})}),t[57]=M,t[58]=le,t[59]=Y,t[60]=X):X=t[60];let Z;t[61]!==d||t[62]!==I?(Z=I??d({id:`mNY1G6`}),t[61]=d,t[62]=I,t[63]=Z):Z=t[63];let ye;t[64]===Z?ye=t[65]:(ye=(0,L.jsx)(ne,{side:`bottom`,children:Z}),t[64]=Z,t[65]=ye);let be;t[66]!==X||t[67]!==ye?(be=(0,L.jsxs)(re,{children:[X,ye]}),t[66]=X,t[67]=ye,t[68]=be):be=t[68];let xe;t[69]===n.additionsTotal?xe=t[70]:(xe=(0,L.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[69]=n.additionsTotal,t[70]=xe);let Se;t[71]===n.deletionsTotal?Se=t[72]:(Se=(0,L.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[71]=n.deletionsTotal,t[72]=Se);let Ce;t[73]!==xe||t[74]!==Se?(Ce=(0,L.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[xe,` `,Se]}),t[73]=xe,t[74]=Se,t[75]=Ce):Ce=t[75];let we;t[76]!==n.lastTs||t[77]!==S?(we=me(n.lastTs,S),t[76]=n.lastTs,t[77]=S,t[78]=we):we=t[78];let Q;t[79]===we?Q=t[80]:(Q=(0,L.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:we}),t[79]=we,t[80]=Q);let Te;t[81]===o?Te=t[82]:(Te=o?(0,L.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:(0,L.jsx)(a,{id:`6q0rnH`})}):null,t[81]=o,t[82]=Te);let Ee;t[83]!==B||t[84]!==U||t[85]!==J||t[86]!==be||t[87]!==Ce||t[88]!==Q||t[89]!==Te?(Ee=(0,L.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[B,U,J,be,Ce,Q,Te]}),t[83]=B,t[84]=U,t[85]=J,t[86]=be,t[87]=Ce,t[88]=Q,t[89]=Te,t[90]=Ee):Ee=t[90];let De;t[91]!==m||t[92]!==u||t[93]!==n.bursts||t[94]!==n.docName?(De=m?(0,L.jsx)(`div`,{children:n.bursts.map(e=>(0,L.jsx)(pe,{burst:e,docName:n.docName,fetchBurstDiff:u},`${n.docName}:${e.stackIndex}`))}):null,t[91]=m,t[92]=u,t[93]=n.bursts,t[94]=n.docName,t[95]=De):De=t[95];let Oe;t[96]===Symbol.for(`react.memo_cache_sentinel`)?(Oe=(0,L.jsx)(w,{children:(0,L.jsx)(a,{id:`SEYWYq`})}),t[96]=Oe):Oe=t[96];let ke;t[97]!==N||t[98]!==p?(ke={docName:p,burstCount:N},t[97]=N,t[98]=p,t[99]=ke):ke=t[99];let Ae;t[100]===Symbol.for(`react.memo_cache_sentinel`)?(Ae={0:(0,L.jsx)(`span`,{className:`font-mono text-foreground`})},t[100]=Ae):Ae=t[100];let je;t[101]===ke?je=t[102]:(je=(0,L.jsxs)(D,{children:[Oe,(0,L.jsx)(C,{children:(0,L.jsx)(a,{id:`ZBYKxv`,values:ke,components:Ae})})]}),t[101]=ke,t[102]=je);let Me;t[103]===Symbol.for(`react.memo_cache_sentinel`)?(Me=()=>y(!1),t[103]=Me):Me=t[103];let Ne;t[104]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=(0,L.jsx)(g,{type:`button`,variant:`outline`,onClick:Me,"data-testid":`activity-panel-undo-all-cancel`,children:(0,L.jsx)(a,{id:`dEgA5A`})}),t[104]=Ne):Ne=t[104];let Pe;t[105]===Symbol.for(`react.memo_cache_sentinel`)?(Pe=(0,L.jsx)(a,{id:`MWrUEd`}),t[105]=Pe):Pe=t[105];let Fe;t[106]===de?Fe=t[107]:(Fe=(0,L.jsxs)(E,{children:[Ne,(0,L.jsx)(g,{type:`button`,variant:`destructive`,onClick:de,"data-testid":`activity-panel-undo-all-confirm`,children:Pe})]}),t[106]=de,t[107]=Fe);let Ie;t[108]!==je||t[109]!==Fe?(Ie=(0,L.jsxs)(T,{className:`sm:max-w-md`,children:[je,Fe]}),t[108]=je,t[109]=Fe,t[110]=Ie):Ie=t[110];let $;t[111]!==_||t[112]!==Ie?($=(0,L.jsx)(O,{open:_,onOpenChange:y,children:Ie}),t[111]=_,t[112]=Ie,t[113]=$):$=t[113];let Le;return t[114]!==Ee||t[115]!==De||t[116]!==$?(Le=(0,L.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Ee,De,$]}),t[114]=Ee,t[115]=De,t[116]=$,t[117]=Le):Le=t[117],Le}function he(e){return!e}function ge(){return Date.now()}async function B(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function V(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function H(e){typeof window>`u`||(window.location.hash=V(e))}function U(){let e=(0,P.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,L.jsx)(c,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),e[0]=t):t=e[0];let n;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,L.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[t,(0,L.jsx)(`span`,{className:`text-sm`,children:(0,L.jsx)(a,{id:`ONPvOb`})})]}),e[1]=n):n=e[1],n}function W(e){let t=(0,P.c)(10),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,L.jsx)(s,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,L.jsx)(`p`,{className:`text-sm font-medium`,children:(0,L.jsx)(a,{id:`DhLHEb`})}),t[1]=o):o=t[1];let c;t[2]===n?c=t[3]:(c=(0,L.jsxs)(`div`,{className:`space-y-1`,children:[o,(0,L.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=c);let l;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(a,{id:`6gRgw8`}),t[4]=l):l=t[4];let u;t[5]===r?u=t[6]:(u=(0,L.jsx)(g,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:l}),t[5]=r,t[6]=u);let d;return t[7]!==c||t[8]!==u?(d=(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,c,u]}),t[7]=c,t[8]=u,t[9]=d):d=t[9],d}function _e(){let e=(0,P.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,L.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,L.jsx)(`p`,{className:`text-sm italic`,children:(0,L.jsx)(a,{id:`iuTKci`})})}),e[0]=t):t=e[0],t}function G(e){let t=(0,P.c)(12),{onExit:n,showBackButton:i}=e,{_:o}=r(),s;t[0]===o?s=t[1]:(s=o({id:`kYL1lH`}),t[0]=o,t[1]=s);let c;t[2]!==n||t[3]!==i?(c=i?(0,L.jsx)(K,{onClick:n}):null,t[2]=n,t[3]=i,t[4]=c):c=t[4];let l;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:(0,L.jsx)(a,{id:`kYL1lH`})}),t[5]=l):l=t[5];let u;t[6]===c?u=t[7]:(u=(0,L.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[c,l]}),t[6]=c,t[7]=u);let d;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,L.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,L.jsx)(`p`,{className:`text-center text-sm italic`,children:(0,L.jsx)(a,{id:`D_WKe_`})})}),t[8]=d):d=t[8];let f;return t[9]!==s||t[10]!==u?(f=(0,L.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":s,children:[u,d]}),t[9]=s,t[10]=u,t[11]=f):f=t[11],f}function K(e){let t=(0,P.c)(9),{onClick:n}=e,{_:i}=r(),o;t[0]===i?o=t[1]:(o=i({id:`ogAuyr`}),t[0]=i,t[1]=o);let s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,L.jsx)(b,{}),t[2]=s):s=t[2];let c;t[3]!==n||t[4]!==o?(c=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":o,"data-testid":`docpanel-exit-agent-mode`,children:s})}),t[3]=n,t[4]=o,t[5]=c):c=t[5];let l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(ne,{side:`bottom`,children:(0,L.jsx)(a,{id:`ogAuyr`})}),t[6]=l):l=t[6];let u;return t[7]===c?u=t[8]:(u=(0,L.jsxs)(re,{children:[c,l]}),t[7]=c,t[8]=u),u}function q(e){let t=(0,P.c)(9),{lastTs:n}=e,[r]=(0,F.useState)(J),i;t[0]!==n||t[1]!==r?(i=n?Y(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let o=i,s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,L.jsx)(`span`,{className:`font-medium`,children:(0,L.jsx)(a,{id:`LCUy_N`})}),t[3]=s):s=t[3];let c;t[4]===o?c=t[5]:(c=o?(0,L.jsxs)(`span`,{children:[` · `,o]}):null,t[4]=o,t[5]=c);let l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(`div`,{className:`mt-1 opacity-80`,children:(0,L.jsx)(a,{id:`GK-IRZ`})}),t[6]=l):l=t[6];let u;return t[7]===c?u=t[8]:(u=(0,L.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[s,c,l]}),t[7]=c,t[8]=u),u}function J(){return Date.now()}function Y(e){let t=Math.max(0,e);if(t<6e4){let e=Math.round(t/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(t<36e5){let e=Math.round(t/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}let n=Math.round(t/36e5);return M._({id:`nYeBmY`,values:{hours:n}})}function ve(e){let t=(0,P.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,L.jsx)(x,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,L.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function X(e){let t=(0,P.c)(26),{data:n,status:i,error:o,reload:s,fetchBurstDiff:c,onExit:l,onNavigate:u,onUndoLast:d,onUndoAll:f,showBackButton:p}=e,{_:m}=r(),h=n?.files?.[0]?.lastTs??null,g=n?.files?.length??0,_;t[0]===m?_=t[1]:(_=m({id:`kYL1lH`}),t[0]=m,t[1]=_);let v;t[2]!==l||t[3]!==p?(v=p?(0,L.jsx)(K,{onClick:l}):null,t[2]=l,t[3]=p,t[4]=v):v=t[4];let y;t[5]!==n||t[6]!==g||t[7]!==h?(y=n?.agent?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(ve,{agent:n.agent}),(0,L.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,L.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?(0,L.jsx)(a,{id:`F6pfE9`}):h===null?(0,L.jsx)(a,{id:`PMyJ9C`}):(0,L.jsx)(a,{id:`237hSL`}),n.files.length>0?(0,L.jsxs)(L.Fragment,{children:[` · `,(0,L.jsx)(a,{id:`u3BOHd`,values:{fileCount:g}})]}):null]})]})]}):(0,L.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:(0,L.jsx)(a,{id:`kYL1lH`})})}),t[5]=n,t[6]=g,t[7]=h,t[8]=y):y=t[8];let b;t[9]!==v||t[10]!==y?(b=(0,L.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[v,y]}),t[9]=v,t[10]=y,t[11]=b):b=t[11];let x;t[12]!==n||t[13]!==o||t[14]!==c||t[15]!==h||t[16]!==u||t[17]!==f||t[18]!==d||t[19]!==s||t[20]!==i?(x=(0,L.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:i===`loading`&&n===null?(0,L.jsx)(U,{}):i===`error`&&o?(0,L.jsx)(W,{error:o,onRetry:s}):n===null?(0,L.jsx)(_e,{}):(0,L.jsxs)(L.Fragment,{children:[!n.sessionAlive&&h!==null?(0,L.jsx)(q,{lastTs:h}):null,n.files.length===0?(0,L.jsx)(_e,{}):n.files.map(e=>(0,L.jsx)(z,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:u,onUndoLast:d,onUndoAll:f,fetchBurstDiff:c},e.docName))]})}),t[12]=n,t[13]=o,t[14]=c,t[15]=h,t[16]=u,t[17]=f,t[18]=d,t[19]=s,t[20]=i,t[21]=x):x=t[21];let S;return t[22]!==_||t[23]!==b||t[24]!==x?(S=(0,L.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":_,children:[b,x]}),t[22]=_,t[23]=b,t[24]=x,t[25]=S):S=t[25],S}function Z(e){let t=(0,P.c)(29),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{showBackButton:i}=n,a=i===void 0?!0:i,{_:o}=r(),{docPanelAgentId:s,closeActivityPanel:c}=l(),{openTargetTransition:d}=u(),{pageMeta:f}=A(),{data:p,status:m,error:h,reload:g,fetchBurstDiff:_}=ce(s);if(s===null){let e;return t[2]!==c||t[3]!==a?(e=(0,L.jsx)(G,{onExit:c,showBackButton:a}),t[2]=c,t[3]=a,t[4]=e):e=t[4],e}let v;t[5]!==d||t[6]!==f?(v=e=>{d(j({kind:`doc`,target:e,docName:e},f)),H(e)},t[5]=d,t[6]=f,t[7]=v):v=t[7];let y=v,b;t[8]!==o||t[9]!==p||t[10]!==s||t[11]!==g?(b=async e=>{try{await B({connectionId:s,docName:e,scope:`last`,agentName:p?.agent?.displayName}),g()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);N.error(o({id:`EqrC_R`,values:{message:n}})),g()}},t[8]=o,t[9]=p,t[10]=s,t[11]=g,t[12]=b):b=t[12];let x=b,S;t[13]!==o||t[14]!==p||t[15]!==s||t[16]!==g?(S=async e=>{try{await B({connectionId:s,docName:e,scope:`file`,agentName:p?.agent?.displayName}),N.success(o({id:`pRc-Im`,values:{docName:e}})),g()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);N.error(o({id:`7KeV5F`,values:{message:n}})),g()}},t[13]=o,t[14]=p,t[15]=s,t[16]=g,t[17]=S):S=t[17];let C=S,w;return t[18]!==c||t[19]!==p||t[20]!==h||t[21]!==_||t[22]!==y||t[23]!==C||t[24]!==x||t[25]!==g||t[26]!==a||t[27]!==m?(w=(0,L.jsx)(X,{data:p,status:m,error:h,reload:g,fetchBurstDiff:_,onExit:c,onNavigate:y,onUndoLast:x,onUndoAll:C,showBackButton:a}),t[18]=c,t[19]=p,t[20]=h,t[21]=_,t[22]=y,t[23]=C,t[24]=x,t[25]=g,t[26]=a,t[27]=m,t[28]=w):w=t[28],w}export{Z as ActivityModeContent};
2
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{a as n,i as r,o as i,r as a,t as o}from"./compiler-runtime-Cs91PcD2.js";import{Sr as s,Xn as c,n as l,r as u,ut as d,wr as f}from"./DocumentContext-D8cckXN4.js";import{at as p,o as m,s as h}from"./dist-8N_b2j7p.js";import{t as g,u as _}from"./button-CmLxDlCv.js";import{f as v,i as y,m as b,r as x,t as S}from"./agent-presence-DYKkeiBZ.js";import{a as C,c as w,i as T,o as E,s as D,t as O}from"./dialog-uOgi9SAD.js";import{o as ee}from"./collapsible-BzkAcCLq.js";import{_ as k,i as A,l as j,z as M}from"./prop-types-C-Qh8A_7.js";import{n as N}from"./dist-DuNRfJxD.js";import{i as te,n as ne,t as re}from"./tooltip-DjrmDp0P.js";var ie=_(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),P=o(),F=e(n(),1),ae=500,I=64;async function oe(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t),r;try{r=await n.json()}catch(e){throw new d(`Could not parse /api/agent-activity response.`,{cause:e,status:n.status})}if(!n.ok){let e=p.safeParse(r);throw e.success?Error(e.data.title):new d(`/api/agent-activity returned a non-RFC-9457 error response.`,{cause:e.error,status:n.status})}let i=m.safeParse(r);if(!i.success)throw new d(`/api/agent-activity returned a body that did not match AgentActivitySuccessSchema.`,{cause:i.error,status:n.status});return i.data}async function se(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r),a;try{a=await i.json()}catch(e){throw new d(`Could not parse /api/agent-burst-diff response.`,{cause:e,status:i.status})}if(!i.ok){let e=p.safeParse(a);throw e.success?Error(e.data.title):new d(`/api/agent-burst-diff returned a non-RFC-9457 error response.`,{cause:e.error,status:i.status})}let o=h.safeParse(a);if(!o.success)throw new d(`/api/agent-burst-diff returned a body that did not match AgentBurstDiffSuccessSchema.`,{cause:o.error,status:i.status});return o.data.diff}function ce(e){let t=(0,P.c)(23),{systemProvider:n}=l(),[r,i]=(0,F.useState)(null),[a,o]=(0,F.useState)(`idle`),[s,c]=(0,F.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new y(I),t[0]=u):u=t[0];let d=(0,F.useRef)(u),f=(0,F.useRef)(0),p;t[1]===n?p=t[2]:(p=e=>{let t=f.current+=1;o(`loading`),c(null),oe(e).then(r=>{if(f.current!==t)return;let a=ue(n,e);i({...r,writingDocs:a}),o(`ready`)}).catch(e=>{f.current===t&&(c(e instanceof Error?e.message:String(e)),o(`error`))})},t[1]=n,t[2]=p);let m=p,h;t[3]!==e||t[4]!==m?(h=()=>{if(!e){f.current+=1,i(null),o(`idle`),c(null),d.current.clear();return}d.current.clear(),m(e);let t=null,n=k(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,m(e)},ae))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=m,t[5]=h):h=t[5];let g;t[6]===e?g=t[7]:(g=[e],t[6]=e,t[7]=g),(0,F.useEffect)(h,g);let _,v;t[8]!==e||t[9]!==n?(_=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ue(n,e);i(e=>!e||le(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},v=[e,n],t[8]=e,t[9]=n,t[10]=_,t[11]=v):(_=t[10],v=t[11]),(0,F.useEffect)(_,v);let b;t[12]===e?b=t[13]:(b=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await se(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=b);let x=b,S;t[14]!==e||t[15]!==m?(S=()=>{e&&m(e)},t[14]=e,t[15]=m,t[16]=S):S=t[16];let C=S,w;return t[17]!==r||t[18]!==s||t[19]!==x||t[20]!==C||t[21]!==a?(w={data:r,status:a,error:s,reload:C,fetchBurstDiff:x},t[17]=r,t[18]=s,t[19]=x,t[20]=C,t[21]=a,t[22]=w):w=t[22],w}function le(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ue(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!S(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var L=i(),de=(0,F.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-InYkbArk.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function fe(e,t){let n=Math.max(0,t-e);if(n<6e4){let e=Math.round(n/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(n<36e5){let e=Math.round(n/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}return new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function pe(e){let t=(0,P.c)(42),{burst:n,docName:i,fetchBurstDiff:o}=e,{_:s}=r(),[c,l]=(0,F.useState)(!1),[u,d]=(0,F.useState)(null),[p,m]=(0,F.useState)(null),[h,g]=(0,F.useState)(!1),[_,v]=(0,F.useState)(R),y,b;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(y=()=>{let e=setInterval(()=>v(Date.now()),3e4);return()=>clearInterval(e)},b=[],t[0]=y,t[1]=b):(y=t[0],b=t[1]),(0,F.useEffect)(y,b);let x;t[2]!==n.stackIndex||t[3]!==u||t[4]!==i||t[5]!==c||t[6]!==o||t[7]!==h?(x=()=>{let e=!c;l(e),e&&u===null&&!h&&(g(!0),m(null),o(i,n.stackIndex).then(e=>{d(e),g(!1)}).catch(e=>{m(e instanceof Error?e.message:String(e)),g(!1)}))},t[2]=n.stackIndex,t[3]=u,t[4]=i,t[5]=c,t[6]=o,t[7]=h,t[8]=x):x=t[8];let S=x,C=n.stackIndex+1,w;t[9]!==s||t[10]!==C||t[11]!==c?(w=s(c?{id:`-i7ik4`,values:{burstNumber:C}}:{id:`EeRZnZ`,values:{burstNumber:C}}),t[9]=s,t[10]=C,t[11]=c,t[12]=w):w=t[12];let T;t[13]===c?T=t[14]:(T=c?(0,L.jsx)(f,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,L.jsx)(ee,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[13]=c,t[14]=T);let E;t[15]!==n.ts||t[16]!==_?(E=fe(n.ts,_),t[15]=n.ts,t[16]=_,t[17]=E):E=t[17];let D;t[18]===E?D=t[19]:(D=(0,L.jsx)(`span`,{className:`font-mono`,children:E}),t[18]=E,t[19]=D);let O;t[20]===n.additions?O=t[21]:(O=(0,L.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[20]=n.additions,t[21]=O);let k;t[22]===n.deletions?k=t[23]:(k=(0,L.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[22]=n.deletions,t[23]=k);let A;t[24]!==O||t[25]!==k?(A=(0,L.jsxs)(`span`,{className:`ml-auto font-mono`,children:[O,` `,k]}),t[24]=O,t[25]=k,t[26]=A):A=t[26];let j;t[27]!==c||t[28]!==A||t[29]!==w||t[30]!==T||t[31]!==D||t[32]!==S?(j=(0,L.jsxs)(`button`,{type:`button`,onClick:S,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":c,"aria-label":w,children:[T,D,A]}),t[27]=c,t[28]=A,t[29]=w,t[30]=T,t[31]=D,t[32]=S,t[33]=j):j=t[33];let M;t[34]!==u||t[35]!==c||t[36]!==p||t[37]!==h?(M=c?(0,L.jsx)(`div`,{className:`bg-muted/20`,children:h?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`38foVZ`})}):p?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:(0,L.jsx)(a,{id:`pmKdif`,values:{loadError:p}})}):u===null?(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`iNFKkm`})}):(0,L.jsx)(F.Suspense,{fallback:(0,L.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:(0,L.jsx)(a,{id:`38foVZ`})}),children:(0,L.jsx)(de,{diff:u})})}):null,t[34]=u,t[35]=c,t[36]=p,t[37]=h,t[38]=M):M=t[38];let N;return t[39]!==j||t[40]!==M?(N=(0,L.jsxs)(`div`,{className:`border-t border-border/50`,children:[j,M]}),t[39]=j,t[40]=M,t[41]=N):N=t[41],N}function R(){return Date.now()}function me(e,t){let n=Math.max(0,t-e);if(n<6e4){let e=Math.round(n/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(n<36e5){let e=Math.round(n/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}let r=Math.round(n/36e5);return M._({id:`nYeBmY`,values:{hours:r}})}function z(e){let t=(0,P.c)(118),{file:n,sessionAlive:i,isWriting:o,onNavigate:s,onUndoLast:c,onUndoAll:l,fetchBurstDiff:u}=e,{_:d}=r(),{docName:p}=n,[m,h]=(0,F.useState)(!1),[_,y]=(0,F.useState)(!1),[b,x]=(0,F.useState)(!1),[S,k]=(0,F.useState)(ge),A,j;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(A=()=>{let e=setInterval(()=>k(Date.now()),3e4);return()=>clearInterval(e)},j=[],t[0]=A,t[1]=j):(A=t[0],j=t[1]),(0,F.useEffect)(A,j),n.bursts.length===0)return null;let M=!i||n.bursts.length===0||b,N=n.bursts.length,ae;t[2]!==d||t[3]!==n.bursts.length||t[4]!==i?(ae=i?n.bursts.length===0?d({id:`2fkdnR`}):null:d({id:`NzFvyK`}),t[2]=d,t[3]=n.bursts.length,t[4]=i,t[5]=ae):ae=t[5];let I=ae,oe;t[6]!==M||t[7]!==n.docName||t[8]!==c?(oe=e=>{e.stopPropagation(),!M&&(x(!0),Promise.resolve(c(n.docName)).finally(()=>x(!1)))},t[6]=M,t[7]=n.docName,t[8]=c,t[9]=oe):oe=t[9];let se=oe,ce;t[10]===M?ce=t[11]:(ce=e=>{e.stopPropagation(),!M&&y(!0)},t[10]=M,t[11]=ce);let le=ce,ue;t[12]!==M||t[13]!==n.docName||t[14]!==l?(ue=()=>{y(!1),!M&&(x(!0),Promise.resolve(l(n.docName)).finally(()=>x(!1)))},t[12]=M,t[13]=n.docName,t[14]=l,t[15]=ue):ue=t[15];let de=ue,fe;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(fe=()=>h(he),t[16]=fe):fe=t[16];let R;t[17]!==d||t[18]!==p||t[19]!==m?(R=d(m?{id:`rVgSRB`,values:{docName:p}}:{id:`tW_yvQ`,values:{docName:p}}),t[17]=d,t[18]=p,t[19]=m,t[20]=R):R=t[20];let z;t[21]===m?z=t[22]:(z=m?(0,L.jsx)(f,{className:`size-4`,"aria-hidden":`true`}):(0,L.jsx)(ee,{className:`size-4`,"aria-hidden":`true`}),t[21]=m,t[22]=z);let B;t[23]!==m||t[24]!==R||t[25]!==z?(B=(0,L.jsx)(`button`,{type:`button`,onClick:fe,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":m,"aria-label":R,"data-testid":`activity-panel-file-row-carrot`,children:z}),t[23]=m,t[24]=R,t[25]=z,t[26]=B):B=t[26];let V;t[27]!==n.docName||t[28]!==s?(V=()=>s(n.docName),t[27]=n.docName,t[28]=s,t[29]=V):V=t[29];let H;t[30]!==d||t[31]!==p?(H=d({id:`QcpeeE`,values:{docName:p}}),t[30]=d,t[31]=p,t[32]=H):H=t[32];let U;t[33]!==n.docName||t[34]!==V||t[35]!==H?(U=(0,L.jsx)(`button`,{type:`button`,onClick:V,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":H,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[33]=n.docName,t[34]=V,t[35]=H,t[36]=U):U=t[36];let W;t[37]!==d||t[38]!==p?(W=d({id:`m4v3XT`,values:{docName:p}}),t[37]=d,t[38]=p,t[39]=W):W=t[39];let _e;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(_e=(0,L.jsx)(v,{className:`size-3.5`,"aria-hidden":`true`}),t[40]=_e):_e=t[40];let G;t[41]!==M||t[42]!==se||t[43]!==W?(G=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:se,disabled:M,"aria-label":W,"data-testid":`activity-panel-undo-last`,children:_e})}),t[41]=M,t[42]=se,t[43]=W,t[44]=G):G=t[44];let K;t[45]!==d||t[46]!==I?(K=I??d({id:`ArBWJf`}),t[45]=d,t[46]=I,t[47]=K):K=t[47];let q;t[48]===K?q=t[49]:(q=(0,L.jsx)(ne,{side:`bottom`,children:K}),t[48]=K,t[49]=q);let J;t[50]!==G||t[51]!==q?(J=(0,L.jsxs)(re,{children:[G,q]}),t[50]=G,t[51]=q,t[52]=J):J=t[52];let Y;t[53]!==d||t[54]!==p?(Y=d({id:`J2MgzQ`,values:{docName:p}}),t[53]=d,t[54]=p,t[55]=Y):Y=t[55];let ve;t[56]===Symbol.for(`react.memo_cache_sentinel`)?(ve=(0,L.jsx)(ie,{className:`size-3.5`,"aria-hidden":`true`}),t[56]=ve):ve=t[56];let X;t[57]!==M||t[58]!==le||t[59]!==Y?(X=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:le,disabled:M,"aria-label":Y,"data-testid":`activity-panel-undo-all`,children:ve})}),t[57]=M,t[58]=le,t[59]=Y,t[60]=X):X=t[60];let Z;t[61]!==d||t[62]!==I?(Z=I??d({id:`mNY1G6`}),t[61]=d,t[62]=I,t[63]=Z):Z=t[63];let ye;t[64]===Z?ye=t[65]:(ye=(0,L.jsx)(ne,{side:`bottom`,children:Z}),t[64]=Z,t[65]=ye);let be;t[66]!==X||t[67]!==ye?(be=(0,L.jsxs)(re,{children:[X,ye]}),t[66]=X,t[67]=ye,t[68]=be):be=t[68];let xe;t[69]===n.additionsTotal?xe=t[70]:(xe=(0,L.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[69]=n.additionsTotal,t[70]=xe);let Se;t[71]===n.deletionsTotal?Se=t[72]:(Se=(0,L.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[71]=n.deletionsTotal,t[72]=Se);let Ce;t[73]!==xe||t[74]!==Se?(Ce=(0,L.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[xe,` `,Se]}),t[73]=xe,t[74]=Se,t[75]=Ce):Ce=t[75];let we;t[76]!==n.lastTs||t[77]!==S?(we=me(n.lastTs,S),t[76]=n.lastTs,t[77]=S,t[78]=we):we=t[78];let Q;t[79]===we?Q=t[80]:(Q=(0,L.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:we}),t[79]=we,t[80]=Q);let Te;t[81]===o?Te=t[82]:(Te=o?(0,L.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:(0,L.jsx)(a,{id:`6q0rnH`})}):null,t[81]=o,t[82]=Te);let Ee;t[83]!==B||t[84]!==U||t[85]!==J||t[86]!==be||t[87]!==Ce||t[88]!==Q||t[89]!==Te?(Ee=(0,L.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[B,U,J,be,Ce,Q,Te]}),t[83]=B,t[84]=U,t[85]=J,t[86]=be,t[87]=Ce,t[88]=Q,t[89]=Te,t[90]=Ee):Ee=t[90];let De;t[91]!==m||t[92]!==u||t[93]!==n.bursts||t[94]!==n.docName?(De=m?(0,L.jsx)(`div`,{children:n.bursts.map(e=>(0,L.jsx)(pe,{burst:e,docName:n.docName,fetchBurstDiff:u},`${n.docName}:${e.stackIndex}`))}):null,t[91]=m,t[92]=u,t[93]=n.bursts,t[94]=n.docName,t[95]=De):De=t[95];let Oe;t[96]===Symbol.for(`react.memo_cache_sentinel`)?(Oe=(0,L.jsx)(w,{children:(0,L.jsx)(a,{id:`SEYWYq`})}),t[96]=Oe):Oe=t[96];let ke;t[97]!==N||t[98]!==p?(ke={docName:p,burstCount:N},t[97]=N,t[98]=p,t[99]=ke):ke=t[99];let Ae;t[100]===Symbol.for(`react.memo_cache_sentinel`)?(Ae={0:(0,L.jsx)(`span`,{className:`font-mono text-foreground`})},t[100]=Ae):Ae=t[100];let je;t[101]===ke?je=t[102]:(je=(0,L.jsxs)(D,{children:[Oe,(0,L.jsx)(C,{children:(0,L.jsx)(a,{id:`ZBYKxv`,values:ke,components:Ae})})]}),t[101]=ke,t[102]=je);let Me;t[103]===Symbol.for(`react.memo_cache_sentinel`)?(Me=()=>y(!1),t[103]=Me):Me=t[103];let Ne;t[104]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=(0,L.jsx)(g,{type:`button`,variant:`outline`,onClick:Me,"data-testid":`activity-panel-undo-all-cancel`,children:(0,L.jsx)(a,{id:`dEgA5A`})}),t[104]=Ne):Ne=t[104];let Pe;t[105]===Symbol.for(`react.memo_cache_sentinel`)?(Pe=(0,L.jsx)(a,{id:`MWrUEd`}),t[105]=Pe):Pe=t[105];let Fe;t[106]===de?Fe=t[107]:(Fe=(0,L.jsxs)(E,{children:[Ne,(0,L.jsx)(g,{type:`button`,variant:`destructive`,onClick:de,"data-testid":`activity-panel-undo-all-confirm`,children:Pe})]}),t[106]=de,t[107]=Fe);let Ie;t[108]!==je||t[109]!==Fe?(Ie=(0,L.jsxs)(T,{className:`sm:max-w-md`,children:[je,Fe]}),t[108]=je,t[109]=Fe,t[110]=Ie):Ie=t[110];let $;t[111]!==_||t[112]!==Ie?($=(0,L.jsx)(O,{open:_,onOpenChange:y,children:Ie}),t[111]=_,t[112]=Ie,t[113]=$):$=t[113];let Le;return t[114]!==Ee||t[115]!==De||t[116]!==$?(Le=(0,L.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Ee,De,$]}),t[114]=Ee,t[115]=De,t[116]=$,t[117]=Le):Le=t[117],Le}function he(e){return!e}function ge(){return Date.now()}async function B(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function V(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function H(e){typeof window>`u`||(window.location.hash=V(e))}function U(){let e=(0,P.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,L.jsx)(c,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),e[0]=t):t=e[0];let n;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,L.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[t,(0,L.jsx)(`span`,{className:`text-sm`,children:(0,L.jsx)(a,{id:`ONPvOb`})})]}),e[1]=n):n=e[1],n}function W(e){let t=(0,P.c)(10),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,L.jsx)(s,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,L.jsx)(`p`,{className:`text-sm font-medium`,children:(0,L.jsx)(a,{id:`DhLHEb`})}),t[1]=o):o=t[1];let c;t[2]===n?c=t[3]:(c=(0,L.jsxs)(`div`,{className:`space-y-1`,children:[o,(0,L.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=c);let l;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(a,{id:`6gRgw8`}),t[4]=l):l=t[4];let u;t[5]===r?u=t[6]:(u=(0,L.jsx)(g,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:l}),t[5]=r,t[6]=u);let d;return t[7]!==c||t[8]!==u?(d=(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,c,u]}),t[7]=c,t[8]=u,t[9]=d):d=t[9],d}function _e(){let e=(0,P.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,L.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,L.jsx)(`p`,{className:`text-sm italic`,children:(0,L.jsx)(a,{id:`iuTKci`})})}),e[0]=t):t=e[0],t}function G(e){let t=(0,P.c)(12),{onExit:n,showBackButton:i}=e,{_:o}=r(),s;t[0]===o?s=t[1]:(s=o({id:`kYL1lH`}),t[0]=o,t[1]=s);let c;t[2]!==n||t[3]!==i?(c=i?(0,L.jsx)(K,{onClick:n}):null,t[2]=n,t[3]=i,t[4]=c):c=t[4];let l;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:(0,L.jsx)(a,{id:`kYL1lH`})}),t[5]=l):l=t[5];let u;t[6]===c?u=t[7]:(u=(0,L.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[c,l]}),t[6]=c,t[7]=u);let d;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,L.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,L.jsx)(`p`,{className:`text-center text-sm italic`,children:(0,L.jsx)(a,{id:`D_WKe_`})})}),t[8]=d):d=t[8];let f;return t[9]!==s||t[10]!==u?(f=(0,L.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":s,children:[u,d]}),t[9]=s,t[10]=u,t[11]=f):f=t[11],f}function K(e){let t=(0,P.c)(9),{onClick:n}=e,{_:i}=r(),o;t[0]===i?o=t[1]:(o=i({id:`ogAuyr`}),t[0]=i,t[1]=o);let s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,L.jsx)(b,{}),t[2]=s):s=t[2];let c;t[3]!==n||t[4]!==o?(c=(0,L.jsx)(te,{asChild:!0,children:(0,L.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":o,"data-testid":`docpanel-exit-agent-mode`,children:s})}),t[3]=n,t[4]=o,t[5]=c):c=t[5];let l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(ne,{side:`bottom`,children:(0,L.jsx)(a,{id:`ogAuyr`})}),t[6]=l):l=t[6];let u;return t[7]===c?u=t[8]:(u=(0,L.jsxs)(re,{children:[c,l]}),t[7]=c,t[8]=u),u}function q(e){let t=(0,P.c)(9),{lastTs:n}=e,[r]=(0,F.useState)(J),i;t[0]!==n||t[1]!==r?(i=n?Y(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let o=i,s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,L.jsx)(`span`,{className:`font-medium`,children:(0,L.jsx)(a,{id:`LCUy_N`})}),t[3]=s):s=t[3];let c;t[4]===o?c=t[5]:(c=o?(0,L.jsxs)(`span`,{children:[` · `,o]}):null,t[4]=o,t[5]=c);let l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,L.jsx)(`div`,{className:`mt-1 opacity-80`,children:(0,L.jsx)(a,{id:`GK-IRZ`})}),t[6]=l):l=t[6];let u;return t[7]===c?u=t[8]:(u=(0,L.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[s,c,l]}),t[7]=c,t[8]=u),u}function J(){return Date.now()}function Y(e){let t=Math.max(0,e);if(t<6e4){let e=Math.round(t/1e3);return M._({id:`pbwTg6`,values:{seconds:e}})}if(t<36e5){let e=Math.round(t/6e4);return M._({id:`_rP3HI`,values:{minutes:e}})}let n=Math.round(t/36e5);return M._({id:`nYeBmY`,values:{hours:n}})}function ve(e){let t=(0,P.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,L.jsx)(x,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,L.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function X(e){let t=(0,P.c)(26),{data:n,status:i,error:o,reload:s,fetchBurstDiff:c,onExit:l,onNavigate:u,onUndoLast:d,onUndoAll:f,showBackButton:p}=e,{_:m}=r(),h=n?.files?.[0]?.lastTs??null,g=n?.files?.length??0,_;t[0]===m?_=t[1]:(_=m({id:`kYL1lH`}),t[0]=m,t[1]=_);let v;t[2]!==l||t[3]!==p?(v=p?(0,L.jsx)(K,{onClick:l}):null,t[2]=l,t[3]=p,t[4]=v):v=t[4];let y;t[5]!==n||t[6]!==g||t[7]!==h?(y=n?.agent?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(ve,{agent:n.agent}),(0,L.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,L.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?(0,L.jsx)(a,{id:`F6pfE9`}):h===null?(0,L.jsx)(a,{id:`PMyJ9C`}):(0,L.jsx)(a,{id:`237hSL`}),n.files.length>0?(0,L.jsxs)(L.Fragment,{children:[` · `,(0,L.jsx)(a,{id:`u3BOHd`,values:{fileCount:g}})]}):null]})]})]}):(0,L.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,L.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:(0,L.jsx)(a,{id:`kYL1lH`})})}),t[5]=n,t[6]=g,t[7]=h,t[8]=y):y=t[8];let b;t[9]!==v||t[10]!==y?(b=(0,L.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[v,y]}),t[9]=v,t[10]=y,t[11]=b):b=t[11];let x;t[12]!==n||t[13]!==o||t[14]!==c||t[15]!==h||t[16]!==u||t[17]!==f||t[18]!==d||t[19]!==s||t[20]!==i?(x=(0,L.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:i===`loading`&&n===null?(0,L.jsx)(U,{}):i===`error`&&o?(0,L.jsx)(W,{error:o,onRetry:s}):n===null?(0,L.jsx)(_e,{}):(0,L.jsxs)(L.Fragment,{children:[!n.sessionAlive&&h!==null?(0,L.jsx)(q,{lastTs:h}):null,n.files.length===0?(0,L.jsx)(_e,{}):n.files.map(e=>(0,L.jsx)(z,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:u,onUndoLast:d,onUndoAll:f,fetchBurstDiff:c},e.docName))]})}),t[12]=n,t[13]=o,t[14]=c,t[15]=h,t[16]=u,t[17]=f,t[18]=d,t[19]=s,t[20]=i,t[21]=x):x=t[21];let S;return t[22]!==_||t[23]!==b||t[24]!==x?(S=(0,L.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":_,children:[b,x]}),t[22]=_,t[23]=b,t[24]=x,t[25]=S):S=t[25],S}function Z(e){let t=(0,P.c)(29),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{showBackButton:i}=n,a=i===void 0?!0:i,{_:o}=r(),{docPanelAgentId:s,closeActivityPanel:c}=l(),{openTargetTransition:d}=u(),{pageMeta:f}=A(),{data:p,status:m,error:h,reload:g,fetchBurstDiff:_}=ce(s);if(s===null){let e;return t[2]!==c||t[3]!==a?(e=(0,L.jsx)(G,{onExit:c,showBackButton:a}),t[2]=c,t[3]=a,t[4]=e):e=t[4],e}let v;t[5]!==d||t[6]!==f?(v=e=>{d(j({kind:`doc`,target:e,docName:e},f)),H(e)},t[5]=d,t[6]=f,t[7]=v):v=t[7];let y=v,b;t[8]!==o||t[9]!==p||t[10]!==s||t[11]!==g?(b=async e=>{try{await B({connectionId:s,docName:e,scope:`last`,agentName:p?.agent?.displayName}),g()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);N.error(o({id:`EqrC_R`,values:{message:n}})),g()}},t[8]=o,t[9]=p,t[10]=s,t[11]=g,t[12]=b):b=t[12];let x=b,S;t[13]!==o||t[14]!==p||t[15]!==s||t[16]!==g?(S=async e=>{try{await B({connectionId:s,docName:e,scope:`file`,agentName:p?.agent?.displayName}),N.success(o({id:`pRc-Im`,values:{docName:e}})),g()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);N.error(o({id:`7KeV5F`,values:{message:n}})),g()}},t[13]=o,t[14]=p,t[15]=s,t[16]=g,t[17]=S):S=t[17];let C=S,w;return t[18]!==c||t[19]!==p||t[20]!==h||t[21]!==_||t[22]!==y||t[23]!==C||t[24]!==x||t[25]!==g||t[26]!==a||t[27]!==m?(w=(0,L.jsx)(X,{data:p,status:m,error:h,reload:g,fetchBurstDiff:_,onExit:c,onNavigate:y,onUndoLast:x,onUndoAll:C,showBackButton:a}),t[18]=c,t[19]=p,t[20]=h,t[21]=_,t[22]=y,t[23]=C,t[24]=x,t[25]=g,t[26]=a,t[27]=m,t[28]=w):w=t[28],w}export{Z as ActivityModeContent};