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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +63 -63
  4. package/dist/constants-Ci-kZ4dC.mjs +2 -0
  5. package/dist/dist-72is7jRd.mjs +1 -0
  6. package/dist/{dist-DoDyZNhy.mjs → dist-BVDj7oJZ.mjs} +2 -2
  7. package/dist/index.mjs +1 -1
  8. package/dist/init-CFmo3Akq.mjs +1 -0
  9. package/dist/init-DWNXfQas.mjs +690 -0
  10. package/dist/{loader-CCBLjGdd.mjs → loader-DkWp7bnK.mjs} +2 -2
  11. package/dist/loader-Dnf_1ZEG.mjs +1 -0
  12. package/dist/open-browser-R_RWX931.mjs +2 -0
  13. package/dist/{preview-BlnBnAM8.mjs → preview-9zw2bHty.mjs} +2 -2
  14. package/dist/preview-DKPvMlKb.mjs +1 -0
  15. package/dist/public/assets/{index-kyv4JIfm.js → index-C2Aa_HrU.js} +2 -2
  16. package/dist/public/index.html +1 -1
  17. package/dist/{repair-launch-json-Drx8-mQf.mjs → repair-launch-json-BZa1WVbN.mjs} +2 -2
  18. package/dist/{repair-mcp-configs-D32OvX6A.mjs → repair-mcp-configs-B1R2_B6E.mjs} +2 -2
  19. package/dist/{repair-skills-DE-X6nG_.mjs → repair-skills-B_aLnXpL.mjs} +2 -2
  20. package/dist/repair-skills-D_mTmSrp.mjs +1 -0
  21. package/dist/{src-BJDidJ1C.mjs → src-mUcDJN0F.mjs} +2 -2
  22. package/dist/start-BshFMALS.mjs +1 -0
  23. package/dist/start-Df010qkz.mjs +3 -0
  24. package/dist/{write-project-skill-CrjKr8MO.mjs → write-project-skill-ClrMnKU-.mjs} +2 -2
  25. package/package.json +1 -1
  26. package/dist/constants-BvUE6Mu8.mjs +0 -2
  27. package/dist/dist-Bc_bWnDQ.mjs +0 -1
  28. package/dist/init-C5xydBwk.mjs +0 -686
  29. package/dist/init-COp9NFui.mjs +0 -1
  30. package/dist/loader-DsrSOTpM.mjs +0 -1
  31. package/dist/open-browser-DHTbHSqx.mjs +0 -2
  32. package/dist/preview-BbnP_W-F.mjs +0 -1
  33. package/dist/repair-skills-BQUSwi1N.mjs +0 -1
  34. package/dist/start-Bu74oLD_.mjs +0 -1
  35. package/dist/start-DOCYHCeK.mjs +0 -3
