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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-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
+ 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-IzGFtO3s.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-DW39-rpS.mjs";import{a as D,c as O,o as k,r as A,s as j,t as M}from"./write-project-skill-DrLvXsq9.mjs";import{n as N}from"./loader-CYxwIWTP.mjs";import{n as P}from"./preview-acIG4uAY.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-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(`
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-l7XNeUBq.mjs";import"./constants-BxczpHmO.mjs";import{l as C,n as w,o as T,r as E,t as D,u as ee}from"./write-project-skill-DrLvXsq9.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-acIG4uAY.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(`
@@ -281,7 +281,7 @@ let ii=/^[a-z0-9-_]+$/i;function ai(e){let t=typeof e;if(t===`object`){if(Array.
281
281
  `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function pi(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(ai(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=fi(0,e,``,t,n);return r[r.length-1]===`
282
282
  `?r:r+`
283
283
  `}function mi(e,t){let n=z(t,e);return n.length>0&&!n.startsWith(`..`)&&!oe(n)}const hi=e=>{try{let t=ne(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return t.length>0?t:null}catch{return null}};function gi(e,t={}){let n=t.homeDir??ce(),r=t.gitTopLevel??hi,i=B(e),a;try{a=ie(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(d(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=ae(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&mi(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}function $(e,t,n,r,i){let a=`urn:uuid:${le()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},s=c.safeParse(o);if(!s.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:s.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const _i=1e4;function vi(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!y(n))return $(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!m(e.headers.host))return $(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!p(r)?($(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const yi=3e4;function bi(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!y(n)||!m(e.headers.host))return t.destroy(),!0;let r=e.headers.origin;return typeof r==`string`&&!p(r)?(t.destroy(),!0):!1}function xi(e,t,n,r,i,a){a.add(t),t.once(`close`,()=>a.delete(t));let o=he({host:r,port:i,timeout:_i});a.add(o),o.once(`close`,()=>a.delete(o));let s=!1,c=n=>{if(!s){if(s=!0,n!==void 0){let t=n.err;console.warn(JSON.stringify({event:n.event,upstreamHost:r,upstreamPort:i,url:e.url,code:t instanceof Error?t.code:void 0,message:t instanceof Error?t.message:void 0}))}try{o.destroy()}catch{}try{t.destroy()}catch{}}};o.once(`connect`,()=>{o.setTimeout(0);let a=[`${e.method??`GET`} ${e.url??`/`} HTTP/1.1`,`host: ${r}:${i}`];for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()!==`host`&&n!==void 0)if(Array.isArray(n))for(let e of n)a.push(`${t}: ${e}`);else a.push(`${t}: ${n}`);try{o.write(`${a.join(`\r
284
- `)}\r\n\r\n`),n.length>0&&o.write(n)}catch(e){c({event:`proxy-upgrade-handshake-write-failed`,err:e});return}o.on(`data`,e=>{t.writable&&t.write(e)}),t.on(`data`,e=>{o.writable&&o.write(e)})}),o.once(`timeout`,()=>{c({event:`proxy-upgrade-upstream-connect-timeout`})}),o.on(`error`,e=>c({event:`proxy-upgrade-upstream-error`,err:e})),t.on(`error`,e=>c({event:`proxy-upgrade-client-error`,err:e})),o.once(`close`,()=>c()),t.once(`close`,()=>c())}const Si=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Ci(e){let t=e.upstreamTimeoutMs??_i,n=new Set,r=fe((n,r)=>{vi(n,r)||Ti(n,r,e.upstreamHost,e.upstreamPort,t)});r.on(`upgrade`,(t,r,i)=>{bi(t,r)||xi(t,r,i,e.upstreamHost,e.upstreamPort,n)}),await new Promise((t,n)=>{let i=e=>n(e);r.once(`error`,i),r.listen(e.listenPort,e.host,()=>{r.off(`error`,i),t()})});let i=r.address();return{httpServer:r,port:typeof i==`object`&&i?i.port:e.listenPort,close:()=>new Promise(e=>{for(let e of n)try{e.destroy()}catch{}n.clear(),r.close(()=>e()),r.closeIdleConnections()})}}function wi(e,t,n){Ti(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??_i)}function Ti(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Si)delete a[e];e.setTimeout(yi,()=>{if(t.headersSent)try{t.end()}catch{}else try{$(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${yi/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=pe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Si)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)$(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)$(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}const Ei=39847,Di=39848;async function Oi(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ki(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,clearArmedPaneTarget:c,createAssetServeMiddleware:u,createContentFilter:d,readArmedPaneTarget:f,readServerLock:p,releaseUiLock:m,updateUiLockPort:h}=await import(`./dist-Y_CEziF9.mjs`),{default:g}=await import(`./build-CCDQyip-.mjs`),{resolveContentDir:_,resolveLockDir:v}=await import(`./dist-Y_CEziF9.mjs`),y=_(e.config,e.cwd),b=v(e.cwd);i(b,{port:0,worktreeRoot:e.cwd});let x=import.meta.dirname??new URL(`.`,import.meta.url).pathname,S=[r(x,`public`),r(x,`../../app/dist`),r(x,`../../../app/dist`)],C=e.assetDir??S.find(e=>t(e)),w=C?g(C,{single:!0,gzip:!0,etag:!0,dev:!0,extensions:[]}):null,T=t(y)?u({contentFilter:d({projectDir:e.cwd,contentDir:y}),contentSirv:g(y,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:a,assetExtensions:l,blocklistExtensions:s}):null,E=e.port,D=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(e.method===`GET`&&(n===`/`||n===``)){let e=f(b);if(e&&!/[\r\n]/.test(e)){c(b),t.statusCode=302,t.setHeader(`Location`,`/${e}`),t.setHeader(`Cache-Control`,`no-store`),t.end();return}}if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&vi(e,t))){if(n===`/api/config`&&e.method===`DELETE`){c(b),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){D?.();let n=p(b),r=e.headers.host??`localhost:${E}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=f(b),o=JSON.stringify({collabUrl:i,previewUrl:null,port:E,paneTarget:a});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(o);return}if(n?.startsWith(`/api/`)){D?.();let r=p(b);if(!r||r.port<=0){$(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}wi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(w&&n?.startsWith(`/assets/`)){w(e,t,()=>{T?T(e,t,()=>Ai(t)):Ai(t)});return}if(T){T(e,t,()=>{w?w(e,t):Ai(t)});return}if(w){w(e,t);return}Ai(t)}},O=new Set,k=(e,t,n)=>{if(bi(e,t))return;let r=e.url?.split(`?`)[0]??``;if(r!==`/collab`&&!r.startsWith(`/collab/`)){t.destroy();return}let i=p(b);if(!i||i.port<=0){console.warn(JSON.stringify({event:`ok-ui-upgrade-no-collab-lock`,url:r,reason:"server.lock missing or port unbound — is `ok start` running?"})),t.destroy();return}xi(e,t,n,`localhost`,i.port,O)},A=()=>{for(let e of O)try{e.destroy()}catch{}O.clear()},te=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],j=[],M=e.port,N=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(j.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},P=async e=>{M=e;for(let e of te){let t=n(ee);t.on(`upgrade`,k),j.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(M,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(M=e.port),n()})})}};try{try{await P(e.port)}catch(t){if(e.fallbackToKernel===!0&&N(t))await ne(),await P(0);else throw t}}catch(e){await ne();try{m(b)}catch{}throw e}let re=M;E=re,h(b,re);let F=e.scheduler??o,ie=e.safetyNetMs??432e5,I=null,L=!1,ae=!1,oe=()=>{L||(L=!0,I!==null&&(F.clearTimeout(I),I=null))},R=()=>{if(oe(),!ae){ae=!0;try{m(b)}catch{}}},z=()=>{L||ie<=0||(I!==null&&(F.clearTimeout(I),I=null),I=F.setTimeout(()=>{I=null,console.warn(`[ui] safety-net (${ie}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}A();for(let e of j)try{e.close()}catch{}R()},ie))},B=()=>{L||ie<=0||z()};return D=B,z(),{httpServers:j,port:re,release:R,detachSafetyNet:oe,nudgeSafetyNet:B,drainUpgradeSockets:A}}function Ai(e){e.headersSent||e.writableEnded||e.destroyed||(e.setHeader(`X-Content-Type-Options`,`nosniff`),e.setHeader(`Cache-Control`,`no-store`),e.statusCode=404,e.end())}function ji(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return{port:t,fallbackToKernel:!1}}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return{port:e,fallbackToKernel:!1}}return{port:Ei,fallbackToKernel:!0}}async function Mi(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-Y_CEziF9.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Ci({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Ni(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Ei}, kernel-allocated fallback if busy)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud. Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BktTaA1t.mjs`),{UiLockCollisionError:r}=await import(`./dist-Y_CEziF9.mjs`),{resolveLockDir:i}=await import(`./dist-Y_CEziF9.mjs`),a=e(),o=t.host,s;try{s=ji(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}let c=s.port;try{let e=await ki({config:a,cwd:process.cwd(),port:c,fallbackToKernel:s.fallbackToKernel,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};e.drainUpgradeSockets(),Oi(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,s;try{s=await Mi({requestedPort:c,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}if(s.mode===`already-running`){if(console.log(`UI already running at http://${a}:${s.port}`),Pi(process)){await new Promise(e=>{let t=t=>{console.log(n(`\n[ui-keepalive] Shutting down (${t})`)),e()};process.once(`SIGINT`,()=>t(`SIGINT`)),process.once(`SIGTERM`,()=>t(`SIGTERM`))});return}process.exit(0)}console.log(`UI running at http://${a}:${s.upstreamPort}; acting as HTTP proxy on port ${s.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})`)),s.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}function Pi(e){let t=e.stdout.isTTY===!0,n=typeof e.env.PORT==`string`&&e.env.PORT!==``;return!t||n}function Fi(e){if(!P(e))return{};let t=F(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(O(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function Ii(e){if(!P(e))return{};let t=F(e,`utf-8`).trim();if(t===``)return{};try{let n=ri(t);if(O(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function Li(e,t){v(e,`${JSON.stringify(t,null,2)}\n`)}function Ri(e,t){let n=pi(t);v(e,n.endsWith(`
284
+ `)}\r\n\r\n`),n.length>0&&o.write(n)}catch(e){c({event:`proxy-upgrade-handshake-write-failed`,err:e});return}o.on(`data`,e=>{t.writable&&t.write(e)}),t.on(`data`,e=>{o.writable&&o.write(e)})}),o.once(`timeout`,()=>{c({event:`proxy-upgrade-upstream-connect-timeout`})}),o.on(`error`,e=>c({event:`proxy-upgrade-upstream-error`,err:e})),t.on(`error`,e=>c({event:`proxy-upgrade-client-error`,err:e})),o.once(`close`,()=>c()),t.once(`close`,()=>c())}const Si=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Ci(e){let t=e.upstreamTimeoutMs??_i,n=new Set,r=fe((n,r)=>{vi(n,r)||Ti(n,r,e.upstreamHost,e.upstreamPort,t)});r.on(`upgrade`,(t,r,i)=>{bi(t,r)||xi(t,r,i,e.upstreamHost,e.upstreamPort,n)}),await new Promise((t,n)=>{let i=e=>n(e);r.once(`error`,i),r.listen(e.listenPort,e.host,()=>{r.off(`error`,i),t()})});let i=r.address();return{httpServer:r,port:typeof i==`object`&&i?i.port:e.listenPort,close:()=>new Promise(e=>{for(let e of n)try{e.destroy()}catch{}n.clear(),r.close(()=>e()),r.closeIdleConnections()})}}function wi(e,t,n){Ti(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??_i)}function Ti(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Si)delete a[e];e.setTimeout(yi,()=>{if(t.headersSent)try{t.end()}catch{}else try{$(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${yi/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=pe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Si)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)$(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)$(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}const Ei=39847,Di=39848;async function Oi(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function ki(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,clearArmedPaneTarget:c,createAssetServeMiddleware:u,createContentFilter:d,readArmedPaneTarget:f,readServerLock:p,releaseUiLock:m,updateUiLockPort:h}=await import(`./dist-DqFZXNT6.mjs`),{default:g}=await import(`./build-CCDQyip-.mjs`),{resolveContentDir:_,resolveLockDir:v}=await import(`./dist-DqFZXNT6.mjs`),y=_(e.config,e.cwd),b=v(e.cwd);i(b,{port:0,worktreeRoot:e.cwd});let x=import.meta.dirname??new URL(`.`,import.meta.url).pathname,S=[r(x,`public`),r(x,`../../app/dist`),r(x,`../../../app/dist`)],C=e.assetDir??S.find(e=>t(e)),w=C?g(C,{single:!0,gzip:!0,etag:!0,dev:!0,extensions:[]}):null,T=t(y)?u({contentFilter:d({projectDir:e.cwd,contentDir:y}),contentSirv:g(y,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:a,assetExtensions:l,blocklistExtensions:s}):null,E=e.port,D=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if(e.method===`GET`&&(n===`/`||n===``)){let e=f(b);if(e&&!/[\r\n]/.test(e)){c(b),t.statusCode=302,t.setHeader(`Location`,`/${e}`),t.setHeader(`Cache-Control`,`no-store`),t.end();return}}if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&vi(e,t))){if(n===`/api/config`&&e.method===`DELETE`){c(b),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){D?.();let n=p(b),r=e.headers.host??`localhost:${E}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=f(b),o=JSON.stringify({collabUrl:i,previewUrl:null,port:E,paneTarget:a});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(o);return}if(n?.startsWith(`/api/`)){D?.();let r=p(b);if(!r||r.port<=0){$(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}wi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(w&&n?.startsWith(`/assets/`)){w(e,t,()=>{T?T(e,t,()=>Ai(t)):Ai(t)});return}if(T){T(e,t,()=>{w?w(e,t):Ai(t)});return}if(w){w(e,t);return}Ai(t)}},O=new Set,k=(e,t,n)=>{if(bi(e,t))return;let r=e.url?.split(`?`)[0]??``;if(r!==`/collab`&&!r.startsWith(`/collab/`)){t.destroy();return}let i=p(b);if(!i||i.port<=0){console.warn(JSON.stringify({event:`ok-ui-upgrade-no-collab-lock`,url:r,reason:"server.lock missing or port unbound — is `ok start` running?"})),t.destroy();return}xi(e,t,n,`localhost`,i.port,O)},A=()=>{for(let e of O)try{e.destroy()}catch{}O.clear()},te=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],j=[],M=e.port,N=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(j.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},P=async e=>{M=e;for(let e of te){let t=n(ee);t.on(`upgrade`,k),j.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(M,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(M=e.port),n()})})}};try{try{await P(e.port)}catch(t){if(e.fallbackToKernel===!0&&N(t))await ne(),await P(0);else throw t}}catch(e){await ne();try{m(b)}catch{}throw e}let re=M;E=re,h(b,re);let F=e.scheduler??o,ie=e.safetyNetMs??432e5,I=null,L=!1,ae=!1,oe=()=>{L||(L=!0,I!==null&&(F.clearTimeout(I),I=null))},R=()=>{if(oe(),!ae){ae=!0;try{m(b)}catch{}}},z=()=>{L||ie<=0||(I!==null&&(F.clearTimeout(I),I=null),I=F.setTimeout(()=>{I=null,console.warn(`[ui] safety-net (${ie}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}A();for(let e of j)try{e.close()}catch{}R()},ie))},B=()=>{L||ie<=0||z()};return D=B,z(),{httpServers:j,port:re,release:R,detachSafetyNet:oe,nudgeSafetyNet:B,drainUpgradeSockets:A}}function Ai(e){e.headersSent||e.writableEnded||e.destroyed||(e.setHeader(`X-Content-Type-Options`,`nosniff`),e.setHeader(`Cache-Control`,`no-store`),e.statusCode=404,e.end())}function ji(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return{port:t,fallbackToKernel:!1}}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return{port:e,fallbackToKernel:!1}}return{port:Ei,fallbackToKernel:!0}}async function Mi(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-DqFZXNT6.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Ci({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Ni(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Ei}, kernel-allocated fallback if busy)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud. Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BktTaA1t.mjs`),{UiLockCollisionError:r}=await import(`./dist-DqFZXNT6.mjs`),{resolveLockDir:i}=await import(`./dist-DqFZXNT6.mjs`),a=e(),o=t.host,s;try{s=ji(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}let c=s.port;try{let e=await ki({config:a,cwd:process.cwd(),port:c,fallbackToKernel:s.fallbackToKernel,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};e.drainUpgradeSockets(),Oi(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,s;try{s=await Mi({requestedPort:c,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}if(s.mode===`already-running`){if(console.log(`UI already running at http://${a}:${s.port}`),Pi(process)){await new Promise(e=>{let t=t=>{console.log(n(`\n[ui-keepalive] Shutting down (${t})`)),e()};process.once(`SIGINT`,()=>t(`SIGINT`)),process.once(`SIGTERM`,()=>t(`SIGTERM`))});return}process.exit(0)}console.log(`UI running at http://${a}:${s.upstreamPort}; acting as HTTP proxy on port ${s.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})`)),s.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}function Pi(e){let t=e.stdout.isTTY===!0,n=typeof e.env.PORT==`string`&&e.env.PORT!==``;return!t||n}function Fi(e){if(!P(e))return{};let t=F(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(O(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function Ii(e){if(!P(e))return{};let t=F(e,`utf-8`).trim();if(t===``)return{};try{let n=ri(t);if(O(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function Li(e,t){v(e,`${JSON.stringify(t,null,2)}\n`)}function Ri(e,t){let n=pi(t);v(e,n.endsWith(`
285
285
  `)?n:`${n}\n`)}const zi=e=>e!==`project`,Bi=e=>e!==`user`;async function Vi(){let e=await wn({message:`Where should the MCP server be configured?
286
286
  `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Hi(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Vi)():`both`}async function Ui(e){return Nr({message:`How do you want to handle Open Knowledge config files (.ok/, .mcp.json, project skills, launch.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:"OK config stays on this machine only; teammates do not see it. Safe escape hatch via `ok config-sharing share`."}]})}async function Wi(e){if(e.sharing!==void 0)return e.sharing;let t=_t(e.projectRoot)===`local-only`?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Ui)(t):t}const Gi=`0.0.1`,Ki=`open-knowledge-ui`,qi=[`-y`,`@inkeep/open-knowledge@latest`,`ui`],Ji=`# ok-ui-v1`,Yi=`${Ji}
287
287
  UIPORT="\${PORT:-${Di}}"
@@ -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-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(`
303
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DfZUXv5e.mjs`),{loadConfig:t}=await import(`./loader-CNpFptP4.mjs`),{resolveContentDir:n}=await import(`./dist-DqFZXNT6.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-BMT_3l9F.mjs.map
305
+ //# sourceMappingURL=init-IzGFtO3s.mjs.map
@@ -0,0 +1 @@
1
+ import{m as e}from"./init-IzGFtO3s.mjs";export{e as runInit};
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-CYxwIWTP.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-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(`
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-l7XNeUBq.mjs";import{t as s}from"./constants-BxczpHmO.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-D4wC401d.mjs.map
4
+ //# sourceMappingURL=loader-CYxwIWTP.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-acIG4uAY.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,3 +1,3 @@
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(`
1
+ import{Gt as e}from"./dist-l7XNeUBq.mjs";import"./constants-BxczpHmO.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-BGMRorsT.mjs.map
3
+ //# sourceMappingURL=preview-acIG4uAY.mjs.map
@@ -1,2 +1,2 @@
1
- import{h as e,n as t}from"./init-BMT_3l9F.mjs";import{t as n}from"./is-object-Cg453afR.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";const o=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],t];function s(e){if(e.runtimeExecutable===`/bin/sh`&&Array.isArray(e.runtimeArgs)){let t=e.runtimeArgs[2];if(typeof t==`string`){if(t.includes(`# ok-ui-v1`))return`canonical`;if(/# ok-ui-v\d+/.test(t))return`legacy-bare`}return`preserved`}if(e.runtimeExecutable===`npx`&&Array.isArray(e.runtimeArgs)){for(let t of o)if(c(e.runtimeArgs,t))return`legacy-bare`}return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(t){let o=t.logger??u,c=a(t.projectDir,`.claude`,`launch.json`);if(t.reclaimDisableEnv===`1`)return o({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:c,outcome:`skipped-reclaim-disabled`},repairedCount:0};if(!r(c))return{outcome:{configPath:c,outcome:`no-file`},repairedCount:0};let l;try{let e=i(c,`utf-8`).trim();l=e?JSON.parse(e):{}}catch(e){let t=e instanceof Error?e.message:String(e);return o({event:`launch-json-repair-read-failed`,configPath:c,error:t}),{outcome:{configPath:c,outcome:`read-failed`,error:t},repairedCount:0}}if(!n(l)){let e=`launch.json root is not an object`;return o({event:`launch-json-repair-read-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`read-failed`,error:e},repairedCount:0}}let d=l.configurations;if(!Array.isArray(d))return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let f=d.find(e=>n(e)&&e.name===`open-knowledge-ui`);if(!f)return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let p=s(f);if(p===`canonical`)return{outcome:{configPath:c,outcome:`canonical`},repairedCount:0};if(p===`preserved`)return{outcome:{configPath:c,outcome:`preserved`},repairedCount:0};let m=e(t.projectDir,{mode:`published`});if(m.action===`failed`){let e=m.error??`unknown write failure`;return o({event:`launch-json-repair-write-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`write-failed`,error:e},repairedCount:0}}return o({event:`launch-json-repair-applied`,configPath:c}),{outcome:{configPath:c,outcome:`repaired`},repairedCount:1}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairLaunchJson};
2
- //# sourceMappingURL=repair-launch-json-Ak_vMWlE.mjs.map
1
+ import{h as e,n as t}from"./init-IzGFtO3s.mjs";import{t as n}from"./is-object-Cg453afR.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";const o=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],t];function s(e){if(e.runtimeExecutable===`/bin/sh`&&Array.isArray(e.runtimeArgs)){let t=e.runtimeArgs[2];if(typeof t==`string`){if(t.includes(`# ok-ui-v1`))return`canonical`;if(/# ok-ui-v\d+/.test(t))return`legacy-bare`}return`preserved`}if(e.runtimeExecutable===`npx`&&Array.isArray(e.runtimeArgs)){for(let t of o)if(c(e.runtimeArgs,t))return`legacy-bare`}return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(t){let o=t.logger??u,c=a(t.projectDir,`.claude`,`launch.json`);if(t.reclaimDisableEnv===`1`)return o({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:c,outcome:`skipped-reclaim-disabled`},repairedCount:0};if(!r(c))return{outcome:{configPath:c,outcome:`no-file`},repairedCount:0};let l;try{let e=i(c,`utf-8`).trim();l=e?JSON.parse(e):{}}catch(e){let t=e instanceof Error?e.message:String(e);return o({event:`launch-json-repair-read-failed`,configPath:c,error:t}),{outcome:{configPath:c,outcome:`read-failed`,error:t},repairedCount:0}}if(!n(l)){let e=`launch.json root is not an object`;return o({event:`launch-json-repair-read-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`read-failed`,error:e},repairedCount:0}}let d=l.configurations;if(!Array.isArray(d))return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let f=d.find(e=>n(e)&&e.name===`open-knowledge-ui`);if(!f)return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let p=s(f);if(p===`canonical`)return{outcome:{configPath:c,outcome:`canonical`},repairedCount:0};if(p===`preserved`)return{outcome:{configPath:c,outcome:`preserved`},repairedCount:0};let m=e(t.projectDir,{mode:`published`});if(m.action===`failed`){let e=m.error??`unknown write failure`;return o({event:`launch-json-repair-write-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`write-failed`,error:e},repairedCount:0}}return o({event:`launch-json-repair-applied`,configPath:c}),{outcome:{configPath:c,outcome:`repaired`},repairedCount:1}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairLaunchJson};
2
+ //# sourceMappingURL=repair-launch-json-Dq4ywehx.mjs.map
@@ -1,2 +1,2 @@
1
- import{d as e,g as t}from"./init-BMT_3l9F.mjs";import{c as n,o as r,r as i}from"./write-project-skill-Bn8zRlMF.mjs";import{t as a}from"./mcp-migrate-event-D0NrGjvc.mjs";import{homedir as o}from"node:os";function s(e){let t=e.logger??u,n=e.home??o(),a=[];if(e.reclaimDisableEnv===`1`)return t({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of i){let i=r[o],s=c(()=>i.configPath(``,n));if(s!==null&&a.push(l({scope:`user`,editorId:o,target:i,home:n,cwd:``,configPath:s,configPathOverride:void 0,logger:t})),i.projectConfigPath){let n=i.projectConfigPath,r=c(()=>n(e.projectDir));r!==null&&a.push(l({scope:`project`,editorId:o,target:i,home:void 0,cwd:e.projectDir,configPath:r,configPathOverride:r,logger:t}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function c(e){try{return e()}catch{return null}}function l(r){let i={scope:r.scope,editorId:r.editorId,configPath:r.configPath},o=e(r.target,r.cwd,r.home,r.configPathOverride);if(o===null)return{...i,outcome:`no-entry`};if(n(o))return{...i,outcome:`canonical`};r.logger(a({scope:r.scope,surface:`cli-repair`,editorId:r.editorId,configPath:r.configPath,priorEntry:o}));let s=t(r.target,r.cwd,{mode:`published`,skipAvailabilityCheck:!0},r.home,r.configPathOverride);if(s.action===`failed`){let e=s.error??`unknown write failure`;return r.logger({event:`mcp-config-repair-write-failed`,scope:r.scope,editorId:r.editorId,configPath:r.configPath,error:e}),{...i,outcome:`write-failed`,error:e}}return{...i,outcome:`repaired`}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{s as repairMcpConfigs};
2
- //# sourceMappingURL=repair-mcp-configs-CnhOJEv-.mjs.map
1
+ import{d as e,g as t}from"./init-IzGFtO3s.mjs";import{c as n,o as r,r as i}from"./write-project-skill-DrLvXsq9.mjs";import{t as a}from"./mcp-migrate-event-D0NrGjvc.mjs";import{homedir as o}from"node:os";function s(e){let t=e.logger??u,n=e.home??o(),a=[];if(e.reclaimDisableEnv===`1`)return t({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of i){let i=r[o],s=c(()=>i.configPath(``,n));if(s!==null&&a.push(l({scope:`user`,editorId:o,target:i,home:n,cwd:``,configPath:s,configPathOverride:void 0,logger:t})),i.projectConfigPath){let n=i.projectConfigPath,r=c(()=>n(e.projectDir));r!==null&&a.push(l({scope:`project`,editorId:o,target:i,home:void 0,cwd:e.projectDir,configPath:r,configPathOverride:r,logger:t}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function c(e){try{return e()}catch{return null}}function l(r){let i={scope:r.scope,editorId:r.editorId,configPath:r.configPath},o=e(r.target,r.cwd,r.home,r.configPathOverride);if(o===null)return{...i,outcome:`no-entry`};if(n(o))return{...i,outcome:`canonical`};r.logger(a({scope:r.scope,surface:`cli-repair`,editorId:r.editorId,configPath:r.configPath,priorEntry:o}));let s=t(r.target,r.cwd,{mode:`published`,skipAvailabilityCheck:!0},r.home,r.configPathOverride);if(s.action===`failed`){let e=s.error??`unknown write failure`;return r.logger({event:`mcp-config-repair-write-failed`,scope:r.scope,editorId:r.editorId,configPath:r.configPath,error:e}),{...i,outcome:`write-failed`,error:e}}return{...i,outcome:`repaired`}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{s as repairMcpConfigs};
2
+ //# sourceMappingURL=repair-mcp-configs-CfALCHuP.mjs.map
@@ -1,3 +1,3 @@
1
- import{t as e}from"./esm-BLMtE3s6.mjs";import{Hi as t,Nr as n,Tr as r,kr as i,zr as a}from"./dist-CWv9hwiJ.mjs";import{i as o,o as s,t as c}from"./write-project-skill-Bn8zRlMF.mjs";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f,rmSync as p,statSync as m,writeFileSync as h}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{homedir as y}from"node:os";const b=[{hostDir:`.claude`,editorId:`claude`},{hostDir:`.cursor`,editorId:`cursor`},{hostDir:`.agents`,editorId:`codex`}],x=`open-knowledge-discovery`,S=[`.agents`,`skills`,x],C={existsSync:e=>l(e),isDirectory:e=>{try{return m(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>f(e),readFileSync:e=>d(e),writeFileSync:(e,t)=>{h(e,t)},mkdirSync:(e,t)=>{u(e,t)},rmSync:(e,t)=>{p(e,t)}},w={resolveProjectBundledSkillDir:()=>a(`project`,{checkDesktop:!1}),resolveDiscoveryBundledSkillDir:()=>a(`discovery`,{checkDesktop:!1}),readBundledVersion:()=>r(),readRecordedVersion:e=>i(e,`cli-hosts`),writeRecordedVersion:(e,n)=>t(e,`cli-hosts`,n,`cli-start`),recordEvent:e=>n(e)};function T(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function E(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(g(t),{recursive:!0}),D(e,t,n)}function D(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=_(e,r),a=_(t,r);n.isDirectory(i)?D(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function O(e,t){if(!e)return!1;try{return t.existsSync(e)?t.readFileSync(e).toString(`utf8`).includes(o):!1}catch{return!1}}function k(e,t,n,r){let i;try{i=t.resolveProjectBundledSkillDir()}catch(e){return r({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let a=[];for(let t of b){let o=_(e,t.hostDir,`skills`,`open-knowledge`),l=_(o,`SKILL.md`),u=n.existsSync(l),d=s[t.editorId]?.projectConfigPath?.(e),f=!u&&O(d,n);if(!u&&!f){a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`no-token`}),r({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:t.editorId,path:o});continue}try{c(o,e),E(i,o,n);let s=u?`reclaimed`:`created`;a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:s}),r({event:u?`project-skill-reclaim-reclaimed`:`project-skill-reclaim-created`,scope:`project`,editorId:t.editorId,path:o})}catch(e){let n=e instanceof Error?e.message:String(e);a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`failed`,error:n}),r({event:`project-skill-reclaim-failed`,scope:`project`,editorId:t.editorId,path:o,error:n})}}return{outcome:`done`,entries:a}}async function A(e,t,n,r){let i=e=>{t.recordEvent(e).catch(()=>{})},a=()=>new Date().toISOString(),o;try{o=await t.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return r({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let s;try{s=await t.readRecordedVersion(e)}catch(e){r({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),s=null}if(s!==null&&s===o)return r({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:o}),{outcome:`skipped`,reason:`version-current`};let c;try{c=t.resolveDiscoveryBundledSkillDir()}catch(e){let t=e instanceof Error?e.message:String(e);return r({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:t}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`bundle-missing:${t}`}),{outcome:`skipped`,reason:`bundle-missing`}}let l=[],u=_(e,...S),d=n.existsSync(u);try{E(c,u,n),l.push({kind:`central`,path:u,outcome:d?`overwritten`:`written`}),r({event:`user-skill-reclaim-central-written`,scope:`user`,path:u,preexisting:d,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);l.push({kind:`central`,path:u,outcome:`failed`,error:t}),r({event:`user-skill-reclaim-central-failed`,scope:`user`,path:u,error:t})}for(let t of b){let i=_(e,t.hostDir),a=_(i,`skills`,x);if(a===u){l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`skipped-collapsed-with-central`});continue}if(!n.existsSync(i)){l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`skipped-host-absent`});continue}let s=n.existsSync(a);try{E(c,a,n),l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:s?`overwritten`:`written`}),r({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:t.editorId,hostDir:t.hostDir,path:a,preexisting:s,version:o})}catch(e){let n=e instanceof Error?e.message:String(e);l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`failed`,error:n}),r({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:t.editorId,hostDir:t.hostDir,path:a,error:n})}}let f=l.find(e=>e.kind===`central`);if(f?.outcome===`written`||f?.outcome===`overwritten`){let n=null;try{await t.writeRecordedVersion(e,o),r({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:o})}catch(e){n=e instanceof Error?e.message:String(e),r({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:o,error:n})}i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:n===null?`installed`:`failed`,version:o,...n===null?{}:{reason:`state-write-failed:${n}`}})}else{let e=l.some(e=>e.kind===`host`&&e.outcome===`failed`);i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,version:o,reason:e?`all-writes-failed`:`no-hosts-installed`})}return{outcome:`done`,version:o,entries:l}}async function j(e){let t=e.logger??T,n=e.fs??C,r=e.home??y(),i={...w,...e.deps};return e.reclaimDisableEnv===`1`?(t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`}):{status:`done`,project:k(e.projectDir,i,n,t),user:await A(r,i,n,t)}}function M(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function N(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`reclaimed`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length;t.push(` Project: ${n} reclaimed, ${r} created, ${i} no-token, ${a} failed.`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`||e.outcome===`overwritten`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,i=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} skipped, ${i} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return t.join(`
1
+ import{t as e}from"./esm-BLMtE3s6.mjs";import{Hi as t,Nr as n,Tr as r,kr as i,zr as a}from"./dist-l7XNeUBq.mjs";import{i as o,o as s,t as c}from"./write-project-skill-DrLvXsq9.mjs";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f,rmSync as p,statSync as m,writeFileSync as h}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{homedir as y}from"node:os";const b=[{hostDir:`.claude`,editorId:`claude`},{hostDir:`.cursor`,editorId:`cursor`},{hostDir:`.agents`,editorId:`codex`}],x=`open-knowledge-discovery`,S=[`.agents`,`skills`,x],C={existsSync:e=>l(e),isDirectory:e=>{try{return m(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>f(e),readFileSync:e=>d(e),writeFileSync:(e,t)=>{h(e,t)},mkdirSync:(e,t)=>{u(e,t)},rmSync:(e,t)=>{p(e,t)}},w={resolveProjectBundledSkillDir:()=>a(`project`,{checkDesktop:!1}),resolveDiscoveryBundledSkillDir:()=>a(`discovery`,{checkDesktop:!1}),readBundledVersion:()=>r(),readRecordedVersion:e=>i(e,`cli-hosts`),writeRecordedVersion:(e,n)=>t(e,`cli-hosts`,n,`cli-start`),recordEvent:e=>n(e)};function T(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function E(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(g(t),{recursive:!0}),D(e,t,n)}function D(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=_(e,r),a=_(t,r);n.isDirectory(i)?D(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function O(e,t){if(!e)return!1;try{return t.existsSync(e)?t.readFileSync(e).toString(`utf8`).includes(o):!1}catch{return!1}}function k(e,t,n,r){let i;try{i=t.resolveProjectBundledSkillDir()}catch(e){return r({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let a=[];for(let t of b){let o=_(e,t.hostDir,`skills`,`open-knowledge`),l=_(o,`SKILL.md`),u=n.existsSync(l),d=s[t.editorId]?.projectConfigPath?.(e),f=!u&&O(d,n);if(!u&&!f){a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`no-token`}),r({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:t.editorId,path:o});continue}try{c(o,e),E(i,o,n);let s=u?`reclaimed`:`created`;a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:s}),r({event:u?`project-skill-reclaim-reclaimed`:`project-skill-reclaim-created`,scope:`project`,editorId:t.editorId,path:o})}catch(e){let n=e instanceof Error?e.message:String(e);a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`failed`,error:n}),r({event:`project-skill-reclaim-failed`,scope:`project`,editorId:t.editorId,path:o,error:n})}}return{outcome:`done`,entries:a}}async function A(e,t,n,r){let i=e=>{t.recordEvent(e).catch(()=>{})},a=()=>new Date().toISOString(),o;try{o=await t.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return r({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let s;try{s=await t.readRecordedVersion(e)}catch(e){r({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),s=null}if(s!==null&&s===o)return r({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:o}),{outcome:`skipped`,reason:`version-current`};let c;try{c=t.resolveDiscoveryBundledSkillDir()}catch(e){let t=e instanceof Error?e.message:String(e);return r({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:t}),i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`bundle-missing:${t}`}),{outcome:`skipped`,reason:`bundle-missing`}}let l=[],u=_(e,...S),d=n.existsSync(u);try{E(c,u,n),l.push({kind:`central`,path:u,outcome:d?`overwritten`:`written`}),r({event:`user-skill-reclaim-central-written`,scope:`user`,path:u,preexisting:d,version:o})}catch(e){let t=e instanceof Error?e.message:String(e);l.push({kind:`central`,path:u,outcome:`failed`,error:t}),r({event:`user-skill-reclaim-central-failed`,scope:`user`,path:u,error:t})}for(let t of b){let i=_(e,t.hostDir),a=_(i,`skills`,x);if(a===u){l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`skipped-collapsed-with-central`});continue}if(!n.existsSync(i)){l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`skipped-host-absent`});continue}let s=n.existsSync(a);try{E(c,a,n),l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:s?`overwritten`:`written`}),r({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:t.editorId,hostDir:t.hostDir,path:a,preexisting:s,version:o})}catch(e){let n=e instanceof Error?e.message:String(e);l.push({kind:`host`,editorId:t.editorId,hostDir:t.hostDir,path:a,outcome:`failed`,error:n}),r({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:t.editorId,hostDir:t.hostDir,path:a,error:n})}}let f=l.find(e=>e.kind===`central`);if(f?.outcome===`written`||f?.outcome===`overwritten`){let n=null;try{await t.writeRecordedVersion(e,o),r({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:o})}catch(e){n=e instanceof Error?e.message:String(e),r({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:o,error:n})}i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:n===null?`installed`:`failed`,version:o,...n===null?{}:{reason:`state-write-failed:${n}`}})}else{let e=l.some(e=>e.kind===`host`&&e.outcome===`failed`);i({ts:a(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,version:o,reason:e?`all-writes-failed`:`no-hosts-installed`})}return{outcome:`done`,version:o,entries:l}}async function j(e){let t=e.logger??T,n=e.fs??C,r=e.home??y(),i={...w,...e.deps};return e.reclaimDisableEnv===`1`?(t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`}):{status:`done`,project:k(e.projectDir,i,n,t),user:await A(r,i,n,t)}}function M(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function N(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`reclaimed`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length;t.push(` Project: ${n} reclaimed, ${r} created, ${i} no-token, ${a} failed.`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`||e.outcome===`overwritten`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,i=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} skipped, ${i} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return t.join(`
2
2
  `)}function P(){return new e(`repair-skills`).description("Refresh bundled SKILL.md files for installed AI editors (project-local + user-global). Runs automatically during `ok start`; this command forces an explicit sweep.").action(async()=>{let e=await j({projectDir:v(process.cwd()),reclaimDisableEnv:process.env.OK_RECLAIM_DISABLE??null});process.stdout.write(`${N(e)}\n`),process.exitCode=M(e)})}export{P as n,j as t};
3
- //# sourceMappingURL=repair-skills-BNYzyMnZ.mjs.map
3
+ //# sourceMappingURL=repair-skills-D1ySiKmX.mjs.map
@@ -0,0 +1 @@
1
+ import{t as e}from"./repair-skills-D1ySiKmX.mjs";export{e as repairSkills};
@@ -1,7 +1,7 @@
1
- import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{c as n,l as r,s as i}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import"./gh-detect-DLds_L3H.mjs";import{Ur as a,vn as o}from"./dist-CWv9hwiJ.mjs";import{g as s,h as c}from"./init-BMT_3l9F.mjs";import{n as l,o as u}from"./write-project-skill-Bn8zRlMF.mjs";import"./loader-D4wC401d.mjs";import{c as d}from"./colors-CBY1ibtz.mjs";import"./preview-BGMRorsT.mjs";import{spawnSync as f}from"node:child_process";import{existsSync as p,lstatSync as m,readFileSync as h,readdirSync as g,statSync as ee}from"node:fs";import{basename as te,dirname as _,isAbsolute as v,join as y,relative as b,resolve as x}from"node:path";import{hostname as ne}from"node:os";import{readFile as S,realpath as C}from"node:fs/promises";function w(e,t,a={}){let o=r(e,t);if(!p(o))return{status:`missing`,lockPath:o};let s;try{s=JSON.parse(h(o,`utf-8`))}catch{return{status:`corrupt`,lockPath:o}}if(!s||typeof s!=`object`||!n(s.pid))return{status:`corrupt`,lockPath:o};let c=s;if(!(a.isAlive??i)(c.pid))return{status:`dead-pid`,lockPath:o,lock:c};let l=a.host??ne();return c.hostname===l?{status:`alive`,lockPath:o,lock:c}:{status:`foreign-host`,lockPath:o,lock:c}}function T(e){return e.replace(/:\d+$/,``)}function E(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function D(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function O(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function k(e){let t=D(e);if(t)return{kind:`doc`,...t};let n=O(e);return n?{kind:`folder`,...n}:null}const A=2e3,j=2e3,re=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function M(e){return re.some(t=>t.test(e))}function ie(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return v(e)?e:null}catch{return null}}function ae(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&v(a)?a:null}function oe(e){let t=[];for(let n of e.split(`
1
+ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{c as n,l as r,s as i}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import"./gh-detect-DLds_L3H.mjs";import{Ur as a,vn as o}from"./dist-l7XNeUBq.mjs";import{g as s,h as c}from"./init-IzGFtO3s.mjs";import{n as l,o as u}from"./write-project-skill-DrLvXsq9.mjs";import"./loader-CYxwIWTP.mjs";import{c as d}from"./colors-CBY1ibtz.mjs";import"./preview-acIG4uAY.mjs";import{spawnSync as f}from"node:child_process";import{existsSync as p,lstatSync as m,readFileSync as h,readdirSync as g,statSync as ee}from"node:fs";import{basename as te,dirname as _,isAbsolute as v,join as y,relative as b,resolve as x}from"node:path";import{hostname as ne}from"node:os";import{readFile as S,realpath as C}from"node:fs/promises";function w(e,t,a={}){let o=r(e,t);if(!p(o))return{status:`missing`,lockPath:o};let s;try{s=JSON.parse(h(o,`utf-8`))}catch{return{status:`corrupt`,lockPath:o}}if(!s||typeof s!=`object`||!n(s.pid))return{status:`corrupt`,lockPath:o};let c=s;if(!(a.isAlive??i)(c.pid))return{status:`dead-pid`,lockPath:o,lock:c};let l=a.host??ne();return c.hostname===l?{status:`alive`,lockPath:o,lock:c}:{status:`foreign-host`,lockPath:o,lock:c}}function T(e){return e.replace(/:\d+$/,``)}function E(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:T(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function D(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function O(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function k(e){let t=D(e);if(t)return{kind:`doc`,...t};let n=O(e);return n?{kind:`folder`,...n}:null}const A=2e3,j=2e3,re=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function M(e){return re.some(t=>t.test(e))}function ie(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return v(e)?e:null}catch{return null}}function ae(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&v(a)?a:null}function oe(e){let t=[];for(let n of e.split(`
2
2
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&M(a)&&t.push({pid:o,command:a})}return t}function se(e){let t=[],n=e.split(`
3
3
  `);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.indexOf(` `);if(i===-1)continue;let a=r.slice(0,i),o=r.slice(i+1).trim(),s=Number.parseInt(a,10);!Number.isNaN(s)&&M(o)&&t.push({pid:s,command:o})}return t}async function ce(){let e=f(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|Open Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:A});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=oe(t);if(n.length>0||t.trim()===``)return n}let t=f(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:A});return t.error!=null||!t.stdout?[]:se(t.stdout)}function le(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=te(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function N(e){let t=f(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:A});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function P(e){let t=f(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:A});if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}async function F(e){let t=f(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:A});if(t.error!=null)return null;let n=t.stdout??``;for(let e of n.split(`
4
4
  `))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function I(e){let t=[],n=e.split(`
5
5
  `);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.split(/\s+/);if(i.length<2)continue;let a=Number.parseInt(i[1]??``,10);Number.isNaN(a)||t.push(a)}return[...new Set(t)]}function L(e){return p(y(e,`server.lock`))||p(y(e,`ui.lock`))}function R(e,t){for(let n of[y(t,`.ok`,`local`),y(t,`.ok`)])p(n)&&L(n)&&e.add(n)}function z(e,t){let n=0,r=(t,i)=>{if(n>=j||(n++,R(e,t),i>=3))return;let a;try{a=g(t)}catch{return}for(let e of a){if(n>=j)return;if(e===`node_modules`||e===`.git`||e===`Library`||e.startsWith(`.`)&&e!==`.ok`)continue;let a=y(t,e),o=!1;try{o=m(a).isDirectory()}catch{continue}o&&r(a,i+1)}};r(t,0)}async function B(){let e=new Set,t=await ce(),n=t.map(e=>F(e.pid)),r=await Promise.all(n);for(let n of t){let t=ie(n.command);t!=null&&p(t)&&e.add(t);let r=ae(n.command);r!=null&&R(e,r)}for(let t of r)t!=null&&R(e,t);let i=f(`lsof`,[`-iTCP`,`-sTCP:LISTEN`,`-nP`],{encoding:`utf-8`,timeout:A});if(i.error==null&&i.stdout){let n=I(i.stdout),r=new Set(t.map(e=>e.pid)),a=n.filter(e=>!r.has(e)).map(e=>F(e)),o=await Promise.all(a);for(let t of o)t!=null&&R(e,t)}(e.size===0||r.some(e=>e===`/`))&&z(e,process.cwd());let a=new Map;for(let t of e)try{let e=await C(t);a.set(e,e)}catch{a.set(t,t)}return[...a.values()]}var V=e(d(),1);function H(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function U(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function W(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:le(r),command:r,isDesktop:H(r)}}function ue(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function G(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&ue(e)?`ui-orphan`:`stale`}const de=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function fe(e){switch(e){case`running`:return V.default.green(e);case`desktop`:return V.default.blue(e);case`foreign`:return V.default.cyan(e);case`ui-orphan`:return V.default.magenta(e);case`stale`:return V.default.yellow(e)}}function K(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function pe(e){return`${K(e.server.usage)} | ${K(e.ui?.usage??null)}`}function me(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function he(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=G(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,me(e),pe(e),t,String(n),U(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=fe(G(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=V.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
6
6
  `)}async function q(e={}){let t=e.discover??B,n=e.inspect??w,r=e.log??(e=>console.log(e)),i=e.resolveCommand??N,a=e.resolveUsage??P,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=W(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:G(e)}));r(JSON.stringify(e,null,2));return}r(he(e.all?s:s.filter(e=>de.has(G(e)))))}function ge(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await q({all:t.all===!0||e===`all`,json:t.json===!0})})}const _e=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`]);function ve(e,t,n=o){if(e!==void 0&&!_e.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let J=null;function ye(e){J=e}function be(){return J??process.cwd()}function xe(e,t,n={}){let r=n.isAlive??i,a=[];for(let[n,i]of[[`server`,e],[`ui`,t]])(i.status===`alive`||i.status===`foreign-host`&&r(i.lock.pid))&&a.push({name:n,pid:i.lock.pid,port:i.lock.port});return{targets:a}}function Y(e){let t=e.inspect??(t=>w(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=xe(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function X(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function Se(e,t=i){let n=await B(),r=null;for(let i of n){let n=w(i,`server`),a=w(i,`ui`);if(X(n,t)&&n.lock.port===e||X(a,t)&&a.lock.port===e)return i;r===null&&(X(n,t)&&n.lock.pid===e||X(a,t)&&a.lock.pid===e)&&(r=i)}return r}function Z(e){let t=Y({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function Ce(e){return new t(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async t=>{let n=t.length===0?void 0:t.join(` `);if(n===void 0){e();let t=Y({lockDir:a(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await q({});return}if(n===`all`){let e=await B();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e){let e=w(n,`server`),r=w(n,`ui`);!X(e,i)&&!X(r,i)||(Z(n),t++)}t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(n)){let e=Number.parseInt(n,10),t=await Se(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}Z(t);return}Z(a(x(be(),n)))})}async function we(e,t){let n,r;try{n=await C(x(e)),r=await C(x(_(e)))}catch{return{kind:`not-git`}}if(!$(n,r))return{kind:`symlink-escape`};let i=y(n,`.git`),a;try{a=ee(i)}catch{return{kind:`not-git`}}let o;if(a.isDirectory()){let e;try{e=await C(i)}catch{return{kind:`not-git`}}if(!$(e,n))return{kind:`symlink-escape`};o=e}else if(a.isFile()){let e;try{e=await S(i,`utf-8`)}catch{return{kind:`not-git`}}let t=/^gitdir:\s*(.+)$/m.exec(e.trim());if(!t)return{kind:`not-git`};let r=t[1].trim(),a=v(r)?r:x(n,r);try{o=await C(a)}catch{return{kind:`not-git`}}}else return{kind:`not-git`};let s=y(await Q(o),`config`),c;try{c=await S(s,`utf-8`)}catch{return{kind:`not-git`}}let l=Ee(c);if(l===null)return{kind:`no-origin`};let u=E(l);if(u===null||u.hostname!==`github.com`)return{kind:`non-github`};let d=u.owner.toLowerCase()===t.owner.toLowerCase(),f=u.name.toLowerCase()===t.repo.toLowerCase();return!d||!f?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://github.com/${u.owner}/${u.name}.git`}}async function Q(e){let t;try{t=(await S(y(e,`commondir`),`utf-8`)).trim()}catch{return e}if(t.length===0)return e;let n=v(t)?t:x(e,t);try{return await C(n)}catch{return n}}function $(e,t){if(e===t)return!0;let n=b(t,e);return n.length>0&&!n.startsWith(`..`)&&!v(n)}function Te(e){let t=e.indexOf(`#`),n=e.indexOf(`;`),r=-1;return t>=0&&n>=0?r=Math.min(t,n):t>=0?r=t:n>=0&&(r=n),(r===-1?e:e.slice(0,r)).trim()}function Ee(e){let t=!1;for(let n of e.split(/\r?\n/)){let e=Te(n);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let r=/^url\s*=\s*(.+)$/.exec(e);if(r)return De(r[1])}return null}function De(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}const Oe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=s(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let n=l(e,t);return{integration:`project-skill`,editorId:e.id,action:n.action,...n.path?{path:n.path}:{},...n.error?{error:n.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function ke(e,t,n={},r=Oe){let i=[];for(let a of t){let t=u[a];for(let a of r)i.push(a.write(t,e,n))}return i}function Ae(e,t,n={}){return{integrations:ke(e,t,n),claudeLaunchJson:t.includes(`claude`)?c(e,n):void 0}}export{ye as a,B as c,D as d,k as f,w as h,Ce as i,N as l,E as m,we as n,ve as o,O as p,Y as r,ge as s,Ae as t,P as u};
7
- //# sourceMappingURL=src-ANkvjof-.mjs.map
7
+ //# sourceMappingURL=src-DW39-rpS.mjs.map
@@ -0,0 +1 @@
1
+ import{_ as e,f as t,r as n}from"./start-D75p8pvD.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
@@ -1,3 +1,3 @@
1
- import{n as e,t}from"./esm-BLMtE3s6.mjs";import{bn as n,ft as r}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{i,t as a}from"./gh-detect-DLds_L3H.mjs";import{$n as o,br as s,ur as c}from"./dist-CWv9hwiJ.mjs";import{n as l}from"./constants-DRZYaWtr.mjs";import{spawn as u}from"node:child_process";import{closeSync as d,existsSync as f,mkdirSync as p,openSync as m,statSync as h}from"node:fs";import{basename as g,dirname as _,join as v}from"node:path";import{homedir as y}from"node:os";import{setTimeout as b}from"node:timers/promises";const x=`Open Knowledge.app`,S=`/Applications/${x}`;function C(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return h(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function w(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(T(e,S))return S;let t=v(e.homeDir??y(),`Applications`,x);return T(e,t)?t:null}function T(e,t){try{let n=v(t,`Contents`,`MacOS`,`Open Knowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function E(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=w(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function D(e){(e.log??(e=>console.error(e)))("Launching Open Knowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function O(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${S}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${S} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${S} but launch dispatch did not fire (caller bug).`}}function k(e){return v(_(e),`..`,`Frameworks`,`Open Knowledge Server.app`,`Contents`,`MacOS`,`Open Knowledge Helper`)}const A=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function j(e){if(e.platform!==`darwin`||!A.test(e.execPath))return null;let t=k(e.execPath);return e.exists(t)?t:null}function M(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??f,a=r[1];return a?{command:j({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function N(e,t){return e.host??t.HOST??`localhost`}function P(e){let t=g(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var F=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function I(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function L(e){f(e.lockDir)||p(e.lockDir,{recursive:!0});let t=m(v(e.lockDir,n),`w`),r=e.spawn??u,{PORT:i,...a}=process.env,o=M();try{let n=r(o.command,[...o.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return n.unref(),n}finally{try{d(t)}catch{}}}function R(e,t,n){return e??(n===void 0?t:void 0)}function z(e,t){return e!==void 0&&t!==null&&t.port>0}function B(e,t,n){return e??(t!=null&&!n?1:0)}async function V(e){let t=e.spawn??u,n=M(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=B(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function H(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const U=r;function W(e){let t=e.sigtermGraceMs??U,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>b(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function G(e){let{config:t,cwd:n,host:r}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:x}=await import(`./dist-Y_CEziF9.mjs`),S=e.log??_(`start`),C=e.singleFile!==void 0,w=e.projectDir??n,T=C?s(e.singleFile).canonicalFilePath:void 0,E=T?h(T):void 0,D=T?m(T):void 0;if(!C){if(!l&&!o(n))throw new F(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-CnhOJEv-.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-Ak_vMWlE.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-DuyR0VaF.mjs`)).repairSkills)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let O=E??x(t,n);!C&&!f(O)&&(p(O,{recursive:!0}),S.info({contentDir:O},`Created content directory`));let k=null,A=async({lockDir:t})=>{if(k=I({uiLock:y(t),isAlive:v}),k.action===`spawn`&&!u)try{let r=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];L({lockDir:t,cwd:n,spawn:e.spawn,args:r}),S.info({reason:k.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else k.action===`skip`&&S.info({port:k.port,pid:k.pid},`UI already running at port ${k.port}`)},j=e.reactShellDistDir===void 0,M=i(),N=c(),P=await g({config:t,contentDir:O,projectDir:C?w:n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:a,tokenStore:M,embeddingsKeyStore:N,...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:j,idleShutdownMs:d,skipAutoInit:!0,...j?{spawnUiSiblingFn:A}:{},idleShutdownHandler:e=>W({readUiLock:()=>y(P.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:S}),log:S,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});k||={action:`skip`,reason:`alive`,pid:0,port:0};let R=k,z=null;if(R.action===`skip`)z=R.port>0?R.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;z=await H({readUiLock:()=>y(P.lockDir),now:Date.now,sleep:e=>b(e),timeoutMs:t,pollIntervalMs:50}),z===null&&S.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:P.httpServer,destroy:P.destroy,lockDir:P.lockDir,contentDir:O,port:P.port,ready:P.ready,degraded:P.degraded,uiSpawnDecision:k,resolvedUiPort:z}}function K(t){if(t===`browser`||t===`app`)return t;throw new e(`--mode must be 'browser' or 'app'`)}function q(t){let n=Number.parseInt(t,10);if(Number.isNaN(n)||n<1||n>65535)throw new e(`--ui-port must be a port number between 1 and 65535`);return n}function J(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Y(e){let t=[`Stopping Open Knowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function X(e,t){let n=J(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-DBiyrzNA.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-BktTaA1t.mjs`),c=process.cwd(),u=e;process.title=P(c);let d=N(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=R(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-Y_CEziF9.mjs`);if(z(m,e(t(c)))){await V({cwd:c,uiPort:m});return}}let g;try{g=await G({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof F&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-Y_CEziF9.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Z(e,t)){await V({cwd:c,uiPort:m});return}let n=Q(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=Y(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Z(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function Q(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=v(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`Open Knowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function $(e){return new t(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,q).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,K).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
1
+ import{n as e,t}from"./esm-BLMtE3s6.mjs";import{bn as n,ft as r}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{i,t as a}from"./gh-detect-DLds_L3H.mjs";import{$n as o,br as s,ur as c}from"./dist-l7XNeUBq.mjs";import{n as l}from"./constants-BxczpHmO.mjs";import{spawn as u}from"node:child_process";import{closeSync as d,existsSync as f,mkdirSync as p,openSync as m,statSync as h}from"node:fs";import{basename as g,dirname as _,join as v}from"node:path";import{homedir as y}from"node:os";import{setTimeout as b}from"node:timers/promises";const x=`Open Knowledge.app`,S=`/Applications/${x}`;function C(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return h(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function w(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(T(e,S))return S;let t=v(e.homeDir??y(),`Applications`,x);return T(e,t)?t:null}function T(e,t){try{let n=v(t,`Contents`,`MacOS`,`Open Knowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function E(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=w(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function D(e){(e.log??(e=>console.error(e)))("Launching Open Knowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function O(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${S}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${S} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${S} but launch dispatch did not fire (caller bug).`}}function k(e){return v(_(e),`..`,`Frameworks`,`Open Knowledge Server.app`,`Contents`,`MacOS`,`Open Knowledge Helper`)}const A=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function j(e){if(e.platform!==`darwin`||!A.test(e.execPath))return null;let t=k(e.execPath);return e.exists(t)?t:null}function M(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??f,a=r[1];return a?{command:j({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function N(e,t){return e.host??t.HOST??`localhost`}function P(e){let t=g(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var F=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function I(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function L(e){f(e.lockDir)||p(e.lockDir,{recursive:!0});let t=m(v(e.lockDir,n),`w`),r=e.spawn??u,{PORT:i,...a}=process.env,o=M();try{let n=r(o.command,[...o.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return n.unref(),n}finally{try{d(t)}catch{}}}function R(e,t,n){return e??(n===void 0?t:void 0)}function z(e,t){return e!==void 0&&t!==null&&t.port>0}function B(e,t,n){return e??(t!=null&&!n?1:0)}async function V(e){let t=e.spawn??u,n=M(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=B(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function H(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const U=r;function W(e){let t=e.sigtermGraceMs??U,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>b(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function G(e){let{config:t,cwd:n,host:r}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:x}=await import(`./dist-DqFZXNT6.mjs`),S=e.log??_(`start`),C=e.singleFile!==void 0,w=e.projectDir??n,T=C?s(e.singleFile).canonicalFilePath:void 0,E=T?h(T):void 0,D=T?m(T):void 0;if(!C){if(!l&&!o(n))throw new F(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&S.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-CfALCHuP.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-Dq4ywehx.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-EgHsxlCA.mjs`)).repairSkills)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){S.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let O=E??x(t,n);!C&&!f(O)&&(p(O,{recursive:!0}),S.info({contentDir:O},`Created content directory`));let k=null,A=async({lockDir:t})=>{if(k=I({uiLock:y(t),isAlive:v}),k.action===`spawn`&&!u)try{let r=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];L({lockDir:t,cwd:n,spawn:e.spawn,args:r}),S.info({reason:k.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else k.action===`skip`&&S.info({port:k.port,pid:k.pid},`UI already running at port ${k.port}`)},j=e.reactShellDistDir===void 0,M=i(),N=c(),P=await g({config:t,contentDir:O,projectDir:C?w:n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:a,tokenStore:M,embeddingsKeyStore:N,...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:j,idleShutdownMs:d,skipAutoInit:!0,...j?{spawnUiSiblingFn:A}:{},idleShutdownHandler:e=>W({readUiLock:()=>y(P.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:S}),log:S,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});k||={action:`skip`,reason:`alive`,pid:0,port:0};let R=k,z=null;if(R.action===`skip`)z=R.port>0?R.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;z=await H({readUiLock:()=>y(P.lockDir),now:Date.now,sleep:e=>b(e),timeoutMs:t,pollIntervalMs:50}),z===null&&S.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:P.httpServer,destroy:P.destroy,lockDir:P.lockDir,contentDir:O,port:P.port,ready:P.ready,degraded:P.degraded,uiSpawnDecision:k,resolvedUiPort:z}}function K(t){if(t===`browser`||t===`app`)return t;throw new e(`--mode must be 'browser' or 'app'`)}function q(t){let n=Number.parseInt(t,10);if(Number.isNaN(n)||n<1||n>65535)throw new e(`--ui-port must be a port number between 1 and 65535`);return n}function J(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function Y(e){let t=[`Stopping Open Knowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function X(e,t){let n=J(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-DBiyrzNA.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-BktTaA1t.mjs`),c=process.cwd(),u=e;process.title=P(c);let d=N(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=R(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-DqFZXNT6.mjs`);if(z(m,e(t(c)))){await V({cwd:c,uiPort:m});return}}let g;try{g=await G({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof F&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-DqFZXNT6.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Z(e,t)){await V({cwd:c,uiPort:m});return}let n=Q(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=Y(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Z(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function Q(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=v(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`Open Knowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function $(e){return new t(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,q).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,K).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
2
2
  `),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.uiPort!==void 0&&e.push(`--ui-port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=E(C());if(n.available){D({spawn:u});return}console.error(O(n.reason)),process.exit(1)}await X(n,t)})}export{D as S,$ as _,B as a,C as b,P as c,R as d,N as f,L as g,z as h,W as i,Y as l,X as m,H as n,V as o,J as p,G as r,I as s,F as t,Z as u,Q as v,E as x,M as y};
3
- //# sourceMappingURL=start-BTUBLJch.mjs.map
3
+ //# sourceMappingURL=start-D75p8pvD.mjs.map
@@ -1,4 +1,4 @@
1
- import{v as e,xt as t}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{F as n,zr as r}from"./dist-CWv9hwiJ.mjs";import{cpSync as i,existsSync as a,lstatSync as o,mkdirSync as s,realpathSync as c,rmSync as l}from"node:fs";import{basename as u,dirname as d,isAbsolute as f,join as p,posix as m,relative as h,resolve as g,sep as _,win32 as v}from"node:path";import{homedir as y}from"node:os";const b=e,x=t,S={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},C=`# ok-mcp-v1`;function w(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`/bin/sh`||!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let n=t.args[2];return typeof n==`string`&&n.includes(`# ok-mcp-v1`)}function T(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=g(e);if(u(t)===`cli.mjs`&&u(d(t))===`dist`)return t;let n=t.split(_),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return p(i.length===0?_:i.join(_),`packages`,`cli`,`dist`,`cli.mjs`)}function E(e={}){return e.mode===`dev`?{command:`node`,args:[T(),`mcp`],env:{...S}}:{command:`/bin/sh`,args:[`-l`,`-c`,`# ok-mcp-v1
1
+ import{v as e,xt as t}from"./server-lock-BpjJj3OD-dsDEfapU.mjs";import{F as n,zr as r}from"./dist-l7XNeUBq.mjs";import{cpSync as i,existsSync as a,lstatSync as o,mkdirSync as s,realpathSync as c,rmSync as l}from"node:fs";import{basename as u,dirname as d,isAbsolute as f,join as p,posix as m,relative as h,resolve as g,sep as _,win32 as v}from"node:path";import{homedir as y}from"node:os";const b=e,x=t,S={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},C=`# ok-mcp-v1`;function w(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`/bin/sh`||!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let n=t.args[2];return typeof n==`string`&&n.includes(`# ok-mcp-v1`)}function T(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=g(e);if(u(t)===`cli.mjs`&&u(d(t))===`dist`)return t;let n=t.split(_),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return p(i.length===0?_:i.join(_),`packages`,`cli`,`dist`,`cli.mjs`)}function E(e={}){return e.mode===`dev`?{command:`node`,args:[T(),`mcp`],env:{...S}}:{command:`/bin/sh`,args:[`-l`,`-c`,`# ok-mcp-v1
2
2
  USER_BUNDLE="$HOME/Applications/Open Knowledge.app/Contents/Resources/cli/bin/ok.sh"
3
3
  [ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
4
4
  BUNDLE="/Applications/Open Knowledge.app/Contents/Resources/cli/bin/ok.sh"
@@ -9,4 +9,4 @@ for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installat
9
9
  done
10
10
  echo "Open Knowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
11
11
  exit 127`]}}function D(e){return e===`win32`?v:m}function O(e={}){let t=e.platformName??process.platform,n=e.home??y();return D(t).join(n,`.claude.json`)}function k(e={}){let t=e.platformName??process.platform,n=e.home??y(),r=e.env??process.env;if(t===`darwin`)return m.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??v.join(n,`AppData`,`Roaming`);return v.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function A(e={}){let t=e.platformName??process.platform,n=e.home??y();return D(t).join(n,`.cursor`,`mcp.json`)}function j(e={}){let t=e.platformName??process.platform,n=e.home??y();return(e.env??process.env).CODEX_HOME??D(t).join(n,`.codex`)}function M(e={}){return D(e.platformName??process.platform).join(j(e),`config.toml`)}const N={claude:{id:`claude`,label:x.claude,configPath:(e,t)=>O({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>E(t),scope:`global`,detectPath:(e,t)=>p(t??y(),`.claude`),projectConfigPath:e=>p(e,`.mcp.json`),projectSkillPath:e=>p(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:x[`claude-desktop`],configPath:(e,t)=>k({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>E(t),scope:`global`,detectPath:(e,t)=>d(k({home:t}))},cursor:{id:`cursor`,label:x.cursor,configPath:(e,t)=>A({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>E(t),scope:`global`,detectPath:(e,t)=>d(A({home:t})),projectConfigPath:e=>p(e,`.cursor`,`mcp.json`),projectSkillPath:e=>p(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:x.codex,configPath:(e,t)=>M({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>n,buildEntry:(e,t)=>E(t),scope:`global`,detectPath:(e,t)=>d(M({home:t})),projectConfigPath:e=>p(e,`.codex`,`config.toml`),projectSkillPath:e=>p(e,`.agents`,`skills`,`open-knowledge`,`SKILL.md`)}};function P(e){let t=e.filter(e=>!Object.hasOwn(N,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${b.join(`, `)}`);return e.map(e=>N[e])}function F(e,t){let n;try{n=c(t)}catch{n=g(t)}let r;try{r=o(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);let i=d(e);for(;i.length>1&&i!==_;){let t;try{t=c(i)}catch(e){if(e.code===`ENOENT`){i=d(i);continue}throw e}let r=h(n,t);if(r===``||!r.startsWith(`..`)&&!f(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function I(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let o=r(`project`,{checkDesktop:!0}),c=d(n);F(c,t);let u=a(n)?`overwritten`:`written`;return l(c,{recursive:!0,force:!0}),s(d(c),{recursive:!0}),i(o,c,{recursive:!0}),{editorId:e.id,label:e.label,action:u,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}export{x as a,w as c,C as i,T as l,I as n,N as o,b as r,E as s,F as t,P as u};
12
- //# sourceMappingURL=write-project-skill-Bn8zRlMF.mjs.map
12
+ //# sourceMappingURL=write-project-skill-DrLvXsq9.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.19.0-beta.2",
3
+ "version": "0.19.0",
4
4
  "license": "GPL-3.0-or-later",
5
5
  "private": false,
6
6
  "type": "module",
@@ -1,2 +0,0 @@
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
@@ -1 +0,0 @@
1
- import{m as e}from"./init-BMT_3l9F.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-D4wC401d.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-BGMRorsT.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{t as e}from"./repair-skills-BNYzyMnZ.mjs";export{e as repairSkills};
@@ -1 +0,0 @@
1
- import{_ as e,f as t,r as n}from"./start-BTUBLJch.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};