@@ -1,686 +0,0 @@
1
- import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{Ba as r,Bt as i,Et as a,Va as o,Xi as s,bi as c,bn as l,ja as u,mt as d}from"./server-lock-iLcBw_q0-pnLGEjec.mjs";import{$n as f,Ca as p,D as m,Gn as h,K as g,O as _,Qn as v,Zn as y,cr as b,d as x,ha as S,ia as C,ir as w,ra as T,ut as E,va as D,vn as ee}from"./dist-DoDyZNhy.mjs";import{r as O,t as k}from"./esm-CsQUg9js.mjs";import{t as te}from"./constants-BvUE6Mu8.mjs";import{a as ne,b as re,d as A,g as j,h as ie,i as ae,m as oe,p as M,s as se,t as ce,x as N}from"./write-project-skill-CrjKr8MO.mjs";import{t as P}from"./is-object-Cg453afR.mjs";import{i as F,n as le,o as I,r as ue,s as L,t as R}from"./colors-8SzMRIVy.mjs";import{t as de}from"./preview-BlnBnAM8.mjs";import{createRequire as fe}from"node:module";import{execFileSync as pe}from"node:child_process";import me,{dirname as z,isAbsolute as he,join as B,relative as V,resolve as ge,sep as _e}from"node:path";import H from"node:process";import{fileURLToPath as ve}from"node:url";import{homedir as ye}from"node:os";import{existsSync as U,lstatSync as be,mkdirSync as xe,readFileSync as W,readlinkSync as Se,realpathSync as Ce,statSync as we,writeFileSync as Te}from"node:fs";import{randomUUID as Ee}from"node:crypto";import{inspect as De,stripVTControlCharacters as Oe,styleText as G}from"node:util";import{AsyncLocalStorage as ke,AsyncResource as Ae}from"node:async_hooks";import{createServer as je,request as Me}from"node:http";import*as Ne from"node:readline";import{connect as Pe}from"node:net";const Fe=new Set([`emacs`,`vim`]);function Ie(e){return Fe.has(e)}function Le(){let e=process.env.INQUIRER_KEYBINDINGS;return e?Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(Ie))):[]}const Re=(e,t=[])=>e.name===`up`||t.includes(`vim`)&&e.name===`k`||t.includes(`emacs`)&&e.ctrl&&e.name===`p`,ze=(e,t=[])=>e.name===`down`||t.includes(`vim`)&&e.name===`j`||t.includes(`emacs`)&&e.ctrl&&e.name===`n`,Be=e=>e.name===`space`,Ve=e=>e.name===`backspace`,He=e=>`1234567890`.includes(e.name),Ue=e=>e.name===`enter`||e.name===`return`;var We=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},Ge=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Ke=class extends Error{name=`ExitPromptError`},qe=class extends Error{name=`HookError`},Je=class extends Error{name=`ValidationError`};const Ye=new ke;function Xe(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Ze(e,t){let n=Xe(e);return Ye.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function K(){let e=Ye.getStore();if(!e)throw new qe(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function Qe(){return K().rl}function $e(e){return Ae.bind((...t)=>{let n=K(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function et(e){let t=K(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function tt(){K().handleChange()}const nt={queue(e){let t=K(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Qe());if(r!=null&&typeof r!=`function`)throw new Je(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=K();$e(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=K();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function rt(e){return typeof e==`function`}function q(e){return et(t=>{let n=Ae.bind(function(e){t.get()!==e&&(t.set(e),tt())});if(t.initialized)return[t.get(),n];let r=rt(e)?e():e;return t.set(r),[r,n]})}function it(e,t){et(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&nt.queue(e),n.set(t)})}function at(){return H.platform.startsWith(`win`)?!!H.env.CI||!!H.env.WT_SESSION||!!H.env.TERMINUS_SUBLIME||H.env.ConEmuTask===`{cmd::Cmder}`||H.env.TERM_PROGRAM===`Terminus-Sublime`||H.env.TERM_PROGRAM===`vscode`||H.env.TERM===`xterm-256color`||H.env.TERM===`alacritty`||H.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:H.env.TERM!==`linux`}const ot={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:`╱`},st={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:`⅒`},ct={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`},lt={...ot,...st},ut={...ot,...ct},dt=at()?lt:ut;Object.entries(st);const ft={prefix:{idle:G(`blue`,`?`),done:G(`green`,dt.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>G(`yellow`,e))},keybindings:[],style:{answer:e=>G(`cyan`,e),message:e=>G(`bold`,e),error:e=>G(`red`,`> ${e}`),defaultAnswer:e=>G(`dim`,`(${e})`),help:e=>G(`dim`,e),highlight:e=>G(`cyan`,e),key:e=>G(`cyan`,G(`bold`,`<${e}>`))}};function pt(){return{...ft,keybindings:Le()}}function mt(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function ht(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=mt(n)&&mt(r)?ht(n,r):r}return t}function gt(...e){return ht(pt(),...e.filter(e=>e!=null))}function _t({status:e=`idle`,theme:t}){let[n,r]=q(!1),[i,a]=q(0),{prefix:o,spinner:s}=gt(t);return it(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function vt(e,t){return et(n=>{let r=n.get();if(!r||r.dependencies.length!==t.length||r.dependencies.some((e,n)=>e!==t[n])){let r=e();return n.set({value:r,dependencies:t}),r}return r.value})}function yt(e){return q({current:e})[0]}function bt(e){let t=yt(e);t.current=e,it(e=>{let n=!1,r=$e((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var xt=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 St=(()=>{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}})(),Ct=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,wt=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,Tt=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Et=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Dt=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Ot=/\t{1,1000}/y,kt=/[\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,At=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,jt=/\p{M}+/gu,Mt={limit:1/0,ellipsis:``},Nt=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Nt(i,Mt,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[At,l],[Tt,0],[Et,o],[Ot,s],[kt,c],[Dt,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(jt,``)){let t=e.codePointAt(0)||0;if(S=Ct(t)?2:wt(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===Dt?St(e.slice(p,n.lastIndex)):n===kt?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}},Pt={limit:1/0,ellipsis:``,ellipsisWidth:0},J=(e,t={})=>Nt(e,Pt,t).width,Ft=`]8;;`,It=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ft}(?<uri>.*))`,`y`),Lt=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},Rt=e=>`[${e}m`,zt=e=>`${Ft}${e}`,Bt=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:J(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=J(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ft,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())},Vt=e=>{let t=e.split(` `),n=t.length;for(;n&&!J(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ht=(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=J(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=J(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(``),Bt(s,r,t),c=J(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Bt(s,r,t),c=J(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Bt(s,r,t),c=J(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Vt(e)));let l=s.join(`
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===`›`){It.lastIndex=e+1;let t=It.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
- `){a&&(r+=zt(``));let e=i?Lt(i):void 0;i&&e&&(r+=Rt(e))}else t===`
4
- `&&(i&&Lt(i)&&(r+=Rt(i)),a&&(r+=zt(a)))}return r},Ut=/\r?\n/;function Wt(e,t,n){return String(e).normalize().split(Ut).map(e=>Ht(e,t,n)).join(`
5
- `)}var Gt=t(xt(),1);function Kt(e,t){return e.split(`
6
- `).flatMap(e=>Wt(e,t,{trim:!1,wordWrap:!1}).split(`
7
- `).map(e=>e.trimEnd())).join(`
8
- `)}function qt(){return(0,Gt.default)({defaultWidth:80,output:Qe().output})}function Jt({active:e,renderedItems:t,pageSize:n,loop:r}){let i=yt({lastPointer:e,lastActive:void 0}),{lastPointer:a,lastActive:o}=i.current,s=Math.floor(n/2),c=t.reduce((e,t)=>e+t.length,0),l=t.slice(0,e).reduce((e,t)=>e+t.length,0),u=l;if(c>n)if(r)u=a,o!=null&&o<e&&e-o<n&&(u=Math.min(s,Math.abs(e-o)===1?Math.min(a+(t[o]?.length??0),Math.max(l,a)):a+e-o));else{let r=t.slice(e).reduce((e,t)=>e+t.length,0);u=r<n-s?n-r:Math.min(l,s)}return i.current.lastPointer=u,i.current.lastActive=e,u}function Yt({items:e,active:t,renderItem:n,pageSize:r,loop:i=!0}){let a=qt(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,r)=>e==null?[]:Kt(n({item:e,index:r,isActive:r===t}),a).split(`
9
- `)),c=s.reduce((e,t)=>e+t.length,0),l=e=>s[e]??[],u=Jt({active:t,renderedItems:s,pageSize:r,loop:i}),d=l(t).slice(0,r),f=u+d.length<=r?u:r-d.length,p=Array.from({length:r});p.splice(f,d.length,...d);let m=new Set([t]),h=f+d.length,g=o(t+1);for(;h<r&&!m.has(g)&&(i&&c>r?g!==t:g>t);){let e=l(g).slice(0,r-h);p.splice(h,e.length,...e),m.add(g),h+=e.length,g=o(g+1)}for(h=f-1,g=o(t-1);h>=0&&!m.has(g)&&(i&&c>r?g!==t:g<t);){let e=l(g),t=e.slice(Math.max(0,e.length-h-1));p.splice(h-t.length+1,t.length,...t),m.add(g),h-=t.length,g=o(g-1)}return p.filter(e=>typeof e==`string`).join(`
10
- `)}var Xt=n(((t,n)=>{let r=e(`stream`);n.exports=class extends r{#e=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on(`pipe`,this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){return this._dest?this._dest[e]:this._src?this._src[e]:t}#n(e,...t){typeof this._dest?.[e]==`function`&&this._dest[e](...t),typeof this._src?.[e]==`function`&&this._src[e](...t)}get isTTY(){return this.#e===null?this.#t(`isTTY`,!1):this.#e}set isTTY(e){this.#e=e}get rows(){return this.#t(`rows`)}get columns(){return this.#t(`columns`)}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return e.indexOf(this._prompt)===0&&(e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit(`data`,e);this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit(`data`,this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit(`data`,e)}end(e){this.muted&&(e=e&&this.replace?e.toString().replace(/./g,this.replace):null),e&&this.emit(`data`,e),this.emit(`end`)}destroy(...e){return this.#n(`destroy`,...e)}destroySoon(...e){return this.#n(`destroySoon`,...e)}close(...e){return this.#n(`close`,...e)}}}));const Zt=[];Zt.push(`SIGHUP`,`SIGINT`,`SIGTERM`),process.platform!==`win32`&&Zt.push(`SIGALRM`,`SIGABRT`,`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&Zt.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`);const Qt=e=>!!e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`,$t=Symbol.for(`signal-exit emitter`),en=globalThis,tn=Object.defineProperty.bind(Object);var nn=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(en[$t])return en[$t];tn(en,$t,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let n=this.listeners[e],r=n.indexOf(t);r!==-1&&(r===0&&n.length===1?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(let i of this.listeners[e])r=i(t,n)===!0||r;return e===`exit`&&(r=this.emit(`afterExit`,t,n)||r),r}},rn=class{};const an=e=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}});var on=class extends rn{onExit(){return()=>{}}load(){}unload(){}},sn=class extends rn{#e=cn.platform===`win32`?`SIGINT`:`SIGHUP`;#t=new nn;#n;#r;#i;#a={};#o=!1;constructor(e){super(),this.#n=e,this.#a={};for(let t of Zt)this.#a[t]=()=>{let n=this.#n.listeners(t),{count:r}=this.#t,i=e;if(typeof i.__signal_exit_emitter__==`object`&&typeof i.__signal_exit_emitter__.count==`number`&&(r+=i.__signal_exit_emitter__.count),n.length===r){this.unload();let n=this.#t.emit(`exit`,null,t),r=t===`SIGHUP`?this.#e:t;n||e.kill(e.pid,r)}};this.#i=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Qt(this.#n))return()=>{};this.#o===!1&&this.load();let n=t?.alwaysLast?`afterExit`:`exit`;return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#t.count+=1;for(let e of Zt)try{let t=this.#a[e];t&&this.#n.on(e,t)}catch{}this.#n.emit=(e,...t)=>this.#c(e,...t),this.#n.reallyExit=e=>this.#s(e)}}unload(){this.#o&&(this.#o=!1,Zt.forEach(e=>{let t=this.#a[e];if(!t)throw Error(`Listener not defined for signal: `+e);try{this.#n.removeListener(e,t)}catch{}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#i,--this.#t.count)}#s(e){return Qt(this.#n)?(this.#n.exitCode=e||0,this.#t.emit(`exit`,this.#n.exitCode,null),this.#i.call(this.#n,this.#n.exitCode)):0}#c(e,...t){let n=this.#r;if(e===`exit`&&Qt(this.#n)){typeof t[0]==`number`&&(this.#n.exitCode=t[0]);let r=n.call(this.#n,e,...t);return this.#t.emit(`exit`,this.#n.exitCode,null),r}else return n.call(this.#n,e,...t)}};const cn=globalThis.process,{onExit:ln,load:un,unload:dn}=an(Qt(cn)?new sn(cn):new on),fn=`\x1B[?25l`,pn=(e=1)=>e>0?`[${e}A`:``,mn=(e=1)=>e>0?`[${e}B`:``,hn=(e,t)=>typeof t==`number`&&!Number.isNaN(t)?`[${t+1};${e+1}H`:`[${e+1}G`,gn=`\x1B[2K`,_n=e=>e>0?(gn+pn(1)).repeat(e-1)+gn+`\x1B[G`:``,vn=e=>e.split(`
11
- `).length,yn=e=>e.split(`
12
- `).pop()??``;var bn=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=``){let n=Oe(yn(e)),r=n;this.rl.line.length>0&&(r=r.slice(0,-this.rl.line.length)),this.rl.setPrompt(r),this.cursorPos=this.rl.getCursorPos();let i=qt();e=Kt(e,i),t=Kt(t,i),n.length%i===0&&(e+=`
13
- `);let a=e+(t?`
14
- `+t:``),o=Math.floor(n.length/i)-this.cursorPos.rows+(t?vn(t):0);o>0&&(a+=pn(o)),a+=hn(this.cursorPos.cols),this.write(mn(this.extraLinesUnderPrompt)+_n(this.height)+a),this.extraLinesUnderPrompt=o,this.height=vn(a)}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(hn(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt(``);let t=mn(this.extraLinesUnderPrompt);t+=e?_n(this.height):`
15
- `,t+=`\x1B[G`,t+=`\x1B[?25h`,this.write(t),this.rl.close()}},xn=class extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}},Sn=t(Xt(),1);const Cn=globalThis.setImmediate;function wn(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(e,n)=>{let r=n.slice(1);return t=r,r},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function Tn(e){let t=wn();return(n,r={})=>{let{input:i=process.stdin,signal:a}=r,o=new Set,s=new Sn.default;s.pipe(r.output??process.stdout);let c=Ne.createInterface({terminal:!0,input:i,output:s});s.mute();let l=new bn(c),{promise:u,resolve:d,reject:f}=xn.withResolver(),p=()=>f(new Ge);if(a){let e=()=>f(new We({cause:a.reason}));if(a.aborted)return e(),Object.assign(u,{cancel:p});a.addEventListener(`abort`,e),o.add(()=>a.removeEventListener(`abort`,e))}o.add(ln((e,t)=>{f(new Ke(`User force closed the prompt with ${e} ${t}`))}));let m=()=>f(new Ke(`User force closed the prompt with SIGINT`));return c.on(`SIGINT`,m),o.add(()=>c.removeListener(`SIGINT`,m)),Ze(c,a=>{let m=Ae.bind(()=>nt.clearAll());c.on(`close`,m),o.add(()=>c.removeListener(`close`,m));let h=()=>{let r=()=>l.checkCursorPos();c.input.on(`keypress`,r),o.add(()=>c.input.removeListener(`keypress`,r));let i=null;a(()=>{let r=!1;try{let a=e(n,e=>{r?d(e):i={value:e}});if(a===void 0){let e=t[1]?.getFileName();throw e&&!e.startsWith(`file://`)&&(e=me.resolve(e)),Error(`Prompt functions must return a string.\n at ${e}`)}let[o,s]=typeof a==`string`?[a]:a;l.render(o,s),nt.run()}catch(e){f(e)}if(r=!0,i!==null){let{value:e}=i;i=null,d(e)}})};return`readableFlowing`in i?Cn(h):h(),Object.assign(u.then(e=>(nt.clearAll(),e),e=>{throw nt.clearAll(),e}).finally(()=>{o.forEach(e=>e()),l.done({clearContent:!!r.clearPromptOnDone}),s.end()}).then(()=>u),{cancel:p})})}}var Y=class{separator=G(`dim`,Array.from({length:15}).join(dt.line));type=`separator`;constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`separator`)}};function En(e){let t=[`.ok/`,`.okignore`];for(let n of se){let r=A[n];if(r.projectConfigPath&&t.push(Rn(r.projectConfigPath(e),e)),r.projectSkillPath){let n=Rn(r.projectSkillPath(e),e);t.push(`${Bn(n)}/`)}}t.push(`.claude/launch.json`);let n=B(e,...i);if(U(n))try{let e=s(W(n,`utf-8`));if(e)for(let[n,r]of Object.entries(e.skills))for(let e of r.hosts){let r=a[e];r&&t.push(`${r}/${n}/`)}}catch{}return Array.from(new Set(t))}function Dn(e,t){let n=jn(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:Mn(n)};let r=Nn(e);if(r.kind!==`ok`)return r.result;let i=U(r.path)?W(r.path,`utf-8`):``,a=Ln(i),o=[],s=[];for(let e of t)In(a,e)?s.push(e):o.push(e);if(o.length===0)return{kind:`updated`,appended:o,alreadyPresent:s,removed:[]};let c=i.length===0||i.endsWith(`
16
- `)?``:`
17
- `,l=`${o.join(`
18
- `)}\n`;try{Te(r.path,`${i}${c}${l}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:o,alreadyPresent:s,removed:[]}}function On(e,t){let n=Nn(e);if(n.kind!==`ok`)return n.result;if(!U(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>Fn(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);let a;try{a=W(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
19
- `),s=new Set,c=[];for(let e of o){let t=e.trim();if(i.has(t)){s.add(t);continue}c.push(e)}let l=t.filter(e=>{for(let t of Fn(e))if(s.has(t))return!0;return!1});if(s.size===0)return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let u=c.join(`
20
- `);if(u!==a)try{Te(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function kn(e){let t=Nn(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!U(t.path))return`shared`;let n;try{n=W(t.path,`utf-8`)}catch{return`shared`}let r=Ln(n),i=En(e);for(let e of i)if(In(r,e))return`local-only`;return`shared`}function An(e){let t=Nn(e);if(t.kind!==`ok`||!U(t.path))return[];let n;try{n=W(t.path,`utf-8`)}catch{return[]}let r=Ln(n);return En(e).filter(e=>In(r,e))}function jn(e,t){let n=[];for(let r of t)if(U(ge(e,r)))try{pe(`git`,[`ls-files`,`--error-unmatch`,`--`,r],{cwd:e,stdio:[`ignore`,`ignore`,`ignore`]}),n.push(r)}catch{}return{tracked:n}}function Mn(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}${e}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
21
- `)}function Nn(e){let t=p(e);switch(t.kind){case`directory`:case`linked`:{let e=B(Pn(t.path),`info`);return U(e)?{kind:`ok`,path:B(e,`exclude`)}:{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-info-dir`}}}case`absent`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-git`}};case`malformed-pointer`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`malformed-pointer`}};case`inaccessible`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}}}}function Pn(e){let t=B(e,`commondir`);if(!U(t))return e;let n;try{n=W(t,`utf-8`).trim()}catch{return e}return n.length===0?e:he(n)?n:ge(e,n)}function Fn(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function In(e,t){for(let n of Fn(t))if(e.has(n))return!0;return!1}function Ln(e){let t=new Set;for(let n of e.split(`
22
- `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function Rn(e,t){return zn(V(t,e))}function zn(e){return _e===`/`?e:e.split(_e).join(`/`)}function Bn(e){let t=e.lastIndexOf(`/`);return t<0?`.`:e.slice(0,t)}function Vn(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function f(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function p(e){r=e,i=``,a=0,o=16,d=0}function m(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Wn(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Wn(e.charCodeAt(r)))for(r++;r<e.length&&Wn(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r);let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Wn(e.charCodeAt(r))){for(r++;r<e.length&&Wn(e.charCodeAt(r));)r++;n=r}else d=3;return e.substring(t,n)}function h(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
23
- `;break;case 114:t+=`\r`;break;case 116:t+=` `;break;case 117:let e=f(4,!0);e>=0?t+=String.fromCharCode(e):d=4;break;default:d=5}i=r;continue}if(a>=0&&a<=31)if(Un(a)){t+=e.substring(i,r),d=2;break}else d=6;r++}return t}function g(){if(i=``,d=0,a=r,c=s,u=l,r>=n)return a=n,o=17;let t=e.charCodeAt(r);if(Hn(t)){do r++,i+=String.fromCharCode(t),t=e.charCodeAt(r);while(Hn(t));return o=15}if(Un(t))return r++,i+=String.fromCharCode(t),t===13&&e.charCodeAt(r)===10&&(r++,i+=`
24
- `),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=h(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!Un(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,Un(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!Wn(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=m(),o=11;default:for(;r<n&&_(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function _(e){if(Hn(e)||Un(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function v(){let e;do e=g();while(e>=12&&e<=15);return e}return{setPosition:p,getPosition:()=>r,scan:t?v:g,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function Hn(e){return e===32||e===9}function Un(e){return e===10||e===13}function Wn(e){return e>=48&&e<=57}var Gn;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(Gn||={});const X=Array(20).fill(0).map((e,t)=>` `.repeat(t)),Kn={" ":{"\n":Array(200).fill(0).map((e,t)=>`
25
- `+` `.repeat(t)),"\r":Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
26
- `+` `.repeat(t))}," ":{"\n":Array(200).fill(0).map((e,t)=>`
27
- `+` `.repeat(t)),"\r":Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
28
- `+` `.repeat(t))}},qn=[`
29
- `,`\r`,`\r
30
- `];function Jn(e,t,n){let r,i,a,o,s;if(t){for(o=t.offset,s=o+t.length,a=o;a>0&&!Qn(e,a-1);)a--;let c=s;for(;c<e.length&&!Qn(e,c);)c++;i=e.substring(a,c),r=Xn(i,n)}else i=e,r=0,a=0,o=0,s=e.length;let c=Zn(n,e),l=qn.includes(c),u=0,d=0,f;f=n.insertSpaces?X[n.tabSize||4]??Yn(X[1],n.tabSize||4):` `;let p=f===` `?` `:` `,m=Vn(i,!1),h=!1;function g(){if(u>1)return Yn(c,u)+Yn(f,r+d);let e=f.length*(r+d);return!l||e>Kn[p][c].length?c+Yn(f,r+d):e<=0?c:Kn[p][c][e]}function _(){let e=m.scan();for(u=0;e===15||e===14;)e===14&&n.keepLines?u+=1:e===14&&(u=1),e=m.scan();return h=e===16||m.getTokenError()!==0,e}let v=[];function y(n,r,i){!h&&(!t||r<s&&i>o)&&e.substring(r,i)!==n&&v.push({offset:r,length:i-r,content:n})}let b=_();if(n.keepLines&&u>0&&y(Yn(c,u),0,0),b!==17){let e=m.getTokenOffset()+a;y(f.length*r<20&&n.insertSpaces?X[f.length*r]:Yn(f,r),a,e)}for(;b!==17;){let e=m.getTokenOffset()+m.getTokenLength()+a,t=_(),r=``,i=!1;for(;u===0&&(t===12||t===13);){let n=m.getTokenOffset()+a;y(X[1],e,n),e=m.getTokenOffset()+m.getTokenLength()+a,i=t===12,r=i?g():``,t=_()}if(t===2)b!==1&&d--,n.keepLines&&u>0||!n.keepLines&&b!==1?r=g():n.keepLines&&(r=X[1]);else if(t===4)b!==3&&d--,n.keepLines&&u>0||!n.keepLines&&b!==3?r=g():n.keepLines&&(r=X[1]);else{switch(b){case 3:case 1:d++,r=n.keepLines&&u>0||!n.keepLines?g():X[1];break;case 5:r=n.keepLines&&u>0||!n.keepLines?g():X[1];break;case 12:r=g();break;case 13:u>0?r=g():i||(r=X[1]);break;case 6:n.keepLines&&u>0?r=g():i||(r=X[1]);break;case 10:n.keepLines&&u>0?r=g():t===6&&!i&&(r=``);break;case 7:case 8:case 9:case 11:case 2:case 4:n.keepLines&&u>0?r=g():(t===12||t===13)&&!i?r=X[1]:t!==5&&t!==17&&(h=!0);break;case 16:h=!0;break}u>0&&(t===12||t===13)&&(r=g())}t===17&&(r=n.keepLines&&u>0?g():n.insertFinalNewline?c:``);let o=m.getTokenOffset()+a;y(r,e,o),b=t}return v}function Yn(e,t){let n=``;for(let r=0;r<t;r++)n+=e;return n}function Xn(e,t){let n=0,r=0,i=t.tabSize||4;for(;n<e.length;){let t=e.charAt(n);if(t===X[1])r++;else if(t===` `)r+=i;else break;n++}return Math.floor(r/i)}function Zn(e,t){for(let e=0;e<t.length;e++){let n=t.charAt(e);if(n===`\r`)return e+1<t.length&&t.charAt(e+1)===`
31
- `?`\r
32
- `:`\r`;if(n===`
33
- `)return`
34
- `}return e&&e.eol||`
35
- `}function Qn(e,t){return`\r
36
- `.indexOf(e.charAt(t))!==-1}var $n;(function(e){e.DEFAULT={allowTrailingComma:!1}})($n||={});function er(e,t=[],n=$n.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function i(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function a(e){return r.children.push(e),e}or(e,{onObjectBegin:e=>{r=a({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=a({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{i(e+t),r.length=e+t-r.offset,r=r.parent,i(e+t)},onArrayBegin:(e,t)=>{r=a({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,i(e+t)},onLiteralValue:(e,t,n)=>{a({type:sr(e),offset:t,length:n,parent:r,value:e}),i(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&i(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let o=r.children[0];return o&&delete o.parent,o}function tr(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}function nr(e){if(!e.parent||!e.parent.children)return[];let t=nr(e.parent);if(e.parent.type===`property`){let n=e.parent.children[0].value;t.push(n)}else if(e.parent.type===`array`){let n=e.parent.children.indexOf(e);n!==-1&&t.push(n)}return t}function rr(e){switch(e.type){case`array`:return e.children.map(rr);case`object`:let t=Object.create(null);for(let n of e.children){let e=n.children[1];e&&(t[n.children[0].value]=rr(e))}return t;case`null`:case`string`:case`number`:case`boolean`:return e.value;default:return}}function ir(e,t,n=!1){return t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}function ar(e,t,n=!1){if(ir(e,t,n)){let r=e.children;if(Array.isArray(r))for(let e=0;e<r.length&&r[e].offset<=t;e++){let i=ar(r[e],t,n);if(i)return i}return e}}function or(e,t,n=$n.DEFAULT){let r=Vn(e,!1),i=[],a=0;function o(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function s(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>!0}function l(e){return e?()=>{a>0?a++:e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===!1&&(a=1)}:()=>!0}function u(e){return e?()=>{a>0&&a--,a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=c(t.onObjectProperty),p=u(t.onObjectEnd),m=l(t.onArrayBegin),h=u(t.onArrayEnd),g=c(t.onLiteralValue),_=s(t.onSeparator),v=o(t.onComment),y=s(t.onError),b=n&&n.disallowComments,x=n&&n.allowTrailingComma;function S(){for(;;){let e=r.scan();switch(r.getTokenError()){case 4:C(14);break;case 5:C(15);break;case 3:C(13);break;case 1:b||C(11);break;case 2:C(12);break;case 6:C(16);break}switch(e){case 12:case 13:b?C(10):v();break;case 16:C(1);break;case 15:case 14:break;default:return e}}}function C(e,t=[],n=[]){if(y(e),t.length+n.length>0){let e=r.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){S();break}else if(n.indexOf(e)!==-1)break;e=S()}}}function w(e){let t=r.getTokenValue();return e?g(t):(f(t),i.push(t)),S(),!0}function T(){switch(r.getToken()){case 11:let e=r.getTokenValue(),t=Number(e);isNaN(t)&&(C(2),t=0),g(t);break;case 7:g(null);break;case 8:g(!0);break;case 9:g(!1);break;default:return!1}return S(),!0}function E(){return r.getToken()===10?(w(!1),r.getToken()===6?(_(`:`),S(),O()||C(4,[],[2,5])):C(5,[],[2,5]),i.pop(),!0):(C(3,[],[2,5]),!1)}function D(){d(),S();let e=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(e||C(4,[],[]),_(`,`),S(),r.getToken()===2&&x)break}else e&&C(6,[],[]);E()||C(4,[],[2,5]),e=!0}return p(),r.getToken()===2?S():C(7,[2],[]),!0}function ee(){m(),S();let e=!0,t=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(t||C(4,[],[]),_(`,`),S(),r.getToken()===4&&x)break}else t&&C(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,O()||C(4,[],[4,5]),t=!0}return h(),e||i.pop(),r.getToken()===4?S():C(8,[4],[]),!0}function O(){switch(r.getToken()){case 3:return ee();case 1:return D();case 10:return w(!0);default:return T()}}return S(),r.getToken()===17?n.allowEmptyContent?!0:(C(4,[],[]),!1):O()?(r.getToken()!==17&&C(9,[],[]),!0):(C(4,[],[]),!1)}function sr(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}function cr(e,t,n,r){let i=t.slice(),a=er(e,[]),o,s;for(;i.length>0&&(s=i.pop(),o=tr(a,i),o===void 0&&n!==void 0);)n=typeof s==`string`?{[s]:n}:[n];if(!o){if(n===void 0)throw Error(`Can not delete in empty document`);return lr(e,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(n)},r)}else if(o.type===`object`&&typeof s==`string`&&Array.isArray(o.children)){let t=tr(o,[s]);if(t!==void 0)if(n===void 0){if(!t.parent)throw Error(`Malformed AST`);let n=o.children.indexOf(t.parent),i,a=t.parent.offset+t.parent.length;if(n>0){let e=o.children[n-1];i=e.offset+e.length}else i=o.offset+1,o.children.length>1&&(a=o.children[1].offset);return lr(e,{offset:i,length:a-i,content:``},r)}else return lr(e,{offset:t.offset,length:t.length,content:JSON.stringify(n)},r);else{if(n===void 0)return[];let t=`${JSON.stringify(s)}: ${JSON.stringify(n)}`,i=r.getInsertionIndex?r.getInsertionIndex(o.children.map(e=>e.children[0].value)):o.children.length,a;if(i>0){let e=o.children[i-1];a={offset:e.offset+e.length,length:0,content:`,`+t}}else a=o.children.length===0?{offset:o.offset+1,length:0,content:t}:{offset:o.offset+1,length:0,content:t+`,`};return lr(e,a,r)}}else if(o.type===`array`&&typeof s==`number`&&Array.isArray(o.children)){let t=s;if(t===-1){let t=`${JSON.stringify(n)}`,i;if(o.children.length===0)i={offset:o.offset+1,length:0,content:t};else{let e=o.children[o.children.length-1];i={offset:e.offset+e.length,length:0,content:`,`+t}}return lr(e,i,r)}else if(n===void 0&&o.children.length>=0){let t=s,n=o.children[t],i;if(o.children.length===1)i={offset:o.offset+1,length:o.length-2,content:``};else if(o.children.length-1===t){let e=o.children[t-1],n=e.offset+e.length;i={offset:n,length:o.offset+o.length-2-n,content:``}}else i={offset:n.offset,length:o.children[t+1].offset-n.offset,content:``};return lr(e,i,r)}else if(n!==void 0){let t,i=`${JSON.stringify(n)}`;if(!r.isArrayInsertion&&o.children.length>s){let e=o.children[s];t={offset:e.offset,length:e.length,content:i}}else if(o.children.length===0||s===0)t={offset:o.offset+1,length:0,content:o.children.length===0?i:i+`,`};else{let e=s>o.children.length?o.children.length:s,n=o.children[e-1];t={offset:n.offset+n.length,length:0,content:`,`+i}}return lr(e,t,r)}else throw Error(`Can not ${n===void 0?`remove`:r.isArrayInsertion?`insert`:`modify`} Array index ${t} as length is not sufficient`)}else throw Error(`Can not add ${typeof s==`number`?`property`:`index`} to parent of type ${o.type}`)}function lr(e,t,n){if(!n.formattingOptions)return[t];let r=ur(e,t),i=t.offset,a=t.offset+t.content.length;if(t.length===0||t.content.length===0){for(;i>0&&!Qn(r,i-1);)i--;for(;a<r.length&&!Qn(r,a);)a++}let o=Jn(r,{offset:i,length:a-i},{...n.formattingOptions,keepLines:!1});for(let e=o.length-1;e>=0;e--){let t=o[e];r=ur(r,t),i=Math.min(i,t.offset),a=Math.max(a,t.offset+t.length),a+=t.content.length-t.length}let s=e.length-(r.length-a)-i;return[{offset:i,length:s,content:r.substring(i,a)}]}function ur(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}var dr;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(dr||={});var fr;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})(fr||={});const pr=er,mr=rr;var hr;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(hr||={});function gr(e,t,n,r){return cr(e,t,n,r)}function _r(e,t){let n=t.slice(0).sort((e,t)=>{let n=e.offset-t.offset;return n===0?e.length-t.length:n}),r=e.length;for(let t=n.length-1;t>=0;t--){let i=n[t];if(i.offset+i.length<=r)e=ur(e,i);else throw Error(`Overlapping edit`);r=i.offset}return e}function vr(e){for(let t of e.split(`
37
- `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function yr(e){let t=(e.match(/\r\n/g)??[]).length;return t===0?!1:t>=(e.match(/\n/g)??[]).length-t}function br(e){try{return we(e).mode&511}catch{return}}function xr(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
38
- `)?`\r
39
- `:`
40
- `,a=gr(r,t,void 0,{formattingOptions:{...vr(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${_r(r,a)}`;return{text:o,changed:o!==e}}const Sr={icon:{checked:G(`green`,dt.circleFilled),unchecked:dt.circle,cursor:dt.pointer,disabledChecked:G(`green`,dt.circleDouble),disabledUnchecked:`-`},style:{disabled:e=>G(`dim`,e),renderSelectedChoices:e=>e.map(e=>e.short).join(`, `),description:e=>G(`cyan`,e),keysHelpTip:e=>e.map(([e,t])=>`${G(`bold`,e)} ${G(`dim`,t)}`).join(G(`dim`,` • `))},i18n:{disabledError:`This option is disabled and cannot be toggled.`}};function Cr(e){return!Y.isSeparator(e)&&!e.disabled}function wr(e){return!Y.isSeparator(e)}function Tr(e){return!Y.isSeparator(e)&&e.checked}function Er(e){return Cr(e)?{...e,checked:!e.checked}:e}function Dr(e){return function(t){return Cr(t)?{...t,checked:e}:t}}function Or(e){return e.map(e=>{if(Y.isSeparator(e))return e;if(typeof e!=`object`||!e||!(`value`in e)){let t=String(e);return{value:e,name:t,short:t,checkedName:t,disabled:!1,checked:!1}}let t=e.name??String(e.value),n={value:e.value,name:t,short:e.short??t,checkedName:e.checkedName??t,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(n.description=e.description),n})}var kr=Tn((e,t)=>{let{pageSize:n=7,loop:r=!0,required:i,validate:a=()=>!0}=e,o={all:`a`,invert:`i`,...e.shortcuts},s=gt(Sr,e.theme),{keybindings:c}=s,[l,u]=q(`idle`),d=_t({status:l,theme:s}),[f,p]=q(Or(e.choices)),m=vt(()=>{let e=f.findIndex(wr),t=f.findLastIndex(wr);if(e===-1)throw new Je(`[checkbox prompt] No selectable choices. All choices are disabled.`);return{first:e,last:t}},[f]),[h,g]=q(m.first),[_,v]=q();bt(async e=>{if(Ue(e)){let e=f.filter(Tr),n=await a([...e]);i&&!e.length?v(`At least one choice must be selected`):n===!0?(u(`done`),t(e.map(e=>e.value))):v(n||`You must select a valid value`)}else if(Re(e,c)||ze(e,c)){if(_&&v(void 0),r||Re(e,c)&&h!==m.first||ze(e,c)&&h!==m.last){let t=Re(e,c)?-1:1,n=h;do n=(n+t+f.length)%f.length;while(!wr(f[n]));g(n)}}else if(Be(e)){let e=f[h];e&&!Y.isSeparator(e)&&(e.disabled?v(s.i18n.disabledError):(v(void 0),p(f.map((e,t)=>t===h?Er(e):e))))}else if(e.name===o.all){let e=f.some(e=>Cr(e)&&!e.checked);p(f.map(Dr(e)))}else if(e.name===o.invert)p(f.map(Er));else if(He(e)){let t=Number(e.name)-1,n=-1,r=f.findIndex(e=>Y.isSeparator(e)?!1:(n++,n===t)),i=f[r];i&&Cr(i)&&(g(r),p(f.map((e,t)=>t===r?Er(e):e)))}});let y=s.style.message(e.message,l),b,x=Yt({items:f,active:h,renderItem({item:e,isActive:t}){if(Y.isSeparator(e))return` ${e.separator}`;let n=t?s.icon.cursor:` `;if(e.disabled){let t=typeof e.disabled==`string`?e.disabled:`(disabled)`,r=e.checked?s.icon.disabledChecked:s.icon.disabledUnchecked;return s.style.disabled(`${n}${r} ${e.name} ${t}`)}t&&(b=e.description);let r=e.checked?s.icon.checked:s.icon.unchecked,i=e.checked?e.checkedName:e.name;return(t?s.style.highlight:e=>e)(`${n}${r} ${i}`)},pageSize:n,loop:r});if(l===`done`){let e=f.filter(Tr);return[d,y,s.style.answer(s.style.renderSelectedChoices(e,f))].filter(Boolean).join(` `)}let S=[[`↑↓`,`navigate`],[`space`,`select`]];o.all&&S.push([o.all,`all`]),o.invert&&S.push([o.invert,`invert`]),S.push([`⏎`,`submit`]);let C=s.style.keysHelpTip(S);return`${[[d,y].filter(Boolean).join(` `),x,` `,b?s.style.description(b):``,_?s.style.error(_):``,C].filter(Boolean).join(`
41
- `).trimEnd()}${fn}`});const Ar={icon:{cursor:dt.pointer},style:{disabled:e=>G(`dim`,e),description:e=>G(`cyan`,e),keysHelpTip:e=>e.map(([e,t])=>`${G(`bold`,e)} ${G(`dim`,t)}`).join(G(`dim`,` • `))},i18n:{disabledError:`This option is disabled and cannot be selected.`},indexMode:`hidden`};function jr(e){return!Y.isSeparator(e)&&!e.disabled}function Mr(e){return!Y.isSeparator(e)}function Nr(e){return e.map(e=>{if(Y.isSeparator(e))return e;if(typeof e!=`object`||!e||!(`value`in e)){let t=String(e);return{value:e,name:t,short:t,disabled:!1}}let t=e.name??String(e.value),n={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(n.description=e.description),n})}var Pr=Tn((e,t)=>{let{loop:n=!0,pageSize:r=7}=e,i=gt(Ar,e.theme),{keybindings:a}=i,[o,s]=q(`idle`),c=_t({status:o,theme:i}),l=yt(),u=!a.includes(`vim`),d=vt(()=>Nr(e.choices),[e.choices]),f=vt(()=>{let e=d.findIndex(Mr),t=d.findLastIndex(Mr);if(e===-1)throw new Je(`[select prompt] No selectable choices. All choices are disabled.`);return{first:e,last:t}},[d]),p=vt(()=>`default`in e?d.findIndex(t=>jr(t)&&t.value===e.default):-1,[e.default,d]),[m,h]=q(p===-1?f.first:p),g=d[m];if(g==null||Y.isSeparator(g))throw Error(`Active index does not point to a choice`);let[_,v]=q();bt((e,r)=>{if(clearTimeout(l.current),_&&v(void 0),Ue(e))g.disabled?v(i.i18n.disabledError):(s(`done`),t(g.value));else if(Re(e,a)||ze(e,a)){if(r.clearLine(0),n||Re(e,a)&&m!==f.first||ze(e,a)&&m!==f.last){let t=Re(e,a)?-1:1,n=m;do n=(n+t+d.length)%d.length;while(!Mr(d[n]));h(n)}}else if(He(e)&&!Number.isNaN(Number(r.line))){let e=Number(r.line)-1,t=-1,n=d.findIndex(n=>Y.isSeparator(n)?!1:(t++,t===e)),i=d[n];i!=null&&jr(i)&&h(n),l.current=setTimeout(()=>{r.clearLine(0)},700)}else if(Ve(e))r.clearLine(0);else if(u){let e=r.line.toLowerCase(),t=d.findIndex(t=>Y.isSeparator(t)||!jr(t)?!1:t.name.toLowerCase().startsWith(e));t!==-1&&h(t),l.current=setTimeout(()=>{r.clearLine(0)},700)}}),it(()=>()=>{clearTimeout(l.current)},[]);let y=i.style.message(e.message,o),b=i.style.keysHelpTip([[`↑↓`,`navigate`],[`⏎`,`select`]]),x=0,S=Yt({items:d,active:m,renderItem({item:e,isActive:t,index:n}){if(Y.isSeparator(e))return x++,` ${e.separator}`;let r=t?i.icon.cursor:` `,a=i.indexMode===`number`?`${n+1-x}. `:``;if(e.disabled){let n=typeof e.disabled==`string`?e.disabled:`(disabled)`,r=t?i.icon.cursor:`-`;return i.style.disabled(`${r} ${a}${e.name} ${n}`)}return(t?i.style.highlight:e=>e)(`${r} ${a}${e.name}`)},pageSize:r,loop:n});if(o===`done`)return[c,y,i.style.answer(g.short)].filter(Boolean).join(` `);let{description:C}=g;return`${[[c,y].filter(Boolean).join(` `),S,` `,C?i.style.description(C):``,_?i.style.error(_):``,b].filter(Boolean).join(`
42
- `).trimEnd()}${fn}`});
43
- /*!
44
- * Copyright (c) Squirrel Chat et al., All rights reserved.
45
- * SPDX-License-Identifier: BSD-3-Clause
46
- *
47
- * Redistribution and use in source and binary forms, with or without
48
- * modification, are permitted provided that the following conditions are met:
49
- *
50
- * 1. Redistributions of source code must retain the above copyright notice, this
51
- * list of conditions and the following disclaimer.
52
- * 2. Redistributions in binary form must reproduce the above copyright notice,
53
- * this list of conditions and the following disclaimer in the
54
- * documentation and/or other materials provided with the distribution.
55
- * 3. Neither the name of the copyright holder nor the names of its contributors
56
- * may be used to endorse or promote products derived from this software without
57
- * specific prior written permission.
58
- *
59
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
60
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
61
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
62
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
63
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
65
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
66
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
67
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
68
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69
- */
70
- function Fr(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Ir(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
71
- `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
72
- `))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Fr(t.toml,t.ptr),i=Ir(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
73
- /*!
74
- * Copyright (c) Squirrel Chat et al., All rights reserved.
75
- * SPDX-License-Identifier: BSD-3-Clause
76
- *
77
- * Redistribution and use in source and binary forms, with or without
78
- * modification, are permitted provided that the following conditions are met:
79
- *
80
- * 1. Redistributions of source code must retain the above copyright notice, this
81
- * list of conditions and the following disclaimer.
82
- * 2. Redistributions in binary form must reproduce the above copyright notice,
83
- * this list of conditions and the following disclaimer in the
84
- * documentation and/or other materials provided with the distribution.
85
- * 3. Neither the name of the copyright holder nor the names of its contributors
86
- * may be used to endorse or promote products derived from this software without
87
- * specific prior written permission.
88
- *
89
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
90
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
91
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
92
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
93
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
94
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
95
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
96
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
97
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
98
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
99
- */
100
- function Lr(e,t){let n=0;for(;e[t-++n]===`\\`;);return--n&&n%2}function Rr(e,t=0,n=e.length){let r=e.indexOf(`
101
- `,t);return e[r-1]===`\r`&&r--,r<=n?r:-1}function zr(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
102
- `)return n;if(r===`\r`&&e[n+1]===`
103
- `)return n+1;if(r<` `&&r!==` `||r===``)throw new Z(`control characters are not allowed in comments`,{toml:e,ptr:t})}return e.length}function Q(e,t,n,r){let i;for(;;){for(;(i=e[t])===` `||i===` `||!n&&(i===`
104
- `||i===`\r`&&e[t+1]===`
105
- `);)t++;if(r||i!==`#`)break;t=zr(e,t)}return t}function Br(e,t,n,r,i=!1){if(!r)return t=Rr(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=Rr(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
106
- `||t===`\r`&&e[a+1]===`
107
- `))return a}throw new Z(`cannot find end of structure`,{toml:e,ptr:t})}function Vr(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!==`'`&&Lr(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}
108
- /*!
109
- * Copyright (c) Squirrel Chat et al., All rights reserved.
110
- * SPDX-License-Identifier: BSD-3-Clause
111
- *
112
- * Redistribution and use in source and binary forms, with or without
113
- * modification, are permitted provided that the following conditions are met:
114
- *
115
- * 1. Redistributions of source code must retain the above copyright notice, this
116
- * list of conditions and the following disclaimer.
117
- * 2. Redistributions in binary form must reproduce the above copyright notice,
118
- * this list of conditions and the following disclaimer in the
119
- * documentation and/or other materials provided with the distribution.
120
- * 3. Neither the name of the copyright holder nor the names of its contributors
121
- * may be used to endorse or promote products derived from this software without
122
- * specific prior written permission.
123
- *
124
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
125
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
126
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
127
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
128
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
129
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
130
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
131
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
132
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
133
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
134
- */
135
- let Hr=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var Ur=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(Hr);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
136
- /*!
137
- * Copyright (c) Squirrel Chat et al., All rights reserved.
138
- * SPDX-License-Identifier: BSD-3-Clause
139
- *
140
- * Redistribution and use in source and binary forms, with or without
141
- * modification, are permitted provided that the following conditions are met:
142
- *
143
- * 1. Redistributions of source code must retain the above copyright notice, this
144
- * list of conditions and the following disclaimer.
145
- * 2. Redistributions in binary form must reproduce the above copyright notice,
146
- * this list of conditions and the following disclaimer in the
147
- * documentation and/or other materials provided with the distribution.
148
- * 3. Neither the name of the copyright holder nor the names of its contributors
149
- * may be used to endorse or promote products derived from this software without
150
- * specific prior written permission.
151
- *
152
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
153
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
154
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
155
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
156
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
157
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
158
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
159
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
160
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
161
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
162
- */
163
- let Wr=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Gr=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Kr=/^[+-]?0[0-9_]/,qr=/^[0-9a-f]{2,8}$/i,Jr={b:`\b`,t:` `,n:`
164
- `,f:`\f`,r:`\r`,e:`\x1B`,'"':`"`,"\\":`\\`};function Yr(e,t=0,n=e.length){let r=e[t]===`'`,i=e[t++]===e[t]&&e[t]===e[t+1];i&&(n-=2,e[t+=2]===`\r`&&t++,e[t]===`
165
- `&&t++);let a=0,o,s=``,c=t;for(;t<n-1;){let n=e[t++];if(n===`
166
- `||n===`\r`&&e[t]===`
167
- `){if(!i)throw new Z(`newlines are not allowed in strings`,{toml:e,ptr:t-1})}else if(n<` `&&n!==` `||n===``)throw new Z(`control characters are not allowed in strings`,{toml:e,ptr:t-1});if(o){if(o=!1,n===`x`||n===`u`||n===`U`){let r=e.slice(t,t+=n===`x`?2:n===`u`?4:8);if(!qr.test(r))throw new Z(`invalid unicode escape`,{toml:e,ptr:a});try{s+=String.fromCodePoint(parseInt(r,16))}catch{throw new Z(`invalid unicode escape`,{toml:e,ptr:a})}}else if(i&&(n===`
168
- `||n===` `||n===` `||n===`\r`)){if(t=Q(e,t-1,!0),e[t]!==`
169
- `&&e[t]!==`\r`)throw new Z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:a});t=Q(e,t)}else if(n in Jr)s+=Jr[n];else throw new Z(`unrecognized escape sequence`,{toml:e,ptr:a});c=t}else !r&&n===`\\`&&(a=t-1,o=!0,s+=e.slice(c,a))}return s+e.slice(c,n-1)}function Xr(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=Wr.test(e);if(i||Gr.test(e)){if(Kr.test(e))throw new Z(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new Z(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new Z(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new Ur(e);if(!a.isValid())throw new Z(`invalid value`,{toml:t,ptr:n});return a}
170
- /*!
171
- * Copyright (c) Squirrel Chat et al., All rights reserved.
172
- * SPDX-License-Identifier: BSD-3-Clause
173
- *
174
- * Redistribution and use in source and binary forms, with or without
175
- * modification, are permitted provided that the following conditions are met:
176
- *
177
- * 1. Redistributions of source code must retain the above copyright notice, this
178
- * list of conditions and the following disclaimer.
179
- * 2. Redistributions in binary form must reproduce the above copyright notice,
180
- * this list of conditions and the following disclaimer in the
181
- * documentation and/or other materials provided with the distribution.
182
- * 3. Neither the name of the copyright holder nor the names of its contributors
183
- * may be used to endorse or promote products derived from this software without
184
- * specific prior written permission.
185
- *
186
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
187
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
188
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
189
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
190
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
191
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
192
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
193
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
194
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
195
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
196
- */
197
- function Zr(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(zr(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Qr(e,t,n,r,i){if(r===0)throw new Z(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?ni(e,t,r,i):ti(e,t,r,i);if(n){if(s=Q(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new Z(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}let o;if(a===`"`||a===`'`){o=Vr(e,t);let r=Yr(e,t,o);if(n){if(o=Q(e,o),e[o]&&e[o]!==`,`&&e[o]!==n&&e[o]!==`
198
- `&&e[o]!==`\r`)throw new Z(`unexpected character encountered`,{toml:e,ptr:o});o+=+(e[o]===`,`)}return[r,o]}o=Br(e,t,`,`,n);let s=Zr(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new Z(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=Q(e,t+s[1]),o+=+(e[o]===`,`)),[Xr(s[0],e,t,i),o]}
199
- /*!
200
- * Copyright (c) Squirrel Chat et al., All rights reserved.
201
- * SPDX-License-Identifier: BSD-3-Clause
202
- *
203
- * Redistribution and use in source and binary forms, with or without
204
- * modification, are permitted provided that the following conditions are met:
205
- *
206
- * 1. Redistributions of source code must retain the above copyright notice, this
207
- * list of conditions and the following disclaimer.
208
- * 2. Redistributions in binary form must reproduce the above copyright notice,
209
- * this list of conditions and the following disclaimer in the
210
- * documentation and/or other materials provided with the distribution.
211
- * 3. Neither the name of the copyright holder nor the names of its contributors
212
- * may be used to endorse or promote products derived from this software without
213
- * specific prior written permission.
214
- *
215
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
216
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
217
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
218
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
219
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
220
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
221
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
222
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
223
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
224
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
225
- */
226
- let $r=/^[a-zA-Z0-9-_]+[ \t]*$/;function ei(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new Z(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `)if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new Z(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let s=Vr(e,t);if(s<0)throw new Z(`unfinished string encountered`,{toml:e,ptr:t});r=e.indexOf(`.`,s);let c=e.slice(s,r<0||r>a?a:r),l=Rr(c);if(l>-1)throw new Z(`newlines are not allowed in keys`,{toml:e,ptr:t+r+l});if(c.trimStart())throw new Z(`found extra tokens after the string part`,{toml:e,ptr:s});if(a<s&&(a=e.indexOf(n,s),a<0))throw new Z(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(Yr(e,t,s))}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!$r.test(n))throw new Z(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}while(r+1&&r<a);return[i,Q(e,a+1,!0,!0)]}function ti(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new Z(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=zr(e,t);else if(o!==` `&&o!==` `&&o!==`
227
- `&&o!==`\r`){let o,s=i,c=!1,[l,u]=ei(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new Z(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new Z(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=Qr(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new Z(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function ni(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new Z(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=zr(e,t);else if(a!==` `&&a!==` `&&a!==`
228
- `&&a!==`\r`){let a=Qr(e,t-1,`]`,n-1,r);i.push(a[0]),t=a[1]}if(!a)throw new Z(`unfinished array encountered`,{toml:e,ptr:t});return[i,t]}
229
- /*!
230
- * Copyright (c) Squirrel Chat et al., All rights reserved.
231
- * SPDX-License-Identifier: BSD-3-Clause
232
- *
233
- * Redistribution and use in source and binary forms, with or without
234
- * modification, are permitted provided that the following conditions are met:
235
- *
236
- * 1. Redistributions of source code must retain the above copyright notice, this
237
- * list of conditions and the following disclaimer.
238
- * 2. Redistributions in binary form must reproduce the above copyright notice,
239
- * this list of conditions and the following disclaimer in the
240
- * documentation and/or other materials provided with the distribution.
241
- * 3. Neither the name of the copyright holder nor the names of its contributors
242
- * may be used to endorse or promote products derived from this software without
243
- * specific prior written permission.
244
- *
245
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
246
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
247
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
248
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
249
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
250
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
251
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
252
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
253
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
254
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
255
- */
256
- function ri(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function ii(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=Q(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=ei(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new Z(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=ri(n[0],r,i,t?2:1);if(!c)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=ei(e,s),i=ri(r[0],a,o,0);if(!i)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=Qr(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=Q(e,s,!0),e[s]&&e[s]!==`
257
- `&&e[s]!==`\r`)throw new Z(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:s});s=Q(e,s)}return r}
258
- /*!
259
- * Copyright (c) Squirrel Chat et al., All rights reserved.
260
- * SPDX-License-Identifier: BSD-3-Clause
261
- *
262
- * Redistribution and use in source and binary forms, with or without
263
- * modification, are permitted provided that the following conditions are met:
264
- *
265
- * 1. Redistributions of source code must retain the above copyright notice, this
266
- * list of conditions and the following disclaimer.
267
- * 2. Redistributions in binary form must reproduce the above copyright notice,
268
- * this list of conditions and the following disclaimer in the
269
- * documentation and/or other materials provided with the distribution.
270
- * 3. Neither the name of the copyright holder nor the names of its contributors
271
- * may be used to endorse or promote products derived from this software without
272
- * specific prior written permission.
273
- *
274
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
275
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
276
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
277
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
278
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
279
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
280
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
281
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
282
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
- */
285
- let ai=/^[a-z0-9-_]+$/i;function oi(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function si(e){for(let t=0;t<e.length;t++)if(oi(e[t])!==`object`)return!1;return e.length!=0}function ci(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function li(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return ci(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return ui(e,n,r);if(t===`array`)return di(e,n,r)}function ui(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=ai.test(o)?o:ci(o),i+=` = `,i+=li(e[o],oi(e[o]),t-1,n)}return i+` }`}function di(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=li(e[i],oi(e[i]),t-1,n)}return r+` ]`}function fi(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
286
- `}[[${t}]]\n`,i+=pi(0,e[a],t,n,r);return i}function pi(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=oi(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=ai.test(c)?c:ci(c);if(e===`array`&&si(t[c]))o+=(o&&`
287
- `)+fi(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
288
- `)+pi(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=li(t[c],e,r,i),a+=`
289
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function mi(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(oi(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=pi(0,e,``,t,n);return r[r.length-1]===`
290
- `?r:r+`
291
- `}const hi=`${M}-dev`;function gi(e){return e.startsWith(M)}function _i(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&gi(n)}function vi(e){return{command:ie,args:[e]}}function yi(e={}){let t=e.mode===`dev`?hi:oe,n={unix:j({...e,platformName:`darwin`}),win32:j({...e,platformName:`win32`})};return`${t}
292
- /**
293
- * Open Knowledge bridge for Pi — MANAGED FILE, written by \`ok init\`.
294
- * Hand edits are overwritten whenever OK re-syncs this project; remove it
295
- * with \`ok deinit\` (or delete the file) to disconnect Pi from OK.
296
- *
297
- * On session start it spawns Open Knowledge's MCP stdio server via OK's
298
- * resilient launcher (bundle, then npx, then version-manager probes), performs
299
- * the MCP handshake, and registers each MCP tool as a Pi tool under an
300
- * \`ok_\` prefix (Pi has no MCP namespacing; the prefix keeps OK's \`edit\` /
301
- * \`write\` from shadowing Pi's built-in tools).
302
- */
303
- import { spawn } from "node:child_process";
304
- import type { ChildProcessWithoutNullStreams } from "node:child_process";
305
-
306
- const LAUNCHERS = ${JSON.stringify(n,null,2)} as const;
307
-
308
- const TOOL_PREFIX = "ok_";
309
- // First contact may cold-install the CLI through npx — allow a generous window.
310
- const INIT_TIMEOUT_MS = 120000;
311
- const STDERR_TAIL_LIMIT = 2000;
312
-
313
- interface McpContentItem {
314
- type: string;
315
- text?: string;
316
- }
317
-
318
- interface McpToolInfo {
319
- name: string;
320
- description?: string;
321
- inputSchema?: Record<string, unknown>;
322
- }
323
-
324
- interface PendingRequest {
325
- resolve: (value: Record<string, unknown>) => void;
326
- reject: (err: Error) => void;
327
- }
328
-
329
- class OkMcpClient {
330
- private child: ChildProcessWithoutNullStreams;
331
- private pending = new Map<number, PendingRequest>();
332
- private nextId = 1;
333
- private buffer = "";
334
- private stderrTail = "";
335
- alive = true;
336
-
337
- constructor(cwd: string, onExit: () => void) {
338
- const launcher = process.platform === "win32" ? LAUNCHERS.win32 : LAUNCHERS.unix;
339
- const env: Record<string, string | undefined> = { ...process.env };
340
- const launcherEnv = (launcher as { env?: Record<string, string> }).env;
341
- if (launcherEnv) Object.assign(env, launcherEnv);
342
- this.child = spawn(launcher.command, [...launcher.args], {
343
- cwd,
344
- env,
345
- stdio: ["pipe", "pipe", "pipe"],
346
- });
347
- this.child.stdout.setEncoding("utf8");
348
- this.child.stdout.on("data", (chunk: string) => this.onStdout(chunk));
349
- this.child.stderr.setEncoding("utf8");
350
- this.child.stderr.on("data", (chunk: string) => {
351
- this.stderrTail = (this.stderrTail + chunk).slice(-STDERR_TAIL_LIMIT);
352
- });
353
- // A write buffered before the pipe breaks surfaces as an 'error' on stdin
354
- // (not on the child); unhandled it would crash Pi's extension host.
355
- // Swallow it — the exit handler owns teardown.
356
- this.child.stdin.on("error", () => {});
357
- const fail = () => {
358
- if (!this.alive) return;
359
- this.alive = false;
360
- const err = new Error(
361
- "Open Knowledge MCP server exited" +
362
- (this.stderrTail ? ": " + this.stderrTail.trim() : ""),
363
- );
364
- for (const p of this.pending.values()) p.reject(err);
365
- this.pending.clear();
366
- onExit();
367
- };
368
- this.child.on("exit", fail);
369
- this.child.on("error", fail);
370
- }
371
-
372
- private onStdout(chunk: string): void {
373
- this.buffer += chunk;
374
- let newline = this.buffer.indexOf("\\n");
375
- while (newline !== -1) {
376
- const line = this.buffer.slice(0, newline).trim();
377
- this.buffer = this.buffer.slice(newline + 1);
378
- if (line.startsWith("{")) {
379
- try {
380
- this.onMessage(JSON.parse(line) as Record<string, unknown>);
381
- } catch {
382
- // Non-JSON noise on stdout is ignored; framing recovers on the next line.
383
- }
384
- }
385
- newline = this.buffer.indexOf("\\n");
386
- }
387
- }
388
-
389
- private onMessage(msg: Record<string, unknown>): void {
390
- const id = msg.id;
391
- if (typeof msg.method === "string") {
392
- // Server-initiated request (e.g. roots/list). This bridge declares no
393
- // client capabilities, so decline rather than leave the server hanging.
394
- if (id !== undefined && id !== null) {
395
- this.send({
396
- jsonrpc: "2.0",
397
- id,
398
- error: { code: -32601, message: "Method not supported by the OK Pi bridge" },
399
- });
400
- }
401
- return;
402
- }
403
- if (typeof id !== "number") return;
404
- const pending = this.pending.get(id);
405
- if (!pending) return;
406
- this.pending.delete(id);
407
- const error = msg.error as { message?: string } | undefined;
408
- if (error) {
409
- pending.reject(new Error(error.message || "Open Knowledge MCP error"));
410
- return;
411
- }
412
- pending.resolve((msg.result ?? {}) as Record<string, unknown>);
413
- }
414
-
415
- private send(msg: Record<string, unknown>): void {
416
- // Buffered stdout can still dispatch onMessage replies after close() ends
417
- // stdin; writing then would raise ERR_STREAM_WRITE_AFTER_END unhandled.
418
- if (!this.alive) return;
419
- this.child.stdin.write(JSON.stringify(msg) + "\\n");
420
- }
421
-
422
- request(
423
- method: string,
424
- params: Record<string, unknown>,
425
- opts: { timeoutMs?: number; signal?: AbortSignal } = {},
426
- ): Promise<Record<string, unknown>> {
427
- if (!this.alive) return Promise.reject(new Error("Open Knowledge MCP server is not running"));
428
- const id = this.nextId++;
429
- return new Promise<Record<string, unknown>>((resolve, reject) => {
430
- let timer: ReturnType<typeof setTimeout> | undefined;
431
- let onAbort: (() => void) | undefined;
432
- const cleanup = () => {
433
- if (timer !== undefined) clearTimeout(timer);
434
- if (onAbort && opts.signal) opts.signal.removeEventListener("abort", onAbort);
435
- this.pending.delete(id);
436
- };
437
- const done: PendingRequest = {
438
- resolve: (value) => {
439
- cleanup();
440
- resolve(value);
441
- },
442
- reject: (err) => {
443
- cleanup();
444
- reject(err);
445
- },
446
- };
447
- this.pending.set(id, done);
448
- if (opts.timeoutMs) {
449
- timer = setTimeout(() => {
450
- done.reject(new Error(method + " timed out after " + opts.timeoutMs + "ms"));
451
- }, opts.timeoutMs);
452
- }
453
- if (opts.signal) {
454
- onAbort = () => {
455
- this.notify("notifications/cancelled", { requestId: id, reason: "aborted" });
456
- done.reject(new Error("Cancelled"));
457
- };
458
- if (opts.signal.aborted) {
459
- onAbort();
460
- return;
461
- }
462
- opts.signal.addEventListener("abort", onAbort, { once: true });
463
- }
464
- this.send({ jsonrpc: "2.0", id, method, params });
465
- });
466
- }
467
-
468
- notify(method: string, params: Record<string, unknown>): void {
469
- if (!this.alive) return;
470
- this.send({ jsonrpc: "2.0", method, params });
471
- }
472
-
473
- close(): void {
474
- this.alive = false;
475
- for (const p of this.pending.values()) {
476
- p.reject(new Error("Open Knowledge MCP client closed"));
477
- }
478
- this.pending.clear();
479
- // ok mcp exits on stdin EOF; the delayed kill is a backstop.
480
- try {
481
- this.child.stdin.end();
482
- } catch {
483
- // Already gone.
484
- }
485
- const child = this.child;
486
- setTimeout(() => {
487
- try {
488
- child.kill();
489
- } catch {
490
- // Already gone.
491
- }
492
- }, 2000).unref();
493
- }
494
- }
495
-
496
- /** JSON Schema pass-through: Pi validates plain JSON Schema parameters. */
497
- function toParameters(inputSchema: Record<string, unknown> | undefined): Record<string, unknown> {
498
- if (!inputSchema || typeof inputSchema !== "object") {
499
- return { type: "object", properties: {} };
500
- }
501
- const schema = { ...inputSchema };
502
- delete schema.$schema;
503
- return schema;
504
- }
505
-
506
- function contentText(content: unknown): string {
507
- if (!Array.isArray(content)) return "";
508
- return (content as McpContentItem[])
509
- .filter((item) => item && item.type === "text" && typeof item.text === "string")
510
- .map((item) => item.text as string)
511
- .join("\\n");
512
- }
513
-
514
- export default function okBridge(pi: {
515
- on(event: string, handler: (event: unknown, ctx: unknown) => unknown): void;
516
- registerTool(definition: Record<string, unknown>): void;
517
- }) {
518
- let client: OkMcpClient | null = null;
519
- let starting: Promise<OkMcpClient> | null = null;
520
- let sessionCwd = process.cwd();
521
- const registeredTools = new Set<string>();
522
-
523
- async function ensureClient(): Promise<OkMcpClient> {
524
- if (client && client.alive) return client;
525
- if (starting) return starting;
526
- starting = (async () => {
527
- const next = new OkMcpClient(sessionCwd, () => {
528
- if (client === next) client = null;
529
- });
530
- try {
531
- await next.request(
532
- "initialize",
533
- {
534
- protocolVersion: "2025-06-18",
535
- capabilities: {},
536
- clientInfo: { name: "pi", version: "1.0.0" },
537
- },
538
- { timeoutMs: INIT_TIMEOUT_MS },
539
- );
540
- } catch (err) {
541
- // A timed-out initialize rejects the request while the child may
542
- // still be running; tear it down so retries don't stack orphans.
543
- next.close();
544
- throw err;
545
- }
546
- next.notify("notifications/initialized", {});
547
- client = next;
548
- return next;
549
- })();
550
- try {
551
- return await starting;
552
- } finally {
553
- starting = null;
554
- }
555
- }
556
-
557
- async function registerOkTools(): Promise<number> {
558
- const mcp = await ensureClient();
559
- const listed = await mcp.request("tools/list", {}, { timeoutMs: INIT_TIMEOUT_MS });
560
- const tools = Array.isArray(listed.tools) ? (listed.tools as McpToolInfo[]) : [];
561
- for (const tool of tools) {
562
- const name = TOOL_PREFIX + tool.name;
563
- if (registeredTools.has(name)) continue;
564
- registeredTools.add(name);
565
- pi.registerTool({
566
- name,
567
- label: "OK " + tool.name,
568
- description: tool.description || "Open Knowledge " + tool.name + " tool.",
569
- parameters: toParameters(tool.inputSchema),
570
- execute: async (
571
- _toolCallId: string,
572
- params: Record<string, unknown>,
573
- signal: AbortSignal | undefined,
574
- ) => {
575
- const live = await ensureClient();
576
- const result = await live.request(
577
- "tools/call",
578
- { name: tool.name, arguments: params ?? {} },
579
- { signal },
580
- );
581
- const text = contentText(result.content);
582
- if (result.isError) {
583
- throw new Error(text || "Open Knowledge tool " + tool.name + " failed");
584
- }
585
- return {
586
- content: [{ type: "text", text }],
587
- details: result.structuredContent,
588
- };
589
- },
590
- });
591
- }
592
- return tools.length;
593
- }
594
-
595
- pi.on("session_start", async (_event, ctx) => {
596
- const cwd = (ctx as { cwd?: string } | undefined)?.cwd;
597
- if (typeof cwd === "string" && cwd.length > 0) sessionCwd = cwd;
598
- try {
599
- await registerOkTools();
600
- } catch (err) {
601
- const ui = (ctx as { ui?: { notify?: (m: string, level: string) => void } } | undefined)?.ui;
602
- try {
603
- ui?.notify?.(
604
- "Open Knowledge tools unavailable: " + (err instanceof Error ? err.message : String(err)),
605
- "warning",
606
- );
607
- } catch {
608
- // Non-interactive mode; the failure will resurface on first tool use.
609
- }
610
- }
611
- });
612
-
613
- pi.on("session_shutdown", async () => {
614
- const pending = starting;
615
- starting = null;
616
- const current = client;
617
- client = null;
618
- current?.close();
619
- // An in-flight ensureClient would otherwise assign a live client after
620
- // shutdown; await it and tear that one down too.
621
- if (pending) {
622
- try {
623
- (await pending).close();
624
- } catch {
625
- // Initialization failed — its catch path already closed the client.
626
- }
627
- }
628
- });
629
- }
630
- `}function bi(e,t){let n=V(t,e);return n.length>0&&!n.startsWith(`..`)&&!he(n)}const xi=e=>{try{let t=pe(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return t.length>0?t:null}catch{return null}};function Si(e,t={}){let n=t.homeDir??ye(),r=t.gitTopLevel??xi,i=ge(e),a;try{a=Ce(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=z(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&bi(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 Ci(e){let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`MODULE_NOT_FOUND`||t===`ERR_MODULE_NOT_FOUND`}function $(e,t){if(!process.env.OK_DEBUG_NATIVE)return;let n=t instanceof Error?t.message:String(t);process.stderr.write(`[ok] native-config ${e}: ${n}\n`)}const wi=[`native`,`index.js`];function Ti(e={}){let t=e.moduleUrl??import.meta.url,n=e.requireModule??fe(t);try{return n(B(z(ve(t)),...wi))}catch(e){Ci(e)||$(`bundled loader failed to load`,e)}try{return n(`@inkeep/open-knowledge-native-config`)}catch(e){return Ci(e)||$(`workspace addon failed to load`,e),null}}function Ei(){let e=Ti();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function Di(e){let t=e,n=new Set;for(;;){let r;try{r=be(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=Se(t)}catch(t){return $(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=he(i)?i:B(z(t),i)}}let Oi;function ki(){return Oi===void 0&&(Oi=Ei()),Oi}function Ai(e,t=ki){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){$(`resolveSymlinkWritePath threw`,e)}return Di(e)}function ji(){let e=Ti();return e&&typeof e.parseTomlToJson==`function`?e:null}function Mi(e){try{let t=e.parseTomlToJson(`probe = 1`);return typeof t==`string`&&t.includes(`probe`)}catch(e){return $(`addon loaded but probe failed`,e),!1}}function Ni(e){if(!P(e))throw Error(`TOML root is not a table`);return e}function Pi(e){return{backend:`native`,parseToObject(t){return Ni(JSON.parse(e.parseTomlToJson(t)))},upsertEntry(t,n,r){let i=e.upsertMcpServer(t,n,JSON.stringify(r));return{text:i.text,existed:i.existed}},removeEntry(t,n){let r=e.removeMcpServer(t,n);return{text:r.text,existed:r.existed}}}}function Fi(){return{backend:`fallback`,parseToObject(e){return Ni(ii(e))}}}function Ii(e=ji){let t=e();return t&&Mi(t)?Pi(t):Fi()}let Li=null;function Ri(){return Li===null&&(Li=Ii()),Li}function zi(e,t,n,r,i){let a=`urn:uuid:${Ee()}`;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=l.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 Bi=1e4;function Vi(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!w(n))return zi(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!f(e.headers.host))return zi(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&&!v(r)?(zi(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const Hi=3e4;function Ui(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!w(n)||!f(e.headers.host))return t.destroy(),!0;let r=e.headers.origin;return typeof r==`string`&&!v(r)?(t.destroy(),!0):!1}function Wi(e,t,n,r,i,a){a.add(t),t.once(`close`,()=>a.delete(t));let o=Pe({host:r,port:i,timeout:Bi});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
631
- `)}\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 Gi=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Ki(e){let t=e.upstreamTimeoutMs??Bi,n=new Set,r=je((n,r)=>{Vi(n,r)||Ji(n,r,e.upstreamHost,e.upstreamPort,t)});r.on(`upgrade`,(t,r,i)=>{Ui(t,r)||Wi(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 qi(e,t,n){Ji(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??Bi)}function Ji(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Gi)delete a[e];e.setTimeout(Hi,()=>{if(t.headersSent)try{t.end()}catch{}else try{zi(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${Hi/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=Me({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Gi)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)zi(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)zi(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 Yi=39847,Xi=39848;async function Zi(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Qi(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:i}=await import(`node:path`),{acquireUiLock:a,clearArmedPaneTarget:s,createAssetServeMiddleware:l,createContentFilter:f,readArmedPaneTarget:p,readServerLock:m,releaseUiLock:h,updateUiLockPort:g}=await import(`./dist-Bc_bWnDQ.mjs`),{default:_}=await import(`./build-gfyDk62R.mjs`),{resolveContentDir:v,resolveLockDir:y}=await import(`./dist-Bc_bWnDQ.mjs`),b=v(e.config,e.cwd),x=y(e.cwd);a(x,{port:0,worktreeRoot:e.cwd});let S=import.meta.dirname??new URL(`.`,import.meta.url).pathname,C=[i(S,`public`),i(S,`../../app/dist`),i(S,`../../../app/dist`)],w=e.assetDir??C.find(e=>t(e)),T=w?_(w,{single:!0,gzip:!0,etag:!0,dev:!0,extensions:[]}):null,E=t(b)?l({contentFilter:f({projectDir:e.cwd,contentDir:b}),contentSirv:_(b,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:o,assetExtensions:u,blocklistExtensions:r}):null,D=e.port,ee=null,O=(e,t)=>{let n=e.url?.split(`?`)[0];if(e.method===`GET`&&(n===`/`||n===``)){let e=p(x);if(e&&!/[\r\n]/.test(e)){s(x),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`){s(x),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){ee?.();let n=m(x),r=e.headers.host??`localhost:${D}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=p(x),o=JSON.stringify({collabUrl:i,previewUrl:null,port:D,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/`)){ee?.();let r=m(x);if(!r||r.port<=0){zi(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}qi(e,t,{upstreamHost:d,upstreamPort:r.port});return}if(T&&n?.startsWith(`/assets/`)){T(e,t,()=>{E?E(e,t,()=>$i(t)):$i(t)});return}if(E){E(e,t,()=>{T?T(e,t):$i(t)});return}if(T){T(e,t);return}$i(t)}},k=new Set,te=(e,t,n)=>{if(Ui(e,t))return;let r=e.url?.split(`?`)[0]??``;if(r!==`/collab`&&!r.startsWith(`/collab/`)){t.destroy();return}let i=m(x);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}Wi(e,t,n,d,i.port,k)},ne=()=>{for(let e of k)try{e.destroy()}catch{}k.clear()},re=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],A=[],j=e.port,ie=e=>e instanceof Error&&e.code===`EADDRINUSE`,ae=async()=>{await Promise.all(A.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},oe=async e=>{j=e;for(let e of re){let t=n(O);t.on(`upgrade`,te),A.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(j,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(j=e.port),n()})})}};try{try{await oe(e.port)}catch(t){if(e.fallbackToKernel===!0&&ie(t))await ae(),await oe(0);else throw t}}catch(e){await ae();try{h(x)}catch{}throw e}let M=j;D=M,g(x,M);let se=e.scheduler??c,ce=e.safetyNetMs??432e5,N=null,P=!1,F=!1,le=()=>{P||(P=!0,N!==null&&(se.clearTimeout(N),N=null))},I=()=>{if(le(),!F){F=!0;try{h(x)}catch{}}},ue=()=>{P||ce<=0||(N!==null&&(se.clearTimeout(N),N=null),N=se.setTimeout(()=>{N=null,console.warn(`[ui] safety-net (${ce}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}ne();for(let e of A)try{e.close()}catch{}I()},ce))},L=()=>{P||ce<=0||ue()};return ee=L,ue(),{httpServers:A,port:M,release:I,detachSafetyNet:le,nudgeSafetyNet:L,drainUpgradeSockets:ne}}function $i(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 ea(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:Yi,fallbackToKernel:!0}}async function ta(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-Bc_bWnDQ.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 Ki({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function na(e){return new k(`ui`).description(`Serve the OpenKnowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Yi}, 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-CmkIIbww.mjs`),{UiLockCollisionError:r}=await import(`./dist-Bc_bWnDQ.mjs`),{resolveLockDir:i}=await import(`./dist-Bc_bWnDQ.mjs`),a=e(),o=t.host,s;try{s=ea(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 Qi({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(),Zi(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 ta({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}`),ra(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 ra(e){let t=e.stdout.isTTY===!0,n=typeof e.env.PORT==`string`&&e.env.PORT!==``;return!t||n}const ia={allowTrailingComma:!0,disallowComments:!1};function aa(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function oa(e){let t=[],n=pr(e,t,ia);return t.some(t=>!aa(t,e))||!n||n.type!==`object`?null:n}function sa(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&mr(e)===t&&(n+=1)}return n}function ca(e,t){S(e,`${JSON.stringify(t,null,2)}\n`)}function la(e,t){let n=mi(t);S(e,n.endsWith(`
632
- `)?n:`${n}\n`)}const ua=10*1024*1024;function da(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>da(e,t[n]));if(P(e)&&P(t)){let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.hasOwn(t,n)&&da(e[n],t[n])):!1}return!1}function fa(e){for(let t of e.split(`
633
- `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function pa(e,t,n){return t===void 0?[e,n]:[e,t,n]}function ma(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function ha(e,t,n){let r=e[t];return n===void 0?r:P(r)?r[n]:void 0}function ga(e,t,n,r,i){if(!U(e))return ca(e,ma(t,i,n,r)),{kind:`written`};let a;try{a=W(e,`utf-8`)}catch(e){return $(`json config read failed`,e),{kind:`declined`,reason:`unparseable`}}if(a.trim()===``)return ca(e,ma(t,i,n,r)),{kind:`written`};if(Buffer.byteLength(a,`utf-8`)>ua)return{kind:`declined`,reason:`oversize`};let o=oa(a);if(!o)return{kind:`declined`,reason:`unparseable`};if(sa(o,t)>1)return{kind:`declined`,reason:`duplicate-container`};let s=ha(mr(o),t,i),c=P(s)?s[n]:void 0,l=c!==void 0;if(l&&da(c,r))return{kind:`overwritten`};let u=a.charCodeAt(0)===65279,d=u?a.slice(1):a,f=d.includes(`\r
634
- `)?`\r
635
- `:`
636
- `,p=gr(d,pa(t,i,n),r,{formattingOptions:{...fa(d),eol:f}}),m=`${u?``:``}${_r(d,p)}`;return m!==a&&S(e,m,{mode:br(e)}),{kind:l?`overwritten`:`written`}}function _a(e,t,n,r,i){let a=``;if(U(t))try{a=W(t,`utf-8`)}catch(e){return $(`toml config read failed`,e),{kind:`declined`,reason:`unparseable`}}let o=a.trim()===``;if(e.backend===`fallback`)return o?(la(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let s=a.charCodeAt(0)===65279,c=s?a.slice(1):a,l=yr(c),u=o||c.endsWith(`
637
- `),d;try{d=e.upsertEntry(c,r,i)}catch(e){return $(`upsertEntry failed`,e),{kind:`declined`,reason:`unparseable`}}let f=d.text;u?f.endsWith(`
638
- `)||(f=`${f}\n`):f=f.replace(/\n+$/,``),l&&(f=f.replace(/\r\n/g,`
639
- `).replace(/\n/g,`\r
640
- `));let p=`${s?``:``}${f}`;return p!==a&&S(t,p,{mode:br(t)}),{kind:d.existed?`overwritten`:`written`}}const va=e=>e!==`project`,ya=e=>e!==`user`;async function ba(){let e=await kr({message:`Where should the MCP server be configured?
641
- `,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 xa(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??ba)():`both`}async function Sa(e){return Pr({message:`How do you want to handle OpenKnowledge 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 Ca(e){if(e.sharing!==void 0)return e.sharing;let t=kn(e.projectRoot)===`local-only`?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Sa)(t):t}var wa=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}};function Ta(e){if(e===void 0||e===!0)return new Set(E);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(E.filter(e=>t.includes(e)))}function Ea(e,t,n){let r=ge(n,e),i;try{i=we(r)}catch(e){let t=e.code;throw t===`ENOENT`?new wa(`--content-dir path does not exist: ${r}`):new wa(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new wa(`--content-dir must be a directory: ${r}`);let a=V(Da(t),Da(r));if(a.startsWith(`..`)||he(a))throw new wa(`--content-dir must be inside the project root (${t}); got ${r}`);return a===``?`.`:a}function Da(e){try{return Ce(e)}catch{return e}}const Oa=`0.0.1`,ka=`open-knowledge-ui`,Aa=[`-y`,`@inkeep/open-knowledge@latest`,`ui`],ja=`# ok-ui-v1`,Ma=`${ja}
642
- UIPORT="\${PORT:-${Xi}}"
643
- unset PORT
644
- USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
645
- [ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" start --ui-port "$UIPORT"
646
- BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
647
- [ -f "$BUNDLE" ] && [ -x "$BUNDLE" ] && exec "$BUNDLE" start --ui-port "$UIPORT"
648
- command -v npx >/dev/null 2>&1 && exec npx -y @inkeep/open-knowledge@latest start --ui-port "$UIPORT"
649
- for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installation/bin "$HOME/.asdf/installs/nodejs"/*/bin /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin" "$HOME/.volta/bin"; do
650
- [ -f "$d/npx" ] && [ -x "$d/npx" ] && exec "$d/npx" -y @inkeep/open-knowledge@latest start --ui-port "$UIPORT"
651
- done
652
- echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
653
- exit 127`,Na=`# ok-ui-win-v1`,Pa=`${Na}
654
- if ($env:PATHEXT -notmatch 'CMD') { $env:PATHEXT = '.COM;.EXE;.BAT;.CMD;' + $env:PATHEXT }
655
- $UIPORT = if ($env:PORT) { $env:PORT } else { '${Xi}' }
656
- Remove-Item Env:PORT -ErrorAction SilentlyContinue
657
- if ($env:APPDATA) {
658
- $shim = Join-Path $env:APPDATA 'npm\\ok.cmd'
659
- if (Test-Path -LiteralPath $shim -PathType Leaf) { & $shim start --ui-port $UIPORT; exit $LASTEXITCODE }
660
- }
661
- $ok = Get-Command ok.cmd -CommandType Application -ErrorAction SilentlyContinue
662
- if ($ok) { & $ok.Source start --ui-port $UIPORT; exit $LASTEXITCODE }
663
- $npx = Get-Command npx.cmd -CommandType Application -ErrorAction SilentlyContinue
664
- if ($npx) { & $npx.Source -y '@inkeep/open-knowledge@latest' start --ui-port $UIPORT; exit $LASTEXITCODE }
665
- $dirs = @()
666
- if ($env:ProgramFiles) { $dirs += Join-Path $env:ProgramFiles 'nodejs' }
667
- if ($env:NVM_SYMLINK) { $dirs += $env:NVM_SYMLINK }
668
- if ($env:LOCALAPPDATA) {
669
- $dirs += Join-Path $env:LOCALAPPDATA 'fnm\\aliases\\default'
670
- $dirs += Join-Path $env:LOCALAPPDATA 'Volta\\bin'
671
- $dirs += Join-Path $env:LOCALAPPDATA 'pnpm'
672
- }
673
- if ($env:USERPROFILE) { $dirs += Join-Path $env:USERPROFILE 'scoop\\shims' }
674
- foreach ($d in $dirs) {
675
- $probe = Join-Path $d 'npx.cmd'
676
- if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' start --ui-port $UIPORT; exit $LASTEXITCODE }
677
- }
678
- [Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
679
- exit 127`;function Fa(e,t={}){let n=B(e,`.claude`,`launch.json`),r=()=>`${ja}
680
- UIPORT="\${PORT:-${Xi}}"
681
- unset PORT
682
- exec node "${re()}" start --ui-port "$UIPORT"`,i=t.platformName??process.platform,a=t.mode===`dev`?{name:ka,runtimeExecutable:`/bin/sh`,runtimeArgs:[`-l`,`-c`,r()],port:Xi,autoPort:!0}:i===`win32`?{name:ka,runtimeExecutable:`powershell`,runtimeArgs:[`-NoProfile`,`-NonInteractive`,`-Command`,Pa],port:Xi,autoPort:!0}:{name:ka,runtimeExecutable:`/bin/sh`,runtimeArgs:[`-l`,`-c`,Ma],port:Xi,autoPort:!0};try{if(ce(n,e),!U(n))return xe(z(n),{recursive:!0}),Te(n,`${JSON.stringify({version:Oa,configurations:[a]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=W(n,`utf-8`).trim(),r=t?JSON.parse(t):{};if(!P(r))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let i=Array.isArray(r.configurations)?r.configurations:[],o=i.findIndex(e=>P(e)&&e.name===`open-knowledge-ui`);o>=0?i[o]=a:i.push(a);let s={...r,version:r.version??Oa,configurations:i};return Te(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 Ia(e,t,n){try{return U(e.detectPath?.(t,n)??z(e.configPath(t,n)))}catch{return!1}}function La(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0;if(!i&&s&&!Ia(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{ce(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return za(e,o,a,n,{isProjectScope:i!==void 0});let c;try{c=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{xe(z(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 l={action:`written`},u;try{D(`${o}.lock`,()=>{let t=Ai(o).writePath;if(xe(z(t),{recursive:!0}),e.format===`toml`){let n=_a(Ri(),t,e.topLevelKey,a,c);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason);return}let n=ga(t,e.topLevelKey,a,c,e.serverMapSubKey);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){u=e instanceof Error?e:Error(String(e))}return u?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:u.message,...i===void 0?{}:{configScope:`project`}}:l.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:l.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:l.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Ra={pi:yi};function za(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Ra[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{xe(z(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{D(`${t}.lock`,()=>{let e=null;try{e=W(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}S(t,c,e===null?void 0:{mode:br(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function Ba(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!U(n)))return{editorId:e.id,label:e.label,path:n}}async function Va(e){let t=N(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>La(t,``,n,e.home))}function Ha(e,t,n,r){let i=Wa(e,t,n,r);return i.kind===`present`?i.entry:null}function Ua(e,t,n,r){let i=ha(e,t,r);if(!P(i))return{kind:`no-entry`};let a=i[n];return P(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function Wa(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!U(i))return{kind:`absent`};try{if(we(i).size>ua)return{kind:`decline`,reason:`oversize`}}catch{return{kind:`decline`,reason:`unparseable`}}let a;try{a=W(i,`utf-8`)}catch{return{kind:`decline`,reason:`unparseable`}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:vi(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=Ri().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return Ua(t,e.topLevelKey,o,e.serverMapSubKey)}let s=oa(a);return s?sa(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:Ua(mr(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function Ga(e={}){let t=ge(e.cwd??process.cwd()),n=Si(t,{homeDir:e.home}),r=n.projectRoot,i=!U(B(r,`.ok`)),a=n.gitRootPromoted?V(r,t):void 0,o=e.contentDir===void 0?n.defaultContentDir:Ea(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&o===`.`&&process.stderr.write(`${L(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${a}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`ok init --content-dir .\`, or set content.dir: ${a} in .ok/config.yml.\n`);let s={mode:e.devMcp?`dev`:`published`},c=await ee(r),l;try{l=h(r,{contentDir:o})}catch(t){let i=A.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:c.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let u=l.created.includes(te),d=!1;if(c.didInit)try{d=C(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}let f=await xa({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),p=e.editors??Za(r,e.home),m=e.editors??se.filter(e=>A[e].projectConfigPath!==void 0),g=N(p),_=N(m),v=e.mcp===!1||f===null,b=Array.from(new Map([...g,...v?[]:_].map(e=>[e.id,e])).values()),S=g.filter(t=>Ia(t,r,e.home)),w=[],D=[],O=new Set;for(let t of b){if(v){let n=``;try{n=t.configPath(r,e.home)}catch{}w.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(va(f)&&g.includes(t)&&t.scope===`global`&&w.push(La(t,r,s,e.home)),ya(f)&&_.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=La(t,r,s,e.home,n);w.push(i),(i.action===`written`||i.action===`overwritten`)&&O.add(n)}}let k=new Set;for(let e of _){let t=e.projectSkillPath?.(r);!t||k.has(t)||(k.add(t),D.push(ae(e,r)))}let re=!v&&f!==null&&ya(f)?_.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,j=v?[]:S.map(e=>Ba(e,r)).filter(e=>e!==void 0).filter(e=>!O.has(e.path)),ie=S.some(e=>e.id===`claude`)&&!v?Fa(r,s):void 0,oe=e.installUserSkill??y,M=e.home??ye(),ce=Ta(e.skills),P=!1,F=!1,le=!1,I=!1;for(let t of E){let n=ce.has(t);if(await T(M,x[t],n).catch(()=>{}),n){P=!0;let n=await oe({home:e.home,bundleId:t,force:!0});n===`installed`?F=!0:n===`failed`?le=!0:I=!0}else try{ne(M,t)}catch{}}let ue=le?`failed`:F?`installed`:P&&I?`skip-current`:`declined`,R=v?`skipped-flag`:`skipped-missing`,de=w.find(e=>e.editorId===`claude`)??w[0]??{action:R,configPath:A.claude.configPath(r,e.home)},fe=await Ka({projectRoot:r,desiredMode:await Ca({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:l.created,contentUpdated:l.updated,contentSkipped:l.skipped,editors:w,projectSkills:D,legacyProjectConfigs:j,launchJson:ie,skillInstall:ue,didGitInit:c.didInit,rootGitignoreCreated:d,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDir:u?o:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:de.action,mcpPath:de.configPath,mcpError:`error`in de?de.error:void 0,projectScopeUnsupportedLabels:re,sharing:fe}}async function Ka(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=kn(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=En(t);if(n===`local-only`){let e=Dn(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`}:qa(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=On(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:qa(t,o,`remove`)}function qa(e,t,n){let r=kn(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 Ja(e){switch(e){case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;default:return`config not readable`}}function Ya(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)?V(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=B(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(R(`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(R(`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(R(`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(R(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(R(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?V(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} ${I(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${I(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${ue(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${c}${l}${i} left unchanged (${Ja(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}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(R(`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?V(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${I(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${I(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${ue(`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} ${V(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(R(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${I(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${I(`already installed at current version`)}`);break;case`declined`:n.push(` open-knowledge ${le(`skipped (opted out via --no-skills)`)}`);break;case`failed`:n.push(` ${L(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${L(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(L(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(L(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`ok init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(" To scope to just that sub-folder, re-run `ok init --content-dir .` from there, or set"),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(de(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...eo(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(`${I(`✓`)} ${R(`Next steps:`)}`),n.push(` 1. Open your editor (${F(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${F(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${F(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${F(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${F(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${F(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
683
- `)}function Xa(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function Za(e,t){let n=[];for(let r of se)Ia(A[r],e,t)&&n.push(r);return n}function Qa(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:De(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function $a(){return new k(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new O(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new O(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new O(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?Qa():null;try{let r;try{r=await Ga({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof wa){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof m||e instanceof _){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof g){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
684
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-DsrSOTpM.mjs`),{resolveContentDir:s}=await import(`./dist-Bc_bWnDQ.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-BbnP_W-F.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(Xa(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${Ya(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function eo(e,t){let n=[];switch(e.kind){case`applied`:return n.push(R(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?n.push(` ${I(`local-only`)} — appended ${e.appended.length} path(s) to ${R(`${t}/.git/info/exclude`)} (per-clone, not committed).`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${I(`local-only`)} — already excluded; nothing to do.`):n.push(` ${I(`local-only`)}`):e.action===`removed`?n.push(` ${I(`shared`)} — removed OK paths from ${R(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${I(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(L(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
685
- `))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${F(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(L(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${F(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${F(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(L(`Sharing mode unavailable: ${e.reason}.`));return n}}export{kr as A,jn as B,pa as C,Ri as D,na as E,pr as F,bt as G,On as H,Dn as I,q as J,_t as K,Mn as L,yr as M,xr as N,Si as O,mr as P,An as R,Fa as S,Va as T,Tn as U,kn as V,fn as W,Ue as Y,Ta as _,Ma as a,Ca as b,Ra as c,Wa as d,Za as f,Ha as g,$a as h,ja as i,br as j,_i as k,Ka as l,eo as m,ka as n,Na as o,Ya as p,gt as q,Aa as r,Pa as s,wa as t,Xa as u,xa as v,La as w,Ga as x,Ea as y,En as z};
686
- //# sourceMappingURL=init-C5xydBwk.mjs.map